index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http/async/CombinedResponseAsyncHttpResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.http.async; import static software.amazon.awssdk.core.SdkStandardLogger.logRequestId; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.Response; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.internal.http.TransformingAsyncResponseHandler; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.Validate; /** * Detects whether the response succeeded or failed by just checking the HTTP status and delegates to appropriate * async response handler. Can be used with streaming or non-streaming requests. */ @SdkInternalApi public final class CombinedResponseAsyncHttpResponseHandler<OutputT> implements TransformingAsyncResponseHandler<Response<OutputT>> { private final TransformingAsyncResponseHandler<OutputT> successResponseHandler; private final TransformingAsyncResponseHandler<? extends SdkException> errorResponseHandler; private CompletableFuture<SdkHttpResponse> headersFuture; public CombinedResponseAsyncHttpResponseHandler( TransformingAsyncResponseHandler<OutputT> successResponseHandler, TransformingAsyncResponseHandler<? extends SdkException> errorResponseHandler) { this.successResponseHandler = successResponseHandler; this.errorResponseHandler = errorResponseHandler; } @Override public void onHeaders(SdkHttpResponse response) { Validate.isTrue(headersFuture != null, "onHeaders() invoked without prepare()."); headersFuture.complete(response); logRequestId(response); if (response.isSuccessful()) { successResponseHandler.onHeaders(response); } else { errorResponseHandler.onHeaders(response); } } @Override public void onError(Throwable error) { if (headersFuture != null) { // Failure in marshalling calls this before prepare() so value is null headersFuture.completeExceptionally(error); } successResponseHandler.onError(error); errorResponseHandler.onError(error); } @Override public void onStream(Publisher<ByteBuffer> publisher) { Validate.isTrue(headersFuture != null, "onStream() invoked without prepare()."); Validate.isTrue(headersFuture.isDone(), "headersFuture is still not completed when onStream() is " + "invoked."); if (headersFuture.isCompletedExceptionally()) { return; } SdkHttpResponse sdkHttpResponse = headersFuture.join(); if (sdkHttpResponse.isSuccessful()) { successResponseHandler.onStream(publisher); } else { errorResponseHandler.onStream(publisher); } } @Override public CompletableFuture<Response<OutputT>> prepare() { headersFuture = new CompletableFuture<>(); CompletableFuture<OutputT> preparedTransformFuture = successResponseHandler.prepare(); CompletableFuture<? extends SdkException> preparedErrorTransformFuture = errorResponseHandler == null ? null : errorResponseHandler.prepare(); return headersFuture.thenCompose(headers -> { SdkHttpFullResponse sdkHttpFullResponse = toFullResponse(headers); if (headers.isSuccessful()) { return preparedTransformFuture.thenApply( r -> Response.<OutputT>builder().response(r) .httpResponse(sdkHttpFullResponse) .isSuccess(true) .build()); } if (preparedErrorTransformFuture != null) { return preparedErrorTransformFuture.thenApply( e -> Response.<OutputT>builder().exception(e) .httpResponse(sdkHttpFullResponse) .isSuccess(false) .build()); } return CompletableFuture.completedFuture( Response.<OutputT>builder().httpResponse(sdkHttpFullResponse) .isSuccess(false) .build()); }); } private static SdkHttpFullResponse toFullResponse(SdkHttpResponse response) { SdkHttpFullResponse.Builder builder = SdkHttpFullResponse.builder() .statusCode(response.statusCode()); response.forEachHeader(builder::putHeader); response.statusText().ifPresent(builder::statusText); return builder.build(); } }
2,000
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http/async/SimpleHttpContentPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.http.async; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.nio.ByteBuffer; import java.util.Optional; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; import software.amazon.awssdk.utils.IoUtils; /** * Implementation of {@link SdkHttpContentPublisher} that provides all it's data at once. Useful for * non streaming operations that are already marshalled into memory. */ @SdkInternalApi public final class SimpleHttpContentPublisher implements SdkHttpContentPublisher { private final byte[] content; private final int length; public SimpleHttpContentPublisher(SdkHttpFullRequest request) { this.content = request.contentStreamProvider().map(p -> invokeSafely(() -> IoUtils.toByteArray(p.newStream()))) .orElseGet(() -> new byte[0]); this.length = content.length; } @Override public Optional<Long> contentLength() { return Optional.of((long) length); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { s.onSubscribe(new SubscriptionImpl(s)); } private class SubscriptionImpl implements Subscription { private boolean running = true; private final Subscriber<? super ByteBuffer> s; private SubscriptionImpl(Subscriber<? super ByteBuffer> s) { this.s = s; } @Override public void request(long n) { if (running) { running = false; if (n <= 0) { s.onError(new IllegalArgumentException("Demand must be positive")); } else { s.onNext(ByteBuffer.wrap(content)); s.onComplete(); } } } @Override public void cancel() { running = false; } } }
2,001
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http/async/AsyncResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.http.async; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.internal.http.TransformingAsyncResponseHandler; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.CompletableFutureUtils; /** * * Response handler for asynchronous non-streaming operations. * * <p> * Adapts an {@link HttpResponseHandler} to the asynchronous {@link TransformingAsyncResponseHandler}. Buffers * all content into a {@link ByteArrayInputStream} then invokes the {@link HttpResponseHandler#handle} * method. * * @param <T> Type that the response handler produces. */ @SdkInternalApi public final class AsyncResponseHandler<T> implements TransformingAsyncResponseHandler<T> { private volatile CompletableFuture<ByteArrayOutputStream> streamFuture; private final HttpResponseHandler<T> responseHandler; private final ExecutionAttributes executionAttributes; private final Function<SdkHttpFullResponse, SdkHttpFullResponse> crc32Validator; private SdkHttpFullResponse.Builder httpResponse; public AsyncResponseHandler(HttpResponseHandler<T> responseHandler, Function<SdkHttpFullResponse, SdkHttpFullResponse> crc32Validator, ExecutionAttributes executionAttributes) { this.responseHandler = responseHandler; this.executionAttributes = executionAttributes; this.crc32Validator = crc32Validator; } @Override public void onHeaders(SdkHttpResponse response) { this.httpResponse = ((SdkHttpFullResponse) response).toBuilder(); } @Override public void onStream(Publisher<ByteBuffer> publisher) { publisher.subscribe(new BaosSubscriber(streamFuture)); } @Override public void onError(Throwable err) { if (streamFuture == null) { prepare(); } streamFuture.completeExceptionally(err); } @Override public CompletableFuture<T> prepare() { streamFuture = new CompletableFuture<>(); return streamFuture.thenCompose(baos -> { if (baos != null) { // Ignore aborts - we already have all of the content. httpResponse.content(AbortableInputStream.create(new ByteArrayInputStream(baos.toByteArray()))); } try { return CompletableFuture.completedFuture(responseHandler.handle(crc32Validator.apply(httpResponse.build()), executionAttributes)); } catch (Exception e) { return CompletableFutureUtils.failedFuture(e); } }); } private static class BaosSubscriber implements Subscriber<ByteBuffer> { private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); private final CompletableFuture<ByteArrayOutputStream> streamFuture; private Subscription subscription; private boolean dataWritten = false; private BaosSubscriber(CompletableFuture<ByteArrayOutputStream> streamFuture) { this.streamFuture = streamFuture; } @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(Long.MAX_VALUE); } @Override public void onNext(ByteBuffer byteBuffer) { dataWritten = true; try { baos.write(BinaryUtils.copyBytesFrom(byteBuffer)); this.subscription.request(1); } catch (IOException e) { // Should never happen streamFuture.completeExceptionally(e); } } @Override public void onError(Throwable throwable) { streamFuture.completeExceptionally(throwable); } @Override public void onComplete() { streamFuture.complete(dataWritten ? baos : null); } } }
2,002
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http/async/AsyncAfterTransmissionInterceptorCallingResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.http.async; import java.nio.ByteBuffer; import java.util.Optional; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.internal.http.TransformingAsyncResponseHandler; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; /** * Async response handler decorator to run interceptors after response is received. * * @param <T> the type of the result */ @SdkInternalApi public final class AsyncAfterTransmissionInterceptorCallingResponseHandler<T> implements TransformingAsyncResponseHandler<T> { private final TransformingAsyncResponseHandler<T> delegate; private final ExecutionContext context; public AsyncAfterTransmissionInterceptorCallingResponseHandler(TransformingAsyncResponseHandler<T> delegate, ExecutionContext context) { this.delegate = delegate; this.context = context; } private SdkHttpResponse beforeUnmarshalling(SdkHttpFullResponse response, ExecutionContext context) { // Update interceptor context to include response InterceptorContext interceptorContext = context.interceptorContext().copy(b -> b.httpResponse(response)); // interceptors.afterTransmission context.interceptorChain().afterTransmission(interceptorContext, context.executionAttributes()); // interceptors.modifyHttpResponse interceptorContext = context.interceptorChain().modifyHttpResponse(interceptorContext, context.executionAttributes()); // interceptors.beforeUnmarshalling context.interceptorChain().beforeUnmarshalling(interceptorContext, context.executionAttributes()); // Store updated context context.interceptorContext(interceptorContext); return interceptorContext.httpResponse(); } @Override public void onHeaders(SdkHttpResponse response) { delegate.onHeaders(beforeUnmarshalling((SdkHttpFullResponse) response, context)); // TODO: Ew } @Override public void onError(Throwable error) { delegate.onError(error); } @Override public void onStream(Publisher<ByteBuffer> publisher) { Optional<Publisher<ByteBuffer>> newPublisher = context.interceptorChain() .modifyAsyncHttpResponse(context.interceptorContext() .toBuilder() .responsePublisher(publisher) .build(), context.executionAttributes()) .responsePublisher(); if (newPublisher.isPresent()) { delegate.onStream(newPublisher.get()); } else { delegate.onStream(publisher); } } @Override public CompletableFuture<T> prepare() { return delegate.prepare(); } }
2,003
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http/async/AsyncStreamingResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.http.async; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; 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.http.HttpResponseHandler; import software.amazon.awssdk.core.internal.http.TransformingAsyncResponseHandler; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; /** * Response handler for asynchronous streaming operations. */ @SdkInternalApi public final class AsyncStreamingResponseHandler<OutputT extends SdkResponse, ReturnT> implements TransformingAsyncResponseHandler<ReturnT> { private final AsyncResponseTransformer<OutputT, ReturnT> asyncResponseTransformer; private volatile HttpResponseHandler<OutputT> responseHandler; public AsyncStreamingResponseHandler(AsyncResponseTransformer<OutputT, ReturnT> asyncResponseTransformer) { this.asyncResponseTransformer = asyncResponseTransformer; } public void responseHandler(HttpResponseHandler<OutputT> responseHandler) { this.responseHandler = responseHandler; } @Override public void onHeaders(SdkHttpResponse response) { try { // TODO would be better to pass in AwsExecutionAttributes to the async response handler so we can // provide them to HttpResponseHandler OutputT resp = responseHandler.handle((SdkHttpFullResponse) response, null); asyncResponseTransformer.onResponse(resp); } catch (Exception e) { asyncResponseTransformer.exceptionOccurred(e); } } @Override public void onStream(Publisher<ByteBuffer> publisher) { asyncResponseTransformer.onStream(SdkPublisher.adapt(publisher)); } @Override public void onError(Throwable error) { asyncResponseTransformer.exceptionOccurred(error); } @Override public CompletableFuture<ReturnT> prepare() { return asyncResponseTransformer.prepare(); } }
2,004
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http/loader/CachingSdkHttpServiceProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.http.loader; import static software.amazon.awssdk.utils.Validate.notNull; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Decorator of {@link SdkHttpServiceProvider} to provide lazy initialized caching. */ @SdkInternalApi final class CachingSdkHttpServiceProvider<T> implements SdkHttpServiceProvider<T> { private final SdkHttpServiceProvider<T> delegate; /** * We assume that the service obtained from the provider chain will always be the same (even if it's an empty optional) so * we cache it as a field. */ private volatile Optional<T> factory; CachingSdkHttpServiceProvider(SdkHttpServiceProvider<T> delegate) { this.delegate = notNull(delegate, "Delegate service provider cannot be null"); } @Override public Optional<T> loadService() { if (factory == null) { synchronized (this) { if (factory == null) { this.factory = delegate.loadService(); } } } return factory; } }
2,005
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http/loader/SdkServiceLoader.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.http.loader; import java.util.Iterator; import java.util.ServiceLoader; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.internal.util.ClassLoaderHelper; /** * Thin layer over {@link ServiceLoader}. */ @SdkInternalApi class SdkServiceLoader { public static final SdkServiceLoader INSTANCE = new SdkServiceLoader(); <T> Iterator<T> loadServices(Class<T> clzz) { return ServiceLoader.load(clzz, ClassLoaderHelper.classLoader(SdkServiceLoader.class)).iterator(); } }
2,006
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http/loader/DefaultSdkAsyncHttpClientBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.http.loader; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpService; import software.amazon.awssdk.utils.AttributeMap; /** * Utility to load the default HTTP client factory and create an instance of {@link SdkHttpClient}. */ @SdkInternalApi public final class DefaultSdkAsyncHttpClientBuilder implements SdkAsyncHttpClient.Builder { private static final SdkHttpServiceProvider<SdkAsyncHttpService> DEFAULT_CHAIN = new CachingSdkHttpServiceProvider<>( new SdkHttpServiceProviderChain<>( SystemPropertyHttpServiceProvider.asyncProvider(), ClasspathSdkHttpServiceProvider.asyncProvider() )); @Override public SdkAsyncHttpClient buildWithDefaults(AttributeMap serviceDefaults) { // TODO We create and build every time. Do we want to cache it instead of the service binding? return DEFAULT_CHAIN .loadService() .map(SdkAsyncHttpService::createAsyncHttpClientFactory) .map(f -> f.buildWithDefaults(serviceDefaults)) .orElseThrow( () -> SdkClientException.builder() .message("Unable to load an HTTP implementation from any provider in the " + "chain. You must declare a dependency on an appropriate HTTP " + "implementation or pass in an SdkHttpClient explicitly to the " + "client builder.") .build()); } }
2,007
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http/loader/SdkHttpServiceProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.http.loader; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Interface to load an HTTP service binding from the environment/classpath. * * @param <T> Type of service binding being loaded. */ @SdkInternalApi interface SdkHttpServiceProvider<T> { /** * @return Empty {@link Optional} if service can't be loaded, otherwise fulfilled {@link Optional} containing service * instance. */ Optional<T> loadService(); }
2,008
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http/loader/SystemPropertyHttpServiceProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.http.loader; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.SdkHttpService; import software.amazon.awssdk.http.async.SdkAsyncHttpService; import software.amazon.awssdk.utils.SystemSetting; /** * Attempts to load the default implementation from the system property {@link SdkSystemSetting#SYNC_HTTP_SERVICE_IMPL}. The * property value should be the fully qualified class name of the factory to use. */ @SdkInternalApi final class SystemPropertyHttpServiceProvider<T> implements SdkHttpServiceProvider<T> { private final SystemSetting implSetting; private final Class<T> serviceClass; /** * @param implSetting {@link SystemSetting} to access the system property that has the implementation FQCN. * @param serviceClass Service type being loaded. */ private SystemPropertyHttpServiceProvider(SystemSetting implSetting, Class<T> serviceClass) { this.implSetting = implSetting; this.serviceClass = serviceClass; } @Override public Optional<T> loadService() { return implSetting .getStringValue() .map(this::createServiceFromProperty); } private T createServiceFromProperty(String httpImplFqcn) { try { return serviceClass.cast(Class.forName(httpImplFqcn).newInstance()); } catch (Exception e) { throw SdkClientException.builder() .message(String.format("Unable to load the HTTP factory implementation from the " + "%s system property. Ensure the class '%s' is present on the classpath" + "and has a no-arg constructor", SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property(), httpImplFqcn)) .cause(e) .build(); } } /** * @return SystemPropertyHttpServiceProvider instance using the sync HTTP system property. */ static SystemPropertyHttpServiceProvider<SdkHttpService> syncProvider() { return new SystemPropertyHttpServiceProvider<>(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL, SdkHttpService.class); } /** * @return SystemPropertyHttpServiceProvider instance using the async HTTP system property. */ static SystemPropertyHttpServiceProvider<SdkAsyncHttpService> asyncProvider() { return new SystemPropertyHttpServiceProvider<>(SdkSystemSetting.ASYNC_HTTP_SERVICE_IMPL, SdkAsyncHttpService.class); } }
2,009
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http/loader/ClasspathSdkHttpServiceProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.http.loader; import java.util.List; import java.util.Optional; import java.util.ServiceLoader; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.SdkHttpService; import software.amazon.awssdk.http.async.SdkAsyncHttpService; import software.amazon.awssdk.utils.SystemSetting; /** * {@link SdkHttpServiceProvider} implementation that uses {@link ServiceLoader} to find HTTP implementations on the * classpath. If more than one implementation is found on the classpath then an exception is thrown. */ @SdkInternalApi final class ClasspathSdkHttpServiceProvider<T> implements SdkHttpServiceProvider<T> { private final SdkServiceLoader serviceLoader; private final SystemSetting implSystemProperty; private final Class<T> serviceClass; @SdkTestInternalApi ClasspathSdkHttpServiceProvider(SdkServiceLoader serviceLoader, SystemSetting implSystemProperty, Class<T> serviceClass) { this.serviceLoader = serviceLoader; this.implSystemProperty = implSystemProperty; this.serviceClass = serviceClass; } @Override public Optional<T> loadService() { Iterable<T> iterable = () -> serviceLoader.loadServices(serviceClass); List<T> impls = StreamSupport .stream(iterable.spliterator(), false) .collect(Collectors.toList()); if (impls.isEmpty()) { return Optional.empty(); } if (impls.size() > 1) { String implText = impls.stream() .map(clazz -> clazz.getClass().getName()) .collect(Collectors.joining(",", "[", "]")); throw SdkClientException.builder().message( String.format( "Multiple HTTP implementations were found on the classpath. To avoid non-deterministic loading " + "implementations, please explicitly provide an HTTP client via the client builders, set the %s " + "system property with the FQCN of the HTTP service to use as the default, or remove all but one " + "HTTP implementation from the classpath. The multiple implementations found were: %s", implSystemProperty.property(), implText)) .build(); } return impls.stream().findFirst(); } /** * @return ClasspathSdkHttpServiceProvider that loads an {@link SdkHttpService} (sync) from the classpath. */ static SdkHttpServiceProvider<SdkHttpService> syncProvider() { return new ClasspathSdkHttpServiceProvider<>(SdkServiceLoader.INSTANCE, SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL, SdkHttpService.class); } /** * @return ClasspathSdkHttpServiceProvider that loads an {@link SdkAsyncHttpService} (async) from the classpath. */ static SdkHttpServiceProvider<SdkAsyncHttpService> asyncProvider() { return new ClasspathSdkHttpServiceProvider<>(SdkServiceLoader.INSTANCE, SdkSystemSetting.ASYNC_HTTP_SERVICE_IMPL, SdkAsyncHttpService.class); } }
2,010
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http/loader/DefaultSdkHttpClientBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.http.loader; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpService; import software.amazon.awssdk.utils.AttributeMap; /** * Utility to load the default HTTP client factory and create an instance of {@link SdkHttpClient}. */ @SdkInternalApi public final class DefaultSdkHttpClientBuilder implements SdkHttpClient.Builder { private static final SdkHttpServiceProvider<SdkHttpService> DEFAULT_CHAIN = new CachingSdkHttpServiceProvider<>( new SdkHttpServiceProviderChain<>( SystemPropertyHttpServiceProvider.syncProvider(), ClasspathSdkHttpServiceProvider.syncProvider() )); @Override public SdkHttpClient buildWithDefaults(AttributeMap serviceDefaults) { // TODO We create and build every time. Do we want to cache it instead of the service binding? return DEFAULT_CHAIN .loadService() .map(SdkHttpService::createHttpClientBuilder) .map(f -> f.buildWithDefaults(serviceDefaults)) .orElseThrow( () -> SdkClientException.builder() .message("Unable to load an HTTP implementation from any provider in the " + "chain. You must declare a dependency on an appropriate HTTP " + "implementation or pass in an SdkHttpClient explicitly to the " + "client builder.") .build()); } }
2,011
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/http/loader/SdkHttpServiceProviderChain.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.http.loader; import static software.amazon.awssdk.utils.Validate.notEmpty; import java.util.Arrays; import java.util.List; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Consults a chain of {@link SdkHttpServiceProvider} looking for one that can provide a service instance. */ @SdkInternalApi final class SdkHttpServiceProviderChain<T> implements SdkHttpServiceProvider<T> { private final List<SdkHttpServiceProvider<T>> httpProviders; @SafeVarargs SdkHttpServiceProviderChain(SdkHttpServiceProvider<T>... httpProviders) { this.httpProviders = Arrays.asList(notEmpty(httpProviders, "httpProviders cannot be null or empty")); } @Override public Optional<T> loadService() { return httpProviders.stream() .map(SdkHttpServiceProvider::loadService) .filter(Optional::isPresent) .map(Optional::get) .findFirst(); } }
2,012
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/compression/Compressor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.compression; import java.io.InputStream; import java.nio.ByteBuffer; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.internal.http.pipeline.stages.CompressRequestStage; /** * Interface for compressors used by {@link CompressRequestStage} to compress requests. */ @SdkInternalApi public interface Compressor { /** * The compression algorithm type. * * @return The {@link String} compression algorithm type. */ String compressorType(); /** * Compress a {@link SdkBytes} payload. * * @param content * @return The compressed {@link SdkBytes}. */ SdkBytes compress(SdkBytes content); /** * Compress a byte[] payload. * * @param content * @return The compressed byte array. */ default byte[] compress(byte[] content) { return compress(SdkBytes.fromByteArray(content)).asByteArray(); } /** * Compress an {@link InputStream} payload. * * @param content * @return The compressed {@link InputStream}. */ default InputStream compress(InputStream content) { return compress(SdkBytes.fromInputStream(content)).asInputStream(); } /** * Compress an {@link ByteBuffer} payload. * * @param content * @return The compressed {@link ByteBuffer}. */ default ByteBuffer compress(ByteBuffer content) { return compress(SdkBytes.fromByteBuffer(content)).asByteBuffer(); } }
2,013
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/compression/CompressorType.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.compression; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; /** * The supported compression algorithms for operations with the requestCompression trait. Each supported algorithm will have an * {@link Compressor} implementation. */ @SdkInternalApi public final class CompressorType { public static final CompressorType GZIP = CompressorType.of("gzip"); private static Map<String, Compressor> compressorMap = new HashMap<String, Compressor>() {{ put("gzip", new GzipCompressor()); }}; private final String id; private CompressorType(String id) { this.id = id; } /** * Creates a new {@link CompressorType} of the given value. */ public static CompressorType of(String value) { Validate.paramNotBlank(value, "compressionType"); return CompressorTypeCache.put(value); } /** * Returns the {@link Set} of {@link String}s of compressor types supported by the SDK. */ public static Set<String> compressorTypes() { return compressorMap.keySet(); } /** * Whether or not the compressor type is supported by the SDK. */ public static boolean isSupported(String compressionType) { return compressorTypes().contains(compressionType); } /** * Maps the {@link CompressorType} to its corresponding {@link Compressor}. */ public Compressor newCompressor() { Compressor compressor = compressorMap.getOrDefault(this.id, null); if (compressor == null) { throw new UnsupportedOperationException("The compression type " + id + " does not have an implementation of " + "Compressor"); } return compressor; } @Override public String toString() { return id; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompressorType that = (CompressorType) o; return Objects.equals(id, that.id) && Objects.equals(compressorMap, that.compressorMap); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (compressorMap != null ? compressorMap.hashCode() : 0); return result; } private static class CompressorTypeCache { private static final ConcurrentHashMap<String, CompressorType> VALUES = new ConcurrentHashMap<>(); private CompressorTypeCache() { } private static CompressorType put(String value) { return VALUES.computeIfAbsent(value, v -> new CompressorType(value)); } } }
2,014
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/compression/GzipCompressor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.compression; import static software.amazon.awssdk.utils.IoUtils.closeQuietly; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.util.zip.GZIPOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; @SdkInternalApi public final class GzipCompressor implements Compressor { private static final String COMPRESSOR_TYPE = "gzip"; private static final Logger log = LoggerFactory.getLogger(GzipCompressor.class); @Override public String compressorType() { return COMPRESSOR_TYPE; } @Override public SdkBytes compress(SdkBytes content) { GZIPOutputStream gzipOutputStream = null; try { ByteArrayOutputStream compressedOutputStream = new ByteArrayOutputStream(); gzipOutputStream = new GZIPOutputStream(compressedOutputStream); gzipOutputStream.write(content.asByteArray()); gzipOutputStream.close(); return SdkBytes.fromByteArray(compressedOutputStream.toByteArray()); } catch (IOException e) { throw new UncheckedIOException(e); } finally { closeQuietly(gzipOutputStream, log); } } }
2,015
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/sync/FileContentStreamProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.sync; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.ContentStreamProvider; /** * {@link ContentStreamProvider} implementation for files. */ @SdkInternalApi public final class FileContentStreamProvider implements ContentStreamProvider { private final Path filePath; private InputStream currentStream; public FileContentStreamProvider(Path filePath) { this.filePath = filePath; } @Override public InputStream newStream() { closeCurrentStream(); currentStream = invokeSafely(() -> Files.newInputStream(filePath)); return currentStream; } private void closeCurrentStream() { if (currentStream != null) { invokeSafely(currentStream::close); currentStream = null; } } }
2,016
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/sync/CompressionContentStreamProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.sync; import java.io.InputStream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.internal.compression.Compressor; import software.amazon.awssdk.core.internal.io.AwsCompressionInputStream; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.utils.IoUtils; /** * {@link ContentStreamProvider} implementation for compression. */ @SdkInternalApi public class CompressionContentStreamProvider implements ContentStreamProvider { private final ContentStreamProvider underlyingInputStreamProvider; private InputStream currentStream; private final Compressor compressor; public CompressionContentStreamProvider(ContentStreamProvider underlyingInputStreamProvider, Compressor compressor) { this.underlyingInputStreamProvider = underlyingInputStreamProvider; this.compressor = compressor; } @Override public InputStream newStream() { closeCurrentStream(); currentStream = AwsCompressionInputStream.builder() .inputStream(underlyingInputStreamProvider.newStream()) .compressor(compressor) .build(); return currentStream; } private void closeCurrentStream() { if (currentStream != null) { IoUtils.closeQuietly(currentStream, null); currentStream = null; } } }
2,017
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/transform/AbstractStreamingRequestMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.transform; import static software.amazon.awssdk.http.Header.CHUNKED; import static software.amazon.awssdk.http.Header.CONTENT_LENGTH; import static software.amazon.awssdk.http.Header.TRANSFER_ENCODING; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.runtime.transform.Marshaller; import software.amazon.awssdk.http.SdkHttpFullRequest; @SdkInternalApi public abstract class AbstractStreamingRequestMarshaller<T> implements Marshaller<T> { protected final Marshaller<T> delegateMarshaller; protected final boolean requiresLength; protected final boolean transferEncoding; protected final boolean useHttp2; protected AbstractStreamingRequestMarshaller(Builder builder) { this.delegateMarshaller = builder.delegateMarshaller; this.requiresLength = builder.requiresLength; this.transferEncoding = builder.transferEncoding; this.useHttp2 = builder.useHttp2; } /** * This method will run certain validations for content-length and add * additional headers (like Transfer-Encoding) if necessary. * * If requiresLength and transferEncoding is not set to true and Content Length is missing, * SDK is not required to calculate the Content-Length and delegate that behavior to the underlying http client. * * @param marshalled A mutable builder for {@link SdkHttpFullRequest} representing a HTTP request. * @param contentLength Optional of content length * @param requiresLength True if Content-Length header is required on the request * @param transferEncoding True if "Transfer-Encoding: chunked" header should be set on request * @param useHttp2 True if the operation uses http2 */ protected final void addHeaders(SdkHttpFullRequest.Builder marshalled, Optional<Long> contentLength, boolean requiresLength, boolean transferEncoding, boolean useHttp2) { if (marshalled.firstMatchingHeader(CONTENT_LENGTH).isPresent()) { return; } if (contentLength.isPresent()) { marshalled.putHeader(CONTENT_LENGTH, Long.toString(contentLength.get())); return; } if (requiresLength) { throw SdkClientException.create("This API requires Content-Length header to be set. " + "Please set the content length on the RequestBody."); } else if (transferEncoding && !useHttp2) { marshalled.putHeader(TRANSFER_ENCODING, CHUNKED); } } protected abstract static class Builder<BuilderT extends Builder> { private Marshaller delegateMarshaller; private boolean requiresLength = Boolean.FALSE; private boolean transferEncoding = Boolean.FALSE; private boolean useHttp2 = Boolean.FALSE; protected Builder() { } /** * @param delegateMarshaller POJO marshaller (for path/query/header members) * @return This object for method chaining */ public BuilderT delegateMarshaller(Marshaller delegateMarshaller) { this.delegateMarshaller = delegateMarshaller; return (BuilderT) this; } /** * @param requiresLength boolean value indicating if Content-Length header is required in the request * @return This object for method chaining */ public BuilderT requiresLength(boolean requiresLength) { this.requiresLength = requiresLength; return (BuilderT) this; } /** * @param transferEncoding boolean value indicating if Transfer-Encoding: chunked header is required in the request * @return This object for method chaining */ public BuilderT transferEncoding(boolean transferEncoding) { this.transferEncoding = transferEncoding; return (BuilderT) this; } /** * @param useHttp2 boolean value indicating if request uses HTTP 2 protocol * @return This object for method chaining */ public BuilderT useHttp2(boolean useHttp2) { this.useHttp2 = useHttp2; return (BuilderT) this; } } }
2,018
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/interceptor/HttpChecksumValidationInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.interceptor; import static software.amazon.awssdk.core.ClientType.ASYNC; import static software.amazon.awssdk.core.ClientType.SYNC; import static software.amazon.awssdk.core.internal.util.HttpChecksumUtils.getAlgorithmChecksumValuePair; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Optional; import java.util.function.Predicate; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.ClientType; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.checksums.ChecksumValidation; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.internal.async.ChecksumValidatingPublisher; import software.amazon.awssdk.core.internal.io.ChecksumValidatingInputStream; import software.amazon.awssdk.core.internal.util.HttpChecksumResolver; import software.amazon.awssdk.core.internal.util.HttpChecksumUtils; import software.amazon.awssdk.utils.Pair; /** * Interceptor to intercepts Sync and Async responses. * The Http Checksum is computed and validated with the one that is passed in the header of the response. */ @SdkInternalApi public final class HttpChecksumValidationInterceptor implements ExecutionInterceptor { private static final Predicate<ExecutionAttributes> IS_FORCE_SKIPPED_VALIDATION = ex -> ChecksumValidation.FORCE_SKIP.equals( ex.getOptionalAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION).orElse(null)); @Override public Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { ChecksumSpecs resolvedChecksumSpecs = HttpChecksumResolver.getResolvedChecksumSpecs(executionAttributes); if (resolvedChecksumSpecs != null && isFlexibleChecksumValidationForResponse(executionAttributes, resolvedChecksumSpecs, SYNC)) { Pair<Algorithm, String> algorithmChecksumPair = getAlgorithmChecksumValuePair( context.httpResponse(), resolvedChecksumSpecs); updateContextWithChecksumValidationStatus(executionAttributes, algorithmChecksumPair); if (algorithmChecksumPair != null && context.responseBody().isPresent()) { return Optional.of(new ChecksumValidatingInputStream( context.responseBody().get(), SdkChecksum.forAlgorithm(algorithmChecksumPair.left()), algorithmChecksumPair.right())); } } return context.responseBody(); } @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { ChecksumSpecs resolvedChecksumSpecs = HttpChecksumResolver.getResolvedChecksumSpecs(executionAttributes); if (resolvedChecksumSpecs != null && isFlexibleChecksumValidationForResponse(executionAttributes, resolvedChecksumSpecs, ASYNC)) { Pair<Algorithm, String> algorithmChecksumPair = getAlgorithmChecksumValuePair(context.httpResponse(), resolvedChecksumSpecs); updateContextWithChecksumValidationStatus(executionAttributes, algorithmChecksumPair); if (algorithmChecksumPair != null && context.responsePublisher().isPresent()) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), SdkChecksum.forAlgorithm(algorithmChecksumPair.left()), algorithmChecksumPair.right())); } } return context.responsePublisher(); } private void updateContextWithChecksumValidationStatus(ExecutionAttributes executionAttributes, Pair<Algorithm, String> algorithmChecksumPair) { if (algorithmChecksumPair == null || algorithmChecksumPair.left() == null) { executionAttributes.putAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION, ChecksumValidation.CHECKSUM_ALGORITHM_NOT_FOUND); } else { executionAttributes.putAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION, ChecksumValidation.VALIDATED); executionAttributes.putAttribute(SdkExecutionAttribute.HTTP_CHECKSUM_VALIDATION_ALGORITHM, algorithmChecksumPair.left()); } } private boolean isFlexibleChecksumValidationForResponse(ExecutionAttributes executionAttributes, ChecksumSpecs checksumSpecs, ClientType clientType) { return HttpChecksumUtils.isHttpChecksumValidationEnabled(checksumSpecs) && executionAttributes.getAttribute(SdkExecutionAttribute.CLIENT_TYPE).equals(clientType) && !IS_FORCE_SKIPPED_VALIDATION.test(executionAttributes); } }
2,019
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/interceptor/DefaultFailedExecutionContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.interceptor; import java.util.Optional; import java.util.concurrent.CompletionException; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An SDK-internal implementation of {@link Context.FailedExecution}. */ @SdkInternalApi public class DefaultFailedExecutionContext implements Context.FailedExecution, ToCopyableBuilder<DefaultFailedExecutionContext.Builder, DefaultFailedExecutionContext> { private final InterceptorContext interceptorContext; private final Throwable exception; private DefaultFailedExecutionContext(Builder builder) { this.exception = unwrap(Validate.paramNotNull(builder.exception, "exception")); this.interceptorContext = Validate.paramNotNull(builder.interceptorContext, "interceptorContext"); } private Throwable unwrap(Throwable exception) { while (exception instanceof CompletionException) { exception = exception.getCause(); } return exception; } @Override public SdkRequest request() { return interceptorContext.request(); } @Override public Optional<SdkHttpRequest> httpRequest() { return Optional.ofNullable(interceptorContext.httpRequest()); } @Override public Optional<SdkHttpResponse> httpResponse() { return Optional.ofNullable(interceptorContext.httpResponse()); } @Override public Optional<SdkResponse> response() { return Optional.ofNullable(interceptorContext.response()); } @Override public Throwable exception() { return exception; } @Override public Builder toBuilder() { return new Builder(this); } public static Builder builder() { return new Builder(); } public static final class Builder implements CopyableBuilder<Builder, DefaultFailedExecutionContext> { private InterceptorContext interceptorContext; private Throwable exception; private Builder() { } private Builder(DefaultFailedExecutionContext defaultFailedExecutionContext) { this.exception = defaultFailedExecutionContext.exception; this.interceptorContext = defaultFailedExecutionContext.interceptorContext; } public Builder exception(Throwable exception) { this.exception = exception; return this; } public Builder interceptorContext(InterceptorContext interceptorContext) { this.interceptorContext = interceptorContext; return this; } @Override public DefaultFailedExecutionContext build() { return new DefaultFailedExecutionContext(this); } } }
2,020
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/interceptor
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/interceptor/trait/RequestCompression.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.internal.interceptor.trait; import java.util.Arrays; import java.util.List; import java.util.Objects; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public final class RequestCompression { private List<String> encodings; private boolean isStreaming; private RequestCompression(Builder builder) { this.encodings = builder.encodings; this.isStreaming = builder.isStreaming; } public List<String> getEncodings() { return encodings; } public boolean isStreaming() { return isStreaming; } public static Builder builder() { return new Builder(); } public static final class Builder { private List<String> encodings; private boolean isStreaming; public Builder encodings(List<String> encodings) { this.encodings = encodings; return this; } public Builder encodings(String... encodings) { if (encodings != null) { this.encodings = Arrays.asList(encodings); } return this; } public Builder isStreaming(boolean isStreaming) { this.isStreaming = isStreaming; return this; } public RequestCompression build() { return new RequestCompression(this); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RequestCompression that = (RequestCompression) o; return isStreaming == that.isStreaming() && Objects.equals(encodings, that.getEncodings()); } @Override public int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + (isStreaming ? 1 : 0); hashCode = 31 * hashCode + Objects.hashCode(encodings); return hashCode; } }
2,021
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/waiters/Waiter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.waiters; import java.util.function.Consumer; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.internal.waiters.DefaultWaiter; /** * Waiter utility class that waits for a resource to transition to the desired state. * * @param <T> the type of the resource returned from the polling function */ @SdkPublicApi public interface Waiter<T> { /** * It returns when the resource enters into a desired state or * it is determined that the resource will never enter into the desired state. * * @param pollingFunction the polling function * @return the {@link WaiterResponse} containing either a response or an exception that has matched with the * waiter success condition */ default WaiterResponse<T> run(Supplier<T> pollingFunction) { throw new UnsupportedOperationException(); } /** * It returns when the resource enters into a desired state or * it is determined that the resource will never enter into the desired state. * * @param pollingFunction the polling function * @param overrideConfig per request override configuration * @return the {@link WaiterResponse} containing either a response or an exception that has matched with the * waiter success condition */ default WaiterResponse<T> run(Supplier<T> pollingFunction, WaiterOverrideConfiguration overrideConfig) { throw new UnsupportedOperationException(); } /** * It returns when the resource enters into a desired state or * it is determined that the resource will never enter into the desired state. * * @param pollingFunction the polling function * @param overrideConfig The consumer that will configure the per request override configuration for waiters * @return the {@link WaiterResponse} containing either a response or an exception that has matched with the * waiter success condition */ default WaiterResponse<T> run(Supplier<T> pollingFunction, Consumer<WaiterOverrideConfiguration.Builder> overrideConfig) { return run(pollingFunction, WaiterOverrideConfiguration.builder().applyMutation(overrideConfig).build()); } /** * Creates a newly initialized builder for the waiter object. * * @param responseClass the response class * @param <T> the type of the response * @return a Waiter builder */ static <T> Builder<T> builder(Class<? extends T> responseClass) { return DefaultWaiter.builder(); } /** * The Waiter Builder * @param <T> the type of the resource */ interface Builder<T> extends WaiterBuilder<T, Builder<T>> { /** * An immutable object that is created from the properties that have been set on the builder. * @return a reference to this object so that method calls can be chained together. */ Waiter<T> build(); } }
2,022
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/waiters/WaiterAcceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.waiters; import java.util.Optional; import java.util.function.Predicate; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; /** * Inspects the response or errors returned from the operation and determines whether an expected state is met and returns the * next {@link WaiterState} that the waiter should be transitioned to. */ @SdkPublicApi public interface WaiterAcceptor<T> { /** * @return the next {@link WaiterState} that the waiter should be transitioned to */ WaiterState waiterState(); /** * Check to see if the response matches with the expected state defined by this acceptor * * @param response the response to inspect * @return whether it accepts the response */ default boolean matches(T response) { return false; } /** * Check to see if the exception matches the expected state defined by this acceptor * * @param throwable the exception to inspect * @return whether it accepts the throwable */ default boolean matches(Throwable throwable) { return false; } /** * Optional message to provide pertaining to the next WaiterState * * @return the optional message */ default Optional<String> message() { return Optional.empty(); } /** * Creates a success waiter acceptor which determines if the exception should transition the waiter to success state * * @param responsePredicate the predicate of the response * @param <T> the response type * @return a {@link WaiterAcceptor} */ static <T> WaiterAcceptor<T> successOnResponseAcceptor(Predicate<T> responsePredicate) { Validate.paramNotNull(responsePredicate, "responsePredicate"); return new WaiterAcceptor<T>() { @Override public WaiterState waiterState() { return WaiterState.SUCCESS; } @Override public boolean matches(T response) { return responsePredicate.test(response); } }; } /** * Creates an error waiter acceptor which determines if the exception should transition the waiter to success state * * @param errorPredicate the {@link Throwable} predicate * @param <T> the response type * @return a {@link WaiterAcceptor} */ static <T> WaiterAcceptor<T> successOnExceptionAcceptor(Predicate<Throwable> errorPredicate) { Validate.paramNotNull(errorPredicate, "errorPredicate"); return new WaiterAcceptor<T>() { @Override public WaiterState waiterState() { return WaiterState.SUCCESS; } @Override public boolean matches(Throwable t) { return errorPredicate.test(t); } }; } /** * Creates an error waiter acceptor which determines if the exception should transition the waiter to failure state * * @param errorPredicate the {@link Throwable} predicate * @param <T> the response type * @return a {@link WaiterAcceptor} */ static <T> WaiterAcceptor<T> errorOnExceptionAcceptor(Predicate<Throwable> errorPredicate) { Validate.paramNotNull(errorPredicate, "errorPredicate"); return new WaiterAcceptor<T>() { @Override public WaiterState waiterState() { return WaiterState.FAILURE; } @Override public boolean matches(Throwable t) { return errorPredicate.test(t); } }; } /** * Creates a success waiter acceptor which determines if the exception should transition the waiter to success state * * @param responsePredicate the predicate of the response * @param <T> the response type * @return a {@link WaiterAcceptor} */ static <T> WaiterAcceptor<T> errorOnResponseAcceptor(Predicate<T> responsePredicate) { Validate.paramNotNull(responsePredicate, "responsePredicate"); return new WaiterAcceptor<T>() { @Override public WaiterState waiterState() { return WaiterState.FAILURE; } @Override public boolean matches(T response) { return responsePredicate.test(response); } }; } /** * Creates a success waiter acceptor which determines if the exception should transition the waiter to success state * * @param responsePredicate the predicate of the response * @param <T> the response type * @return a {@link WaiterAcceptor} */ static <T> WaiterAcceptor<T> errorOnResponseAcceptor(Predicate<T> responsePredicate, String message) { Validate.paramNotNull(responsePredicate, "responsePredicate"); Validate.paramNotNull(message, "message"); return new WaiterAcceptor<T>() { @Override public WaiterState waiterState() { return WaiterState.FAILURE; } @Override public boolean matches(T response) { return responsePredicate.test(response); } @Override public Optional<String> message() { return Optional.of(message); } }; } /** * Creates a retry on exception waiter acceptor which determines if the exception should transition the waiter to retry state * * @param errorPredicate the {@link Throwable} predicate * @param <T> the response type * @return a {@link WaiterAcceptor} */ static <T> WaiterAcceptor<T> retryOnExceptionAcceptor(Predicate<Throwable> errorPredicate) { Validate.paramNotNull(errorPredicate, "errorPredicate"); return new WaiterAcceptor<T>() { @Override public WaiterState waiterState() { return WaiterState.RETRY; } @Override public boolean matches(Throwable t) { return errorPredicate.test(t); } }; } /** * Creates a retry on exception waiter acceptor which determines if the exception should transition the waiter to retry state * * @param responsePredicate the {@link Throwable} predicate * @param <T> the response type * @return a {@link WaiterAcceptor} */ static <T> WaiterAcceptor<T> retryOnResponseAcceptor(Predicate<T> responsePredicate) { Validate.paramNotNull(responsePredicate, "responsePredicate"); return new WaiterAcceptor<T>() { @Override public WaiterState waiterState() { return WaiterState.RETRY; } @Override public boolean matches(T t) { return responsePredicate.test(t); } }; } }
2,023
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/waiters/WaiterState.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.waiters; import software.amazon.awssdk.annotations.SdkPublicApi; @SdkPublicApi public enum WaiterState { /** * Indicates the waiter succeeded and must no longer continue waiting. */ SUCCESS, /** * Indicates the waiter failed and must not continue waiting. */ FAILURE, /** * Indicates that the waiter encountered an expected failure case and should retry if possible. */ RETRY }
2,024
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/waiters/WaiterBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.waiters; import java.util.List; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; @SdkPublicApi public interface WaiterBuilder<T, B> { /** * Defines a list of {@link WaiterAcceptor}s to check whether an expected state has met after executing an operation. * * <p> * The SDK will iterate over the acceptors list and the first acceptor to match the result of the operation transitions * the waiter to the state specified in the acceptor. * * <p> * This completely overrides any WaiterAcceptor currently configured in the builder via * {@link #addAcceptor(WaiterAcceptor)} * * @param waiterAcceptors the waiter acceptors * @return a reference to this object so that method calls can be chained together. */ B acceptors(List<WaiterAcceptor<? super T>> waiterAcceptors); /** * Adds a {@link WaiterAcceptor} to the end of the ordered waiterAcceptors list. * * <p> * The SDK will iterate over the acceptors list and the first acceptor to match the result of the operation transitions * the waiter to the state specified in the acceptor. * * @param waiterAcceptors the waiter acceptors * @return a reference to this object so that method calls can be chained together. */ B addAcceptor(WaiterAcceptor<? super T> waiterAcceptors); /** * Defines overrides to the default SDK waiter configuration that should be used * for waiters created by this builder. * * @param overrideConfiguration the override configuration * @return a reference to this object so that method calls can be chained together. */ B overrideConfiguration(WaiterOverrideConfiguration overrideConfiguration); /** * Defines a {@link WaiterOverrideConfiguration} to use when polling a resource * * @param overrideConfiguration the polling strategy to use * @return a reference to this object so that method calls can be chained together. */ default B overrideConfiguration(Consumer<WaiterOverrideConfiguration.Builder> overrideConfiguration) { WaiterOverrideConfiguration.Builder builder = WaiterOverrideConfiguration.builder(); overrideConfiguration.accept(builder); return overrideConfiguration(builder.build()); } }
2,025
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/waiters/WaiterOverrideConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.waiters; import java.time.Duration; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Configuration values for the {@link Waiter}. All values are optional, and the default values will be used * if they are not specified. */ @SdkPublicApi public final class WaiterOverrideConfiguration implements ToCopyableBuilder<WaiterOverrideConfiguration.Builder, WaiterOverrideConfiguration> { private final Integer maxAttempts; private final BackoffStrategy backoffStrategy; private final Duration waitTimeout; public WaiterOverrideConfiguration(Builder builder) { this.maxAttempts = Validate.isPositiveOrNull(builder.maxAttempts, "maxAttempts"); this.backoffStrategy = builder.backoffStrategy; this.waitTimeout = Validate.isPositiveOrNull(builder.waitTimeout, "waitTimeout"); } public static Builder builder() { return new Builder(); } /** * @return the optional maximum number of attempts that should be used when polling the resource */ public Optional<Integer> maxAttempts() { return Optional.ofNullable(maxAttempts); } /** * @return the optional {@link BackoffStrategy} that should be used when polling the resource */ public Optional<BackoffStrategy> backoffStrategy() { return Optional.ofNullable(backoffStrategy); } /** * @return the optional amount of time to wait that should be used when polling the resource * */ public Optional<Duration> waitTimeout() { return Optional.ofNullable(waitTimeout); } @Override public Builder toBuilder() { return new Builder().maxAttempts(maxAttempts) .backoffStrategy(backoffStrategy) .waitTimeout(waitTimeout); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WaiterOverrideConfiguration that = (WaiterOverrideConfiguration) o; if (!Objects.equals(maxAttempts, that.maxAttempts)) { return false; } if (!Objects.equals(backoffStrategy, that.backoffStrategy)) { return false; } return Objects.equals(waitTimeout, that.waitTimeout); } @Override public int hashCode() { int result = maxAttempts != null ? maxAttempts.hashCode() : 0; result = 31 * result + (backoffStrategy != null ? backoffStrategy.hashCode() : 0); result = 31 * result + (waitTimeout != null ? waitTimeout.hashCode() : 0); return result; } @Override public String toString() { return ToString.builder("WaiterOverrideConfiguration") .add("maxAttempts", maxAttempts) .add("waitTimeout", waitTimeout) .add("backoffStrategy", backoffStrategy) .build(); } public static final class Builder implements CopyableBuilder<WaiterOverrideConfiguration.Builder, WaiterOverrideConfiguration> { private BackoffStrategy backoffStrategy; private Integer maxAttempts; private Duration waitTimeout; private Builder() { } /** * Define the {@link BackoffStrategy} that computes the delay before the next retry request. * * @param backoffStrategy The new backoffStrategy value. * @return This object for method chaining. */ public Builder backoffStrategy(BackoffStrategy backoffStrategy) { this.backoffStrategy = backoffStrategy; return this; } /** * Define the maximum number of attempts to try before transitioning the waiter to a failure state. * * @param maxAttempts The new maxAttempts value. * @return This object for method chaining. */ public Builder maxAttempts(Integer maxAttempts) { this.maxAttempts = maxAttempts; return this; } /** * Define the amount of time to wait for the resource to transition to the desired state before * timing out. This wait timeout doesn't have strict guarantees on how quickly a request is aborted * when the timeout is breached. The request can timeout early if it is determined that the next * retry will breach the max wait time. It's disabled by default. * * @param waitTimeout The new waitTimeout value. * @return This object for method chaining. */ public Builder waitTimeout(Duration waitTimeout) { this.waitTimeout = waitTimeout; return this; } @Override public WaiterOverrideConfiguration build() { return new WaiterOverrideConfiguration(this); } } }
2,026
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/waiters/AsyncWaiter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.waiters; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Consumer; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.internal.waiters.DefaultAsyncWaiter; /** * Waiter utility class that waits for a resource to transition to the desired state asynchronously * * @param <T> the type of the resource returned from the polling function */ @SdkPublicApi public interface AsyncWaiter<T> { /** * Runs the provided polling function. It completes successfully when the resource enters into a desired state or * exceptionally when it is determined that the resource will never enter into the desired state. * * @param asyncPollingFunction the polling function to trigger * @return A {@link CompletableFuture} containing the {@link WaiterResponse} */ default CompletableFuture<WaiterResponse<T>> runAsync(Supplier<CompletableFuture<T>> asyncPollingFunction) { throw new UnsupportedOperationException(); } /** * Runs the provided polling function. It completes successfully when the resource enters into a desired state or * exceptionally when it is determined that the resource will never enter into the desired state. * * @param asyncPollingFunction the polling function to trigger * @param overrideConfig per request override configuration * @return A {@link CompletableFuture} containing the {@link WaiterResponse} */ default CompletableFuture<WaiterResponse<T>> runAsync(Supplier<CompletableFuture<T>> asyncPollingFunction, WaiterOverrideConfiguration overrideConfig) { throw new UnsupportedOperationException(); } /** * Runs the provided polling function. It completes successfully when the resource enters into a desired state or * exceptionally when it is determined that the resource will never enter into the desired state. * * @param asyncPollingFunction the polling function to trigger * @param overrideConfig The consumer that will configure the per request override configuration for waiters * @return A {@link CompletableFuture} containing the {@link WaiterResponse} */ default CompletableFuture<WaiterResponse<T>> runAsync(Supplier<CompletableFuture<T>> asyncPollingFunction, Consumer<WaiterOverrideConfiguration.Builder> overrideConfig) { return runAsync(asyncPollingFunction, WaiterOverrideConfiguration.builder().applyMutation(overrideConfig).build()); } /** * Creates a newly initialized builder for the waiter object. * * @param responseClass the response class * @param <T> the type of the response * @return a Waiter builder */ static <T> Builder<T> builder(Class<? extends T> responseClass) { return DefaultAsyncWaiter.builder(); } /** * The Waiter Builder * @param <T> the type of the resource */ interface Builder<T> extends WaiterBuilder<T, Builder<T>> { /** * Defines the {@link ScheduledExecutorService} used to schedule async polling attempts. * * @param scheduledExecutorService the schedule executor service * @return a reference to this object so that method calls can be chained together. */ Builder<T> scheduledExecutorService(ScheduledExecutorService scheduledExecutorService); /** * An immutable object that is created from the properties that have been set on the builder. * @return a reference to this object so that method calls can be chained together. */ AsyncWaiter<T> build(); } }
2,027
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/waiters/WaiterResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.waiters; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.internal.waiters.ResponseOrException; /** * The response returned from a waiter operation * @param <T> the type of the response */ @SdkPublicApi public interface WaiterResponse<T> { /** * @return the ResponseOrException union received that has matched with the waiter success condition */ ResponseOrException<T> matched(); /** * @return the number of attempts executed */ int attemptsExecuted(); }
2,028
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/adapter/TypeAdapter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.adapter; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Adapter interface to convert one type to another * * @param <SourceT> * Source type * @param <DestinationT> * Destination type */ @SdkProtectedApi public interface TypeAdapter<SourceT, DestinationT> { DestinationT adapt(SourceT source); }
2,029
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/adapter/StandardMemberCopier.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.adapter; import java.io.InputStream; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.time.Instant; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.utils.BinaryUtils; /** * Used in combination with the generated member copiers to implement deep * copies of shape members. */ @SdkProtectedApi public final class StandardMemberCopier { private StandardMemberCopier() { } public static String copy(String s) { return s; } public static Short copy(Short s) { return s; } public static Integer copy(Integer i) { return i; } public static Long copy(Long l) { return l; } public static Float copy(Float f) { return f; } public static Double copy(Double d) { return d; } public static BigDecimal copy(BigDecimal bd) { return bd; } public static Boolean copy(Boolean b) { return b; } public static InputStream copy(InputStream is) { return is; } public static Instant copy(Instant i) { return i; } public static SdkBytes copy(SdkBytes bytes) { return bytes; } public static ByteBuffer copy(ByteBuffer bb) { if (bb == null) { return null; } return ByteBuffer.wrap(BinaryUtils.copyBytesFrom(bb)).asReadOnlyBuffer(); } }
2,030
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document/DocumentVisitor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.document; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkNumber; /** * Document visitor interface. * * @param <R> Return type of the visitor. */ @SdkPublicApi public interface DocumentVisitor<R> { /** * Visits a Document Null. * * @return value of the visitor */ R visitNull(); /** * Visits a Boolean Document. * * @param document Document to visit, * @return Return value of the visitor. */ R visitBoolean(Boolean document); /** * Visits a String Document. * * @param document Document to visit, * @return Return value of the visitor. */ R visitString(String document); /** * Visits a Number Document. * * @param document Document to visit, * @return Return value of the visitor. */ R visitNumber(SdkNumber document); /** * Visits a Map Document. * * @param documentMap Document to visit, * @return Return value of the visitor. */ R visitMap(Map<String, Document> documentMap); /** * Visits a List Document. * * @param documentList Document to visit, * @return Return value of the visitor. */ R visitList(List<Document> documentList); }
2,031
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document/Document.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.document; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.text.ParseException; import java.util.List; import java.util.Map; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.core.document.internal.BooleanDocument; import software.amazon.awssdk.core.document.internal.ListDocument; import software.amazon.awssdk.core.document.internal.MapDocument; import software.amazon.awssdk.core.document.internal.NullDocument; import software.amazon.awssdk.core.document.internal.NumberDocument; import software.amazon.awssdk.core.document.internal.StringDocument; /** * Interface for Document Types. * Document types are used to carry open content that is Data with no fixed schema, data that can't be modeled using rigid types, * or data that has a schema that evolves outside the purview of a service * without requiring techniques like embedding JSON inside JSON strings. * Document type value is serialized using the same format as its surroundings and requires no additional encoding or escaping. * This interface specifies all the methods to access a Document, also provides constructor methods for * instantiating Document. * */ @SdkPublicApi @Immutable public interface Document extends Serializable { /** * Create {@link Document} from a string, using the provided String. * @param string String value. * @return Implementation of Document that stores a String. */ static Document fromString(String string) { return new StringDocument(string); } /** * Create {@link Document} from a boolean. * @param booleanValue Boolean value. * @return Implementation of Document that stores a Boolean. */ static Document fromBoolean(boolean booleanValue) { return new BooleanDocument(booleanValue); } /** * Create {@link Document} from a {@link SdkNumber}. * @param number {@link SdkNumber} sdkNumber with the given precision type. * @return Implementation of Document that stores a {@link SdkNumber}. */ static Document fromNumber(SdkNumber number) { return new NumberDocument(number); } /** * Create {@link Document} from a int. * @param number int type number. * @return Implementation of Document that stores a {@link SdkNumber} constructed {@link SdkNumber#fromInteger(int)}. */ static Document fromNumber(int number) { return new NumberDocument(SdkNumber.fromInteger(number)); } /** * Create {@link Document} from a long. * @param number long type number. * @return Implementation of Document that stores a {@link SdkNumber} constructed {@link SdkNumber#longValue()}. */ static Document fromNumber(long number) { return new NumberDocument(SdkNumber.fromLong(number)); } /** * Create {@link Document} from a float. * @param number float type number. * @return Implementation of Document that stores a {@link SdkNumber} constructed {@link SdkNumber#floatValue()} */ static Document fromNumber(float number) { return new NumberDocument(SdkNumber.fromFloat(number)); } /** * Create {@link Document} from a double. * @param number double type number. * @return Implementation of Document that stores a {@link SdkNumber} constructed {@link SdkNumber#fromDouble(double)} */ static Document fromNumber(double number) { return new NumberDocument(SdkNumber.fromDouble(number)); } /** * Create {@link Document} from a BigDecimal. * @param number BigDecimal type number. * @return Implementation of Document that stores a {@link SdkNumber} constructed {@link SdkNumber#fromBigDecimal(BigDecimal)} */ static Document fromNumber(BigDecimal number) { return new NumberDocument(SdkNumber.fromBigDecimal(number)); } /** * Create {@link Document} from a BigInteger. * @param number BigInteger type number. * @return Implementation of Document that stores a {@link SdkNumber} constructed {@link SdkNumber#fromBigInteger(BigInteger)} */ static Document fromNumber(BigInteger number) { return new NumberDocument(SdkNumber.fromBigInteger(number)); } /** * Create {@link Document} from a String. * @param number String representation of a number. * @return Implementation of Document that stores a {@link SdkNumber} constructed {@link SdkNumber#fromString(String)} * @throws ParseException Throws ParseException when the inputString is not of Number format. */ static Document fromNumber(String number) { return new NumberDocument(SdkNumber.fromString(number)); } /** * Creates a Document from a Map of Documents. * @param documentMap Map with Keys of Type Strinb and Value of Document type. * @return Implementation of Document that stores a Map with String Keys and Document Values. */ static Document fromMap(Map<String, Document> documentMap) { return new MapDocument(documentMap); } /** * Create a {@link ListBuilder} for generating a {@link Document} by directly allowing user add Documents. * @param documentList List of Documents. * @return Implementation of Document that stores a Lists of Documents. */ static Document fromList(List<Document> documentList) { return new ListDocument(documentList); } /** * Create a {@link MapBuilder} for generating a {@link Document} by directly allowing user to put String Keys * and Document Values in the builder methods. * @return Builder to Construct Document with Map of Documents. */ static MapBuilder mapBuilder() { return MapDocument.mapBuilder(); } /** * Provides Builder methods of {@link ListBuilder} to directly create Document with List of Documents * @return Builder methods to Construct Document with List of Documents. */ static ListBuilder listBuilder() { return ListDocument.listBuilder(); } /** * Creates a document is a {@code null} value. * * @return Implementation of a Null Document. */ static Document fromNull() { return new NullDocument(); } /** * Gets the value of the document as a Java type that represents the * document type data model: {@code boolean}, {@code String} for Strings and Numbers, * {@code null}, {@code List<Object>}, or * {@code Map<String, Object>}. * @return Returns the document as one of a fixed set of Java types. */ Object unwrap(); /** * Checks if the document is a {@code null} value. * @return Returns true if the document is a {@code null} value. */ default boolean isNull() { return false; } /** * @return Returns true if this document is a boolean value. */ default boolean isBoolean() { return false; } /** * Gets the document as a {@code boolean} if it is a boolean. * @return Returns the boolean value. * @throws UnsupportedOperationException if the document is not a boolean. */ boolean asBoolean(); /** * @return Returns true if this document is a string value. */ default boolean isString() { return false; } /** * Gets the document as a {@code String}. * * @return Returns the string value. * @throws UnsupportedOperationException if the document is not a string. */ String asString(); /** * @return Returns true if this document is a number value. */ default boolean isNumber() { return false; } /** * Gets the document as a {@link SdkNumber} if it is a {@link SdkNumber}. * @return Returns the {@link SdkNumber}. * @throws UnsupportedOperationException if the document is not a number. */ SdkNumber asNumber(); /** * @return Returns true if this document is a Map. */ default boolean isMap() { return false; } /** * Gets the document as a {@code Map}. * <p>Each value contained in the {@code Map} is the same as how the value * would be represented by {@link Document}. * @return Returns the Document map. * @throws UnsupportedOperationException if the document is not an Map. */ Map<String, Document> asMap(); /** * @return Returns true if this document is a document type List. */ default boolean isList() { return false; } /** * Gets the document as a {@code List} if it is a document type array. * <p>Each value contained in the {@code List} is the same as how the * value would be represented by {@link Document}. * * @return Returns the lists of Document. * @throws UnsupportedOperationException if the document is not an List. */ List<Document> asList(); /** * Accepts a visitor to the Document. * @param <R> visitor return type. * @param visitor Visitor to dispatch to. * @return Returns the accepted result. */ <R> R accept(DocumentVisitor<? extends R> visitor); /** * Accepts a visitor with the Document. * @param visitor Visitor to dispatch to. */ void accept(VoidDocumentVisitor visitor); interface MapBuilder { /** * Inserts a Key Value pair to a Document Map with String key and a Document created from the given String. * @param key Map Key for the Document. * @param stringValue String value which will be used to create a Document to be inserted in a DocumentMap. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putString(String key, String stringValue); /** * Inserts a Key Value pair to a Document Map with String key and a Document created from the given Number. * @param key Map Key for the Document. * @param numberValue Number value which will be used to create a Document to be inserted in a DocumentMap. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putNumber(String key, SdkNumber numberValue); /** * Inserts a Key Value pair to a Document Map with String key and a Document created from the given integer. * @param key Map Key for the Document. * @param numberValue Integer value which will be used to create a Document to be inserted in a DocumentMap. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putNumber(String key, int numberValue); /** * Inserts a Key Value pair to a Document Map with String key and a Document created from the given long. * @param key Map Key for the Document. * @param numberValue long value which will be used to create a Document to be inserted in a DocumentMap. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putNumber(String key, long numberValue); /** * Inserts a Key Value pair to a Document Map with String key and a Document created from the given double. * @param key Map Key for the Document. * @param numberValue double value which will be used to create a Document to be inserted in a DocumentMap. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putNumber(String key, double numberValue); /** * Inserts a Key Value pair to a Document Map with String key and a Document created from the given float. * @param key Map Key for the Document. * @param numberValue float value which will be used to create a Document to be inserted in a DocumentMap. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putNumber(String key, float numberValue); /** * Inserts a Key Value pair to a Document Map with String key and a Document created from the given BigDecimal. * @param key Map Key for the Document. * @param numberValue BigDecimal value which will be used to create a Document to be inserted in a DocumentMap. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putNumber(String key, BigDecimal numberValue); /** * Inserts a Key Value pair to a Document Map with String key and a Document created from the given BigInteger. * @param key Map Key for the Document. * @param numberValue BigInteger value which will be used to create a Document to be inserted in a DocumentMap. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putNumber(String key, BigInteger numberValue); /** * * Inserts a Key Value pair to a Document Map with String key and a Document created from the given String. * @param key Map Key for the Document. * @param numberValue String value which will be used to create a Document to be inserted in a DocumentMap. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putNumber(String key, String numberValue); /** * Inserts a Key Value pair to a Document Map with String key and a Document created from the given boolean. * @param key Map Key for the Document. * @param booleanValue Boolean value which will be used to create a Document to be inserted in a DocumentMap. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putBoolean(String key, boolean booleanValue); /** * Inserts a Key Value pair to a Document Map with String key and the given Document. * @param key Map Key for the Document. * @param document Document to be inserted in a DocumentMap. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putDocument(String key, Document document); /** * Inserts a Key Value pair to a Document Map with String key and value with Null Document. * @param key Map Key for the Document. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putNull(String key); /** * Inserts a Key Value pair to a Document Map with String key and value as List of Document. * @param key Map Key for the Document. * @param documentList List of Documents. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putList(String key, List<Document> documentList); /** * Inserts a Key Value pair to a Document Map with String key and value constructed from Consumer of * {@link ListBuilder}. * @param key Map Key for the Document. * @param listBuilderConsumer Consumer that accepts {@link ListBuilder} * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putList(String key, Consumer<ListBuilder> listBuilderConsumer); /** * Inserts a Key Value pair to a Document Map with String key and Document constructed from Document Map. * @param key Map Key for the Document. * @param documentMap Map of Document. * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putMap(String key, Map<String, Document> documentMap); /** * Inserts a Key Value pair to a Document Map with String key and value constructed from Consumer of * {@link MapBuilder}. * @param key Map Key for the Document. * @param mapBuilderConsumer Consumer that accepts {@link ListBuilder} * @return Builder which provides APIs to put Key Value pair to a Document Map. */ MapBuilder putMap(String key, Consumer<MapBuilder> mapBuilderConsumer); /** * Creates a new {@link Document} with the key value pair pair inserted using put method. * @return The new {@link Document}. */ Document build(); } interface ListBuilder { /** * Adds a Document which is constructed from the given stringValue.. * @param stringValue String Value from which the Document to be added is created. * @return Builder which provides APIs to add Document to a Document List. */ ListBuilder addString(String stringValue); /** * Adds a Document which is constructed from the given boolean. * @param booleanValue Boolean value from which the Document to be added is created. * @return Builder which provides APIs to add Document to a Document List. */ ListBuilder addBoolean(boolean booleanValue); /** * Adds a Document which is constructed from the given {@link SdkNumber}. * @param numberValue {@link SdkNumber} from which the Document to be added is created. * @return Builder which provides APIs to add Document to a Document List. */ ListBuilder addNumber(SdkNumber numberValue); /** * Adds a Document which is constructed from the given integer. * @param numberValue integer from which the Document to be added is created. * @return Builder which provides APIs to add Document to a Document List. */ ListBuilder addNumber(int numberValue); /** * Adds a Document which is constructed from the given long. * @param numberValue long from which the Document to be added is created. * @return Builder which provides APIs to add Document to a Document List. */ ListBuilder addNumber(long numberValue); /** * Adds a Document which is constructed from the given float. * @param numberValue float from which the Document to be added is created. * @return Builder which provides APIs to add Document to a Document List. */ ListBuilder addNumber(float numberValue); /** * Adds a Document which is constructed from the given double. * @param numberValue double from which the Document to be added is created. * @return Builder which provides APIs to add Document to a Document List. */ ListBuilder addNumber(double numberValue); /** * Adds a Document which is constructed from the given BigDecimal. * @param numberValue BigDecimal from which the Document to be added is created. * @return Builder which provides APIs to add Document to a Document List. */ ListBuilder addNumber(BigDecimal numberValue); /** * Adds a Document which is constructed from the given BigInteger. * @param numberValue BigInteger from which the Document to be added is created. * @return Builder which provides APIs to add Document to a Document List. */ ListBuilder addNumber(BigInteger numberValue); /** * * Adds a Document which is constructed from the given String. * @param numberValue String from which the Document to be added is created. * @return Builder which provides APIs to add Document to a Document List. */ ListBuilder addNumber(String numberValue); /** * Adds a Document to the constructed Document List. * @param document Document that will be added to a Document List. * @return Builder which provides APIs to add Document to a Document List. */ ListBuilder addDocument(Document document); /** * Inserts a Document Value constructed from Consumer of {@link MapBuilder}. * @param mapBuilderConsumer Consumer that accepts {@link ListBuilder} * @return Builder which provides APIs to put Key Value pair to a Document Map. */ ListBuilder addMap(Consumer<MapBuilder> mapBuilderConsumer); /** * Inserts a Null Document to the constructed Document List. * @return Builder which provides APIs to add Document to a Document List. */ ListBuilder addNull(); /** * Creates a new {@link Document} with the List members as added with add method. * @return The new {@link Document}. */ Document build(); } }
2,032
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document/VoidDocumentVisitor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.document; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkNumber; /** * Document visitor interface with no return type. * */ @SdkPublicApi public interface VoidDocumentVisitor { /** * Visits a Document Null. */ default void visitNull() { } /** * Visits a Boolean Document. * @param document Document to visit, */ default void visitBoolean(Boolean document) { } /** * Visits a String Document. * @param document Document to visit, */ default void visitString(String document) { } /** * Visits a Number Document. * @param document Document to visit, */ default void visitNumber(SdkNumber document) { } /** * Visits a Map Document. * @param documentMap Document to visit, */ default void visitMap(Map<String, Document> documentMap) { } /** * Visits a List Document. * @param documentList Document to visit, */ default void visitList(List<Document> documentList) { } }
2,033
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document/internal/ListDocument.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.document.internal; import static java.util.stream.Collectors.toList; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.core.document.DocumentVisitor; import software.amazon.awssdk.core.document.VoidDocumentVisitor; import software.amazon.awssdk.utils.Validate; @SdkInternalApi @Immutable public final class ListDocument implements Document { private static final long serialVersionUID = 1L; private final List<Document> value; /** * Create a New {@link ListDocument} with List of Document documentList as passed in constructor * @param documentList ListDocument documentList. */ public ListDocument(List<Document> documentList) { Validate.notNull(documentList, "List documentList cannot be null"); this.value = Collections.unmodifiableList(documentList); } /** * Provides Builder methods of {@link ListBuilderInternal} to directly create Document with List of Documents * @return Builder methods to Construct Document with List of Documents. */ public static ListBuilder listBuilder() { return new ListBuilderInternal(); } /** * Gets the value of the document as a Java type that represents the * Loops through the individual Document and unwraps each of the document. * @return Returns the {@code List<Object>}. */ @Override public Object unwrap() { return value.stream().map(Document::unwrap).collect(toList()); } /** * {@inheritdoc} */ @Override public boolean asBoolean() { throw new UnsupportedOperationException("A Document List cannot be converted to a Boolean."); } /** * {@inheritdoc} */ @Override public String asString() { throw new UnsupportedOperationException("A Document List cannot be converted to a String."); } /** * {@inheritdoc} */ @Override public SdkNumber asNumber() { throw new UnsupportedOperationException("A Document List cannot be converted to a Number."); } /** * {@inheritdoc} */ @Override public Map<String, Document> asMap() { throw new UnsupportedOperationException("A Document List cannot be converted to a Map."); } /** * @return true, since this is a Document List. */ @Override public boolean isList() { return true; } /** * * @return unmodifiableList of the List of Documents in the {{@link ListDocument}}. */ @Override public List<Document> asList() { return value; } /** * Accepts a visitor with the Document. * @param <R> visitor return type. * @param visitor Visitor to dispatch to. * @return Returns the accepted result by calling visitList of visitor. */ @Override public <R> R accept(DocumentVisitor<? extends R> visitor) { return visitor.visitList(this.asList()); } /** * Accepts a visitor with the Document. Calls visitList of visitor. * @param visitor Visitor to dispatch to. */ @Override public void accept(VoidDocumentVisitor visitor) { visitor.visitList(Collections.unmodifiableList(this.asList())); } @Override public String toString() { return value.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ListDocument)) { return false; } ListDocument that = (ListDocument) o; return Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hashCode(value); } /** * Internal List Builder for easy construction of Document Lists. */ public static class ListBuilderInternal implements ListBuilder { private final List<Document> documentList = new ArrayList<>(); /** * {@inheritdoc} */ @Override public ListBuilder addString(String stringValue) { documentList.add(Document.fromString(stringValue)); return this; } /** * {@inheritdoc} */ @Override public ListBuilder addBoolean(boolean booleanValue) { documentList.add(Document.fromBoolean(booleanValue)); return this; } /** * {@inheritdoc} */ @Override public ListBuilder addNumber(SdkNumber numberValue) { documentList.add(Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public ListBuilder addNumber(int numberValue) { documentList.add(Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public ListBuilder addNumber(long numberValue) { documentList.add(Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public ListBuilder addNumber(float numberValue) { documentList.add(Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public ListBuilder addNumber(double numberValue) { documentList.add(Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public ListBuilder addNumber(BigDecimal numberValue) { documentList.add(Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public ListBuilder addNumber(BigInteger numberValue) { documentList.add(Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public ListBuilder addNumber(String numberValue) { documentList.add(Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public ListBuilder addDocument(Document document) { documentList.add(document); return this; } /** * {@inheritdoc} */ @Override public ListBuilder addMap(Consumer<MapBuilder> mapBuilderConsumer) { MapBuilder mapBuilder = MapDocument.mapBuilder(); mapBuilderConsumer.accept(mapBuilder); documentList.add(mapBuilder.build()); return this; } /** * {@inheritdoc} */ @Override public ListBuilder addNull() { documentList.add(Document.fromNull()); return this; } /** * {@inheritdoc} */ @Override public Document build() { return new ListDocument(documentList); } } }
2,034
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document/internal/NullDocument.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.document.internal; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.core.document.DocumentVisitor; import software.amazon.awssdk.core.document.VoidDocumentVisitor; @SdkInternalApi @Immutable public final class NullDocument implements Document { private static final long serialVersionUID = 1L; /** * Unwraps NullDocument as null. * @return null */ @Override public Object unwrap() { return null; } /** * {@inheritdoc} */ @Override public boolean asBoolean() { throw new UnsupportedOperationException("A Document Null cannot be converted to a Boolean."); } /** * {@inheritdoc} */ @Override public String asString() { throw new UnsupportedOperationException("A Document Null cannot be converted to a String."); } /** * {@inheritdoc} */ @Override public SdkNumber asNumber() { throw new UnsupportedOperationException("A Document Null cannot be converted to a Number."); } /** * {@inheritdoc} */ @Override public Map<String, Document> asMap() { throw new UnsupportedOperationException("A Document Null cannot be converted to a Map."); } /** * @return true ,since this is a Document Null. */ @Override public boolean isNull() { return true; } /** * {@inheritdoc} */ @Override public List<Document> asList() { throw new UnsupportedOperationException("A Document Null cannot be converted to a List."); } /** * Accepts a visitor with the Document. * @param <R> visitor return type. * @param visitor Visitor to dispatch to. * @return Returns the accepted result by calling visitNull of visitor. */ @Override public <R> R accept(DocumentVisitor<? extends R> visitor) { return visitor.visitNull(); } /** * Accepts a visitor with the Document. Calls visitNull of visitor. * @param visitor Visitor to dispatch to. */ @Override public void accept(VoidDocumentVisitor visitor) { visitor.visitNull(); } @Override public String toString() { return "null"; } @Override public int hashCode() { return 0; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof NullDocument)) { return false; } NullDocument that = (NullDocument) obj; return that.isNull() == this.isNull(); } }
2,035
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document/internal/BooleanDocument.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.document.internal; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.core.document.DocumentVisitor; import software.amazon.awssdk.core.document.VoidDocumentVisitor; /** * Represents a Boolean Document. */ @SdkInternalApi @Immutable public final class BooleanDocument implements Document { private static final long serialVersionUID = 1L; private final boolean value; /** * Create a New {@link BooleanDocument} with boolean value as passed in constructor * @param value boolean value. */ public BooleanDocument(boolean value) { this.value = value; } /** * Unwraps the Document Boolean to a Boolean Object. * @return boolean value. */ @Override public Object unwrap() { return value; } /** * Indicates this is a Boolean Document. * @return true since this is a Boolean Document. */ @Override public boolean isBoolean() { return true; } /** * Gets the boolean value of the Document. * @return boolean value. */ @Override public boolean asBoolean() { return value; } /** * {@inheritdoc} */ @Override public String asString() { throw new UnsupportedOperationException("A Document Boolean cannot be converted to a String."); } /** * {@inheritdoc} */ @Override public SdkNumber asNumber() { throw new UnsupportedOperationException("A Document Boolean cannot be converted to a Number."); } /** * {@inheritdoc} */ @Override public Map<String, Document> asMap() { throw new UnsupportedOperationException("A Document Boolean cannot be converted to a Map."); } /** * {@inheritdoc} */ @Override public List<Document> asList() { throw new UnsupportedOperationException("A Document Boolean cannot be converted to a List."); } /** * Accepts a visitor with the Document. * @param <R> visitor return type. * @param visitor Visitor to dispatch to. * @return Returns the accepted result by calling visitBoolean of visitor. */ @Override public <R> R accept(DocumentVisitor<? extends R> visitor) { return visitor.visitBoolean(asBoolean()); } /** * Accepts a visitor with the Document. Calls visitBoolean of visitor. * @param visitor Visitor to dispatch to. */ @Override public void accept(VoidDocumentVisitor visitor) { visitor.visitBoolean(asBoolean()); } @Override public String toString() { return Boolean.toString(value); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BooleanDocument)) { return false; } BooleanDocument that = (BooleanDocument) o; return value == that.value; } @Override public int hashCode() { return Boolean.hashCode(value); } }
2,036
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document/internal/MapDocument.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.document.internal; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.core.document.DocumentVisitor; import software.amazon.awssdk.core.document.VoidDocumentVisitor; import software.amazon.awssdk.utils.Validate; @SdkInternalApi @Immutable public final class MapDocument implements Document { private static final long serialVersionUID = 1L; private final Map<String, Document> value; /** * Create a New {@link MapDocument} with Map of Document value as passed in constructor * @param documentMap ListDocument documentList. */ public MapDocument(Map<String, Document> documentMap) { Validate.notNull(documentMap, "Map cannot be null"); this.value = Collections.unmodifiableMap(documentMap); } /** * Create a {@link MapBuilderInternal} for generating a * {@link Document} by directly allowing user to put String Keys * and Document Values in the builder methods. * @return Builder to Construct Document with Map of Documents. */ public static MapBuilder mapBuilder() { return new MapBuilderInternal(); } /** * Gets the value of the document as a Java type that represents the * Loops through the individual Map Entries and unwarap each of the Document Value. * @return Returns the Map with Keys as String and Values as {@code Map<Object>}. */ @Override public Object unwrap() { Map<String, Object> unwrappedMap = new LinkedHashMap<>(); value.entrySet().forEach(mapEntry -> unwrappedMap.put(mapEntry.getKey(), mapEntry.getValue().unwrap())); return Collections.unmodifiableMap(unwrappedMap); } /** * @return UnsupportedOperationException */ @Override public boolean asBoolean() { throw new UnsupportedOperationException("A Document Map cannot be converted to a Boolean."); } /** * @return UnsupportedOperationException */ @Override public String asString() { throw new UnsupportedOperationException("A Document Map cannot be converted to a String."); } /** * @return UnsupportedOperationException */ @Override public SdkNumber asNumber() { throw new UnsupportedOperationException("A Document Map cannot be converted to a Number."); } /** * @return UnsupportedOperationException */ @Override public boolean isMap() { return true; } /** * * @return unmodifiableMap of the Map of Documents in the {{@link MapDocument}}. */ @Override public Map<String, Document> asMap() { return value; } /** * @return UnsupportedOperationException */ @Override public List<Document> asList() { throw new UnsupportedOperationException("A Document Map cannot be converted to a List."); } /** * Accepts a visitor with the Document. * @param <R> visitor return type. * @param visitor Visitor to dispatch to. * @return Returns the accepted result by calling visitMap of visitor. */ @Override public <R> R accept(DocumentVisitor<? extends R> visitor) { return visitor.visitMap(Collections.unmodifiableMap(this.asMap())); } /** * Accepts a visitor with the Document. Calls visitMap of visitor. * @param visitor Visitor to dispatch to. */ @Override public void accept(VoidDocumentVisitor visitor) { visitor.visitMap(this.asMap()); } public static class MapBuilderInternal implements MapBuilder { private final Map<String, Document> documentMap = new LinkedHashMap<>(); /** * {@inheritdoc} */ @Override public MapBuilder putString(String key, String stringValue) { documentMap.put(key, Document.fromString(stringValue)); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putNumber(String key, SdkNumber numberValue) { documentMap.put(key, Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putNumber(String key, int numberValue) { documentMap.put(key, Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putNumber(String key, long numberValue) { documentMap.put(key, Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putNumber(String key, double numberValue) { documentMap.put(key, Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putNumber(String key, float numberValue) { documentMap.put(key, Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putNumber(String key, BigDecimal numberValue) { documentMap.put(key, Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putNumber(String key, BigInteger numberValue) { documentMap.put(key, Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putNumber(String key, String numberValue) { documentMap.put(key, Document.fromNumber(numberValue)); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putBoolean(String key, boolean booleanValue) { documentMap.put(key, Document.fromBoolean(booleanValue)); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putDocument(String key, Document document) { Validate.notNull(document, "Document cannot be null"); documentMap.put(key, document); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putNull(String key) { documentMap.put(key, Document.fromNull()); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putList(String key, List<Document> documentList) { documentMap.put(key, Document.fromList(documentList)); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putList(String key, Consumer<ListBuilder> listBuilderConsumer) { ListBuilder listBuilder = ListDocument.listBuilder(); listBuilderConsumer.accept(listBuilder); documentMap.put(key, listBuilder.build()); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putMap(String key, Map<String, Document> documentMap) { Validate.notNull(documentMap, "documentMap cannot be null"); this.documentMap.put(key, Document.fromMap(documentMap)); return this; } /** * {@inheritdoc} */ @Override public MapBuilder putMap(String key, Consumer<MapBuilder> mapBuilderConsumer) { MapBuilder mapBuilder = MapDocument.mapBuilder(); mapBuilderConsumer.accept(mapBuilder); this.documentMap.put(key, mapBuilder.build()); return this; } /** * {@inheritdoc} */ @Override public Document build() { return new MapDocument(documentMap); } } @Override public String toString() { if (value.isEmpty()) { return "{}"; } StringBuilder output = new StringBuilder(); output.append("{"); value.forEach((k, v) -> output.append("\"").append(k).append("\": ") .append(v.toString()).append(",")); output.setCharAt(output.length() - 1, '}'); return output.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof MapDocument)) { return false; } MapDocument that = (MapDocument) o; return Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hashCode(value); } }
2,037
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document/internal/StringDocument.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.document.internal; import java.util.List; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.core.document.DocumentVisitor; import software.amazon.awssdk.core.document.VoidDocumentVisitor; import software.amazon.awssdk.utils.Validate; @SdkInternalApi @Immutable public final class StringDocument implements Document { private static final long serialVersionUID = 1L; private final String value; /** * Create a New {@link StringDocument} with boolean value as passed in constructor * @param string boolean value. */ public StringDocument(String string) { Validate.notNull(string, "String cannot be null"); this.value = string; } /** * Unwraps the Document Boolean to a String Object. * @return string value. */ @Override public Object unwrap() { return value; } /** * {@inheritdoc} */ @Override public boolean asBoolean() { throw new UnsupportedOperationException("A Document String cannot be converted to a Boolean."); } /** * @return true, since this is a Document String. */ @Override public boolean isString() { return true; } /** * Gets the String value of the Document. * @return string value. */ @Override public String asString() { return value; } /** * @return true, since this is a Document String. */ @Override public SdkNumber asNumber() { throw new UnsupportedOperationException("A Document String cannot be converted to a Number."); } /** * @return true, since this is a Document String. */ @Override public Map<String, Document> asMap() { throw new UnsupportedOperationException("A Document String cannot be converted to a Map."); } /** * @return true, since this is a Document String. */ @Override public List<Document> asList() { throw new UnsupportedOperationException("A Document String cannot be converted to a List."); } /** * Accepts a visitor with the Document. * @param <R> visitor return type. * @param visitor Visitor to dispatch to. * @return Returns the accepted result by calling visitString of visitor. */ @Override public <R> R accept(DocumentVisitor<? extends R> visitor) { return visitor.visitString(asString()); } /** * Accepts a visitor with the Document. Calls visitString of visitor. * @param visitor Visitor to dispatch to. */ @Override public void accept(VoidDocumentVisitor visitor) { visitor.visitString(asString()); } @Override public String toString() { // Does not handle unicode control characters return "\"" + value.replace("\\", "\\\\") .replace("\"", "\\\"") + "\""; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof StringDocument)) { return false; } StringDocument that = (StringDocument) o; return Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hashCode(value); } }
2,038
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/document/internal/NumberDocument.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.document.internal; import java.util.List; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.core.document.DocumentVisitor; import software.amazon.awssdk.core.document.VoidDocumentVisitor; import software.amazon.awssdk.utils.Validate; @SdkInternalApi @Immutable public class NumberDocument implements Document { private static final long serialVersionUID = 1L; private final SdkNumber number; /** * Created a {{@link NumberDocument}} with the specified {{@link SdkNumber}}. * {{@link SdkNumber}} is provided as an input to NumberDocument to maintain arbitrary precision of any given number. * @param number */ public NumberDocument(SdkNumber number) { Validate.notNull(number, "Number cannot be null."); this.number = number; } /** * Unwraps the Document Number to string value of the {{@link SdkNumber}}. * @return {{@link SdkNumber}} value. */ @Override public Object unwrap() { return number.stringValue(); } /** * {@inheritdoc} */ @Override public boolean asBoolean() { throw new UnsupportedOperationException("A Document Number cannot be converted to a Boolean."); } /** * {@inheritdoc} */ @Override public String asString() { throw new UnsupportedOperationException("A Document Number cannot be converted to a String."); } /** * {@inheritdoc} */ @Override public boolean isNumber() { return true; } /** * Returned as {{@link SdkNumber}}. * The number value can be extracted from the Document by using below methods * @see SdkNumber#intValue() * @see SdkNumber#longValue() () * @see SdkNumber#floatValue() () * @see SdkNumber#shortValue() () * @see SdkNumber#bigDecimalValue() () * @see SdkNumber#stringValue() * @see SdkNumber#floatValue() () * @see SdkNumber#doubleValue() () () * @return {{@link SdkNumber}} value. */ @Override public SdkNumber asNumber() { return number; } @Override public Map<String, Document> asMap() { throw new UnsupportedOperationException("A Document Number cannot be converted to a Map."); } /** * {@inheritdoc} */ @Override public List<Document> asList() { throw new UnsupportedOperationException("A Document Number cannot be converted to a List."); } /** * Accepts a visitor with the Document. * @param <R> visitor return type. * @param visitor Visitor to dispatch to. * @return Returns the accepted result by calling visitNumber of visitor. */ @Override public <R> R accept(DocumentVisitor<? extends R> visitor) { return visitor.visitNumber(this.asNumber()); } /** * Accepts a visitor with the Document. Calls visitNumber of visitor. * @param visitor Visitor to dispatch to. */ @Override public void accept(VoidDocumentVisitor visitor) { visitor.visitNumber(this.asNumber()); } @Override public String toString() { return String.valueOf(number); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof NumberDocument)) { return false; } NumberDocument that = (NumberDocument) o; return Objects.equals(number, that.number); } @Override public int hashCode() { return Objects.hashCode(number); } }
2,039
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/protocol/VoidSdkResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.protocol; import java.util.Collections; import java.util.List; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Dummy implementation of {@link SdkResponse}. */ @SdkProtectedApi public final class VoidSdkResponse extends SdkResponse { private static final List<SdkField<?>> SDK_FIELDS = Collections.unmodifiableList(Collections.emptyList()); private VoidSdkResponse(Builder builder) { super(builder); } @Override public Builder toBuilder() { return builder(); } public static Builder builder() { return new Builder(); } @Override public List<SdkField<?>> sdkFields() { return SDK_FIELDS; } public static final class Builder extends BuilderImpl implements SdkPojo, SdkBuilder<Builder, SdkResponse> { private Builder() { } @Override public SdkResponse build() { return new VoidSdkResponse(this); } @Override public List<SdkField<?>> sdkFields() { return SDK_FIELDS; } } }
2,040
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/protocol/MarshallingType.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.protocol; import java.math.BigDecimal; import java.time.Instant; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.document.Document; /** * Represents the various types supported for marshalling. * * @param <T> Java type bound to the marshalling type. */ @SdkProtectedApi public interface MarshallingType<T> { /** * Used when a value is null (and thus type can't be determined). */ MarshallingType<Void> NULL = newType(Void.class); MarshallingType<String> STRING = newType(String.class); MarshallingType<Integer> INTEGER = newType(Integer.class); MarshallingType<Long> LONG = newType(Long.class); MarshallingType<Float> FLOAT = newType(Float.class); MarshallingType<Double> DOUBLE = newType(Double.class); MarshallingType<BigDecimal> BIG_DECIMAL = newType(BigDecimal.class); MarshallingType<Boolean> BOOLEAN = newType(Boolean.class); MarshallingType<Instant> INSTANT = newType(Instant.class); MarshallingType<SdkBytes> SDK_BYTES = newType(SdkBytes.class); MarshallingType<SdkPojo> SDK_POJO = newType(SdkPojo.class); MarshallingType<List<?>> LIST = newType(List.class); MarshallingType<Map<String, ?>> MAP = newType(Map.class); MarshallingType<Short> SHORT = newType(Short.class); MarshallingType<Document> DOCUMENT = newType(Document.class); Class<? super T> getTargetClass(); static <T> MarshallingType<T> newType(Class<? super T> clzz) { return new MarshallingType<T>() { @Override public Class<? super T> getTargetClass() { return clzz; } @Override public String toString() { return clzz.getSimpleName(); } }; } }
2,041
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/protocol/MarshallLocation.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.protocol; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Enum representing the various locations data can be marshalled to. */ @SdkProtectedApi public enum MarshallLocation { /** * Payload of the request (format depends on the protocol/content-type) */ // TODO change to default or NONE as actual location depends on protocol PAYLOAD, /** * Add as a query parameter. */ QUERY_PARAM, /** * HTTP header. */ HEADER, /** * Replace the placeholder in the request URI (non-greedy). */ PATH, /** * Replace the placeholder in the request URI (greedy). This location is really the same as {@link #PATH}, * the only difference is whether it's URL encoded or not. Members bound to the {@link #PATH} will be URL * encoded before replacing, members bound to {@link #GREEDY_PATH} will not be URL encoded. */ GREEDY_PATH, /** * HTTP status code of response. */ STATUS_CODE; }
2,042
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/checksums/Md5Checksum.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.checksums; import java.security.MessageDigest; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Implementation of {@link SdkChecksum} to calculate an MD5 checksum. */ @SdkInternalApi public class Md5Checksum implements SdkChecksum { private MessageDigest digest; private MessageDigest digestLastMarked; public Md5Checksum() { this.digest = getDigest(); } @Override public void update(int b) { digest.update((byte) b); } @Override public void update(byte[] b, int off, int len) { digest.update(b, off, len); } @Override public long getValue() { throw new UnsupportedOperationException("Use getChecksumBytes() instead."); } @Override public void reset() { digest = (digestLastMarked == null) // This is necessary so that should there be a reset without a // preceding mark, the MD5 would still be computed correctly. ? getDigest() : cloneFrom(digestLastMarked); } private MessageDigest getDigest() { try { return MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new IllegalStateException("Unexpected error creating MD5 checksum", e); } } @Override public byte[] getChecksumBytes() { return digest.digest(); } @Override public void mark(int readLimit) { digestLastMarked = cloneFrom(digest); } private MessageDigest cloneFrom(MessageDigest from) { try { return (MessageDigest) from.clone(); } catch (CloneNotSupportedException e) { // should never occur throw new IllegalStateException("unexpected", e); } } }
2,043
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/checksums/Algorithm.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.checksums; import java.util.Map; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.internal.EnumUtils; /** * Enum that indicates all the checksums supported by Flexible checksums in a Service Request/Response Header. */ @SdkPublicApi public enum Algorithm { CRC32C("crc32c", 8), CRC32("crc32", 8), SHA256("sha256", 44), SHA1("sha1", 28), ; private static final Map<String, Algorithm> VALUE_MAP = EnumUtils.uniqueIndex(Algorithm.class, a -> StringUtils.upperCase(a.value)); private final String value; private final int length; Algorithm(String value, int length) { this.value = value; this.length = length; } public static Algorithm fromValue(String value) { if (value == null) { return null; } // The clients will send the algorithm name in all upper case // try using that name directly and if not found then normalize // it and try again. Algorithm algorithm = VALUE_MAP.get(value); if (algorithm == null) { String normalizedValue = StringUtils.upperCase(value); algorithm = VALUE_MAP.get(normalizedValue); if (algorithm == null) { throw new IllegalArgumentException("The provided value is not a valid algorithm " + value); } } return algorithm; } @Override public String toString() { return String.valueOf(value); } /** * Length corresponds to Base64Encoded length for a given Checksum. * This is always fixed for a checksum. * @return length of base64 Encoded checksum. */ public Integer base64EncodedLength() { return this.length; } }
2,044
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/checksums/ChecksumValidation.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.checksums; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; /** * Enum to indicate the checksum validation is performed on a Response that supports Http Checksum Validation. * The status of Checksum validation can be obtained by accessing {@link SdkExecutionAttribute#HTTP_RESPONSE_CHECKSUM_VALIDATION} * on an execution context by using * {@link ExecutionInterceptor#afterExecution(Context.AfterExecution, ExecutionAttributes)}. * Possible Checksum Validations * {@link #VALIDATED} * {@link #FORCE_SKIP} * {@link #CHECKSUM_ALGORITHM_NOT_FOUND} * {@link #CHECKSUM_RESPONSE_NOT_FOUND} * */ @SdkPublicApi public enum ChecksumValidation { /** * Checksum validation was performed on the response. */ VALIDATED, /** * Checksum validation was skipped since response has customization for specific checksum values. */ FORCE_SKIP, /** * Response has checksum mode enabled but Algorithm was not found in client. */ CHECKSUM_ALGORITHM_NOT_FOUND, /** * Response has checksum mode enabled but response header did not have checksum. */ CHECKSUM_RESPONSE_NOT_FOUND, }
2,045
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/checksums/Sha256Checksum.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.checksums; import java.security.MessageDigest; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Implementation of {@link SdkChecksum} to calculate an Sha-256 Checksum. */ @SdkInternalApi public class Sha256Checksum implements SdkChecksum { private MessageDigest digest; private MessageDigest digestLastMarked; public Sha256Checksum() { this.digest = getDigest(); } @Override public void update(int b) { digest.update((byte) b); } @Override public void update(byte[] b, int off, int len) { digest.update(b, off, len); } @Override public long getValue() { throw new UnsupportedOperationException("Use getChecksumBytes() instead."); } @Override public void reset() { digest = (digestLastMarked == null) // This is necessary so that should there be a reset without a // preceding mark, the Sha-256 would still be computed correctly. ? getDigest() : cloneFrom(digestLastMarked); } private MessageDigest getDigest() { try { return MessageDigest.getInstance("SHA-256"); } catch (Exception e) { throw new IllegalStateException("Unexpected error creating SHA-256 checksum", e); } } @Override public byte[] getChecksumBytes() { return digest.digest(); } @Override public void mark(int readLimit) { digestLastMarked = cloneFrom(digest); } private MessageDigest cloneFrom(MessageDigest from) { try { return (MessageDigest) from.clone(); } catch (CloneNotSupportedException e) { // should never occur throw new IllegalStateException("unexpected", e); } } }
2,046
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/checksums/Sha1Checksum.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.checksums; import java.security.MessageDigest; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Implementation of {@link SdkChecksum} to calculate an Sha-1 checksum. */ @SdkInternalApi public class Sha1Checksum implements SdkChecksum { private MessageDigest digest; private MessageDigest digestLastMarked; public Sha1Checksum() { this.digest = getDigest(); } @Override public void update(int b) { digest.update((byte) b); } @Override public void update(byte[] b, int off, int len) { digest.update(b, off, len); } @Override public long getValue() { throw new UnsupportedOperationException("Use getChecksumBytes() instead."); } @Override public void reset() { digest = (digestLastMarked == null) // This is necessary so that should there be a reset without a // preceding mark, the Sha-1 would still be computed correctly. ? getDigest() : cloneFrom(digestLastMarked); } private MessageDigest getDigest() { try { return MessageDigest.getInstance("SHA-1"); } catch (Exception e) { throw new IllegalStateException("Unexpected error creating SHA-1 checksum", e); } } @Override public byte[] getChecksumBytes() { return digest.digest(); } @Override public void mark(int readLimit) { digestLastMarked = cloneFrom(digest); } private MessageDigest cloneFrom(MessageDigest from) { try { return (MessageDigest) from.clone(); } catch (CloneNotSupportedException e) { // should never occur throw new IllegalStateException("unexpected", e); } } }
2,047
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/checksums/SdkChecksum.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.checksums; import java.nio.ByteBuffer; import java.util.zip.Checksum; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Extension of {@link Checksum} to support checksums and checksum validations used by the SDK that * are not provided by the JDK. */ @SdkPublicApi public interface SdkChecksum extends Checksum { /** * Returns the computed checksum in a byte array rather than the long provided by * {@link #getValue()}. * * @return byte[] containing the checksum */ byte[] getChecksumBytes(); /** * Allows marking a checksum for checksums that support the ability to mark and reset. * * @param readLimit the maximum limit of bytes that can be read before the mark position becomes invalid. */ void mark(int readLimit); /** * Gets the Checksum based on the required Algorithm. * Instances for CRC32C, CRC32 Algorithm will be added from CRT Java library once they are available in release. * @param algorithm Algorithm for calculating the checksum * @return Optional Checksum instances. */ static SdkChecksum forAlgorithm(Algorithm algorithm) { switch (algorithm) { case SHA256: return new Sha256Checksum(); case SHA1: return new Sha1Checksum(); case CRC32: return new Crc32Checksum(); case CRC32C: return new Crc32CChecksum(); default: throw new UnsupportedOperationException("Checksum not supported for " + algorithm); } } /** * Updates the current checksum with the specified array of bytes. * * @param b the array of bytes to update the checksum with * * @throws NullPointerException * if {@code b} is {@code null} */ default void update(byte[] b) { update(b, 0, b.length); } /** * Updates the current checksum with the bytes from the specified buffer. * * The checksum is updated with the remaining bytes in the buffer, starting * at the buffer's position. Upon return, the buffer's position will be * updated to its limit; its limit will not have been changed. * * @apiNote For best performance with DirectByteBuffer and other ByteBuffer * implementations without a backing array implementers of this interface * should override this method. * * @implSpec The default implementation has the following behavior.<br> * For ByteBuffers backed by an accessible byte array. * <pre>{@code * update(buffer.array(), * buffer.position() + buffer.arrayOffset(), * buffer.remaining()); * }</pre> * For ByteBuffers not backed by an accessible byte array. * <pre>{@code * byte[] b = new byte[Math.min(buffer.remaining(), 4096)]; * while (buffer.hasRemaining()) { * int length = Math.min(buffer.remaining(), b.length); * buffer.get(b, 0, length); * update(b, 0, length); * } * }</pre> * * @param buffer the ByteBuffer to update the checksum with * * @throws NullPointerException * if {@code buffer} is {@code null} * */ default void update(ByteBuffer buffer) { int pos = buffer.position(); int limit = buffer.limit(); int rem = limit - pos; if (rem <= 0) { return; } if (buffer.hasArray()) { update(buffer.array(), pos + buffer.arrayOffset(), rem); } else { byte[] b = new byte[Math.min(buffer.remaining(), 4096)]; while (buffer.hasRemaining()) { int length = Math.min(buffer.remaining(), b.length); buffer.get(b, 0, length); update(b, 0, length); } } buffer.position(limit); } }
2,048
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/checksums/ChecksumSpecs.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.checksums; import java.util.Collections; import java.util.List; import java.util.Objects; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Defines all the Specifications that are required while adding HttpChecksum to a request and validating HttpChecksum of a * response. */ @SdkInternalApi public class ChecksumSpecs { private final Algorithm algorithm; private final String headerName; private final List<Algorithm> responseValidationAlgorithms; private final boolean isValidationEnabled; private final boolean isRequestChecksumRequired; private final boolean isRequestStreaming; private ChecksumSpecs(Builder builder) { this.algorithm = builder.algorithm; this.headerName = builder.headerName; this.responseValidationAlgorithms = builder.responseValidationAlgorithms; this.isValidationEnabled = builder.isValidationEnabled; this.isRequestChecksumRequired = builder.isRequestChecksumRequired; this.isRequestStreaming = builder.isRequestStreaming; } public static Builder builder() { return new Builder(); } public Algorithm algorithm() { return algorithm; } public String headerName() { return headerName; } public boolean isRequestStreaming() { return isRequestStreaming; } public boolean isValidationEnabled() { return isValidationEnabled; } public boolean isRequestChecksumRequired() { return isRequestChecksumRequired; } public List<Algorithm> responseValidationAlgorithms() { return responseValidationAlgorithms; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ChecksumSpecs)) { return false; } ChecksumSpecs checksum = (ChecksumSpecs) o; return algorithm() == checksum.algorithm() && isRequestStreaming() == checksum.isRequestStreaming() && Objects.equals(headerName(), checksum.headerName()) && Objects.equals(responseValidationAlgorithms(), checksum.responseValidationAlgorithms()) && Objects.equals(isValidationEnabled(), checksum.isValidationEnabled()) && Objects.equals(isRequestChecksumRequired(), checksum.isRequestChecksumRequired()); } @Override public int hashCode() { int result = algorithm != null ? algorithm.hashCode() : 0; result = 31 * result + (headerName != null ? headerName.hashCode() : 0); result = 31 * result + (responseValidationAlgorithms != null ? responseValidationAlgorithms.hashCode() : 0); result = 31 * result + (isValidationEnabled ? 1 : 0); result = 31 * result + (isRequestChecksumRequired ? 1 : 0); result = 31 * result + (isRequestStreaming ? 1 : 0); return result; } @Override public String toString() { return "ChecksumSpecs{" + "algorithm=" + algorithm + ", headerName='" + headerName + '\'' + ", responseValidationAlgorithms=" + responseValidationAlgorithms + ", isValidationEnabled=" + isValidationEnabled + ", isRequestChecksumRequired=" + isRequestChecksumRequired + ", isStreamingData=" + isRequestStreaming + '}'; } public static final class Builder { private Algorithm algorithm; private String headerName; private List<Algorithm> responseValidationAlgorithms; private boolean isValidationEnabled; private boolean isRequestChecksumRequired; private boolean isRequestStreaming; private Builder() { } public Builder algorithm(Algorithm algorithm) { this.algorithm = algorithm; return this; } public Builder headerName(String headerName) { this.headerName = headerName; return this; } public Builder responseValidationAlgorithms(List<Algorithm> responseValidationAlgorithms) { this.responseValidationAlgorithms = responseValidationAlgorithms != null ? Collections.unmodifiableList(responseValidationAlgorithms) : null; return this; } public Builder isValidationEnabled(boolean isValidationEnabled) { this.isValidationEnabled = isValidationEnabled; return this; } public Builder isRequestChecksumRequired(boolean isRequestChecksumRequired) { this.isRequestChecksumRequired = isRequestChecksumRequired; return this; } public Builder isRequestStreaming(boolean isRequestStreaming) { this.isRequestStreaming = isRequestStreaming; return this; } public ChecksumSpecs build() { return new ChecksumSpecs(this); } } }
2,049
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/checksums/Crc32CChecksum.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.checksums; import static software.amazon.awssdk.core.internal.util.HttpChecksumUtils.longToByte; import java.lang.reflect.Method; import java.util.Arrays; import java.util.zip.Checksum; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.internal.checksums.factory.CrtBasedChecksumProvider; import software.amazon.awssdk.core.internal.checksums.factory.SdkCrc32C; /** * Implementation of {@link SdkChecksum} to calculate an CRC32C checksum. */ @SdkInternalApi public class Crc32CChecksum implements SdkChecksum { private Checksum crc32c; private Checksum lastMarkedCrc32C; private final boolean isCrtBasedChecksum; /** * Creates CRT Based Crc32C checksum if Crt classpath for Crc32c is loaded, else create Sdk Implemented Crc32c */ public Crc32CChecksum() { crc32c = CrtBasedChecksumProvider.createCrc32C(); isCrtBasedChecksum = crc32c != null; if (!isCrtBasedChecksum) { crc32c = SdkCrc32C.create(); } } @Override public byte[] getChecksumBytes() { return Arrays.copyOfRange(longToByte(crc32c.getValue()), 4, 8); } @Override public void mark(int readLimit) { this.lastMarkedCrc32C = cloneChecksum(crc32c); } @Override public void update(int b) { crc32c.update(b); } @Override public void update(byte[] b, int off, int len) { crc32c.update(b, off, len); } @Override public long getValue() { return crc32c.getValue(); } @Override public void reset() { if (lastMarkedCrc32C == null) { crc32c.reset(); } else { crc32c = cloneChecksum(lastMarkedCrc32C); } } private Checksum cloneChecksum(Checksum checksum) { if (isCrtBasedChecksum) { try { Method method = checksum.getClass().getDeclaredMethod("clone"); return (Checksum) method.invoke(checksum); } catch (ReflectiveOperationException e) { throw new IllegalStateException("Could not clone checksum class " + checksum.getClass(), e); } } else { return (Checksum) ((SdkCrc32C) checksum).clone(); } } }
2,050
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/checksums/Crc32Checksum.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.checksums; import static software.amazon.awssdk.core.internal.util.HttpChecksumUtils.longToByte; import java.lang.reflect.Method; import java.util.Arrays; import java.util.zip.Checksum; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.internal.checksums.factory.CrtBasedChecksumProvider; import software.amazon.awssdk.core.internal.checksums.factory.SdkCrc32; /** * Implementation of {@link SdkChecksum} to calculate an CRC32 checksum. */ @SdkInternalApi public class Crc32Checksum implements SdkChecksum { private Checksum crc32; private Checksum lastMarkedCrc32; private final boolean isCrtBasedChecksum; /** * Creates CRT Based Crc32 checksum if Crt classpath for Crc32 is loaded, else create Sdk Implemented Crc32. */ public Crc32Checksum() { crc32 = CrtBasedChecksumProvider.createCrc32(); isCrtBasedChecksum = crc32 != null; if (!isCrtBasedChecksum) { crc32 = SdkCrc32.create(); } } @Override public byte[] getChecksumBytes() { return Arrays.copyOfRange(longToByte(crc32.getValue()), 4, 8); } @Override public void mark(int readLimit) { this.lastMarkedCrc32 = cloneChecksum(crc32); } @Override public void update(int b) { crc32.update(b); } @Override public void update(byte[] b, int off, int len) { crc32.update(b, off, len); } @Override public long getValue() { return crc32.getValue(); } @Override public void reset() { if ((lastMarkedCrc32 == null)) { crc32.reset(); } else { crc32 = cloneChecksum(lastMarkedCrc32); } } private Checksum cloneChecksum(Checksum checksum) { if (isCrtBasedChecksum) { try { Method method = checksum.getClass().getDeclaredMethod("clone"); return (Checksum) method.invoke(checksum); } catch (ReflectiveOperationException e) { throw new IllegalStateException("Could not clone checksum class " + checksum.getClass(), e); } } else { return (Checksum) ((SdkCrc32) checksum).clone(); } } }
2,051
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/http/MetricCollectingHttpResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.http; import java.time.Duration; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.internal.util.MetricUtils; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.utils.Pair; /** * An implementation of {@link HttpResponseHandler} that publishes the time it took to execute { * @link #handle(SdkHttpFullResponse, ExecutionAttributes)} as the provieded duration metric to the * {@link SdkExecutionAttribute#API_CALL_ATTEMPT_METRIC_COLLECTOR}. */ @SdkProtectedApi public final class MetricCollectingHttpResponseHandler<T> implements HttpResponseHandler<T> { public final SdkMetric<? super Duration> metric; public final HttpResponseHandler<T> delegateToTime; private MetricCollectingHttpResponseHandler(SdkMetric<? super Duration> durationMetric, HttpResponseHandler<T> delegateToTime) { this.metric = durationMetric; this.delegateToTime = delegateToTime; } public static <T> MetricCollectingHttpResponseHandler<T> create(SdkMetric<? super Duration> durationMetric, HttpResponseHandler<T> delegateToTime) { return new MetricCollectingHttpResponseHandler<>(durationMetric, delegateToTime); } @Override public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { Pair<T, Duration> result = MetricUtils.measureDurationUnsafe(() -> delegateToTime.handle(response, executionAttributes)); collector(executionAttributes).ifPresent(c -> c.reportMetric(metric, result.right())); return result.left(); } private Optional<MetricCollector> collector(ExecutionAttributes attributes) { if (attributes == null) { return Optional.empty(); } return Optional.ofNullable(attributes.getAttribute(SdkExecutionAttribute.API_CALL_ATTEMPT_METRIC_COLLECTOR)); } @Override public boolean needsConnectionLeftOpen() { return delegateToTime.needsConnectionLeftOpen(); } }
2,052
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/http/ExecutionContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.http; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkProtectedApi; 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.signer.Signer; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * <b>Warning:</b> This class should only be accessed by a single thread and be used throughout a single request lifecycle. */ @NotThreadSafe @SdkProtectedApi public final class ExecutionContext implements ToCopyableBuilder<ExecutionContext.Builder, ExecutionContext> { private final Signer signer; private InterceptorContext interceptorContext; private final ExecutionInterceptorChain interceptorChain; private final ExecutionAttributes executionAttributes; private final MetricCollector metricCollector; private ExecutionContext(final Builder builder) { this.signer = builder.signer; this.interceptorContext = builder.interceptorContext; this.interceptorChain = builder.interceptorChain; this.executionAttributes = builder.executionAttributes; this.metricCollector = builder.metricCollector; } public static ExecutionContext.Builder builder() { return new ExecutionContext.Builder(); } public InterceptorContext interceptorContext() { return interceptorContext; } //TODO: We should switch to fully immutable execution contexts. Currently, we mutate it for the interceptor // context, credential providers, etc public ExecutionContext interceptorContext(InterceptorContext interceptorContext) { this.interceptorContext = interceptorContext; return this; } public ExecutionInterceptorChain interceptorChain() { return interceptorChain; } public ExecutionAttributes executionAttributes() { return executionAttributes; } public Signer signer() { return signer; } public MetricCollector metricCollector() { return metricCollector; } @Override public Builder toBuilder() { return new Builder(this); } public static class Builder implements CopyableBuilder<Builder, ExecutionContext> { private InterceptorContext interceptorContext; private ExecutionInterceptorChain interceptorChain; private ExecutionAttributes executionAttributes; private Signer signer; private MetricCollector metricCollector; private Builder() { } private Builder(ExecutionContext executionContext) { this.signer = executionContext.signer; this.interceptorContext = executionContext.interceptorContext; this.interceptorChain = executionContext.interceptorChain; this.executionAttributes = executionContext.executionAttributes; this.metricCollector = executionContext.metricCollector; } public Builder interceptorContext(InterceptorContext interceptorContext) { this.interceptorContext = interceptorContext; return this; } public Builder interceptorChain(ExecutionInterceptorChain interceptorChain) { this.interceptorChain = interceptorChain; return this; } public Builder executionAttributes(ExecutionAttributes executionAttributes) { this.executionAttributes = executionAttributes; return this; } public Builder signer(Signer signer) { this.signer = signer; return this; } public Builder metricCollector(MetricCollector metricCollector) { this.metricCollector = metricCollector; return this; } @Override public ExecutionContext build() { return new ExecutionContext(this); } } }
2,053
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/http/Crc32Validation.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.http; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.util.Optional; import java.util.zip.GZIPInputStream; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.internal.util.Crc32ChecksumValidatingInputStream; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpFullResponse; /** * Validate and decompress input data if necessary. */ @SdkProtectedApi public final class Crc32Validation { private Crc32Validation() { } public static SdkHttpFullResponse validate(boolean calculateCrc32FromCompressedData, SdkHttpFullResponse httpResponse) { if (!httpResponse.content().isPresent()) { return httpResponse; } return httpResponse.toBuilder().content( process(calculateCrc32FromCompressedData, httpResponse, httpResponse.content().get())).build(); } private static AbortableInputStream process(boolean calculateCrc32FromCompressedData, SdkHttpFullResponse httpResponse, AbortableInputStream content) { Optional<Long> crc32Checksum = getCrc32Checksum(httpResponse); if (shouldDecompress(httpResponse)) { if (calculateCrc32FromCompressedData && crc32Checksum.isPresent()) { return decompressing(crc32Validating(content, crc32Checksum.get())); } if (crc32Checksum.isPresent()) { return crc32Validating(decompressing(content), crc32Checksum.get()); } return decompressing(content); } return crc32Checksum.map(aLong -> crc32Validating(content, aLong)).orElse(content); } private static AbortableInputStream crc32Validating(AbortableInputStream source, long expectedChecksum) { return AbortableInputStream.create(new Crc32ChecksumValidatingInputStream(source, expectedChecksum), source); } private static Optional<Long> getCrc32Checksum(SdkHttpFullResponse httpResponse) { return httpResponse.firstMatchingHeader("x-amz-crc32") .map(Long::valueOf); } private static boolean shouldDecompress(SdkHttpFullResponse httpResponse) { return httpResponse.firstMatchingHeader("Content-Encoding") .filter(e -> e.equals("gzip")) .isPresent(); } private static AbortableInputStream decompressing(AbortableInputStream source) { return AbortableInputStream.create(invokeSafely(() -> new GZIPInputStream(source)), source); } }
2,054
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/http/HttpResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.http; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; /** * Responsible for handling an HTTP response and returning an object of type T. * For example, a typical response handler might accept a response, and * translate it into a concrete typed object. * * @param <T> * The output of this response handler. */ @SdkProtectedApi @FunctionalInterface public interface HttpResponseHandler<T> { String X_AMZN_REQUEST_ID_HEADER = "x-amzn-RequestId"; String X_AMZN_REQUEST_ID_HEADER_ALTERNATE = "x-amz-request-id"; Set<String> X_AMZN_REQUEST_ID_HEADERS = Collections.unmodifiableSet(Stream.of(X_AMZN_REQUEST_ID_HEADER, X_AMZN_REQUEST_ID_HEADER_ALTERNATE) .collect(Collectors.toSet())); String X_AMZ_ID_2_HEADER = "x-amz-id-2"; /** * Accepts an HTTP response object, and returns an object of type T. * Individual implementations may choose to handle the response however they * need to, and return any type that they need to. * * @param response The HTTP response to handle, as received from an AWS service. * @param executionAttributes The attributes attached to this particular execution. * @return An object of type T, as defined by individual implementations. * * @throws Exception * If any problems are encountered handling the response. */ T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception; /** * Indicates if this response handler requires that the underlying HTTP * connection <b>not</b> be closed automatically after the response is * handled. * <p> * For example, if the object returned by this response handler manually * manages the stream of data from the HTTP connection, and doesn't read all * the data from the connection in the {@link #handle(SdkHttpFullResponse, ExecutionAttributes)} method, * this method can be used to prevent the underlying connection from being * prematurely closed. * <p> * Response handlers should use this option very carefully, since it means * that resource cleanup is no longer handled automatically, and if * neglected, can result in the client runtime running out of resources for * new HTTP connections. * * @return True if this response handler requires that the underlying HTTP * connection be left open, and not automatically closed, otherwise * false. */ default boolean needsConnectionLeftOpen() { return false; } }
2,055
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/sync/ResponseTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.sync; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.ResponseInputStream; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.internal.http.InterruptMonitor; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Logger; /** * Interface for processing a streaming response from a service in a synchronous fashion. This interfaces gives * access to the unmarshalled response POJO which may contain metadata about the streamed contents. It also provides access * to the content via an {@link AbortableInputStream}. Callers do not need to worry about calling {@link InputStream#close()} * on the content, but if they wish to stop reading data from the stream {@link AbortableInputStream#abort()} may be called * to kill the underlying HTTP connection. This is generally not recommended and should only be done when the cost of reading * the rest of the data exceeds the cost of establishing a new connection. If callers do not call abort and do not read all * of the data in the stream, then the content will be drained by the SDK and the underlying HTTP connection will be returned to * the connection pool (if applicable). * <h3>Retries</h3> * <p> * Exceptions thrown from the transformer's {@link #transform(Object, AbortableInputStream)} method are not automatically retried * by the RetryPolicy of the client. Since we can't know if a transformer implementation is idempotent or safe to retry, if you * wish to retry on the event of a failure you must throw a {@link SdkException} with retryable set to true from the transformer. * This exception can wrap the original exception that was thrown. Note that throwing a {@link * SdkException} that is marked retryable from the transformer does not guarantee the request will be retried, * retries are still limited by the max retry attempts and retry throttling * feature of the {@link RetryPolicy}. * * <h3>Thread Interrupts</h3> * <p> * Implementations should have proper handling of Thread interrupts. For long running, non-interruptible tasks, it is recommended * to check the thread interrupt status periodically and throw an {@link InterruptedException} if set. When an {@link * InterruptedException} is thrown from a interruptible task, you should either re-interrupt the current thread and return or * throw that {@link InterruptedException} from the {@link #transform(Object, AbortableInputStream)} method. Failure to do these * things may prevent the SDK from stopping the request in a timely manner in the event the thread is interrupted externally. * * @param <ResponseT> Type of unmarshalled POJO response. * @param <ReturnT> Return type of the {@link #transform(Object, AbortableInputStream)} method. Implementations are free to * perform whatever transformations are appropriate. */ @FunctionalInterface @SdkPublicApi public interface ResponseTransformer<ResponseT, ReturnT> { /** * Process the response contents. * * @param response Unmarshalled POJO response * @param inputStream Input stream of streamed data. * @return Transformed type. * @throws Exception if any error occurs during processing of the response. This will be re-thrown by the SDK, possibly * wrapped in an {@link SdkClientException}. */ ReturnT transform(ResponseT response, AbortableInputStream inputStream) throws Exception; /** * Hook to allow connection to be left open after the SDK returns a response. Useful for returning the InputStream to * the response content from the transformer. * * @return True if connection (and InputStream) should be left open after the SDK returns a response, false otherwise. */ default boolean needsConnectionLeftOpen() { return false; } /** * Creates a response transformer that writes all response content to the specified file. If the file already exists * then a {@link java.nio.file.FileAlreadyExistsException} will be thrown. * * @param path Path to file to write to. * @param <ResponseT> Type of unmarshalled response POJO. * @return ResponseTransformer instance. */ static <ResponseT> ResponseTransformer<ResponseT, ResponseT> toFile(Path path) { return (resp, in) -> { try { InterruptMonitor.checkInterrupted(); Files.copy(in, path); return resp; } catch (IOException copyException) { String copyError = "Failed to read response into file: " + path; // If the write failed because of the state of the file, don't retry the request. if (copyException instanceof FileAlreadyExistsException || copyException instanceof DirectoryNotEmptyException) { throw new IOException(copyError, copyException); } // Try to clean up the file so that we can retry the request. If we can't delete it, don't retry the request. try { Files.deleteIfExists(path); } catch (IOException deletionException) { Logger.loggerFor(ResponseTransformer.class) .error(() -> "Failed to delete destination file '" + path + "' after reading the service response " + "failed.", deletionException); throw new IOException(copyError + ". Additionally, the file could not be cleaned up (" + deletionException.getMessage() + "), so the request will not be retried.", copyException); } // Retry the request throw RetryableException.builder().message(copyError).cause(copyException).build(); } }; } /** * Creates a response transformer that writes all response content to the specified file. If the file already exists * then a {@link java.nio.file.FileAlreadyExistsException} will be thrown. * * @param file File to write to. * @param <ResponseT> Type of unmarshalled response POJO. * @return ResponseTransformer instance. */ static <ResponseT> ResponseTransformer<ResponseT, ResponseT> toFile(File file) { return toFile(file.toPath()); } /** * Creates a response transformer that writes all response content to the given {@link OutputStream}. Note that * the {@link OutputStream} is not closed or flushed after writing. * * @param outputStream Output stream to write data to. * @param <ResponseT> Type of unmarshalled response POJO. * @return ResponseTransformer instance. */ static <ResponseT> ResponseTransformer<ResponseT, ResponseT> toOutputStream(OutputStream outputStream) { return (resp, in) -> { InterruptMonitor.checkInterrupted(); IoUtils.copy(in, outputStream); return resp; }; } /** * Creates a response transformer that loads all response content into memory, exposed as {@link ResponseBytes}. This allows * for conversion into a {@link String}, {@link ByteBuffer}, etc. * * @param <ResponseT> Type of unmarshalled response POJO. * @return The streaming response transformer that can be used on the client streaming method. */ static <ResponseT> ResponseTransformer<ResponseT, ResponseBytes<ResponseT>> toBytes() { return (response, inputStream) -> { try { InterruptMonitor.checkInterrupted(); return ResponseBytes.fromByteArrayUnsafe(response, IoUtils.toByteArray(inputStream)); } catch (IOException e) { throw RetryableException.builder().message("Failed to read response.").cause(e).build(); } }; } /** * Creates a response transformer that returns an unmanaged input stream with the response content. This input stream must * be explicitly closed to release the connection. The unmarshalled response object can be obtained via the {@link * ResponseInputStream#response} method. * <p> * Note that the returned stream is not subject to the retry policy or timeout settings (except for socket timeout) * of the client. No retries will be performed in the event of a socket read failure or connection reset. * * @param <ResponseT> Type of unmarshalled response POJO. * @return ResponseTransformer instance. */ static <ResponseT> ResponseTransformer<ResponseT, ResponseInputStream<ResponseT>> toInputStream() { return unmanaged(ResponseInputStream::new); } /** * Static helper method to create a response transformer that allows the connection to be left open. Useful for creating a * {@link ResponseTransformer} with a lambda or method reference rather than an anonymous inner class. * * @param transformer Transformer to wrap. * @param <ResponseT> Type of unmarshalled response POJO. * @param <ReturnT> Return type of transformer. * @return New {@link ResponseTransformer} which does not close the connection afterwards. */ static <ResponseT, ReturnT> ResponseTransformer<ResponseT, ReturnT> unmanaged( ResponseTransformer<ResponseT, ReturnT> transformer) { return new ResponseTransformer<ResponseT, ReturnT>() { @Override public ReturnT transform(ResponseT response, AbortableInputStream inputStream) throws Exception { InterruptMonitor.checkInterrupted(); return transformer.transform(response, inputStream); } @Override public boolean needsConnectionLeftOpen() { return true; } }; } }
2,056
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/sync/RequestBody.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.sync; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import static software.amazon.awssdk.utils.Validate.isNotNegative; import static software.amazon.awssdk.utils.Validate.paramNotNull; import static software.amazon.awssdk.utils.Validate.validState; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Optional; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.internal.sync.FileContentStreamProvider; import software.amazon.awssdk.core.internal.util.Mimetype; import software.amazon.awssdk.core.io.ReleasableInputStream; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.IoUtils; /** * Represents the body of an HTTP request. Must be provided for operations that have a streaming input. * Offers various convenience factory methods from common sources of data (File, String, byte[], etc). */ @SdkPublicApi public final class RequestBody { // TODO Handle stream management (progress listener, orig input stream tracking, etc private final ContentStreamProvider contentStreamProvider; private final Long contentLength; private final String contentType; private RequestBody(ContentStreamProvider contentStreamProvider, Long contentLength, String contentType) { this.contentStreamProvider = paramNotNull(contentStreamProvider, "contentStreamProvider"); this.contentLength = contentLength != null ? isNotNegative(contentLength, "Content-length") : null; this.contentType = paramNotNull(contentType, "contentType"); } /** * @return RequestBody as an {@link InputStream}. */ public ContentStreamProvider contentStreamProvider() { return contentStreamProvider; } /** * @deprecated by {@link #optionalContentLength()} * @return Content length of {@link RequestBody}. */ @Deprecated public long contentLength() { validState(this.contentLength != null, "Content length is invalid, please use optionalContentLength() for your case."); return contentLength; } /** * @return Optional object of content length of {@link RequestBody}. */ public Optional<Long> optionalContentLength() { return Optional.ofNullable(contentLength); } /** * @return Content type of {@link RequestBody}. */ public String contentType() { return contentType; } /** * Create a {@link RequestBody} using the full contents of the specified file. * * @param path File to send to the service. * @return RequestBody instance. */ public static RequestBody fromFile(Path path) { return new RequestBody(new FileContentStreamProvider(path), invokeSafely(() -> Files.size(path)), Mimetype.getInstance().getMimetype(path)); } /** * Create a {@link RequestBody} using the full contents of the specified file. * * @param file File to send to the service. * @return RequestBody instance. */ public static RequestBody fromFile(File file) { return fromFile(file.toPath()); } /** * Creates a {@link RequestBody} from an input stream. {@value Header#CONTENT_LENGTH} must * be provided so that the SDK does not have to make two passes of the data. * <p> * The stream will not be closed by the SDK. It is up to to caller of this method to close the stream. The stream * should not be read outside of the SDK (by another thread) as it will change the state of the {@link InputStream} and * could tamper with the sending of the request. * <p> * To support resetting via {@link ContentStreamProvider}, this uses {@link InputStream#reset()} and uses a read limit of * 128 KiB. If you need more control, use {@link #fromContentProvider(ContentStreamProvider, long, String)} or * {@link #fromContentProvider(ContentStreamProvider, String)}. * * @param inputStream Input stream to send to the service. The stream will not be closed by the SDK. * @param contentLength Content length of data in input stream. * @return RequestBody instance. */ public static RequestBody fromInputStream(InputStream inputStream, long contentLength) { IoUtils.markStreamWithMaxReadLimit(inputStream); InputStream nonCloseable = nonCloseableInputStream(inputStream); return fromContentProvider(() -> { if (nonCloseable.markSupported()) { invokeSafely(nonCloseable::reset); } return nonCloseable; }, contentLength, Mimetype.MIMETYPE_OCTET_STREAM); } /** * Creates a {@link RequestBody} from a string. String is sent using the provided encoding. * * @param contents String to send to the service. * @param cs The {@link Charset} to use. * @return RequestBody instance. */ public static RequestBody fromString(String contents, Charset cs) { return fromBytesDirect(contents.getBytes(cs), Mimetype.MIMETYPE_TEXT_PLAIN + "; charset=" + cs.name()); } /** * Creates a {@link RequestBody} from a string. String is sent as UTF-8 encoded bytes. * * @param contents String to send to the service. * @return RequestBody instance. */ public static RequestBody fromString(String contents) { return fromString(contents, StandardCharsets.UTF_8); } /** * Creates a {@link RequestBody} from a byte array. The contents of the byte array are copied so modifications to the * original byte array are not reflected in the {@link RequestBody}. * * @param bytes The bytes to send to the service. * @return RequestBody instance. */ public static RequestBody fromBytes(byte[] bytes) { return fromBytesDirect(Arrays.copyOf(bytes, bytes.length)); } /** * Creates a {@link RequestBody} from a {@link ByteBuffer}. Buffer contents are copied so any modifications * made to the original {@link ByteBuffer} are not reflected in the {@link RequestBody}. * <p> * <b>NOTE:</b> This method always copies the entire contents of the buffer, ignoring the current read position. Use * {@link #fromRemainingByteBuffer(ByteBuffer)} if you need it to copy only the remaining readable bytes. * * @param byteBuffer ByteBuffer to send to the service. * @return RequestBody instance. */ public static RequestBody fromByteBuffer(ByteBuffer byteBuffer) { return fromBytesDirect(BinaryUtils.copyAllBytesFrom(byteBuffer)); } /** * Creates a {@link RequestBody} from the remaining readable bytes from a {@link ByteBuffer}. Unlike * {@link #fromByteBuffer(ByteBuffer)}, this method respects the current read position of the buffer and reads only * the remaining bytes. The buffer is copied before reading so no changes are made to original buffer. * * @param byteBuffer ByteBuffer to send to the service. * @return RequestBody instance. */ public static RequestBody fromRemainingByteBuffer(ByteBuffer byteBuffer) { return fromBytesDirect(BinaryUtils.copyRemainingBytesFrom(byteBuffer)); } /** * Creates a {@link RequestBody} with no content. * * @return RequestBody instance. */ public static RequestBody empty() { return fromBytesDirect(new byte[0]); } /** * Creates a {@link RequestBody} from the given {@link ContentStreamProvider}. * * @param provider The content provider. * @param contentLength The content length. * @param mimeType The MIME type of the content. * * @return The created {@code RequestBody}. */ public static RequestBody fromContentProvider(ContentStreamProvider provider, long contentLength, String mimeType) { return new RequestBody(provider, contentLength, mimeType); } /** * Creates a {@link RequestBody} from the given {@link ContentStreamProvider}. * * @param provider The content provider. * @param mimeType The MIME type of the content. * * @return The created {@code RequestBody}. */ public static RequestBody fromContentProvider(ContentStreamProvider provider, String mimeType) { return new RequestBody(provider, null, mimeType); } /** * Creates a {@link RequestBody} using the specified bytes (without copying). */ private static RequestBody fromBytesDirect(byte[] bytes) { return fromBytesDirect(bytes, Mimetype.MIMETYPE_OCTET_STREAM); } /** * Creates a {@link RequestBody} using the specified bytes (without copying). */ private static RequestBody fromBytesDirect(byte[] bytes, String mimetype) { return fromContentProvider(() -> new ByteArrayInputStream(bytes), bytes.length, mimetype); } private static InputStream nonCloseableInputStream(InputStream inputStream) { return inputStream != null ? ReleasableInputStream.wrap(inputStream).disableClose() : null; } }
2,057
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/exception/NonRetryableException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.exception; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Extension of {@link SdkException} that can be used by clients to * explicitly have an exception not retried. This exception will never be * thrown by the SDK unless explicitly used by the client. * * See {@link RetryableException} for marking retryable exceptions. */ @SdkPublicApi public final class NonRetryableException extends SdkClientException { protected NonRetryableException(Builder b) { super(b); } @Override public boolean retryable() { return false; } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public static NonRetryableException create(String message) { return builder().message(message).build(); } public static NonRetryableException create(String message, Throwable cause) { return builder().message(message).cause(cause).build(); } public interface Builder extends SdkClientException.Builder { @Override Builder message(String message); @Override Builder cause(Throwable cause); @Override Builder writableStackTrace(Boolean writableStackTrace); @Override NonRetryableException build(); } protected static final class BuilderImpl extends SdkClientException.BuilderImpl implements Builder { protected BuilderImpl() { } protected BuilderImpl(NonRetryableException ex) { super(ex); } @Override public Builder message(String message) { this.message = message; return this; } @Override public String message() { return message; } @Override public Throwable cause() { return cause; } @Override public Builder cause(Throwable cause) { this.cause = cause; return this; } @Override public Builder writableStackTrace(Boolean writableStackTrace) { this.writableStackTrace = writableStackTrace; return this; } @Override public NonRetryableException build() { return new NonRetryableException(this); } } }
2,058
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/exception/SdkServiceException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.exception; import java.util.Collections; import java.util.List; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.http.HttpStatusCode; /** * Extension of SdkException that represents an error response returned by * the requested downstream service. Receiving an exception of this type indicates that * the caller's request was correctly transmitted to the service, but for some * reason, the service was not able to process it, and returned an error * response instead. * <p> * Exceptions that extend {@link SdkServiceException} are assumed to be able to be * successfully retried. * <p> * SdkServiceException provides callers several pieces of information that can * be used to obtain more information about the error and why it occurred. * * @see SdkClientException */ @SdkPublicApi public class SdkServiceException extends SdkException implements SdkPojo { private final String requestId; private final String extendedRequestId; private final int statusCode; protected SdkServiceException(Builder b) { super(b); this.requestId = b.requestId(); this.extendedRequestId = b.extendedRequestId(); this.statusCode = b.statusCode(); } /** * The requestId that was returned by the called service. * @return String containing the requestId */ public String requestId() { return requestId; } /** * The extendedRequestId that was returned by the called service. * @return String ctontaining the extendedRequestId */ public String extendedRequestId() { return extendedRequestId; } /** * The status code that was returned by the called service. * @return int containing the status code. */ public int statusCode() { return statusCode; } /** * Specifies whether or not an exception may have been caused by clock skew. */ public boolean isClockSkewException() { return false; } /** * Specifies whether or not an exception is caused by throttling. * * @return true if the status code is 429, otherwise false. */ public boolean isThrottlingException() { return statusCode == HttpStatusCode.THROTTLING; } /** * @return {@link Builder} instance to construct a new {@link SdkServiceException}. */ public static Builder builder() { return new BuilderImpl(); } /** * Create a {@link SdkServiceException.Builder} initialized with the properties of this {@code SdkServiceException}. * * @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; } @Override public List<SdkField<?>> sdkFields() { return Collections.emptyList(); } public interface Builder extends SdkException.Builder, SdkPojo { @Override Builder message(String message); @Override Builder cause(Throwable cause); @Override Builder writableStackTrace(Boolean writableStackTrace); /** * Specifies the requestId returned by the called service. * * @param requestId A string that identifies the request made to a service. * @return This object for method chaining. */ Builder requestId(String requestId); /** * The requestId returned by the called service. * * @return String containing the requestId */ String requestId(); /** * Specifies the extendedRequestId returned by the called service. * * @param extendedRequestId A string that identifies the request made to a service. * @return This object for method chaining. */ Builder extendedRequestId(String extendedRequestId); /** * The extendedRequestId returned by the called service. * * @return String containing the extendedRequestId */ String extendedRequestId(); /** * Specifies the status code returned by the service. * * @param statusCode an int containing the status code returned by the service. * @return This method for object chaining. */ Builder statusCode(int statusCode); /** * The status code returned by the service. * @return int containing the status code */ int statusCode(); /** * Creates a new {@link SdkServiceException} with the specified properties. * * @return The new {@link SdkServiceException}. */ @Override SdkServiceException build(); } protected static class BuilderImpl extends SdkException.BuilderImpl implements Builder { protected String requestId; protected String extendedRequestId; protected int statusCode; protected BuilderImpl() { } protected BuilderImpl(SdkServiceException ex) { super(ex); this.requestId = ex.requestId(); this.extendedRequestId = ex.extendedRequestId(); this.statusCode = ex.statusCode(); } @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 String requestId() { return requestId; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } @Override public String extendedRequestId() { return extendedRequestId; } public String getExtendedRequestId() { return extendedRequestId; } public void setExtendedRequestId(String extendedRequestId) { this.extendedRequestId = extendedRequestId; } @Override public Builder statusCode(int statusCode) { this.statusCode = statusCode; return this; } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } @Override public int statusCode() { return statusCode; } @Override public SdkServiceException build() { return new SdkServiceException(this); } @Override public List<SdkField<?>> sdkFields() { return Collections.emptyList(); } } }
2,059
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/exception/SdkInterruptedException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.exception; import java.io.InputStream; import java.util.Optional; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.SdkHttpFullResponse; @SdkPublicApi public final class SdkInterruptedException extends InterruptedException { private static final long serialVersionUID = 8194951388566545094L; private final transient InputStream responseStream; public SdkInterruptedException() { this.responseStream = null; } public SdkInterruptedException(SdkHttpFullResponse response) { this.responseStream = Optional.ofNullable(response) .flatMap(SdkHttpFullResponse::content) .orElse(null); } public Optional<InputStream> getResponseStream() { return Optional.ofNullable(responseStream); } }
2,060
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/exception/SdkException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.exception; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.builder.Buildable; /** * Base class for all exceptions thrown by the SDK. * * @see SdkServiceException * @see SdkClientException */ @SdkPublicApi public class SdkException extends RuntimeException { private static final long serialVersionUID = 1L; protected SdkException(Builder builder) { super(messageFromBuilder(builder), builder.cause(), true, writableStackTraceFromBuilder(builder)); } /** * Use the message from the builder, if it's specified, otherwise inherit the message from the "cause" exception. */ private static String messageFromBuilder(Builder builder) { if (builder.message() != null) { return builder.message(); } if (builder.cause() != null) { return builder.cause().getMessage(); } return null; } private static boolean writableStackTraceFromBuilder(Builder builder) { return builder.writableStackTrace() == null || builder.writableStackTrace(); } public static SdkException create(String message, Throwable cause) { return SdkException.builder().message(message).cause(cause).build(); } /** * Specifies whether or not an exception can be expected to succeed on a retry. */ public boolean retryable() { return false; } /** * Create a {@link SdkException.Builder} initialized with the properties of this {@code SdkException}. * * @return A new builder initialized with this config's properties. */ public Builder toBuilder() { return new BuilderImpl(this); } /** * @return {@link Builder} instance to construct a new {@link SdkException}. */ public static Builder builder() { return new BuilderImpl(); } public interface Builder extends Buildable { /** * Specifies the exception that caused this exception to occur. * * @param cause The exception that caused this exception to occur. * @return This object for method chaining. */ Builder cause(Throwable cause); /** * The exception that caused this exception to occur. * * @return The exception that caused this exception to occur. */ Throwable cause(); /** * Specifies the details of this exception. * * @param message The details of this exception. * @return This method for object chaining */ Builder message(String message); /** * The details of this exception. * * @return Details of this exception. */ String message(); /** * Specifies whether the stack trace in this exception can be written. * * @param writableStackTrace Whether the stack trace can be written. * @return This method for object chaining */ Builder writableStackTrace(Boolean writableStackTrace); /** * Whether the stack trace in this exception can be written. */ Boolean writableStackTrace(); /** * Creates a new {@link SdkException} with the specified properties. * * @return The new {@link SdkException}. */ @Override SdkException build(); } protected static class BuilderImpl implements Builder { protected Throwable cause; protected String message; protected Boolean writableStackTrace; protected BuilderImpl() { } protected BuilderImpl(SdkException ex) { this.cause = ex.getCause(); this.message = ex.getMessage(); } public Throwable getCause() { return cause; } public void setCause(Throwable cause) { this.cause = cause; } @Override public Builder cause(Throwable cause) { this.cause = cause; return this; } @Override public Throwable cause() { return cause; } public String getMessage() { return message; } @Override public Builder message(String message) { this.message = message; return this; } public void setMessage(String message) { this.message = message; } @Override public String message() { return message; } @Override public Builder writableStackTrace(Boolean writableStackTrace) { this.writableStackTrace = writableStackTrace; return this; } public void setWritableStackTrace(Boolean writableStackTrace) { this.writableStackTrace = writableStackTrace; } @Override public Boolean writableStackTrace() { return writableStackTrace; } public Boolean getWritableStackTrace() { return writableStackTrace; } @Override public SdkException build() { return new SdkException(this); } } }
2,061
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/exception/AbortedException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.exception; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Extension of {@link SdkClientException} that is thrown whenever an * operation has been aborted by the SDK. * * This exception is not meant to be retried. */ @SdkPublicApi public final class AbortedException extends SdkClientException { private AbortedException(Builder b) { super(b); } public static AbortedException create(String message) { return builder().message(message).build(); } public static AbortedException create(String message, Throwable cause) { return builder().message(message).cause(cause).build(); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder extends SdkClientException.Builder { @Override Builder message(String message); @Override Builder cause(Throwable cause); @Override Builder writableStackTrace(Boolean writableStackTrace); @Override AbortedException build(); } protected static final class BuilderImpl extends SdkClientException.BuilderImpl implements Builder { protected BuilderImpl() { } protected BuilderImpl(AbortedException ex) { super(ex); } @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 AbortedException build() { return new AbortedException(this); } } }
2,062
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/exception/RetryableException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.exception; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Extension of {@link SdkException} that can be used by clients to * explicitly have an exception retried. This exception will never be * thrown by the SDK unless explicitly used by the client. * * See {@link NonRetryableException} for marking non-retryable exceptions. */ @SdkPublicApi public final class RetryableException extends SdkClientException { protected RetryableException(Builder b) { super(b); } public static RetryableException create(String message) { return builder().message(message).build(); } public static RetryableException create(String message, Throwable cause) { return builder().message(message).cause(cause).build(); } @Override public boolean retryable() { return true; } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder extends SdkClientException.Builder { @Override Builder message(String message); @Override Builder cause(Throwable cause); @Override Builder writableStackTrace(Boolean writableStackTrace); @Override RetryableException build(); } protected static final class BuilderImpl extends SdkClientException.BuilderImpl implements Builder { protected BuilderImpl() { } protected BuilderImpl(RetryableException ex) { super(ex); } @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 RetryableException build() { return new RetryableException(this); } } }
2,063
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/exception/Crc32MismatchException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.exception; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Extension of {@link SdkClientException} that is thrown whenever the * client-side computed CRC32 does not match the server-side computed CRC32. */ @SdkPublicApi public final class Crc32MismatchException extends SdkClientException { private static final long serialVersionUID = 1L; /** * Creates a new CRC32MismatchException with the specified message. */ protected Crc32MismatchException(Builder b) { super(b); } public static Crc32MismatchException create(String message, Throwable cause) { return builder().message(message).cause(cause).build(); } @Override public boolean retryable() { return true; } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder extends SdkClientException.Builder { @Override Builder message(String message); @Override Builder cause(Throwable cause); @Override Builder writableStackTrace(Boolean writableStackTrace); @Override Crc32MismatchException build(); } protected static final class BuilderImpl extends SdkClientException.BuilderImpl implements Builder { protected BuilderImpl() { } protected BuilderImpl(Crc32MismatchException ex) { super(ex); } @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 Crc32MismatchException build() { return new Crc32MismatchException(this); } } }
2,064
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/exception/ApiCallTimeoutException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.exception; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; /** * Signals that an api call could not complete within the specified timeout. * * @see ClientOverrideConfiguration#apiCallTimeout() */ @SdkPublicApi public final class ApiCallTimeoutException extends SdkClientException { private static final long serialVersionUID = 1L; private ApiCallTimeoutException(Builder b) { super(b); } public static ApiCallTimeoutException create(long timeout) { return builder().message(String.format("Client execution did not complete before the specified timeout configuration: " + "%s millis", timeout)) .build(); } public static ApiCallTimeoutException create(String message, Throwable cause) { return builder().message(message).cause(cause).build(); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder extends SdkClientException.Builder { @Override Builder message(String message); @Override Builder cause(Throwable cause); @Override Builder writableStackTrace(Boolean writableStackTrace); @Override ApiCallTimeoutException build(); } protected static final class BuilderImpl extends SdkClientException.BuilderImpl implements Builder { protected BuilderImpl() { } protected BuilderImpl(ApiCallTimeoutException ex) { super(ex); } @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 ApiCallTimeoutException build() { return new ApiCallTimeoutException(this); } } }
2,065
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/exception/SdkClientException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.exception; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting; /** * Base type for all client exceptions thrown by the SDK. * * This exception is thrown when service could not be contacted for a response, * or when client is unable to parse the response from service. * <p> * Exceptions that extend {@link SdkClientException} are assumed to be not retryable, with a few exceptions: * <ul> * <li>{@link RetryableException} - usable when calls should explicitly be retried</li> * <li>Exceptions mentioned as a retryable exception in {@link SdkDefaultRetrySetting}</li> * </ul> * * @see SdkServiceException */ @SdkPublicApi public class SdkClientException extends SdkException { protected SdkClientException(Builder b) { super(b); } public static SdkClientException create(String message) { return SdkClientException.builder().message(message).build(); } public static SdkClientException create(String message, Throwable cause) { return SdkClientException.builder().message(message).cause(cause).build(); } /** * Create a {@link Builder} initialized with the properties of this {@code SdkClientException}. * * @return A new builder initialized with this config's properties. */ @Override public Builder toBuilder() { return new BuilderImpl(this); } /** * @return {@link Builder} instance to construct a new {@link SdkClientException}. */ public static Builder builder() { return new BuilderImpl(); } public interface Builder extends SdkException.Builder { @Override Builder message(String message); @Override Builder cause(Throwable cause); @Override Builder writableStackTrace(Boolean writableStackTrace); @Override SdkClientException build(); } protected static class BuilderImpl extends SdkException.BuilderImpl implements Builder { protected BuilderImpl() { } protected BuilderImpl(SdkClientException ex) { super(ex); } @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 SdkClientException build() { return new SdkClientException(this); } } }
2,066
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/exception/ApiCallAttemptTimeoutException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.exception; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; /** * Signals that an api call attempt could not complete within the specified timeout. * * @see ClientOverrideConfiguration#apiCallAttemptTimeout() */ @SdkPublicApi public final class ApiCallAttemptTimeoutException extends SdkClientException { private static final long serialVersionUID = 1L; private ApiCallAttemptTimeoutException(Builder b) { super(b); } public static ApiCallAttemptTimeoutException create(long timeout) { return builder().message(String.format("HTTP request execution did not complete before the specified timeout " + "configuration: %s millis", timeout)) .build(); } public static ApiCallAttemptTimeoutException create(String message, Throwable cause) { return builder().message(message).cause(cause).build(); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder extends SdkClientException.Builder { @Override Builder message(String message); @Override Builder cause(Throwable cause); @Override Builder writableStackTrace(Boolean writableStackTrace); @Override ApiCallAttemptTimeoutException build(); } protected static final class BuilderImpl extends SdkClientException.BuilderImpl implements Builder { protected BuilderImpl() { } protected BuilderImpl(ApiCallAttemptTimeoutException ex) { super(ex); } @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 ApiCallAttemptTimeoutException build() { return new ApiCallAttemptTimeoutException(this); } } }
2,067
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/handler/AsyncClientHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.handler; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Client interface to invoke an API. */ @SdkProtectedApi public interface AsyncClientHandler extends SdkAutoCloseable { /** * Execute's a web service request. Handles marshalling and unmarshalling of data and making the * underlying HTTP call(s). * * @param executionParams Parameters specific to this invocation of an API. * @param <InputT> Input POJO type * @param <OutputT> Output POJO type * @return Unmarshalled output POJO type. */ <InputT extends SdkRequest, OutputT extends SdkResponse> CompletableFuture<OutputT> execute( ClientExecutionParams<InputT, OutputT> executionParams); /** * Execute's a streaming web service request. Handles marshalling and unmarshalling of data and making the * underlying HTTP call(s). * * @param executionParams Parameters specific to this invocation of an API. * @param asyncResponseTransformer Response handler to consume streaming data in an asynchronous fashion. * @param <InputT> Input POJO type * @param <OutputT> Output POJO type * @param <ReturnT> Transformed result returned by asyncResponseTransformer. * @return CompletableFuture containing transformed result type as returned by asyncResponseTransformer. */ <InputT extends SdkRequest, OutputT extends SdkResponse, ReturnT> CompletableFuture<ReturnT> execute( ClientExecutionParams<InputT, OutputT> executionParams, AsyncResponseTransformer<OutputT, ReturnT> asyncResponseTransformer); }
2,068
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/handler/SdkAsyncClientHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.handler; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOptionValidation; import software.amazon.awssdk.core.internal.handler.BaseAsyncClientHandler; import software.amazon.awssdk.core.internal.http.AmazonAsyncHttpClient; /** * Default implementation of {@link AsyncClientHandler}. */ @Immutable @ThreadSafe @SdkProtectedApi public class SdkAsyncClientHandler extends BaseAsyncClientHandler implements AsyncClientHandler { public SdkAsyncClientHandler(SdkClientConfiguration clientConfiguration) { super(clientConfiguration, new AmazonAsyncHttpClient(clientConfiguration)); SdkClientOptionValidation.validateAsyncClientOptions(clientConfiguration); } }
2,069
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/handler/SdkSyncClientHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.handler; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOptionValidation; import software.amazon.awssdk.core.internal.handler.BaseSyncClientHandler; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.sync.ResponseTransformer; /** * Client handler for SDK clients. */ @ThreadSafe @Immutable @SdkProtectedApi public class SdkSyncClientHandler extends BaseSyncClientHandler implements SyncClientHandler { protected SdkSyncClientHandler(SdkClientConfiguration clientConfiguration) { super(clientConfiguration, new AmazonSyncHttpClient(clientConfiguration)); SdkClientOptionValidation.validateSyncClientOptions(clientConfiguration); } @Override public <InputT extends SdkRequest, OutputT extends SdkResponse> OutputT execute( ClientExecutionParams<InputT, OutputT> executionParams) { return super.execute(executionParams); } @Override public <InputT extends SdkRequest, OutputT extends SdkResponse, ReturnT> ReturnT execute( ClientExecutionParams<InputT, OutputT> executionParams, ResponseTransformer<OutputT, ReturnT> responseTransformer) { return super.execute(executionParams, responseTransformer); } }
2,070
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/handler/ClientExecutionParams.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.handler; import java.net.URI; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.CredentialType; import software.amazon.awssdk.core.Response; import software.amazon.awssdk.core.SdkProtocolMetadata; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.runtime.transform.Marshaller; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.metrics.MetricCollector; /** * Encapsulates parameters needed for a particular API call. Captures input and output pojo types. * * @param <InputT> Input POJO type. * @param <OutputT> Output POJO type. */ @SdkProtectedApi @NotThreadSafe public final class ClientExecutionParams<InputT extends SdkRequest, OutputT> { private InputT input; private RequestBody requestBody; private AsyncRequestBody asyncRequestBody; private Marshaller<InputT> marshaller; private HttpResponseHandler<OutputT> responseHandler; private HttpResponseHandler<? extends SdkException> errorResponseHandler; private HttpResponseHandler<Response<OutputT>> combinedResponseHandler; private boolean fullDuplex; private boolean hasInitialRequestEvent; private String hostPrefixExpression; private String operationName; private SdkProtocolMetadata protocolMetadata; private URI discoveredEndpoint; private CredentialType credentialType; private MetricCollector metricCollector; private final ExecutionAttributes attributes = new ExecutionAttributes(); private SdkClientConfiguration requestConfiguration; public Marshaller<InputT> getMarshaller() { return marshaller; } public ClientExecutionParams<InputT, OutputT> withMarshaller(Marshaller<InputT> marshaller) { this.marshaller = marshaller; return this; } public InputT getInput() { return input; } public ClientExecutionParams<InputT, OutputT> withInput(InputT input) { this.input = input; return this; } public HttpResponseHandler<OutputT> getResponseHandler() { return responseHandler; } public ClientExecutionParams<InputT, OutputT> withResponseHandler( HttpResponseHandler<OutputT> responseHandler) { this.responseHandler = responseHandler; return this; } public HttpResponseHandler<? extends SdkException> getErrorResponseHandler() { return errorResponseHandler; } public ClientExecutionParams<InputT, OutputT> withErrorResponseHandler( HttpResponseHandler<? extends SdkException> errorResponseHandler) { this.errorResponseHandler = errorResponseHandler; return this; } /** * Non-streaming requests can use handlers that handle both error and success as a single handler instead of * submitting individual success and error handlers. This allows the protocol to have more control over how to * determine success and failure from a given HTTP response. This handler is mutually exclusive to * {@link #getResponseHandler()} and {@link #getErrorResponseHandler()} and an exception will be thrown if this * constraint is violated. */ public HttpResponseHandler<Response<OutputT>> getCombinedResponseHandler() { return combinedResponseHandler; } public ClientExecutionParams<InputT, OutputT> withCombinedResponseHandler( HttpResponseHandler<Response<OutputT>> combinedResponseHandler) { this.combinedResponseHandler = combinedResponseHandler; return this; } public RequestBody getRequestBody() { return requestBody; } public ClientExecutionParams<InputT, OutputT> withRequestBody(RequestBody requestBody) { this.requestBody = requestBody; return this; } public AsyncRequestBody getAsyncRequestBody() { return asyncRequestBody; } public ClientExecutionParams<InputT, OutputT> withAsyncRequestBody(AsyncRequestBody asyncRequestBody) { this.asyncRequestBody = asyncRequestBody; return this; } public boolean isFullDuplex() { return fullDuplex; } /** * Sets whether the API is a full duplex ie, request and response are streamed in parallel. */ public ClientExecutionParams<InputT, OutputT> withFullDuplex(boolean fullDuplex) { this.fullDuplex = fullDuplex; return this; } public boolean hasInitialRequestEvent() { return hasInitialRequestEvent; } /** * Sets whether this is an event streaming request over RPC. */ public ClientExecutionParams<InputT, OutputT> withInitialRequestEvent(boolean hasInitialRequestEvent) { this.hasInitialRequestEvent = hasInitialRequestEvent; return this; } public String getOperationName() { return operationName; } /** * Sets the operation name of the API. */ public ClientExecutionParams<InputT, OutputT> withOperationName(String operationName) { this.operationName = operationName; return this; } public SdkProtocolMetadata getProtocolMetadata() { return protocolMetadata; } /** * Sets the protocol metadata of the API. */ public ClientExecutionParams<InputT, OutputT> withProtocolMetadata(SdkProtocolMetadata protocolMetadata) { this.protocolMetadata = protocolMetadata; return this; } public String hostPrefixExpression() { return hostPrefixExpression; } /** * Sets the resolved host prefix expression that will be added as a prefix to the original endpoint. * This value is present only if the operation is tagged with endpoint trait. */ public ClientExecutionParams<InputT, OutputT> hostPrefixExpression(String hostPrefixExpression) { this.hostPrefixExpression = hostPrefixExpression; return this; } public URI discoveredEndpoint() { return discoveredEndpoint; } public ClientExecutionParams<InputT, OutputT> discoveredEndpoint(URI discoveredEndpoint) { this.discoveredEndpoint = discoveredEndpoint; return this; } public CredentialType credentialType() { return credentialType; } public ClientExecutionParams<InputT, OutputT> credentialType(CredentialType credentialType) { this.credentialType = credentialType; return this; } public ClientExecutionParams<InputT, OutputT> withMetricCollector(MetricCollector metricCollector) { this.metricCollector = metricCollector; return this; } public <T> ClientExecutionParams<InputT, OutputT> putExecutionAttribute(ExecutionAttribute<T> attribute, T value) { this.attributes.putAttribute(attribute, value); return this; } public ExecutionAttributes executionAttributes() { return attributes; } public MetricCollector getMetricCollector() { return metricCollector; } public SdkClientConfiguration requestConfiguration() { return requestConfiguration; } public <T> ClientExecutionParams<InputT, OutputT> withRequestConfiguration(SdkClientConfiguration requestConfiguration) { this.requestConfiguration = requestConfiguration; return this; } }
2,071
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/handler/SyncClientHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.handler; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Client interface to invoke an API. */ @SdkProtectedApi public interface SyncClientHandler extends SdkAutoCloseable { /** * Execute's a web service request. Handles marshalling and unmarshalling of data and making the * underlying HTTP call(s). * * @param executionParams Parameters specific to this invocation of an API. * @param <InputT> Input POJO type * @param <OutputT> Output POJO type * @return Unmarshalled output POJO type. */ <InputT extends SdkRequest, OutputT extends SdkResponse> OutputT execute( ClientExecutionParams<InputT, OutputT> executionParams); /** * Execute's a streaming web service request. Handles marshalling and unmarshalling of data and making the * underlying HTTP call(s). * * @param executionParams Parameters specific to this invocation of an API. * @param responseTransformer Response handler for a streaming response. Receives unmarshalled POJO and input stream and * returns a transformed result. * @param <InputT> Input POJO type * @param <OutputT> Output POJO type * @param <ReturnT> Transformed result returned by responseTransformer. Returned by this method. * @return Transformed result as returned by responseTransformer. */ <InputT extends SdkRequest, OutputT extends SdkResponse, ReturnT> ReturnT execute( ClientExecutionParams<InputT, OutputT> executionParams, ResponseTransformer<OutputT, ReturnT> responseTransformer); }
2,072
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/handler/AttachHttpMetadataResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.handler; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; /** * Decorate {@link HttpResponseHandler} to attach {@link SdkHttpResponse} to the response object. */ @SdkProtectedApi public final class AttachHttpMetadataResponseHandler<T extends SdkResponse> implements HttpResponseHandler<T> { private final HttpResponseHandler<T> delegate; public AttachHttpMetadataResponseHandler(HttpResponseHandler<T> delegate) { this.delegate = delegate; } @Override @SuppressWarnings("unchecked") public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { return (T) delegate.handle(response, executionAttributes) .toBuilder() .sdkHttpResponse(response) .build(); } }
2,073
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/config/ClientOverrideConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.config; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static software.amazon.awssdk.core.client.config.SdkClientOption.ADDITIONAL_HTTP_HEADERS; import static software.amazon.awssdk.core.client.config.SdkClientOption.API_CALL_ATTEMPT_TIMEOUT; import static software.amazon.awssdk.core.client.config.SdkClientOption.API_CALL_TIMEOUT; import static software.amazon.awssdk.core.client.config.SdkClientOption.COMPRESSION_CONFIGURATION; import static software.amazon.awssdk.core.client.config.SdkClientOption.CONFIGURED_COMPRESSION_CONFIGURATION; import static software.amazon.awssdk.core.client.config.SdkClientOption.CONFIGURED_SCHEDULED_EXECUTOR_SERVICE; import static software.amazon.awssdk.core.client.config.SdkClientOption.EXECUTION_ATTRIBUTES; import static software.amazon.awssdk.core.client.config.SdkClientOption.EXECUTION_INTERCEPTORS; import static software.amazon.awssdk.core.client.config.SdkClientOption.METRIC_PUBLISHERS; import static software.amazon.awssdk.core.client.config.SdkClientOption.PROFILE_FILE_SUPPLIER; import static software.amazon.awssdk.core.client.config.SdkClientOption.PROFILE_NAME; import static software.amazon.awssdk.core.client.config.SdkClientOption.RETRY_POLICY; import static software.amazon.awssdk.core.client.config.SdkClientOption.SCHEDULED_EXECUTOR_SERVICE; import static software.amazon.awssdk.utils.ScheduledExecutorUtils.unmanagedScheduledExecutor; import static software.amazon.awssdk.utils.ScheduledExecutorUtils.unwrapUnmanagedScheduledExecutor; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Consumer; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ToBuilderIgnoreField; import software.amazon.awssdk.core.CompressionConfiguration; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.core.SdkPlugin; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSupplier; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Configuration values for which the client already provides sensible defaults. All values are optional, and not specifying them * will use optimal values defined by the service itself. * * <p>Use {@link #builder()} to create a set of options.</p> */ @SdkPublicApi public final class ClientOverrideConfiguration implements ToCopyableBuilder<ClientOverrideConfiguration.Builder, ClientOverrideConfiguration> { /** * The set of options modified by this ClientOverrideConfiguration. This is used when the ClientOverrideConfiguration * is created from a {@link SdkClientConfiguration} to filter out properties that this object doesn't use. * * This is important so that unrelated configuration values don't "pass through" from when this object is created * from a SdkClientConfiguration and then converted back. */ private static final Set<ClientOption<?>> CLIENT_OVERRIDE_OPTIONS; /** * The set of options that can be visible from this ClientOverrideConfiguration, but can't be modified directly. For * example, when this ClientOverrideConfiguration is created from an SdkClientConfiguration, we want the * {@link SdkClientOption#COMPRESSION_CONFIGURATION} to be visible to {@link #compressionConfiguration()} even though * the setting that this object manipulates is {@link SdkClientOption#CONFIGURED_COMPRESSION_CONFIGURATION}. * * In practice, this means that when we create a ClientOverrideConfiguration from a SdkClientConfiguration, these * values can be read by users of the ClientOverrideConfiguration, but these values won't be included in the result * of {@link #asSdkClientConfiguration()}. */ private static final Set<ClientOption<?>> RESOLVED_OPTIONS; static { Set<ClientOption<?>> options = new HashSet<>(); options.add(ADDITIONAL_HTTP_HEADERS); options.add(EXECUTION_INTERCEPTORS); options.add(METRIC_PUBLISHERS); options.add(EXECUTION_ATTRIBUTES); options.add(CONFIGURED_COMPRESSION_CONFIGURATION); options.add(CONFIGURED_SCHEDULED_EXECUTOR_SERVICE); options.add(RETRY_POLICY); options.add(API_CALL_TIMEOUT); options.add(API_CALL_ATTEMPT_TIMEOUT); options.add(PROFILE_FILE_SUPPLIER); options.add(PROFILE_NAME); CLIENT_OVERRIDE_OPTIONS = Collections.unmodifiableSet(options); Set<ClientOption<?>> resolvedOptions = new HashSet<>(); resolvedOptions.add(COMPRESSION_CONFIGURATION); resolvedOptions.add(SCHEDULED_EXECUTOR_SERVICE); RESOLVED_OPTIONS = Collections.unmodifiableSet(resolvedOptions); } private final SdkClientConfiguration config; private final SdkClientConfiguration resolvedConfig; private final Map<String, List<String>> headers; private final List<ExecutionInterceptor> executionInterceptors; private final List<MetricPublisher> metricPublishers; private final ExecutionAttributes executionAttributes; /** * Initialize this configuration. Private to require use of {@link #builder()}. */ @SdkInternalApi ClientOverrideConfiguration(SdkClientConfiguration config, SdkClientConfiguration resolvedConfig) { this.config = config; this.resolvedConfig = resolvedConfig; // Store separately any mutable types, so that modifications to the underlying option (e.g. from the builder) would not // be visible to users of this configuration Map<String, List<String>> headers = config.option(ADDITIONAL_HTTP_HEADERS); this.headers = headers == null ? emptyMap() : CollectionUtils.deepUnmodifiableMap(headers, () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); List<ExecutionInterceptor> interceptors = config.option(EXECUTION_INTERCEPTORS); this.executionInterceptors = interceptors == null ? emptyList() : Collections.unmodifiableList(new ArrayList<>(interceptors)); List<MetricPublisher> metricPublishers = config.option(METRIC_PUBLISHERS); this.metricPublishers = metricPublishers == null ? emptyList() : Collections.unmodifiableList(new ArrayList<>(metricPublishers)); ExecutionAttributes executionAttributes = config.option(EXECUTION_ATTRIBUTES); this.executionAttributes = executionAttributes == null ? new ExecutionAttributes() : ExecutionAttributes.unmodifiableExecutionAttributes(executionAttributes); Validate.isPositiveOrNull(apiCallTimeout().orElse(null), "apiCallTimeout"); Validate.isPositiveOrNull(apiCallAttemptTimeout().orElse(null), "apiCallAttemptTimeout"); } @Override @ToBuilderIgnoreField({"config", "resolvedConfig"}) public Builder toBuilder() { return new DefaultBuilder(this.config.toBuilder(), this.resolvedConfig.toBuilder()) .headers(headers) .executionInterceptors(executionInterceptors) .executionAttributes(executionAttributes) .metricPublishers(metricPublishers); } /** * Create a {@link Builder}, used to create a {@link ClientOverrideConfiguration}. */ public static Builder builder() { return new DefaultBuilder(); } @SdkInternalApi SdkClientConfiguration asSdkClientConfiguration() { return config; } /** * An unmodifiable representation of the set of HTTP headers that should be sent with every request. * * <p> * If not set, this will return an empty map. * * @see Builder#headers(Map) */ public Map<String, List<String>> headers() { return headers; } /** * The optional retry policy that should be used when handling failure cases. * * @see Builder#retryPolicy(RetryPolicy) */ public Optional<RetryPolicy> retryPolicy() { return Optional.ofNullable(config.option(RETRY_POLICY)); } /** * Load the optional requested advanced option that was configured on the client builder. * * @see Builder#putAdvancedOption(SdkAdvancedClientOption, Object) */ public <T> Optional<T> advancedOption(SdkAdvancedClientOption<T> option) { return Optional.ofNullable(config.option(option)); } /** * An immutable collection of {@link ExecutionInterceptor}s that should be hooked into the execution of each request, in the * order that they should be applied. * */ public List<ExecutionInterceptor> executionInterceptors() { return executionInterceptors; } /** * The optional scheduled executor service that should be used for scheduling tasks such as async retry attempts * and timeout task. * <p> * <b>The SDK will not automatically close the executor when the client is closed. It is the responsibility of the * user to manually close the executor once all clients utilizing it have been closed.</b> */ public Optional<ScheduledExecutorService> scheduledExecutorService() { // If the client override configuration is accessed from a plugin or a client, we want the actual executor service we're // using to be available. For that reason, we should check the SCHEDULED_EXECUTOR_SERVICE. ScheduledExecutorService scheduledExecutorService = resolvedConfig.option(SCHEDULED_EXECUTOR_SERVICE); if (scheduledExecutorService == null) { // Unwrap the executor to ensure that read-after-write returns the same values. scheduledExecutorService = unwrapUnmanagedScheduledExecutor(config.option(CONFIGURED_SCHEDULED_EXECUTOR_SERVICE)); } return Optional.ofNullable(scheduledExecutorService); } /** * The amount of time to allow the client to complete the execution of an API call. This timeout covers the entire client * execution except for marshalling. This includes request handler execution, all HTTP requests including retries, * unmarshalling, etc. This value should always be positive, if present. * * <p>The api call timeout feature doesn't have strict guarantees on how quickly a request is aborted when the * timeout is breached. The typical case aborts the request within a few milliseconds but there may occasionally be * requests that don't get aborted until several seconds after the timer has been breached. Because of this, the client * execution timeout feature should not be used when absolute precision is needed. * * <p>This may be used together with {@link #apiCallAttemptTimeout()} to enforce both a timeout on each individual HTTP * request (i.e. each retry) and the total time spent on all requests across retries (i.e. the 'api call' time). * * @see Builder#apiCallTimeout(Duration) */ public Optional<Duration> apiCallTimeout() { return Optional.ofNullable(config.option(API_CALL_TIMEOUT)); } /** * The amount of time to wait for the http request to complete before giving up and timing out. This value should always be * positive, if present. * * <p>The request timeout feature doesn't have strict guarantees on how quickly a request is aborted when the timeout is * breached. The typical case aborts the request within a few milliseconds but there may occasionally be requests that * don't get aborted until several seconds after the timer has been breached. Because of this, the request timeout * feature should not be used when absolute precision is needed. * * <p>This may be used together with {@link #apiCallTimeout()} to enforce both a timeout on each individual HTTP * request * (i.e. each retry) and the total time spent on all requests across retries (i.e. the 'api call' time). * * @see Builder#apiCallAttemptTimeout(Duration) */ public Optional<Duration> apiCallAttemptTimeout() { return Optional.ofNullable(config.option(API_CALL_ATTEMPT_TIMEOUT)); } /** * The profile file supplier that should be used by default for all profile-based configuration in the SDK client. * * @see Builder#defaultProfileFileSupplier(Supplier) */ public Optional<Supplier<ProfileFile>> defaultProfileFileSupplier() { return Optional.ofNullable(config.option(PROFILE_FILE_SUPPLIER)); } /** * The profile file that should be used by default for all profile-based configuration in the SDK client. * * @see Builder#defaultProfileFile(ProfileFile) */ public Optional<ProfileFile> defaultProfileFile() { return Optional.ofNullable(config.option(PROFILE_FILE_SUPPLIER)).map(Supplier::get); } /** * The profile name that should be used by default for all profile-based configuration in the SDK client. * * @see Builder#defaultProfileName(String) */ public Optional<String> defaultProfileName() { return Optional.ofNullable(config.option(PROFILE_NAME)); } /** * The metric publishers to use to publisher metrics collected for this client. * * @return The metric publisher. */ public List<MetricPublisher> metricPublishers() { return metricPublishers; } /** * Returns the additional execution attributes to be added for this client. * * @Return Map of execution attributes. */ public ExecutionAttributes executionAttributes() { return executionAttributes; } /** * The compression configuration object, which includes options to enable/disable compression and set the minimum * compression threshold. * * @see Builder#compressionConfiguration(CompressionConfiguration) */ public Optional<CompressionConfiguration> compressionConfiguration() { // If the client override configuration is accessed from a plugin or a client, we want the compression configuration // we're using to be available. For that reason, we should check the COMPRESSION_CONFIGURATION. CompressionConfiguration compressionConfig = resolvedConfig.option(COMPRESSION_CONFIGURATION); if (compressionConfig == null) { compressionConfig = config.option(CONFIGURED_COMPRESSION_CONFIGURATION); } return Optional.ofNullable(compressionConfig); } @Override public String toString() { return ToString.builder("ClientOverrideConfiguration") .add("headers", headers()) .add("retryPolicy", retryPolicy().orElse(null)) .add("apiCallTimeout", apiCallTimeout().orElse(null)) .add("apiCallAttemptTimeout", apiCallAttemptTimeout().orElse(null)) .add("executionInterceptors", executionInterceptors()) .add("profileFileSupplier", defaultProfileFileSupplier().orElse(null)) .add("profileFile", defaultProfileFile().orElse(null)) .add("profileName", defaultProfileName().orElse(null)) .add("scheduledExecutorService", scheduledExecutorService().orElse(null)) .add("compressionConfiguration", compressionConfiguration().orElse(null)) .build(); } /** * A builder for {@link ClientOverrideConfiguration}. * * <p>All implementations of this interface are mutable and not thread safe.</p> */ public interface Builder extends CopyableBuilder<Builder, ClientOverrideConfiguration> { /** * Add a single header to be set on the HTTP request. * <p> * This overrides any values for the given header set on the request by default by the SDK. * * <p> * This overrides any values already configured with this header name in the builder. * * @param name The name of the header. * @param value The value of the header. * @return This object for method chaining. */ default Builder putHeader(String name, String value) { putHeader(name, Collections.singletonList(value)); return this; } /** * Add a single header with multiple values to be set on the HTTP request. * <p> * This overrides any values for the given header set on the request by default by the SDK. * * <p> * This overrides any values already configured with this header name in the builder. * * @param name The name of the header. * @param values The values of the header. * @return This object for method chaining. */ Builder putHeader(String name, List<String> values); /** * Configure headers to be set on the HTTP request. * <p> * This overrides any values for the given headers set on the request by default by the SDK. * * <p> * This overrides any values currently configured in the builder. * * @param headers The set of additional headers. * @return This object for method chaining. */ Builder headers(Map<String, List<String>> headers); Map<String, List<String>> headers(); /** * Configure the retry policy that should be used when handling failure cases. * * @see ClientOverrideConfiguration#retryPolicy() */ Builder retryPolicy(RetryPolicy retryPolicy); /** * Configure the retry policy the should be used when handling failure cases. */ default Builder retryPolicy(Consumer<RetryPolicy.Builder> retryPolicy) { return retryPolicy(RetryPolicy.builder().applyMutation(retryPolicy).build()); } /** * Configure the retry mode used to determine the retry policy that is used when handling failure cases. This is * shorthand for {@code retryPolicy(RetryPolicy.forRetryMode(retryMode))}, and overrides any configured retry policy on * this builder. */ default Builder retryPolicy(RetryMode retryMode) { return retryPolicy(RetryPolicy.forRetryMode(retryMode)); } RetryPolicy retryPolicy(); /** * Configure a list of execution interceptors that will have access to read and modify the request and response objcets as * they are processed by the SDK. These will replace any interceptors configured previously with this method or * {@link #addExecutionInterceptor(ExecutionInterceptor)}. * * <p> * The provided interceptors are executed in the order they are configured and are always later in the order than the ones * automatically added by the SDK. See {@link ExecutionInterceptor} for a more detailed explanation of interceptor order. * * <p> * This overrides any values currently configured in the builder. * * @see ClientOverrideConfiguration#executionInterceptors() */ Builder executionInterceptors(List<ExecutionInterceptor> executionInterceptors); /** * Add an execution interceptor that will have access to read and modify the request and response objects as they are * processed by the SDK. * * <p> * Interceptors added using this method are executed in the order they are configured and are always later in the order * than the ones automatically added by the SDK. See {@link ExecutionInterceptor} for a more detailed explanation of * interceptor order. * * @see ClientOverrideConfiguration#executionInterceptors() */ Builder addExecutionInterceptor(ExecutionInterceptor executionInterceptor); List<ExecutionInterceptor> executionInterceptors(); /** * Configure the scheduled executor service that should be used for scheduling tasks such as async retry attempts * and timeout task. * * <p> * <b>The SDK will not automatically close the executor when the client is closed. It is the responsibility of the * user to manually close the executor once all clients utilizing it have been closed.</b> * * <p> * When modifying this option from an {@link SdkPlugin}, it is strongly recommended to decorate the * {@link #scheduledExecutorService()}. If you will be replacing it entirely, you MUST shut it down to prevent the * resources being leaked. * * @see ClientOverrideConfiguration#scheduledExecutorService() */ Builder scheduledExecutorService(ScheduledExecutorService scheduledExecutorService); ScheduledExecutorService scheduledExecutorService(); /** * Configure an advanced override option. These values are used very rarely, and the majority of SDK customers can ignore * them. * * @param option The option to configure. * @param value The value of the option. * @param <T> The type of the option. */ <T> Builder putAdvancedOption(SdkAdvancedClientOption<T> option, T value); /** * Configure the map of advanced override options. This will override all values currently configured. The values in the * map must match the key type of the map, or a runtime exception will be raised. */ Builder advancedOptions(Map<SdkAdvancedClientOption<?>, ?> advancedOptions); AttributeMap advancedOptions(); /** * Configure the amount of time to allow the client to complete the execution of an API call. This timeout covers the * entire client execution except for marshalling. This includes request handler execution, all HTTP requests including * retries, unmarshalling, etc. This value should always be positive, if present. * * <p>The api call timeout feature doesn't have strict guarantees on how quickly a request is aborted when the * timeout is breached. The typical case aborts the request within a few milliseconds but there may occasionally be * requests that don't get aborted until several seconds after the timer has been breached. Because of this, the client * execution timeout feature should not be used when absolute precision is needed. * * <p> * For synchronous streaming operations, implementations of {@link ResponseTransformer} must handle interrupt * properly to allow the the SDK to timeout the request in a timely manner. * * <p>This may be used together with {@link #apiCallAttemptTimeout()} to enforce both a timeout on each individual HTTP * request (i.e. each retry) and the total time spent on all requests across retries (i.e. the 'api call' time). * * <p> * You can also configure it on a per-request basis via * {@link RequestOverrideConfiguration.Builder#apiCallTimeout(Duration)}. * Note that request-level timeout takes precedence. * * @see ClientOverrideConfiguration#apiCallTimeout() */ Builder apiCallTimeout(Duration apiCallTimeout); Duration apiCallTimeout(); /** * Configure the amount of time to wait for the http request to complete before giving up and timing out. This value * should always be positive, if present. * * <p>The request timeout feature doesn't have strict guarantees on how quickly a request is aborted when the timeout is * breached. The typical case aborts the request within a few milliseconds but there may occasionally be requests that * don't get aborted until several seconds after the timer has been breached. Because of this, the api call attempt * timeout feature should not be used when absolute precision is needed. * * <p>For synchronous streaming operations, the process in {@link ResponseTransformer} is not timed and will not * be aborted. * * <p>This may be used together with {@link #apiCallTimeout()} to enforce both a timeout on each individual HTTP * request (i.e. each retry) and the total time spent on all requests across retries (i.e. the 'api call' time). * * <p> * You can also configure it on a per-request basis via * {@link RequestOverrideConfiguration.Builder#apiCallAttemptTimeout(Duration)}. * Note that request-level timeout takes precedence. * * @see ClientOverrideConfiguration#apiCallAttemptTimeout() */ Builder apiCallAttemptTimeout(Duration apiCallAttemptTimeout); Duration apiCallAttemptTimeout(); /** * Configure a {@link ProfileFileSupplier} that should be used by default for all profile-based configuration in the SDK * client. * * <p>This is equivalent to setting {@link #defaultProfileFile(ProfileFile)}, except the supplier is read every time * the configuration is requested. It's recommended to use {@link ProfileFileSupplier} that provides configurable * caching for the reading of the profile file. * * <p>If this is not set, the {@link ProfileFile#defaultProfileFile()} is used. * * @see #defaultProfileFile(ProfileFile) * @see #defaultProfileName(String) */ Builder defaultProfileFileSupplier(Supplier<ProfileFile> defaultProfileFile); Supplier<ProfileFile> defaultProfileFileSupplier(); /** * Configure the profile file that should be used by default for all profile-based configuration in the SDK client. * * <p>This is equivalent to setting the {@link ProfileFileSystemSetting#AWS_CONFIG_FILE} and * {@link ProfileFileSystemSetting#AWS_SHARED_CREDENTIALS_FILE} environment variables or system properties. * * <p>Like the system settings, this value is only used when determining default values. For example, directly configuring * the retry policy, credentials provider or region will mean that the configured values will be used instead of those * from the profile file. * * <p>Like the {@code --profile} setting in the CLI, profile-based configuration loaded from this profile file has lower * priority than more specific environment variables, like the {@code AWS_REGION} environment variable. * * <p>If this is not set, the {@link ProfileFile#defaultProfileFile()} is used. * * @see #defaultProfileFileSupplier(Supplier) * @see #defaultProfileName(String) */ Builder defaultProfileFile(ProfileFile defaultProfileFile); ProfileFile defaultProfileFile(); /** * Configure the profile name that should be used by default for all profile-based configuration in the SDK client. * * <p>This is equivalent to setting the {@link ProfileFileSystemSetting#AWS_PROFILE} environment variable or system * property. * * <p>Like the system setting, this value is only used when determining default values. For example, directly configuring * the retry policy, credentials provider or region will mean that the configured values will be used instead of those * from this profile. * * <p>If this is not set, the {@link ProfileFileSystemSetting#AWS_PROFILE} (or {@code "default"}) is used. * * @see #defaultProfileFile(ProfileFile) */ Builder defaultProfileName(String defaultProfileName); String defaultProfileName(); /** * Set the Metric publishers to be use to publish metrics for this client. This overwrites the current list of * metric publishers set on the builder. * * @param metricPublishers The metric publishers. */ Builder metricPublishers(List<MetricPublisher> metricPublishers); /** * Add a metric publisher to the existing list of previously set publishers to be used for publishing metrics * for this client. * * @param metricPublisher The metric publisher to add. */ Builder addMetricPublisher(MetricPublisher metricPublisher); List<MetricPublisher> metricPublishers(); /** * Sets the additional execution attributes collection for this client. * @param executionAttributes Execution attributes map for this client. * @return This object for method chaining. */ Builder executionAttributes(ExecutionAttributes executionAttributes); /** * Put an execution attribute into to the existing collection of execution attributes. * @param attribute The execution attribute object * @param value The value of the execution attribute. */ <T> Builder putExecutionAttribute(ExecutionAttribute<T> attribute, T value); ExecutionAttributes executionAttributes(); /** * Sets the {@link CompressionConfiguration} for this client. */ Builder compressionConfiguration(CompressionConfiguration compressionConfiguration); /** * Sets the {@link CompressionConfiguration} for this client. */ default Builder compressionConfiguration(Consumer<CompressionConfiguration.Builder> compressionConfiguration) { return compressionConfiguration(CompressionConfiguration.builder() .applyMutation(compressionConfiguration) .build()); } CompressionConfiguration compressionConfiguration(); } /** * An SDK-internal implementation of {@link ClientOverrideConfiguration.Builder}. */ @SdkInternalApi static final class DefaultBuilder implements Builder { private final SdkClientConfiguration.Builder config; private final SdkClientConfiguration.Builder resolvedConfig; @SdkInternalApi DefaultBuilder(SdkClientConfiguration.Builder config) { this(); RESOLVED_OPTIONS.forEach(o -> copyValue(o, config, this.resolvedConfig)); CLIENT_OVERRIDE_OPTIONS.forEach(o -> copyValue(o, config, this.config)); SdkAdvancedClientOption.options().forEach(o -> copyValue(o, config, this.config)); } private DefaultBuilder() { this(SdkClientConfiguration.builder(), SdkClientConfiguration.builder()); } private DefaultBuilder(SdkClientConfiguration.Builder config, SdkClientConfiguration.Builder resolvedConfig) { this.config = config; this.resolvedConfig = resolvedConfig; } @Override public Builder headers(Map<String, List<String>> headers) { Validate.paramNotNull(headers, "headers"); this.config.option(ADDITIONAL_HTTP_HEADERS, CollectionUtils.deepCopyMap(headers, this::newHeaderMap)); return this; } public void setHeaders(Map<String, List<String>> additionalHttpHeaders) { headers(additionalHttpHeaders); } @Override public Map<String, List<String>> headers() { return CollectionUtils.unmodifiableMapOfLists(config.option(ADDITIONAL_HTTP_HEADERS)); } @Override public Builder putHeader(String header, List<String> values) { Validate.paramNotNull(header, "header"); Validate.paramNotNull(values, "values"); config.computeOptionIfAbsent(ADDITIONAL_HTTP_HEADERS, this::newHeaderMap) .put(header, new ArrayList<>(values)); return this; } @Override public Builder retryPolicy(RetryPolicy retryPolicy) { config.option(RETRY_POLICY, retryPolicy); return this; } public void setRetryPolicy(RetryPolicy retryPolicy) { retryPolicy(retryPolicy); } @Override public RetryPolicy retryPolicy() { return config.option(RETRY_POLICY); } @Override public Builder executionInterceptors(List<ExecutionInterceptor> executionInterceptors) { Validate.paramNotNull(executionInterceptors, "executionInterceptors"); config.option(EXECUTION_INTERCEPTORS, new ArrayList<>(executionInterceptors)); return this; } @Override public Builder addExecutionInterceptor(ExecutionInterceptor executionInterceptor) { config.computeOptionIfAbsent(EXECUTION_INTERCEPTORS, ArrayList::new).add(executionInterceptor); return this; } public void setExecutionInterceptors(List<ExecutionInterceptor> executionInterceptors) { executionInterceptors(executionInterceptors); } @Override public List<ExecutionInterceptor> executionInterceptors() { List<ExecutionInterceptor> interceptors = config.option(EXECUTION_INTERCEPTORS); return Collections.unmodifiableList(interceptors == null ? emptyList() : interceptors); } @Override public ScheduledExecutorService scheduledExecutorService() { // If the client override configuration is accessed from a plugin or a client, we want the actual executor service // we're using to be available. For that reason, we should check the SCHEDULED_EXECUTOR_SERVICE. ScheduledExecutorService resolvedExecutor = resolvedConfig.option(SCHEDULED_EXECUTOR_SERVICE); if (resolvedExecutor != null) { return resolvedExecutor; } // Unwrap the unmanaged executor to preserve read-after-write consistency. return unwrapUnmanagedScheduledExecutor(config.option(CONFIGURED_SCHEDULED_EXECUTOR_SERVICE)); } @Override public Builder scheduledExecutorService(ScheduledExecutorService scheduledExecutorService) { // For read-after-write consistency, just remove the SCHEDULED_EXECUTOR_SERVICE when this is set. resolvedConfig.option(SCHEDULED_EXECUTOR_SERVICE, null); config.option(CONFIGURED_SCHEDULED_EXECUTOR_SERVICE, unmanagedScheduledExecutor(scheduledExecutorService)); return this; } @Override public <T> Builder putAdvancedOption(SdkAdvancedClientOption<T> option, T value) { config.option(option, value); return this; } @Override public Builder advancedOptions(Map<SdkAdvancedClientOption<?>, ?> advancedOptions) { SdkAdvancedClientOption.options().forEach(o -> this.config.option(o, null)); this.config.putAll(advancedOptions); return this; } public void setAdvancedOptions(Map<SdkAdvancedClientOption<?>, Object> advancedOptions) { advancedOptions(advancedOptions); } @Override public AttributeMap advancedOptions() { AttributeMap.Builder resultBuilder = AttributeMap.builder(); SdkAdvancedClientOption.options().forEach(o -> setValue(o, resultBuilder)); return resultBuilder.build(); } @Override public Builder apiCallTimeout(Duration apiCallTimeout) { config.option(API_CALL_TIMEOUT, apiCallTimeout); return this; } public void setApiCallTimeout(Duration apiCallTimeout) { apiCallTimeout(apiCallTimeout); } @Override public Duration apiCallTimeout() { return config.option(API_CALL_TIMEOUT); } @Override public Builder apiCallAttemptTimeout(Duration apiCallAttemptTimeout) { config.option(API_CALL_ATTEMPT_TIMEOUT, apiCallAttemptTimeout); return this; } public void setApiCallAttemptTimeout(Duration apiCallAttemptTimeout) { apiCallAttemptTimeout(apiCallAttemptTimeout); } @Override public Duration apiCallAttemptTimeout() { return config.option(API_CALL_ATTEMPT_TIMEOUT); } @Override public Builder defaultProfileFileSupplier(Supplier<ProfileFile> defaultProfileFileSupplier) { config.option(PROFILE_FILE_SUPPLIER, defaultProfileFileSupplier); return this; } @Override public Supplier<ProfileFile> defaultProfileFileSupplier() { return config.option(PROFILE_FILE_SUPPLIER); } @Override public ProfileFile defaultProfileFile() { Supplier<ProfileFile> supplier = defaultProfileFileSupplier(); return supplier == null ? null : supplier.get(); } @Override public Builder defaultProfileFile(ProfileFile defaultProfileFile) { defaultProfileFileSupplier(ProfileFileSupplier.fixedProfileFile(defaultProfileFile)); return this; } @Override public String defaultProfileName() { return config.option(PROFILE_NAME); } @Override public Builder defaultProfileName(String defaultProfileName) { config.option(PROFILE_NAME, defaultProfileName); return this; } @Override public Builder metricPublishers(List<MetricPublisher> metricPublishers) { Validate.paramNotNull(metricPublishers, "metricPublishers"); config.option(METRIC_PUBLISHERS, new ArrayList<>(metricPublishers)); return this; } public void setMetricPublishers(List<MetricPublisher> metricPublishers) { metricPublishers(metricPublishers); } @Override public Builder addMetricPublisher(MetricPublisher metricPublisher) { Validate.paramNotNull(metricPublisher, "metricPublisher"); config.computeOptionIfAbsent(METRIC_PUBLISHERS, ArrayList::new).add(metricPublisher); return this; } @Override public List<MetricPublisher> metricPublishers() { List<MetricPublisher> metricPublishers = config.option(METRIC_PUBLISHERS); return Collections.unmodifiableList(metricPublishers == null ? emptyList() : metricPublishers); } @Override public Builder executionAttributes(ExecutionAttributes executionAttributes) { Validate.paramNotNull(executionAttributes, "executionAttributes"); config.option(EXECUTION_ATTRIBUTES, executionAttributes); return this; } @Override public <T> Builder putExecutionAttribute(ExecutionAttribute<T> executionAttribute, T value) { config.computeOptionIfAbsent(EXECUTION_ATTRIBUTES, ExecutionAttributes::new) .putAttribute(executionAttribute, value); return this; } @Override public ExecutionAttributes executionAttributes() { ExecutionAttributes attributes = config.option(EXECUTION_ATTRIBUTES); return attributes == null ? new ExecutionAttributes() : attributes; } @Override public Builder compressionConfiguration(CompressionConfiguration compressionConfiguration) { // For read-after-write consistency, just remove the COMPRESSION_CONFIGURATION when this is set. resolvedConfig.option(COMPRESSION_CONFIGURATION, null); config.option(CONFIGURED_COMPRESSION_CONFIGURATION, compressionConfiguration); return this; } public void setRequestCompressionEnabled(CompressionConfiguration compressionConfiguration) { compressionConfiguration(compressionConfiguration); } @Override public CompressionConfiguration compressionConfiguration() { // If the client override configuration is accessed from a plugin or a client, we want the actual configuration // we're using to be available. For that reason, we should check the COMPRESSION_CONFIGURATION. CompressionConfiguration resolvedCompressionConfig = resolvedConfig.option(COMPRESSION_CONFIGURATION); if (resolvedCompressionConfig != null) { return resolvedCompressionConfig; } return config.option(CONFIGURED_COMPRESSION_CONFIGURATION); } @Override public ClientOverrideConfiguration build() { return new ClientOverrideConfiguration(config.build(), resolvedConfig.build()); } private Map<String, List<String>> newHeaderMap() { return new TreeMap<>(String.CASE_INSENSITIVE_ORDER); } private <T> void copyValue(ClientOption<T> option, SdkClientConfiguration.Builder src, SdkClientConfiguration.Builder dst) { T value = src.option(option); if (value != null) { dst.option(option, value); } } private <T> void setValue(ClientOption<T> option, AttributeMap.Builder dst) { T value = config.option(option); if (value != null) { dst.put(option, value); } } } }
2,074
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/config/SdkClientConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.config; import static software.amazon.awssdk.core.client.config.SdkClientOption.ENDPOINT_OVERRIDDEN; import static software.amazon.awssdk.core.client.config.SdkClientOption.SIGNER_OVERRIDDEN; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.internal.SdkInternalTestAdvancedClientOption; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A collection of configuration that is required by an AWS client in order to operate. * * Configuration can be set via {@link SdkClientConfiguration.Builder#option(ClientOption, Object)} and checked via * {@link SdkClientConfiguration#option(ClientOption)}. * * This configuration can be merged with other configuration using {@link SdkClientConfiguration#merge}. * * This configuration object can be {@link #close()}d to release all closeable resources configured within it. */ @SdkProtectedApi public final class SdkClientConfiguration implements ToCopyableBuilder<SdkClientConfiguration.Builder, SdkClientConfiguration>, SdkAutoCloseable { private final AttributeMap attributes; private SdkClientConfiguration(AttributeMap attributes) { this.attributes = attributes; } /** * Create a builder for a {@link SdkClientConfiguration}. */ public static SdkClientConfiguration.Builder builder() { return new Builder(AttributeMap.builder()); } /** * Create a {@link SdkClientConfiguration} from the provided {@link ClientOverrideConfiguration}. This copies the * properties out of the configuration and ensures that _OVERRIDDEN properties are properly set, like * {@link SdkClientOption#SIGNER_OVERRIDDEN}. */ public static SdkClientConfiguration fromOverrideConfiguration(ClientOverrideConfiguration configuration) { SdkClientConfiguration result = configuration.asSdkClientConfiguration(); Boolean endpointOverriddenOverride = result.option(SdkInternalTestAdvancedClientOption.ENDPOINT_OVERRIDDEN_OVERRIDE); Signer signerFromOverride = result.option(SdkAdvancedClientOption.SIGNER); if (endpointOverriddenOverride == null && signerFromOverride == null) { return result; } SdkClientConfiguration.Builder resultBuilder = result.toBuilder(); if (signerFromOverride != null) { resultBuilder.option(SIGNER_OVERRIDDEN, true); } if (endpointOverriddenOverride != null) { resultBuilder.option(ENDPOINT_OVERRIDDEN, endpointOverriddenOverride); } return resultBuilder.build(); } /** * Retrieve the value of a specific option. */ public <T> T option(ClientOption<T> option) { return attributes.get(option); } /** * Create a {@link ClientOverrideConfiguration} using the values currently in this configuration. */ public ClientOverrideConfiguration asOverrideConfiguration() { return new ClientOverrideConfiguration.DefaultBuilder(toBuilder()).build(); } /** * Merge this configuration with another configuration, where this configuration's values take precedence. */ public SdkClientConfiguration merge(SdkClientConfiguration configuration) { return new SdkClientConfiguration(attributes.merge(configuration.attributes)); } public SdkClientConfiguration merge(Consumer<SdkClientConfiguration.Builder> configuration) { return merge(builder().applyMutation(configuration).build()); } @Override public String toString() { return ToString.builder("SdkClientConfiguration") .add("attributes", attributes) .build(); } @Override public Builder toBuilder() { return new Builder(attributes.toBuilder()); } /** * Close this configuration, which closes all closeable attributes. */ @Override public void close() { attributes.close(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SdkClientConfiguration that = (SdkClientConfiguration) o; return attributes.equals(that.attributes); } @Override public int hashCode() { return attributes.hashCode(); } public static final class Builder implements CopyableBuilder<Builder, SdkClientConfiguration> { private final AttributeMap.Builder attributes; private Builder(AttributeMap.Builder attributes) { this.attributes = attributes; } /** * Create a {@link ClientOverrideConfiguration.Builder} using the values currently in this builder. */ public ClientOverrideConfiguration.Builder asOverrideConfigurationBuilder() { return new ClientOverrideConfiguration.DefaultBuilder(this); } /** * Configure the value of a specific option. */ public <T> Builder option(ClientOption<T> option, T value) { this.attributes.put(option, value); return this; } /** * Add a mapping between the provided option and value provider. * * The lazy value will only be resolved when the value is needed. During resolution, the lazy value is provided with a * value reader. The value reader will fail if the reader attempts to read its own value (directly, or indirectly * through other lazy values). * * If a value is updated that a lazy value is depended on, the lazy value will be re-resolved the next time the lazy * value is accessed. */ public <T> Builder lazyOption(ClientOption<T> option, AttributeMap.LazyValue<T> lazyValue) { this.attributes.putLazy(option, lazyValue); return this; } /** * Equivalent to {@link #lazyOption(ClientOption, AttributeMap.LazyValue)}, but does not assign the value if there is * already a non-null value assigned for the provided option. */ public <T> Builder lazyOptionIfAbsent(ClientOption<T> option, AttributeMap.LazyValue<T> lazyValue) { this.attributes.putLazyIfAbsent(option, lazyValue); return this; } /** * Retrieve the value of a specific option. */ public <T> T option(ClientOption<T> option) { return this.attributes.get(option); } /** * Add a mapping between the provided key and value, if the current value for the option is null. Returns the value. */ public <T> T computeOptionIfAbsent(ClientOption<T> option, Supplier<T> valueSupplier) { return this.attributes.computeIfAbsent(option, valueSupplier); } /** * Adds all the options from the map provided. This is not type safe, and will throw an exception during creation if * a value in the map is not of the correct type for its option. */ public Builder putAll(Map<? extends ClientOption<?>, ?> options) { this.attributes.putAll(options); return this; } /** * Put all of the attributes from the provided override configuration into this one. */ public Builder putAll(ClientOverrideConfiguration configuration) { this.attributes.putAll(fromOverrideConfiguration(configuration).attributes); return this; } @Override public Builder copy() { return new Builder(attributes.copy()); } @Override public SdkClientConfiguration build() { return new SdkClientConfiguration(attributes.build()); } } }
2,075
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/config/ClientAsyncConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.config; import static software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR; import java.util.Map; import java.util.concurrent.Executor; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.ExecutorUtils; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Async configuration values for which the client already provides sensible defaults. All values are optional, and not specifying * them will use optimal values defined by the service itself. * * <p>Use {@link #builder()} to create a set of options.</p> */ @Immutable @SdkPublicApi public final class ClientAsyncConfiguration implements ToCopyableBuilder<ClientAsyncConfiguration.Builder, ClientAsyncConfiguration> { private final AttributeMap advancedOptions; private ClientAsyncConfiguration(DefaultBuilder builder) { this.advancedOptions = builder.advancedOptions.build(); } public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder().advancedOptions(advancedOptions); } /** * Load the requested advanced option that was configured on the client builder. This will return null if the value was not * configured. * * @see Builder#advancedOption(SdkAdvancedAsyncClientOption, Object) */ public <T> T advancedOption(SdkAdvancedAsyncClientOption<T> option) { return advancedOptions.get(option); } /** * Configure and create a {@link ClientAsyncConfiguration}. Created via {@link ClientAsyncConfiguration#builder()}. */ public interface Builder extends CopyableBuilder<Builder, ClientAsyncConfiguration> { /** * Configure an advanced async option. These values are used very rarely, and the majority of SDK customers can ignore * them. * * @param option The option to configure. * @param value The value of the option. * @param <T> The type of the option. */ <T> Builder advancedOption(SdkAdvancedAsyncClientOption<T> option, T value); /** * Configure the map of advanced override options. This will override all values currently configured. The values in the * map must match the key type of the map, or a runtime exception will be raised. */ Builder advancedOptions(Map<SdkAdvancedAsyncClientOption<?>, ?> advancedOptions); } private static class DefaultBuilder implements Builder { private AttributeMap.Builder advancedOptions = AttributeMap.builder(); @Override public <T> Builder advancedOption(SdkAdvancedAsyncClientOption<T> option, T value) { if (option == FUTURE_COMPLETION_EXECUTOR) { Executor executor = FUTURE_COMPLETION_EXECUTOR.convertValue(value); this.advancedOptions.put(FUTURE_COMPLETION_EXECUTOR, ExecutorUtils.unmanagedExecutor(executor)); } else { this.advancedOptions.put(option, value); } return this; } @Override public Builder advancedOptions(Map<SdkAdvancedAsyncClientOption<?>, ?> advancedOptions) { this.advancedOptions.putAll(advancedOptions); return this; } public void setAdvancedOptions(Map<SdkAdvancedAsyncClientOption<?>, Object> advancedOptions) { advancedOptions(advancedOptions); } @Override public ClientAsyncConfiguration build() { return new ClientAsyncConfiguration(this); } Builder advancedOptions(AttributeMap advancedOptions) { this.advancedOptions = advancedOptions.toBuilder(); return this; } } }
2,076
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/config/SdkAdvancedAsyncClientOption.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.config; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; import software.amazon.awssdk.annotations.SdkPublicApi; /** * A collection of advanced options that can be configured on an async AWS client via * {@link ClientAsyncConfiguration.Builder#advancedOption(SdkAdvancedAsyncClientOption, * 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 SdkAdvancedAsyncClientOption<T> extends ClientOption<T> { /** * Configure the {@link Executor} that should be used to complete the {@link CompletableFuture} that is returned by the async * service client. By default, this is a dedicated, per-client {@link ThreadPoolExecutor} that is managed by the SDK. * <p> * The configured {@link Executor} will be invoked by the async HTTP client's I/O threads (e.g., EventLoops), which must be * reserved for non-blocking behavior. Blocking an I/O thread can cause severe performance degradation, including across * multiple clients, as clients are configured, by default, to share a single I/O thread pool (e.g., EventLoopGroup). * <p> * You should typically only want to customize the future-completion {@link Executor} for a few possible reasons: * <ol> * <li>You want more fine-grained control over the {@link ThreadPoolExecutor} used, such as configuring the pool size * or sharing a single pool between multiple clients. * <li>You want to add instrumentation (i.e., metrics) around how the {@link Executor} is used. * <li>You know, for certain, that all of your {@link CompletableFuture} usage is strictly non-blocking, and you wish to * remove the minor overhead incurred by using a separate thread. In this case, you can use * {@code Runnable::run} to execute the future-completion directly from within the I/O thread. * </ol> */ public static final SdkAdvancedAsyncClientOption<Executor> FUTURE_COMPLETION_EXECUTOR = new SdkAdvancedAsyncClientOption<>(Executor.class); private SdkAdvancedAsyncClientOption(Class<T> valueClass) { super(valueClass); } }
2,077
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/config/SdkAdvancedClientOption.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.config; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.signer.Signer; /** * A collection of advanced options that can be configured on an AWS client via * {@link ClientOverrideConfiguration.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 class SdkAdvancedClientOption<T> extends ClientOption<T> { private static final Set<SdkAdvancedClientOption<?>> OPTIONS = ConcurrentHashMap.newKeySet(); /** * Set the prefix of the user agent that is sent with each request to AWS. */ public static final SdkAdvancedClientOption<String> USER_AGENT_PREFIX = new SdkAdvancedClientOption<>(String.class); /** * Set the suffix of the user agent that is sent with each request to AWS. */ public static final SdkAdvancedClientOption<String> USER_AGENT_SUFFIX = new SdkAdvancedClientOption<>(String.class); /** * Define the signer that should be used when authenticating with AWS. */ public static final SdkAdvancedClientOption<Signer> SIGNER = new SdkAdvancedClientOption<>(Signer.class); /** * Define the signer that should be used for token-based authentication with AWS. */ public static final SdkAdvancedClientOption<Signer> TOKEN_SIGNER = new SdkAdvancedClientOption<>(Signer.class); /** * SDK uses endpoint trait and hostPrefix trait specified in service model to modify * the endpoint host that the API request is sent to. * * Customers can set this value to True to disable the behavior. */ public static final SdkAdvancedClientOption<Boolean> DISABLE_HOST_PREFIX_INJECTION = new SdkAdvancedClientOption<>(Boolean.class); protected SdkAdvancedClientOption(Class<T> valueClass) { super(valueClass); OPTIONS.add(this); } /** * Retrieve all of the advanced client options loaded so far. */ static Set<SdkAdvancedClientOption<?>> options() { return Collections.unmodifiableSet(OPTIONS); } }
2,078
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/config/ClientOption.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.config; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.AttributeMap; /** * An option in a {@link SdkClientConfiguration}. * * @see SdkAdvancedClientOption * @see SdkClientOption */ @SdkProtectedApi public abstract class ClientOption<T> extends AttributeMap.Key<T> { protected ClientOption(Class<T> valueClass) { super(valueClass); } protected ClientOption(UnsafeValueType unsafeValueType) { super(unsafeValueType); } }
2,079
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/config/SdkClientOptionValidation.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.config; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.Validate; /** * A set of static methods used to validate that a {@link SdkClientConfiguration} contains all of * the values required for the SDK to function. */ @SdkProtectedApi public class SdkClientOptionValidation { protected SdkClientOptionValidation() { } public static void validateAsyncClientOptions(SdkClientConfiguration c) { require("asyncConfiguration.advancedOption[FUTURE_COMPLETION_EXECUTOR]", c.option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR)); require("asyncHttpClient", c.option(SdkClientOption.ASYNC_HTTP_CLIENT)); validateClientOptions(c); } public static void validateSyncClientOptions(SdkClientConfiguration c) { require("syncHttpClient", c.option(SdkClientOption.SYNC_HTTP_CLIENT)); validateClientOptions(c); } private static void validateClientOptions(SdkClientConfiguration c) { require("endpoint", c.option(SdkClientOption.ENDPOINT)); require("overrideConfiguration.additionalHttpHeaders", c.option(SdkClientOption.ADDITIONAL_HTTP_HEADERS)); require("overrideConfiguration.executionInterceptors", c.option(SdkClientOption.EXECUTION_INTERCEPTORS)); require("overrideConfiguration.retryPolicy", c.option(SdkClientOption.RETRY_POLICY)); require("overrideConfiguration.advancedOption[USER_AGENT_PREFIX]", c.option(SdkAdvancedClientOption.USER_AGENT_PREFIX)); require("overrideConfiguration.advancedOption[USER_AGENT_SUFFIX]", c.option(SdkAdvancedClientOption.USER_AGENT_SUFFIX)); require("overrideConfiguration.advancedOption[CRC32_FROM_COMPRESSED_DATA_ENABLED]", c.option(SdkClientOption.CRC32_FROM_COMPRESSED_DATA_ENABLED)); } /** * Validate that the customer set the provided field. */ protected static <U> U require(String field, U required) { return Validate.notNull(required, "The '%s' must be configured in the client builder.", field); } }
2,080
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/config/SdkClientOption.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.config; import java.net.URI; import java.time.Duration; import java.util.List; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.ClientType; import software.amazon.awssdk.core.CompressionConfiguration; import software.amazon.awssdk.core.ServiceConfiguration; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; 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.endpoints.EndpointProvider; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; 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.MetricPublisher; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.utils.AttributeMap; /** * A set of internal options required by the SDK via {@link SdkClientConfiguration}. */ @SdkProtectedApi public final class SdkClientOption<T> extends ClientOption<T> { /** * @see ClientOverrideConfiguration#headers() */ public static final SdkClientOption<Map<String, List<String>>> ADDITIONAL_HTTP_HEADERS = new SdkClientOption<>(new UnsafeValueType(Map.class)); /** * @see ClientOverrideConfiguration#retryPolicy() */ public static final SdkClientOption<RetryPolicy> RETRY_POLICY = new SdkClientOption<>(RetryPolicy.class); /** * @see ClientOverrideConfiguration#executionInterceptors() */ public static final SdkClientOption<List<ExecutionInterceptor>> EXECUTION_INTERCEPTORS = new SdkClientOption<>(new UnsafeValueType(List.class)); /** * The effective endpoint the client is configured to make requests to. If the client has been configured with * an endpoint override then this value will be the provided endpoint value. */ public static final SdkClientOption<URI> ENDPOINT = new SdkClientOption<>(URI.class); /** * A flag that when set to true indicates the endpoint stored in {@link SdkClientOption#ENDPOINT} was a customer * supplied value and not generated by the client based on Region metadata. */ public static final SdkClientOption<Boolean> ENDPOINT_OVERRIDDEN = new SdkClientOption<>(Boolean.class); /** * Service-specific configuration used by some services, like S3. */ public static final SdkClientOption<ServiceConfiguration> SERVICE_CONFIGURATION = new SdkClientOption<>(ServiceConfiguration.class); /** * Whether to calculate the CRC 32 checksum of a message based on the uncompressed data. By default, this is false. */ public static final SdkClientOption<Boolean> CRC32_FROM_COMPRESSED_DATA_ENABLED = new SdkClientOption<>(Boolean.class); /** * The internal SDK scheduled executor service that is used for scheduling tasks such as async retry attempts * and timeout task. */ public static final SdkClientOption<ScheduledExecutorService> SCHEDULED_EXECUTOR_SERVICE = new SdkClientOption<>(ScheduledExecutorService.class); /** * The internal SDK scheduled executor service that is set by the customer. This is likely only useful within configuration * classes, and will be converted into a {@link #SCHEDULED_EXECUTOR_SERVICE} for the SDK's runtime. */ public static final SdkClientOption<ScheduledExecutorService> CONFIGURED_SCHEDULED_EXECUTOR_SERVICE = new SdkClientOption<>(ScheduledExecutorService.class); /** * The asynchronous HTTP client implementation to make HTTP requests with. */ public static final SdkClientOption<SdkAsyncHttpClient> ASYNC_HTTP_CLIENT = new SdkClientOption<>(SdkAsyncHttpClient.class); /** * An asynchronous HTTP client set by the customer. This is likely only useful within configuration classes, and * will be converted into a {@link #ASYNC_HTTP_CLIENT} for the SDK's runtime. */ public static final SdkClientOption<SdkAsyncHttpClient> CONFIGURED_ASYNC_HTTP_CLIENT = new SdkClientOption<>(SdkAsyncHttpClient.class); /** * An asynchronous HTTP client builder set by the customer. This is likely only useful within configuration classes, and * will be converted into a {@link #ASYNC_HTTP_CLIENT} for the SDK's runtime. */ public static final SdkClientOption<SdkAsyncHttpClient.Builder<?>> CONFIGURED_ASYNC_HTTP_CLIENT_BUILDER = new SdkClientOption<>(new UnsafeValueType(SdkAsyncHttpClient.Builder.class)); /** * The HTTP client implementation to make HTTP requests with. */ public static final SdkClientOption<SdkHttpClient> SYNC_HTTP_CLIENT = new SdkClientOption<>(SdkHttpClient.class); /** * An HTTP client set by the customer. This is likely only useful within configuration classes, and * will be converted into a {@link #SYNC_HTTP_CLIENT} for the SDK's runtime. */ public static final SdkClientOption<SdkHttpClient> CONFIGURED_SYNC_HTTP_CLIENT = new SdkClientOption<>(SdkHttpClient.class); /** * An HTTP client builder set by the customer. This is likely only useful within configuration classes, and * will be converted into a {@link #SYNC_HTTP_CLIENT} for the SDK's runtime. */ public static final SdkClientOption<SdkHttpClient.Builder<?>> CONFIGURED_SYNC_HTTP_CLIENT_BUILDER = new SdkClientOption<>(new UnsafeValueType(SdkAsyncHttpClient.Builder.class)); /** * Configuration that should be used to build the {@link #SYNC_HTTP_CLIENT} or {@link #ASYNC_HTTP_CLIENT}. */ public static final SdkClientOption<AttributeMap> HTTP_CLIENT_CONFIG = new SdkClientOption<>(AttributeMap.class); /** * The type of client used to make requests. */ public static final SdkClientOption<ClientType> CLIENT_TYPE = new SdkClientOption<>(ClientType.class); /** * @see ClientOverrideConfiguration#apiCallAttemptTimeout() */ public static final SdkClientOption<Duration> API_CALL_ATTEMPT_TIMEOUT = new SdkClientOption<>(Duration.class); /** * @see ClientOverrideConfiguration#apiCallTimeout() */ public static final SdkClientOption<Duration> API_CALL_TIMEOUT = new SdkClientOption<>(Duration.class); /** * Descriptive name for the service. Used primarily for metrics and also in metadata like AwsErrorDetails. */ public static final SdkClientOption<String> SERVICE_NAME = new SdkClientOption<>(String.class); /** * Whether or not endpoint discovery is enabled for this client. */ public static final SdkClientOption<Boolean> ENDPOINT_DISCOVERY_ENABLED = new SdkClientOption<>(Boolean.class); /** * The profile file to use for this client. * * @deprecated This option was used to: * - Read configuration options in profile files in aws-core, sdk-core * - Build service configuration objects from profile files in codegen, s3control * - Build service configuration objects from profile files, set endpoint options in s3 * - Set retry mode in dynamodb, kinesis * This has been replaced with {@code PROFILE_FILE_SUPPLIER.get()}. */ @Deprecated public static final SdkClientOption<ProfileFile> PROFILE_FILE = new SdkClientOption<>(ProfileFile.class); /** * The profile file supplier to use for this client. */ public static final SdkClientOption<Supplier<ProfileFile>> PROFILE_FILE_SUPPLIER = new SdkClientOption<>(new UnsafeValueType(Supplier.class)); /** * The profile name to use for this client. */ public static final SdkClientOption<String> PROFILE_NAME = new SdkClientOption<>(String.class); public static final SdkClientOption<List<MetricPublisher>> METRIC_PUBLISHERS = new SdkClientOption<>(new UnsafeValueType(List.class)); /** * Option to specify if the default signer has been overridden on the client. */ public static final SdkClientOption<Boolean> SIGNER_OVERRIDDEN = new SdkClientOption<>(Boolean.class); /** * Option to specify additional execution attributes to each client call. */ public static final SdkClientOption<ExecutionAttributes> EXECUTION_ATTRIBUTES = new SdkClientOption<>(new UnsafeValueType(ExecutionAttributes.class)); /** * Option to specify the internal user agent. */ public static final SdkClientOption<String> INTERNAL_USER_AGENT = new SdkClientOption<>(String.class); /** * A user agent prefix that is specific to the client (agnostic of the request). */ public static final SdkClientOption<String> CLIENT_USER_AGENT = new SdkClientOption<>(String.class); /** * Option to specify the default retry mode. * * @see RetryMode.Resolver#defaultRetryMode(RetryMode) */ public static final SdkClientOption<RetryMode> DEFAULT_RETRY_MODE = new SdkClientOption<>(RetryMode.class); /** * The {@link EndpointProvider} configured on the client. */ public static final SdkClientOption<EndpointProvider> ENDPOINT_PROVIDER = new SdkClientOption<>(EndpointProvider.class); /** * The {@link AuthSchemeProvider} configured on the client. */ public static final SdkClientOption<AuthSchemeProvider> AUTH_SCHEME_PROVIDER = new SdkClientOption<>(AuthSchemeProvider.class); /** * The {@link AuthScheme}s configured on the client. */ public static final SdkClientOption<Map<String, AuthScheme<?>>> AUTH_SCHEMES = new SdkClientOption<>(new UnsafeValueType(Map.class)); /** * The IdentityProviders configured on the client. */ public static final SdkClientOption<IdentityProviders> IDENTITY_PROVIDERS = new SdkClientOption<>(IdentityProviders.class); /** * The container for any client contexts parameters set on the client. */ public static final SdkClientOption<AttributeMap> CLIENT_CONTEXT_PARAMS = new SdkClientOption<>(AttributeMap.class); /** * Configuration of the COMPRESSION_CONFIGURATION. Unlike {@link #COMPRESSION_CONFIGURATION}, this may contain null values. */ public static final SdkClientOption<CompressionConfiguration> CONFIGURED_COMPRESSION_CONFIGURATION = new SdkClientOption<>(CompressionConfiguration.class); /** * Option used by the rest of the SDK to read the {@link CompressionConfiguration}. This will never contain null values. */ public static final SdkClientOption<CompressionConfiguration> COMPRESSION_CONFIGURATION = new SdkClientOption<>(CompressionConfiguration.class); private SdkClientOption(Class<T> valueClass) { super(valueClass); } private SdkClientOption(UnsafeValueType valueType) { super(valueType); } }
2,081
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/builder/SdkClientBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.builder; import java.net.URI; import java.util.List; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPreviewApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkPlugin; 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.utils.builder.SdkBuilder; /** * 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 <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 SdkClientBuilder<B extends SdkClientBuilder<B, C>, C> extends SdkBuilder<B, C> { /** * Specify overrides to the default SDK configuration that should be used for clients created by this builder. */ B overrideConfiguration(ClientOverrideConfiguration overrideConfiguration); /** * Similar to {@link #overrideConfiguration(ClientOverrideConfiguration)}, but takes a lambda to configure a new * {@link ClientOverrideConfiguration.Builder}. This removes the need to called {@link ClientOverrideConfiguration#builder()} * and {@link ClientOverrideConfiguration.Builder#build()}. */ default B overrideConfiguration(Consumer<ClientOverrideConfiguration.Builder> overrideConfiguration) { return overrideConfiguration(ClientOverrideConfiguration.builder().applyMutation(overrideConfiguration).build()); } /** * Retrieve the current override configuration. This allows further overrides across calls. Can be modified by first * converting to a builder with {@link ClientOverrideConfiguration#toBuilder()}. * @return The existing override configuration for the builder. */ ClientOverrideConfiguration overrideConfiguration(); /** * Configure the endpoint with which the SDK should communicate. * <p> * It is important to know that {@link EndpointProvider}s and the endpoint override on the client are not mutually * exclusive. In all existing cases, the endpoint override is passed as a parameter to the provider and the provider *may* * modify it. For example, the S3 provider may add the bucket name as a prefix to the endpoint override for virtual bucket * addressing. */ B endpointOverride(URI endpointOverride); /** * Configure this client with an additional auth scheme, or replace one already on the client. * * <p>By default, the SDK will only know about default auth schemes that ship with the service. If you want to modify those * existing auth schemes or add a custom one (you select with a custom auth scheme resolver), you can add that new auth * scheme with this method. */ default B putAuthScheme(AuthScheme<?> authScheme) { throw new UnsupportedOperationException(); } /** * Adds a plugin to the client builder. The plugins will be invoked when building the client to allow them to change the * configuration of the built client. */ @SdkPreviewApi default B addPlugin(SdkPlugin plugin) { throw new UnsupportedOperationException(); } /** * Returns the list of plugins configured on the client builder. */ @SdkPreviewApi default List<SdkPlugin> plugins() { throw new UnsupportedOperationException(); } }
2,082
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/builder/SdkDefaultClientBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.builder; import static software.amazon.awssdk.core.ClientType.ASYNC; import static software.amazon.awssdk.core.ClientType.SYNC; import static software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR; import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.USER_AGENT_PREFIX; import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.USER_AGENT_SUFFIX; import static software.amazon.awssdk.core.client.config.SdkClientOption.ADDITIONAL_HTTP_HEADERS; import static software.amazon.awssdk.core.client.config.SdkClientOption.ASYNC_HTTP_CLIENT; import static software.amazon.awssdk.core.client.config.SdkClientOption.CLIENT_TYPE; import static software.amazon.awssdk.core.client.config.SdkClientOption.CLIENT_USER_AGENT; import static software.amazon.awssdk.core.client.config.SdkClientOption.COMPRESSION_CONFIGURATION; import static software.amazon.awssdk.core.client.config.SdkClientOption.CONFIGURED_ASYNC_HTTP_CLIENT; import static software.amazon.awssdk.core.client.config.SdkClientOption.CONFIGURED_ASYNC_HTTP_CLIENT_BUILDER; import static software.amazon.awssdk.core.client.config.SdkClientOption.CONFIGURED_COMPRESSION_CONFIGURATION; import static software.amazon.awssdk.core.client.config.SdkClientOption.CONFIGURED_SCHEDULED_EXECUTOR_SERVICE; import static software.amazon.awssdk.core.client.config.SdkClientOption.CONFIGURED_SYNC_HTTP_CLIENT; import static software.amazon.awssdk.core.client.config.SdkClientOption.CONFIGURED_SYNC_HTTP_CLIENT_BUILDER; import static software.amazon.awssdk.core.client.config.SdkClientOption.CRC32_FROM_COMPRESSED_DATA_ENABLED; import static software.amazon.awssdk.core.client.config.SdkClientOption.DEFAULT_RETRY_MODE; import static software.amazon.awssdk.core.client.config.SdkClientOption.EXECUTION_INTERCEPTORS; import static software.amazon.awssdk.core.client.config.SdkClientOption.HTTP_CLIENT_CONFIG; import static software.amazon.awssdk.core.client.config.SdkClientOption.IDENTITY_PROVIDERS; import static software.amazon.awssdk.core.client.config.SdkClientOption.INTERNAL_USER_AGENT; import static software.amazon.awssdk.core.client.config.SdkClientOption.METRIC_PUBLISHERS; import static software.amazon.awssdk.core.client.config.SdkClientOption.PROFILE_FILE; import static software.amazon.awssdk.core.client.config.SdkClientOption.PROFILE_FILE_SUPPLIER; import static software.amazon.awssdk.core.client.config.SdkClientOption.PROFILE_NAME; import static software.amazon.awssdk.core.client.config.SdkClientOption.RETRY_POLICY; import static software.amazon.awssdk.core.client.config.SdkClientOption.SCHEDULED_EXECUTOR_SERVICE; import static software.amazon.awssdk.core.client.config.SdkClientOption.SYNC_HTTP_CLIENT; import static software.amazon.awssdk.utils.CollectionUtils.mergeLists; import static software.amazon.awssdk.utils.Validate.paramNotNull; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkPreviewApi; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.core.CompressionConfiguration; import software.amazon.awssdk.core.SdkPlugin; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.client.config.ClientAsyncConfiguration; 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.interceptor.ClasspathInterceptorChainFactory; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkAsyncHttpClientBuilder; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkHttpClientBuilder; import software.amazon.awssdk.core.internal.http.pipeline.stages.ApplyUserAgentStage; import software.amazon.awssdk.core.internal.http.pipeline.stages.CompressRequestStage; import software.amazon.awssdk.core.internal.interceptor.HttpChecksumValidationInterceptor; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.util.SdkUserAgent; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.AttributeMap.LazyValueSource; import software.amazon.awssdk.utils.Either; import software.amazon.awssdk.utils.Lazy; import software.amazon.awssdk.utils.OptionalUtils; import software.amazon.awssdk.utils.ThreadFactoryBuilder; import software.amazon.awssdk.utils.Validate; /** * An SDK-internal implementation of the methods in {@link SdkClientBuilder}, {@link SdkAsyncClientBuilder} and * {@link SdkSyncClientBuilder}. 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 SdkClientBuilder}s, this class is not thread safe.</p> * * @param <B> The type of builder, for chaining. * @param <C> The type of client generated by this builder. */ @SdkProtectedApi public abstract class SdkDefaultClientBuilder<B extends SdkClientBuilder<B, C>, C> implements SdkClientBuilder<B, C> { private static final SdkHttpClient.Builder DEFAULT_HTTP_CLIENT_BUILDER = new DefaultSdkHttpClientBuilder(); private static final SdkAsyncHttpClient.Builder DEFAULT_ASYNC_HTTP_CLIENT_BUILDER = new DefaultSdkAsyncHttpClientBuilder(); protected final SdkClientConfiguration.Builder clientConfiguration = SdkClientConfiguration.builder(); protected final AttributeMap.Builder clientContextParams = AttributeMap.builder(); private final SdkHttpClient.Builder defaultHttpClientBuilder; private final SdkAsyncHttpClient.Builder defaultAsyncHttpClientBuilder; private final List<SdkPlugin> plugins = new ArrayList<>(); private ClientOverrideConfiguration overrideConfig; protected SdkDefaultClientBuilder() { this(DEFAULT_HTTP_CLIENT_BUILDER, DEFAULT_ASYNC_HTTP_CLIENT_BUILDER); } @SdkTestInternalApi protected SdkDefaultClientBuilder(SdkHttpClient.Builder defaultHttpClientBuilder, SdkAsyncHttpClient.Builder defaultAsyncHttpClientBuilder) { this.defaultHttpClientBuilder = defaultHttpClientBuilder; this.defaultAsyncHttpClientBuilder = defaultAsyncHttpClientBuilder; } /** * Build a client using the current state of this builder. This is marked final in order to allow this class to add standard * "build" logic between all service clients. Service clients are expected to implement the {@link #buildClient} method, that * accepts the immutable client configuration generated by this build method. */ @Override public final C build() { return buildClient(); } /** * Implemented by child classes to create a client using the provided immutable configuration objects. The async and sync * configurations are not yet immutable. Child classes will need to make them immutable in order to validate them and pass * them to the client's constructor. * * @return A client based on the provided configuration. */ protected abstract C buildClient(); /** * Return a client configuration object, populated with the following chain of priorities. * <ol> * <li>Client Configuration Overrides</li> * <li>Customer Configuration</li> * <li>Service-Specific Defaults</li> * <li>Global Defaults</li> * </ol> */ protected final SdkClientConfiguration syncClientConfiguration() { clientConfiguration.option(SdkClientOption.CLIENT_CONTEXT_PARAMS, clientContextParams.build()); SdkClientConfiguration configuration = clientConfiguration.build(); // Apply overrides configuration = setOverrides(configuration); // Apply defaults configuration = mergeChildDefaults(configuration); configuration = mergeGlobalDefaults(configuration); // Create additional configuration from the default-applied configuration configuration = finalizeChildConfiguration(configuration); configuration = finalizeSyncConfiguration(configuration); configuration = finalizeConfiguration(configuration); // Invoke the plugins configuration = invokePlugins(configuration); return configuration; } /** * Return a client configuration object, populated with the following chain of priorities. * <ol> * <li>Client Configuration Overrides</li> * <li>Customer Configuration</li> * <li>Implementation/Service-Specific Configuration</li> * <li>Global Default Configuration</li> * </ol> */ protected final SdkClientConfiguration asyncClientConfiguration() { clientConfiguration.option(SdkClientOption.CLIENT_CONTEXT_PARAMS, clientContextParams.build()); SdkClientConfiguration configuration = clientConfiguration.build(); // Apply overrides configuration = setOverrides(configuration); // Apply defaults configuration = mergeChildDefaults(configuration); configuration = mergeGlobalDefaults(configuration); // Create additional configuration from the default-applied configuration configuration = finalizeChildConfiguration(configuration); configuration = finalizeAsyncConfiguration(configuration); configuration = finalizeConfiguration(configuration); // Invoke the plugins configuration = invokePlugins(configuration); return configuration; } /** * Apply the client override configuration to the provided configuration. This generally does not need to be overridden by * child classes, but some previous client versions override it. */ protected SdkClientConfiguration setOverrides(SdkClientConfiguration configuration) { if (overrideConfig == null) { return configuration; } return configuration.toBuilder() .putAll(overrideConfig) .build(); } /** * Optionally overridden by child implementations to apply implementation-specific default configuration. * (eg. AWS's default credentials providers) */ protected SdkClientConfiguration mergeChildDefaults(SdkClientConfiguration configuration) { return configuration; } /** * Apply global default configuration */ private SdkClientConfiguration mergeGlobalDefaults(SdkClientConfiguration configuration) { Supplier<ProfileFile> defaultProfileFileSupplier = new Lazy<>(ProfileFile::defaultProfileFile)::getValue; configuration = configuration.merge(c -> c.option(EXECUTION_INTERCEPTORS, new ArrayList<>()) .option(METRIC_PUBLISHERS, new ArrayList<>()) .option(ADDITIONAL_HTTP_HEADERS, new LinkedHashMap<>()) .option(PROFILE_FILE_SUPPLIER, defaultProfileFileSupplier) .lazyOption(PROFILE_FILE, conf -> conf.get(PROFILE_FILE_SUPPLIER).get()) .option(PROFILE_NAME, ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow()) .option(USER_AGENT_PREFIX, SdkUserAgent.create().userAgent()) .option(USER_AGENT_SUFFIX, "") .option(CRC32_FROM_COMPRESSED_DATA_ENABLED, false) .option(CONFIGURED_COMPRESSION_CONFIGURATION, CompressionConfiguration.builder().build())); return configuration; } /** * Optionally overridden by child implementations to derive implementation-specific configuration from the * default-applied configuration. (eg. AWS's endpoint, derived from the region). */ protected SdkClientConfiguration finalizeChildConfiguration(SdkClientConfiguration configuration) { return configuration; } /** * Finalize sync-specific configuration from the default-applied configuration. */ private SdkClientConfiguration finalizeSyncConfiguration(SdkClientConfiguration config) { return config.toBuilder() .lazyOption(SdkClientOption.SYNC_HTTP_CLIENT, c -> resolveSyncHttpClient(c, config)) .option(SdkClientOption.CLIENT_TYPE, SYNC) .build(); } /** * Finalize async-specific configuration from the default-applied configuration. */ private SdkClientConfiguration finalizeAsyncConfiguration(SdkClientConfiguration config) { return config.toBuilder() .lazyOptionIfAbsent(FUTURE_COMPLETION_EXECUTOR, this::resolveAsyncFutureCompletionExecutor) .lazyOption(ASYNC_HTTP_CLIENT, c -> resolveAsyncHttpClient(c, config)) .option(SdkClientOption.CLIENT_TYPE, ASYNC) .build(); } /** * Finalize global configuration from the default-applied configuration. */ private SdkClientConfiguration finalizeConfiguration(SdkClientConfiguration config) { return config.toBuilder() .lazyOption(SCHEDULED_EXECUTOR_SERVICE, this::resolveScheduledExecutorService) .lazyOptionIfAbsent(RETRY_POLICY, this::resolveRetryPolicy) .option(EXECUTION_INTERCEPTORS, resolveExecutionInterceptors(config)) .lazyOption(CLIENT_USER_AGENT, this::resolveClientUserAgent) .lazyOption(COMPRESSION_CONFIGURATION, this::resolveCompressionConfiguration) .lazyOptionIfAbsent(IDENTITY_PROVIDERS, c -> IdentityProviders.builder().build()) .build(); } private CompressionConfiguration resolveCompressionConfiguration(LazyValueSource config) { CompressionConfiguration compressionConfig = config.get(CONFIGURED_COMPRESSION_CONFIGURATION); return compressionConfig.toBuilder() .requestCompressionEnabled(resolveCompressionEnabled(config, compressionConfig)) .minimumCompressionThresholdInBytes(resolveMinCompressionThreshold(config, compressionConfig)) .build(); } private Boolean resolveCompressionEnabled(LazyValueSource config, CompressionConfiguration compressionConfig) { Supplier<Optional<Boolean>> systemSettingConfiguration = () -> SdkSystemSetting.AWS_DISABLE_REQUEST_COMPRESSION.getBooleanValue() .map(v -> !v); Supplier<Optional<Boolean>> profileFileConfiguration = () -> config.get(PROFILE_FILE_SUPPLIER).get() .profile(config.get(PROFILE_NAME)) .flatMap(p -> p.booleanProperty(ProfileProperty.DISABLE_REQUEST_COMPRESSION)) .map(v -> !v); return OptionalUtils.firstPresent(Optional.ofNullable(compressionConfig.requestCompressionEnabled()), systemSettingConfiguration, profileFileConfiguration) .orElse(true); } private Integer resolveMinCompressionThreshold(LazyValueSource config, CompressionConfiguration compressionConfig) { Supplier<Optional<Integer>> systemSettingConfiguration = SdkSystemSetting.AWS_REQUEST_MIN_COMPRESSION_SIZE_BYTES::getIntegerValue; Supplier<Optional<Integer>> profileFileConfiguration = () -> config.get(PROFILE_FILE_SUPPLIER).get() .profile(config.get(PROFILE_NAME)) .flatMap(p -> p.property(ProfileProperty.REQUEST_MIN_COMPRESSION_SIZE_BYTES)) .map(Integer::parseInt); return OptionalUtils.firstPresent(Optional.ofNullable(compressionConfig.minimumCompressionThresholdInBytes()), systemSettingConfiguration, profileFileConfiguration) .orElse(CompressRequestStage.DEFAULT_MIN_COMPRESSION_SIZE); } /** * By default, returns the configuration as-is. Classes extending this method will take care of running the plugins and * return the updated configuration if plugins are supported. */ @SdkPreviewApi protected SdkClientConfiguration invokePlugins(SdkClientConfiguration config) { return config; } private String resolveClientUserAgent(LazyValueSource config) { return ApplyUserAgentStage.resolveClientUserAgent(config.get(USER_AGENT_PREFIX), config.get(INTERNAL_USER_AGENT), config.get(CLIENT_TYPE), config.get(SYNC_HTTP_CLIENT), config.get(ASYNC_HTTP_CLIENT), config.get(RETRY_POLICY)); } private RetryPolicy resolveRetryPolicy(LazyValueSource config) { RetryMode retryMode = RetryMode.resolver() .profileFile(config.get(PROFILE_FILE_SUPPLIER)) .profileName(config.get(PROFILE_NAME)) .defaultRetryMode(config.get(DEFAULT_RETRY_MODE)) .resolve(); return RetryPolicy.forRetryMode(retryMode); } /** * Finalize which sync HTTP client will be used for the created client. */ private SdkHttpClient resolveSyncHttpClient(LazyValueSource config, SdkClientConfiguration deprecatedConfigDoNotUseThis) { SdkHttpClient httpClient = config.get(CONFIGURED_SYNC_HTTP_CLIENT); SdkHttpClient.Builder<?> httpClientBuilder = config.get(CONFIGURED_SYNC_HTTP_CLIENT_BUILDER); Validate.isTrue(httpClient == null || httpClientBuilder == null, "The httpClient and the httpClientBuilder can't both be configured."); AttributeMap httpClientConfig = getHttpClientConfig(config, deprecatedConfigDoNotUseThis); return Either.fromNullable(httpClient, httpClientBuilder) .map(e -> e.map(Function.identity(), b -> b.buildWithDefaults(httpClientConfig))) .orElseGet(() -> defaultHttpClientBuilder.buildWithDefaults(httpClientConfig)); } /** * Finalize which async HTTP client will be used for the created client. */ private SdkAsyncHttpClient resolveAsyncHttpClient(LazyValueSource config, SdkClientConfiguration deprecatedConfigDoNotUseThis) { Validate.isTrue(config.get(CONFIGURED_ASYNC_HTTP_CLIENT) == null || config.get(CONFIGURED_ASYNC_HTTP_CLIENT_BUILDER) == null, "The asyncHttpClient and the asyncHttpClientBuilder can't both be configured."); AttributeMap httpClientConfig = getHttpClientConfig(config, deprecatedConfigDoNotUseThis); return Either.fromNullable(config.get(CONFIGURED_ASYNC_HTTP_CLIENT), config.get(CONFIGURED_ASYNC_HTTP_CLIENT_BUILDER)) .map(e -> e.map(Function.identity(), b -> b.buildWithDefaults(httpClientConfig))) .orElseGet(() -> defaultAsyncHttpClientBuilder.buildWithDefaults(httpClientConfig)); } private AttributeMap getHttpClientConfig(LazyValueSource config, SdkClientConfiguration deprecatedConfigDoNotUseThis) { AttributeMap httpClientConfig = config.get(HTTP_CLIENT_CONFIG); if (httpClientConfig == null) { // We must be using an old client, use the deprecated way of loading HTTP_CLIENT_CONFIG, instead. This won't take // into account any configuration changes (e.g. defaults mode) from plugins, but this is the best we can do without // breaking protected APIs. TODO: if we ever break protected APIs, remove these "childHttpConfig" hooks. httpClientConfig = childHttpConfig(deprecatedConfigDoNotUseThis); } return httpClientConfig; } /** * @deprecated Configure {@link SdkClientOption#HTTP_CLIENT_CONFIG} from {@link #finalizeChildConfiguration} instead. */ @Deprecated protected AttributeMap childHttpConfig(SdkClientConfiguration configuration) { return childHttpConfig(); } /** * @deprecated Configure {@link SdkClientOption#HTTP_CLIENT_CONFIG} from {@link #finalizeChildConfiguration} instead. */ @Deprecated protected AttributeMap childHttpConfig() { return AttributeMap.empty(); } /** * Finalize which async executor service will be used for the created client. The default async executor * service has at least 8 core threads and can scale up to at least 64 threads when needed depending * on the number of processors available. */ private Executor resolveAsyncFutureCompletionExecutor(LazyValueSource config) { int processors = Runtime.getRuntime().availableProcessors(); int corePoolSize = Math.max(8, processors); int maxPoolSize = Math.max(64, processors * 2); ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1_000), new ThreadFactoryBuilder() .threadNamePrefix("sdk-async-response").build()); // Allow idle core threads to time out executor.allowCoreThreadTimeOut(true); return executor; } /** * Finalize the internal SDK scheduled executor service that is used for scheduling tasks such as async retry attempts and * timeout task. */ private ScheduledExecutorService resolveScheduledExecutorService(LazyValueSource c) { ScheduledExecutorService executor = c.get(CONFIGURED_SCHEDULED_EXECUTOR_SERVICE); if (executor != null) { return executor; } return Executors.newScheduledThreadPool(5, new ThreadFactoryBuilder().threadNamePrefix("sdk-ScheduledExecutor").build()); } /** * Finalize which execution interceptors will be used for the created client. */ private List<ExecutionInterceptor> resolveExecutionInterceptors(SdkClientConfiguration config) { List<ExecutionInterceptor> globalInterceptors = new ArrayList<>(); globalInterceptors.addAll(sdkInterceptors()); globalInterceptors.addAll(new ClasspathInterceptorChainFactory().getGlobalInterceptors()); return mergeLists(globalInterceptors, config.option(EXECUTION_INTERCEPTORS)); } /** * The set of interceptors that should be included with all services. */ private List<ExecutionInterceptor> sdkInterceptors() { return Collections.unmodifiableList(Arrays.asList( new HttpChecksumValidationInterceptor() )); } @Override public final B endpointOverride(URI endpointOverride) { if (endpointOverride == null) { clientConfiguration.option(SdkClientOption.ENDPOINT, null); clientConfiguration.option(SdkClientOption.ENDPOINT_OVERRIDDEN, false); } else { Validate.paramNotNull(endpointOverride.getScheme(), "The URI scheme of endpointOverride"); clientConfiguration.option(SdkClientOption.ENDPOINT, endpointOverride); clientConfiguration.option(SdkClientOption.ENDPOINT_OVERRIDDEN, true); } return thisBuilder(); } public final void setEndpointOverride(URI endpointOverride) { endpointOverride(endpointOverride); } public final B asyncConfiguration(ClientAsyncConfiguration asyncConfiguration) { clientConfiguration.option(FUTURE_COMPLETION_EXECUTOR, asyncConfiguration.advancedOption(FUTURE_COMPLETION_EXECUTOR)); return thisBuilder(); } public final void setAsyncConfiguration(ClientAsyncConfiguration asyncConfiguration) { asyncConfiguration(asyncConfiguration); } @Override public final B overrideConfiguration(ClientOverrideConfiguration overrideConfig) { this.overrideConfig = overrideConfig; return thisBuilder(); } public final void setOverrideConfiguration(ClientOverrideConfiguration overrideConfiguration) { overrideConfiguration(overrideConfiguration); } @Override public final ClientOverrideConfiguration overrideConfiguration() { if (overrideConfig == null) { return ClientOverrideConfiguration.builder().build(); } return overrideConfig; } public final B httpClient(SdkHttpClient httpClient) { if (httpClient != null) { httpClient = new NonManagedSdkHttpClient(httpClient); } clientConfiguration.option(CONFIGURED_SYNC_HTTP_CLIENT, httpClient); return thisBuilder(); } public final B httpClientBuilder(SdkHttpClient.Builder httpClientBuilder) { clientConfiguration.option(CONFIGURED_SYNC_HTTP_CLIENT_BUILDER, httpClientBuilder); return thisBuilder(); } public final B httpClient(SdkAsyncHttpClient httpClient) { if (httpClient != null) { httpClient = new NonManagedSdkAsyncHttpClient(httpClient); } clientConfiguration.option(CONFIGURED_ASYNC_HTTP_CLIENT, httpClient); return thisBuilder(); } public final B httpClientBuilder(SdkAsyncHttpClient.Builder httpClientBuilder) { clientConfiguration.option(CONFIGURED_ASYNC_HTTP_CLIENT_BUILDER, httpClientBuilder); return thisBuilder(); } public final B metricPublishers(List<MetricPublisher> metricPublishers) { clientConfiguration.option(METRIC_PUBLISHERS, metricPublishers); return thisBuilder(); } @Override public final B addPlugin(SdkPlugin plugin) { plugins.add(paramNotNull(plugin, "plugin")); return thisBuilder(); } @Override public final List<SdkPlugin> plugins() { return Collections.unmodifiableList(plugins); } /** * Return "this" for method chaining. */ @SuppressWarnings("unchecked") protected B thisBuilder() { return (B) this; } /** * Wrapper around {@link SdkHttpClient} to prevent it from being closed. Used when the customer provides * an already built client in which case they are responsible for the lifecycle of it. */ @SdkTestInternalApi public static final class NonManagedSdkHttpClient implements SdkHttpClient { private final SdkHttpClient delegate; private NonManagedSdkHttpClient(SdkHttpClient delegate) { this.delegate = paramNotNull(delegate, "SdkHttpClient"); } @Override public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request) { return delegate.prepareRequest(request); } @Override public void close() { // Do nothing, this client is managed by the customer. } @Override public String clientName() { return delegate.clientName(); } } /** * Wrapper around {@link SdkAsyncHttpClient} to prevent it from being closed. Used when the customer provides * an already built client in which case they are responsible for the lifecycle of it. */ @SdkTestInternalApi public static final class NonManagedSdkAsyncHttpClient implements SdkAsyncHttpClient { private final SdkAsyncHttpClient delegate; NonManagedSdkAsyncHttpClient(SdkAsyncHttpClient delegate) { this.delegate = paramNotNull(delegate, "SdkAsyncHttpClient"); } @Override public CompletableFuture<Void> execute(AsyncExecuteRequest request) { return delegate.execute(request); } @Override public String clientName() { return delegate.clientName(); } @Override public void close() { // Do nothing, this client is managed by the customer. } } }
2,083
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/builder/SdkAsyncClientBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.builder; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.client.config.ClientAsyncConfiguration; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; /** * This includes required and optional override configuration required by every 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 SdkAsyncClientBuilder<B extends SdkAsyncClientBuilder<B, C>, C> { /** * Specify overrides to the default SDK async configuration that should be used for clients created by this builder. */ B asyncConfiguration(ClientAsyncConfiguration clientAsyncConfiguration); /** * Similar to {@link #asyncConfiguration(ClientAsyncConfiguration)}, but takes a lambda to configure a new * {@link ClientAsyncConfiguration.Builder}. This removes the need to called {@link ClientAsyncConfiguration#builder()} * and {@link ClientAsyncConfiguration.Builder#build()}. */ default B asyncConfiguration(Consumer<ClientAsyncConfiguration.Builder> clientAsyncConfiguration) { return asyncConfiguration(ClientAsyncConfiguration.builder().applyMutation(clientAsyncConfiguration).build()); } /** * Sets the {@link SdkAsyncHttpClient} that the SDK service client will use to make HTTP calls. This HTTP client may be * shared between multiple SDK service clients to share a common connection pool. To create a client you must use an * implementation specific builder. Note that this method is only recommended when you wish to share an HTTP client across * multiple SDK service clients. If you do not wish to share HTTP clients, it is recommended to use * {@link #httpClientBuilder(SdkAsyncHttpClient.Builder)} so that service specific default configuration may be applied. * * <p> * <b>This client must be closed by the caller when it is ready to be disposed. The SDK will not close the HTTP client * when the service client is closed.</b> * </p> * * @return This builder for method chaining. */ B httpClient(SdkAsyncHttpClient httpClient); /** * Sets a custom HTTP client builder that will be used to obtain a configured instance of {@link SdkAsyncHttpClient}. Any * service specific HTTP configuration will be merged with the builder's configuration prior to creating the client. When * there is no desire to share HTTP clients across multiple service clients, the client builder is the preferred way to * customize the HTTP client as it benefits from service specific defaults. * * <p> * <b>Clients created by the builder are managed by the SDK and will be closed when the service client is closed.</b> * </p> * * @return This builder for method chaining. */ B httpClientBuilder(SdkAsyncHttpClient.Builder httpClientBuilder); }
2,084
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/client/builder/SdkSyncClientBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client.builder; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.SdkHttpClient; /** * 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 SdkSyncClientBuilder<B extends SdkSyncClientBuilder<B, C>, C> { /** * Sets the {@link SdkHttpClient} that the SDK service client will use to make HTTP calls. This HTTP client may be * shared between multiple SDK service clients to share a common connection pool. To create a client you must use an * implementation-specific builder. Note that this method is only recommended when you wish to share an HTTP client across * multiple SDK service clients. If you do not wish to share HTTP clients, it is recommended to use * {@link #httpClientBuilder(SdkHttpClient.Builder)} so that service-specific default configuration may be applied. * * <p> * <b>This client must be closed by the user when it is ready to be disposed. The SDK will not close the HTTP client * when the service client is closed.</b> * </p> */ B httpClient(SdkHttpClient httpClient); /** * Sets a {@link SdkHttpClient.Builder} that will be used to obtain a configured instance of {@link SdkHttpClient}. Any * service-specific HTTP configuration will be merged with the builder's configuration prior to creating the client. When * there is no desire to share HTTP clients across multiple service clients, the client builder is the preferred way to * customize the HTTP client as it benefits from service-specific default configuration. * * <p> * <b>Clients created by the builder are managed by the SDK and will be closed when the service client is closed.</b> * </p> */ B httpClientBuilder(SdkHttpClient.Builder httpClientBuilder); }
2,085
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/interceptor/ExecutionInterceptorChain.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.interceptor; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.internal.interceptor.DefaultFailedExecutionContext; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * A wrapper for a list of {@link ExecutionInterceptor}s that ensures the interceptors are executed in the correct order as it * is documented in the {@link ExecutionInterceptor} documentation. * * Interceptors are invoked in forward order up to {@link #beforeTransmission} and in reverse order after (and including) * {@link #afterTransmission}. This ensures the last interceptors to modify the request are the first interceptors to see the * response. */ @SdkProtectedApi public class ExecutionInterceptorChain { private static final Logger LOG = Logger.loggerFor(ExecutionInterceptorChain.class); private final List<ExecutionInterceptor> interceptors; /** * Create a chain that will execute the provided interceptors in the order they are provided. */ public ExecutionInterceptorChain(List<ExecutionInterceptor> interceptors) { this.interceptors = new ArrayList<>(Validate.paramNotNull(interceptors, "interceptors")); LOG.debug(() -> "Creating an interceptor chain that will apply interceptors in the following order: " + interceptors); } public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { interceptors.forEach(i -> i.beforeExecution(context, executionAttributes)); } public InterceptorContext modifyRequest(InterceptorContext context, ExecutionAttributes executionAttributes) { InterceptorContext result = context; for (ExecutionInterceptor interceptor : interceptors) { SdkRequest interceptorResult = interceptor.modifyRequest(result, executionAttributes); validateInterceptorResult(result.request(), interceptorResult, interceptor, "modifyRequest"); result = result.copy(b -> b.request(interceptorResult)); } return result; } public void beforeMarshalling(Context.BeforeMarshalling context, ExecutionAttributes executionAttributes) { interceptors.forEach(i -> i.beforeMarshalling(context, executionAttributes)); } public void afterMarshalling(Context.AfterMarshalling context, ExecutionAttributes executionAttributes) { interceptors.forEach(i -> i.afterMarshalling(context, executionAttributes)); } public InterceptorContext modifyHttpRequestAndHttpContent(InterceptorContext context, ExecutionAttributes executionAttributes) { InterceptorContext result = context; for (ExecutionInterceptor interceptor : interceptors) { AsyncRequestBody asyncRequestBody = interceptor.modifyAsyncHttpContent(result, executionAttributes).orElse(null); RequestBody requestBody = interceptor.modifyHttpContent(result, executionAttributes).orElse(null); SdkHttpRequest interceptorResult = interceptor.modifyHttpRequest(result, executionAttributes); validateInterceptorResult(result.httpRequest(), interceptorResult, interceptor, "modifyHttpRequest"); InterceptorContext.Builder builder = result.toBuilder(); applySdkHttpFullRequestHack(result, builder); result = builder.httpRequest(interceptorResult) .asyncRequestBody(asyncRequestBody) .requestBody(requestBody) .build(); } return result; } private void applySdkHttpFullRequestHack(InterceptorContext context, InterceptorContext.Builder builder) { // Someone thought it would be a great idea to allow interceptors to return SdkHttpFullRequest to modify the payload // instead of using the modifyPayload method. This is for backwards-compatibility with those interceptors. // TODO: Update interceptors to use the proper payload-modifying method so that this code path is only used for older // client versions. Maybe if we ever decide to break @SdkProtectedApis (if we stop using Jackson?!) we can even remove // this hack! SdkHttpFullRequest sdkHttpFullRequest = (SdkHttpFullRequest) context.httpRequest(); if (context.requestBody().isPresent()) { return; } Optional<ContentStreamProvider> contentStreamProvider = sdkHttpFullRequest.contentStreamProvider(); if (!contentStreamProvider.isPresent()) { return; } long contentLength = Long.parseLong(sdkHttpFullRequest.firstMatchingHeader("Content-Length").orElse("0")); String contentType = sdkHttpFullRequest.firstMatchingHeader("Content-Type").orElse(""); RequestBody requestBody = RequestBody.fromContentProvider(contentStreamProvider.get(), contentLength, contentType); builder.requestBody(requestBody); } public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { interceptors.forEach(i -> i.beforeTransmission(context, executionAttributes)); } public void afterTransmission(Context.AfterTransmission context, ExecutionAttributes executionAttributes) { reverseForEach(i -> i.afterTransmission(context, executionAttributes)); } public InterceptorContext modifyHttpResponse(InterceptorContext context, ExecutionAttributes executionAttributes) { InterceptorContext result = context; for (int i = interceptors.size() - 1; i >= 0; i--) { SdkHttpResponse interceptorResult = interceptors.get(i).modifyHttpResponse(result, executionAttributes); validateInterceptorResult(result.httpResponse(), interceptorResult, interceptors.get(i), "modifyHttpResponse"); InputStream response = interceptors.get(i).modifyHttpResponseContent(result, executionAttributes).orElse(null); result = result.toBuilder().httpResponse(interceptorResult).responseBody(response).build(); } return result; } public InterceptorContext modifyAsyncHttpResponse(InterceptorContext context, ExecutionAttributes executionAttributes) { InterceptorContext result = context; for (int i = interceptors.size() - 1; i >= 0; i--) { ExecutionInterceptor interceptor = interceptors.get(i); Publisher<ByteBuffer> newResponsePublisher = interceptor.modifyAsyncHttpResponseContent(result, executionAttributes).orElse(null); result = result.toBuilder() .responsePublisher(newResponsePublisher) .build(); } return result; } public void beforeUnmarshalling(Context.BeforeUnmarshalling context, ExecutionAttributes executionAttributes) { reverseForEach(i -> i.beforeUnmarshalling(context, executionAttributes)); } public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { reverseForEach(i -> i.afterUnmarshalling(context, executionAttributes)); } public InterceptorContext modifyResponse(InterceptorContext context, ExecutionAttributes executionAttributes) { InterceptorContext result = context; for (int i = interceptors.size() - 1; i >= 0; i--) { SdkResponse interceptorResult = interceptors.get(i).modifyResponse(result, executionAttributes); validateInterceptorResult(result.response(), interceptorResult, interceptors.get(i), "modifyResponse"); result = result.copy(b -> b.response(interceptorResult)); } return result; } public void afterExecution(Context.AfterExecution context, ExecutionAttributes executionAttributes) { reverseForEach(i -> i.afterExecution(context, executionAttributes)); } public DefaultFailedExecutionContext modifyException(DefaultFailedExecutionContext context, ExecutionAttributes executionAttributes) { DefaultFailedExecutionContext result = context; for (int i = interceptors.size() - 1; i >= 0; i--) { Throwable interceptorResult = interceptors.get(i).modifyException(result, executionAttributes); validateInterceptorResult(result.exception(), interceptorResult, interceptors.get(i), "modifyException"); result = result.copy(b -> b.exception(interceptorResult)); } return result; } public void onExecutionFailure(Context.FailedExecution context, ExecutionAttributes executionAttributes) { interceptors.forEach(i -> i.onExecutionFailure(context, executionAttributes)); } /** * Validate the result of calling an interceptor method that is attempting to modify the message to make sure its result is * valid. */ private void validateInterceptorResult(Object originalMessage, Object newMessage, ExecutionInterceptor interceptor, String methodName) { if (!Objects.equals(originalMessage, newMessage)) { LOG.debug(() -> "Interceptor '" + interceptor + "' modified the message with its " + methodName + " method."); LOG.trace(() -> "Old: " + originalMessage + "\nNew: " + newMessage); } Validate.validState(newMessage != null, "Request interceptor '%s' returned null from its %s interceptor.", interceptor, methodName); Validate.isInstanceOf(originalMessage.getClass(), newMessage, "Request interceptor '%s' returned '%s' from its %s method, but '%s' was expected.", interceptor, newMessage.getClass(), methodName, originalMessage.getClass()); } /** * Execute the provided action against the interceptors in this chain in the reverse order they are configured. */ private void reverseForEach(Consumer<ExecutionInterceptor> action) { for (int i = interceptors.size() - 1; i >= 0; i--) { action.accept(interceptors.get(i)); } } }
2,086
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/interceptor/ClasspathInterceptorChainFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.interceptor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.internal.util.ClassLoaderHelper; import software.amazon.awssdk.utils.Validate; /** * Factory for creating request/response handler chains from the classpath. */ @SdkProtectedApi public final class ClasspathInterceptorChainFactory { private static final String GLOBAL_INTERCEPTOR_PATH = "software/amazon/awssdk/global/handlers/execution.interceptors"; /** * Constructs a new request handler chain by analyzing the specified classpath resource. * * @param resource The resource to load from the classpath containing the list of request handlers to instantiate. * @return A list of request handlers based on the handlers referenced in the specified resource. */ public List<ExecutionInterceptor> getInterceptors(String resource) { return new ArrayList<>(createExecutionInterceptorsFromClasspath(resource)); } /** * Load the global handlers by reading the global execution interceptors resource. */ public List<ExecutionInterceptor> getGlobalInterceptors() { return new ArrayList<>(createExecutionInterceptorsFromClasspath(GLOBAL_INTERCEPTOR_PATH)); } private Collection<ExecutionInterceptor> createExecutionInterceptorsFromClasspath(String path) { try { return createExecutionInterceptorsFromResources(classLoader().getResources(path)) .collect(Collectors.toMap(p -> p.getClass().getSimpleName(), p -> p, (p1, p2) -> p1)).values(); } catch (IOException e) { throw SdkClientException.builder() .message("Unable to instantiate execution interceptor chain.") .cause(e) .build(); } } private Stream<ExecutionInterceptor> createExecutionInterceptorsFromResources(Enumeration<URL> resources) { if (resources == null) { return Stream.empty(); } return Collections.list(resources).stream().flatMap(this::createExecutionInterceptorFromResource); } private Stream<ExecutionInterceptor> createExecutionInterceptorFromResource(URL resource) { try { if (resource == null) { return Stream.empty(); } List<ExecutionInterceptor> interceptors = new ArrayList<>(); try (InputStream stream = resource.openStream(); InputStreamReader streamReader = new InputStreamReader(stream, StandardCharsets.UTF_8); BufferedReader fileReader = new BufferedReader(streamReader)) { String interceptorClassName = fileReader.readLine(); while (interceptorClassName != null) { ExecutionInterceptor interceptor = createExecutionInterceptor(interceptorClassName); if (interceptor != null) { interceptors.add(interceptor); } interceptorClassName = fileReader.readLine(); } } return interceptors.stream(); } catch (IOException e) { throw SdkClientException.builder() .message("Unable to instantiate execution interceptor chain.") .cause(e) .build(); } } private ExecutionInterceptor createExecutionInterceptor(String interceptorClassName) { if (interceptorClassName == null) { return null; } interceptorClassName = interceptorClassName.trim(); if (interceptorClassName.equals("")) { return null; } try { Class<?> executionInterceptorClass = ClassLoaderHelper.loadClass(interceptorClassName, ExecutionInterceptor.class, getClass()); Object executionInterceptorObject = executionInterceptorClass.newInstance(); if (executionInterceptorObject instanceof ExecutionInterceptor) { return (ExecutionInterceptor) executionInterceptorObject; } else { throw SdkClientException.builder() .message("Unable to instantiate request handler chain for client. Listed" + " request handler ('" + interceptorClassName + "') does not implement" + " the " + ExecutionInterceptor.class + " API.") .build(); } } catch (IllegalAccessException | ClassNotFoundException | InstantiationException e) { throw SdkClientException.builder() .message("Unable to instantiate executor interceptor for client.") .cause(e) .build(); } } private ClassLoader classLoader() { return Validate.notNull(ClassLoaderHelper.classLoader(getClass()), "Failed to load the classloader of this class or the system."); } }
2,087
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/interceptor/Context.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.interceptor; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Optional; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; /** * A wrapper for the immutable context objects that are visible to the {@link ExecutionInterceptor}s. */ @SdkProtectedApi public final class Context { private Context() { } /** * The state of the execution when the {@link ExecutionInterceptor#beforeExecution} method is invoked. */ @ThreadSafe @SdkPublicApi public interface BeforeExecution { /** * The {@link SdkRequest} to be executed. */ SdkRequest request(); } /** * The state of the execution when the {@link ExecutionInterceptor#modifyRequest} method is invoked. */ @ThreadSafe @SdkPublicApi public interface ModifyRequest extends BeforeExecution { } /** * The state of the execution when the {@link ExecutionInterceptor#beforeMarshalling} method is invoked. */ @ThreadSafe @SdkPublicApi public interface BeforeMarshalling extends ModifyRequest { } /** * The state of the execution when the {@link ExecutionInterceptor#afterMarshalling} method is invoked. */ @ThreadSafe @SdkPublicApi public interface AfterMarshalling extends BeforeMarshalling { /** * The {@link SdkHttpRequest} that was created as a result of marshalling the {@link #request()}. This is the HTTP * request that will be sent to the downstream service. */ SdkHttpRequest httpRequest(); /** * The {@link RequestBody} that represents the body of an HTTP request. */ Optional<RequestBody> requestBody(); /** * The {@link AsyncRequestBody} that allows non-blocking streaming of request content. */ Optional<AsyncRequestBody> asyncRequestBody(); } /** * The state of the execution when the {@link ExecutionInterceptor#modifyHttpRequest} method is invoked. */ @ThreadSafe @SdkPublicApi public interface ModifyHttpRequest extends AfterMarshalling { } /** * The state of the execution when the {@link ExecutionInterceptor#beforeTransmission} method is invoked. */ @ThreadSafe @SdkPublicApi public interface BeforeTransmission extends ModifyHttpRequest { } /** * The state of the execution when the {@link ExecutionInterceptor#afterTransmission} method is invoked. */ @ThreadSafe @SdkPublicApi public interface AfterTransmission extends BeforeTransmission { /** * The HTTP response returned by the service with which the SDK is communicating. */ SdkHttpResponse httpResponse(); /** * The {@link Publisher} that provides {@link ByteBuffer} events upon request. */ Optional<Publisher<ByteBuffer>> responsePublisher(); /** * The {@link InputStream} that provides streaming content returned from the service. */ Optional<InputStream> responseBody(); } /** * The state of the execution when the {@link ExecutionInterceptor#modifyHttpResponse} method is invoked. */ @ThreadSafe @SdkPublicApi public interface ModifyHttpResponse extends AfterTransmission { } /** * The state of the execution when the {@link ExecutionInterceptor#beforeUnmarshalling} method is invoked. */ @ThreadSafe @SdkPublicApi public interface BeforeUnmarshalling extends ModifyHttpResponse { } /** * The state of the execution when the {@link ExecutionInterceptor#afterUnmarshalling} method is invoked. */ @ThreadSafe @SdkPublicApi public interface AfterUnmarshalling extends BeforeUnmarshalling { /** * The {@link SdkResponse} that was generated by unmarshalling the {@link #httpResponse()}. */ SdkResponse response(); } /** * The state of the execution when the {@link ExecutionInterceptor#modifyResponse} method is invoked. */ @ThreadSafe @SdkPublicApi public interface ModifyResponse extends AfterUnmarshalling { } /** * The state of the execution when the {@link ExecutionInterceptor#afterExecution} method is invoked. */ @ThreadSafe @SdkPublicApi public interface AfterExecution extends ModifyResponse { } /** * All information that is known about a particular execution that has failed. This is given to * {@link ExecutionInterceptor#onExecutionFailure} if an entire execution fails for any reason. This includes all information * that is known about the request, like the {@link #request()} and the {@link #exception()} that caused the failure. */ @ThreadSafe @SdkPublicApi public interface FailedExecution { /** * The exception associated with the failed execution. This is the reason the execution has failed, and is the exception * that will be returned or thrown from the client method call. This will never return null. */ Throwable exception(); /** * The latest version of the {@link SdkRequest} available when the execution failed. This will never return null. */ SdkRequest request(); /** * The latest version of the {@link SdkHttpFullRequest} available when the execution failed. If the execution failed * before or during request marshalling, this will return {@link Optional#empty()}. */ Optional<SdkHttpRequest> httpRequest(); /** * The latest version of the {@link SdkHttpFullResponse} available when the execution failed. If the execution failed * before or during transmission, this will return {@link Optional#empty()}. */ Optional<SdkHttpResponse> httpResponse(); /** * The latest version of the {@link SdkResponse} available when the execution failed. If the execution failed before or * during response unmarshalling, this will return {@link Optional#empty()}. */ Optional<SdkResponse> response(); } }
2,088
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/interceptor/ExecutionAttribute.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.interceptor; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; /** * An attribute attached to a particular execution, stored in {@link ExecutionAttributes}. * * This is typically used as a static final field in an {@link ExecutionInterceptor}: * <pre> * {@code * class MyExecutionInterceptor implements ExecutionInterceptor { * private static final ExecutionAttribute<String> DATA = new ExecutionAttribute<>(); * * public void beforeExecution(Context.BeforeExecution execution, ExecutionAttributes executionAttributes) { * executionAttributes.put(DATA, "Request: " + execution.request()); * } * * public void afterExecution(Context.AfterExecution execution, ExecutionAttributes executionAttributes) { * String data = executionAttributes.get(DATA); // Retrieve the value saved in beforeExecution. * } * } * } </pre> * * @param <T> The type of data associated with this attribute. */ @SdkPublicApi public final class ExecutionAttribute<T> { private static final ConcurrentMap<String, ExecutionAttribute<?>> NAME_HISTORY = new ConcurrentHashMap<>(); private final String name; private final ValueStorage<T> storage; /** * Creates a new {@link ExecutionAttribute} bound to the provided type param. * * @param name Descriptive name for the attribute, used primarily for debugging purposes. */ public ExecutionAttribute(String name) { this(name, null); } private ExecutionAttribute(String name, ValueStorage<T> storage) { this.name = name; this.storage = storage == null ? new DefaultValueStorage() : storage; ensureUnique(); } /** * Create an execution attribute whose value is derived from another attribute. * * <p>Whenever this value is read, its value is read from a different "real" attribute, and whenever this value is written its * value is written to the "real" attribute, instead. * * <p>This is useful when new attributes are created to replace old attributes, but for backwards-compatibility those old * attributes still need to be made available. * * @param name The name of the attribute to create * @param attributeType The type of the attribute being created * @param realAttribute The "real" attribute from which this attribute is derived */ public static <T, U> DerivedAttributeBuilder<T, U> derivedBuilder(String name, @SuppressWarnings("unused") Class<T> attributeType, ExecutionAttribute<U> realAttribute) { return new DerivedAttributeBuilder<>(name, realAttribute); } /** * Create an execution attribute whose value is backed by another attribute, and gets mapped to another execution attribute. * * <p>Whenever this value is read, its value is read from the backing attribute, but whenever this value is written its * value is written to the given attribute AND the mapped attribute. * * <p>This is useful when you have a complex attribute relationship, where certain attributes may depend on other attributes. * * @param name The name of the attribute to create * @param backingAttributeSupplier The supplier for the backing attribute, which this attribute is backed by * @param attributeSupplier The supplier for the attribute which is mapped from the backing attribute */ static <T, U> MappedAttributeBuilder<T, U> mappedBuilder(String name, Supplier<ExecutionAttribute<T>> backingAttributeSupplier, Supplier<ExecutionAttribute<U>> attributeSupplier) { return new MappedAttributeBuilder<>(name, backingAttributeSupplier, attributeSupplier); } private void ensureUnique() { ExecutionAttribute<?> prev = NAME_HISTORY.putIfAbsent(name, this); if (prev != null) { throw new IllegalArgumentException(String.format("No duplicate ExecutionAttribute names allowed but both " + "ExecutionAttributes %s and %s have the same name: %s. " + "ExecutionAttributes should be referenced from a shared static " + "constant to protect against erroneous or unexpected collisions.", Integer.toHexString(System.identityHashCode(prev)), Integer.toHexString(System.identityHashCode(this)), name)); } } @Override public String toString() { return name; } /** * This override considers execution attributes with the same name * to be the same object for the purpose of attribute merge. * @return boolean indicating whether the objects are equal or not. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ExecutionAttribute that = (ExecutionAttribute) o; return that.name.equals(this.name); } /** * This override considers execution attributes with the same name * to be the same object for the purpose of attribute merge. * @return hash code */ @Override public int hashCode() { return Objects.hashCode(name); } /** * Visible for {@link ExecutionAttributes} to invoke when writing or reading values for this attribute. */ ValueStorage<T> storage() { return storage; } public static final class DerivedAttributeBuilder<T, U> { private final String name; private final ExecutionAttribute<U> realAttribute; private Function<U, T> readMapping; private BiFunction<U, T, U> writeMapping; private DerivedAttributeBuilder(String name, ExecutionAttribute<U> realAttribute) { this.name = name; this.realAttribute = realAttribute; } /** * Set the "read" mapping for this derived attribute. The provided function accepts the current value of the * "real" attribute and returns the value of the derived attribute. */ public DerivedAttributeBuilder<T, U> readMapping(Function<U, T> readMapping) { this.readMapping = readMapping; return this; } /** * Set the "write" mapping for this derived attribute. The provided function accepts the current value of the "real" * attribute, the value that we're trying to set to the derived attribute, and returns the value to set to the "real" * attribute. */ public DerivedAttributeBuilder<T, U> writeMapping(BiFunction<U, T, U> writeMapping) { this.writeMapping = writeMapping; return this; } public ExecutionAttribute<T> build() { return new ExecutionAttribute<>(name, new DerivationValueStorage<>(this)); } } /** * The value storage allows reading or writing values to this attribute. Used by {@link ExecutionAttributes} for storing * attribute values, whether they are "real" or derived. */ interface ValueStorage<T> { /** * Retrieve an attribute's value from the provided attribute map. */ T get(Map<ExecutionAttribute<?>, Object> attributes); /** * Set an attribute's value to the provided attribute map. */ void set(Map<ExecutionAttribute<?>, Object> attributes, T value); /** * Set an attribute's value to the provided attribute map, if the value is not already in the map. */ void setIfAbsent(Map<ExecutionAttribute<?>, Object> attributes, T value); } /** * An implementation of {@link ValueStorage} that stores the current execution attribute in the provided attributes map. */ private final class DefaultValueStorage implements ValueStorage<T> { @SuppressWarnings("unchecked") // Safe because of the implementation of set() @Override public T get(Map<ExecutionAttribute<?>, Object> attributes) { return (T) attributes.get(ExecutionAttribute.this); } @Override public void set(Map<ExecutionAttribute<?>, Object> attributes, T value) { attributes.put(ExecutionAttribute.this, value); } @Override public void setIfAbsent(Map<ExecutionAttribute<?>, Object> attributes, T value) { attributes.putIfAbsent(ExecutionAttribute.this, value); } } /** * An implementation of {@link ValueStorage} that derives its value from a different execution attribute in the provided * attributes map. */ private static final class DerivationValueStorage<T, U> implements ValueStorage<T> { private final ExecutionAttribute<U> realAttribute; private final Function<U, T> readMapping; private final BiFunction<U, T, U> writeMapping; private DerivationValueStorage(DerivedAttributeBuilder<T, U> builder) { this.realAttribute = Validate.paramNotNull(builder.realAttribute, "realAttribute"); this.readMapping = Validate.paramNotNull(builder.readMapping, "readMapping"); this.writeMapping = Validate.paramNotNull(builder.writeMapping, "writeMapping"); } @SuppressWarnings("unchecked") // Safe because of the implementation of set @Override public T get(Map<ExecutionAttribute<?>, Object> attributes) { return readMapping.apply((U) attributes.get(realAttribute)); } @SuppressWarnings("unchecked") // Safe because of the implementation of set @Override public void set(Map<ExecutionAttribute<?>, Object> attributes, T value) { attributes.compute(realAttribute, (k, real) -> writeMapping.apply((U) real, value)); } @Override public void setIfAbsent(Map<ExecutionAttribute<?>, Object> attributes, T value) { T currentValue = get(attributes); if (currentValue == null) { set(attributes, value); } } } /** * An implementation of {@link ValueStorage} that is backed by a different execution attribute in the provided * attributes map (mirrors its value), and maps (updates) to another attribute. */ private static final class MappedValueStorage<T, U> implements ValueStorage<T> { private final Supplier<ExecutionAttribute<T>> backingAttributeSupplier; private final Supplier<ExecutionAttribute<U>> attributeSupplier; private final BiFunction<T, U, T> readMapping; private final BiFunction<U, T, U> writeMapping; private MappedValueStorage(MappedAttributeBuilder<T, U> builder) { this.backingAttributeSupplier = Validate.paramNotNull(builder.backingAttributeSupplier, "backingAttributeSupplier"); this.attributeSupplier = Validate.paramNotNull(builder.attributeSupplier, "attributeSupplier"); this.readMapping = Validate.paramNotNull(builder.readMapping, "readMapping"); this.writeMapping = Validate.paramNotNull(builder.writeMapping, "writeMapping"); } @SuppressWarnings("unchecked") // Safe because of the implementation of set @Override public T get(Map<ExecutionAttribute<?>, Object> attributes) { return readMapping.apply( (T) attributes.get(backingAttributeSupplier.get()), (U) attributes.get(attributeSupplier.get()) ); } @SuppressWarnings("unchecked") // Safe because of the implementation of set @Override public void set(Map<ExecutionAttribute<?>, Object> attributes, T value) { attributes.put(backingAttributeSupplier.get(), value); attributes.compute(attributeSupplier.get(), (k, attr) -> writeMapping.apply((U) attr, value)); } @Override public void setIfAbsent(Map<ExecutionAttribute<?>, Object> attributes, T value) { T currentValue = get(attributes); if (currentValue == null) { set(attributes, value); } } } protected static final class MappedAttributeBuilder<T, U> { private final String name; private final Supplier<ExecutionAttribute<T>> backingAttributeSupplier; private final Supplier<ExecutionAttribute<U>> attributeSupplier; private BiFunction<T, U, T> readMapping; private BiFunction<U, T, U> writeMapping; private MappedAttributeBuilder(String name, Supplier<ExecutionAttribute<T>> backingAttributeSupplier, Supplier<ExecutionAttribute<U>> attributeSupplier) { this.name = name; this.backingAttributeSupplier = backingAttributeSupplier; this.attributeSupplier = attributeSupplier; } /** * Set the "read" mapping for this mapped attribute. The provided function accepts the current value of the * backing attribute, */ public MappedAttributeBuilder<T, U> readMapping(BiFunction<T, U, T> readMapping) { this.readMapping = readMapping; return this; } /** * Set the "write" mapping for this derived attribute. The provided function accepts the current value of the mapped * attribute, the value that we are mapping from (the "backing" attribute), and returns the value to set to the mapped * attribute. */ public MappedAttributeBuilder<T, U> writeMapping(BiFunction<U, T, U> writeMapping) { this.writeMapping = writeMapping; return this; } public ExecutionAttribute<T> build() { return new ExecutionAttribute<>(name, new MappedValueStorage<>(this)); } } }
2,089
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/interceptor/ExecutionInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.interceptor; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Optional; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncRequestBody; // CHECKSTYLE:OFF - Avoid "Unused Import" error. If we use the FQCN in the Javadoc, we'll run into line length issues instead. import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; // CHECKSTYLE:ON import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; /** * An interceptor that is invoked during the execution lifecycle of a request/response (execution). This can be used to publish * metrics, modify a request in-flight, debug request processing, view exceptions, etc. This interface exposes different methods * for hooking into different parts of the lifecycle of an execution. * * <p> * <b>Interceptor Hooks</b> * Methods for a given interceptor are executed in a predictable order, each receiving the information that is known about the * message so far as well as a {@link ExecutionAttributes} object for storing data that is specific to a particular execution. * <ol> * <li>{@link #beforeExecution} - Read the request before it is modified by other interceptors.</li> * <li>{@link #modifyRequest} - Modify the request object before it is marshalled into an HTTP request.</li> * <li>{@link #beforeMarshalling} - Read the request that has potentially been modified by other request interceptors before * it is marshalled into an HTTP request.</li> * <li>{@link #afterMarshalling} - Read the HTTP request after it is created and before it can be modified by other * interceptors.</li> * <li>{@link #modifyHttpRequest} - Modify the HTTP request object before it is transmitted.</li> * <li>{@link #beforeTransmission} - Read the HTTP request that has potentially been modified by other request interceptors * before it is sent to the service.</li> * <li>{@link #afterTransmission} - Read the HTTP response after it is received and before it can be modified by other * interceptors.</li> * <li>{@link #modifyHttpResponse} - Modify the HTTP response object before it is unmarshalled.</li> * <li>{@link #beforeUnmarshalling} - Read the HTTP response that has potentially been modified by other request interceptors * before it is unmarshalled.</li> * <li>{@link #afterUnmarshalling} - Read the response after it is created and before it can be modified by other * interceptors.</li> * <li>{@link #modifyResponse} - Modify the response object before before it is returned to the client.</li> * <li>{@link #afterExecution} - Read the response that has potentially been modified by other request interceptors.</li> * </ol> * An additional {@link #onExecutionFailure} method is provided that is invoked if an execution fails at any point during the * lifecycle of a request, including exceptions being thrown from this or other interceptors. * <p> * * <p> * <b>Interceptor Registration</b> * Interceptors can be registered in one of many ways. * <ol> * <li><i>Override Configuration Interceptors</i> are the most common method for SDK users to register an interceptor. These * interceptors are explicitly added to the client builder's override configuration when a client is created using the {@link * ClientOverrideConfiguration.Builder#addExecutionInterceptor(ExecutionInterceptor)} * method.</li> * * <li><i>Global Interceptors</i> are interceptors loaded from the classpath for all clients. When any service client is * created by a client builder, all jars on the classpath (from the perspective of the current thread's classloader) are * checked for a file named '/software/amazon/awssdk/global/handlers/execution.interceptors'. Any interceptors listed in these * files (new line separated) are instantiated using their default constructor and loaded into the client.</li> * * <li><i>Service Interceptors</i> are interceptors loaded from the classpath for a particular service's clients. When a * service client is created by a client builder, all jars on the classpath (from the perspective of the current thread's * classloader) are checked for a file named '/software/amazon/awssdk/services/{service}/execution.interceptors', where * {service} is the package name of the service client. Any interceptors listed in these files (new line separated) are * instantiated using their default constructor and loaded into the client.</li> * </ol> * <p> * * <p> * <b>Interceptor Order</b> * The order in which interceptors are executed is sometimes relevant to the accuracy of the interceptor itself. For example, an * interceptor that adds a field to a message should be executed before an interceptor that reads and modifies that field. * Interceptor's order is determined by their method of registration. The following order is used: * <ol> * <li><i>Global Interceptors</i>. Interceptors earlier in the classpath will be placed earlier in the interceptor order than * interceptors later in the classpath. Interceptors earlier within a specific file on the classpath will be placed earlier in * the order than interceptors later in the file.</li> * * <li><i>Service Interceptors</i>. Interceptors earlier in the classpath will be placed earlier in the interceptor order than * interceptors later in the classpath. Interceptors earlier within a specific file on the classpath will be placed earlier in * the order than interceptors later in the file.</li> * * <li><i>Override Configuration Interceptors</i>. Any interceptors registered using * {@link ClientOverrideConfiguration.Builder#addExecutionInterceptor(ExecutionInterceptor)} * in the order they were added.</li> * </ol> * When a request is being processed (up to and including {@link #beforeTransmission}, interceptors are applied in forward-order, * according to the order described above. When a response is being processed (after and including {@link #afterTransmission}, * interceptors are applied in reverse-order from the order described above. This means that the last interceptors to touch the * request are the first interceptors to touch the response. * <p> * * <p> * <b>Execution Attributes</b> * {@link ExecutionAttributes} are unique to an execution (the process of an SDK processing a {@link SdkRequest}). This mutable * collection of attributes is created when a call to a service client is made and can be mutated throughout the course of the * client call. These attributes are made available to every interceptor hook and is available for storing data between method * calls. The SDK provides some attributes automatically, available via {@link SdkExecutionAttribute}. */ @SdkPublicApi public interface ExecutionInterceptor { /** * Read a request that has been given to a service client before it is modified by other interceptors. * {@link #beforeMarshalling} should be used in most circumstances for reading the request because it includes modifications * made by other interceptors. * * <p>This method is guaranteed to be executed on the thread that is making the client call. This is true even if a non- * blocking I/O client is used. This is useful for transferring data that may be stored thread-locally into the execution's * {@link ExecutionAttributes}. * * @param context The current state of the execution, including the unmodified SDK request from the service client call. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to */ default void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { } /** * Modify an {@link SdkRequest} given to a service client before it is marshalled into an {@link SdkHttpFullRequest}. * * @param context The current state of the execution, including the current SDK request from the service client call. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to * give data to future lifecycle methods. * @return The potentially-modified request that should be used for the rest of the execution. Must not be null. */ default SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { return context.request(); } /** * Read the finalized request as it will be given to the marshaller to be converted into an {@link SdkHttpFullRequest}. * * @param context The current state of the execution, including the SDK request (potentially modified by other interceptors) * from the service client call. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to */ default void beforeMarshalling(Context.BeforeMarshalling context, ExecutionAttributes executionAttributes) { } /** * Read the marshalled HTTP request, before it is modified by other interceptors. {@link #beforeTransmission} should be used * in most circumstances for reading the HTTP request because it includes modifications made by other interceptors. * * @param context The current state of the execution, including the SDK and unmodified HTTP request. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to */ default void afterMarshalling(Context.AfterMarshalling context, ExecutionAttributes executionAttributes) { } /** * Modify the {@link SdkHttpFullRequest} before it is sent to the service. * * @param context The current state of the execution, including the SDK and current HTTP request. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to * give data to future lifecycle methods. * @return The potentially-modified HTTP request that should be sent to the service. Must not be null. */ default SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { return context.httpRequest(); } default Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { return context.requestBody(); } default Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { return context.asyncRequestBody(); } /** * Read the finalized HTTP request as it will be sent to the HTTP client. This includes modifications made by other * interceptors and the message signature. It is possible that the HTTP client could further modify the request, so debug- * level wire logging should be trusted over the parameters to this method. * * <p>Note: Unlike many other lifecycle methods, this one may be invoked multiple times. If the {@link RetryPolicy} determines * a request failure is retriable, this will be invoked for each retry attempt. * * @param context The current state of the execution, including the SDK and HTTP request (potentially modified by other * interceptors) to be sent to the downstream service. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to */ default void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { } /** * Read the HTTP response as it was returned by the HTTP client, before it is modified by other interceptors. * {@link #beforeUnmarshalling} should be used in most circumstances for reading the HTTP response because it includes * modifications made by other interceptors. * * <p>It is possible that the HTTP client could have already modified this response, so debug-level wire logging should be * trusted over the parameters to this method. * * <p>Note: Unlike many other lifecycle methods, this one may be invoked multiple times. If the {@link RetryPolicy} determines * the error code returned by the service is retriable, this will be invoked for each response returned by the service. * * @param context The current state of the execution, including the SDK and HTTP requests and the unmodified HTTP response. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to */ default void afterTransmission(Context.AfterTransmission context, ExecutionAttributes executionAttributes) { } /** * Modify the {@link SdkHttpFullRequest} before it is unmarshalled into an {@link SdkResponse}. * * <p>Note: Unlike many other lifecycle methods, this one may be invoked multiple times. If the {@link RetryPolicy} determines * the error code returned by the service is retriable, this will be invoked for each response returned by the service. * * @param context The current state of the execution, including the SDK and HTTP requests and the current HTTP response. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to * give data to future lifecycle methods. * @return The potentially-modified HTTP response that should be given to the unmarshaller. Must not be null. */ default SdkHttpResponse modifyHttpResponse(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { return context.httpResponse(); } /** * Modify the {@link SdkHttpFullRequest} before it is unmarshalled into an {@link SdkResponse}. * * <p>Note: Unlike many other lifecycle methods, this one may be invoked multiple times. If the {@link RetryPolicy} determines * the error code returned by the service is retriable, this will be invoked for each response returned by the service. * * @param context The current state of the execution, including the SDK and HTTP requests and the current HTTP response. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to * give data to future lifecycle methods. * @return The potentially-modified HTTP response that should be given to the unmarshaller. Must not be null. */ default Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { // get headers here return context.responsePublisher(); } /** * Modify the {@link SdkHttpFullRequest} before it is unmarshalled into an {@link SdkResponse}. * * <p>Note: Unlike many other lifecycle methods, this one may be invoked multiple times. If the {@link RetryPolicy} determines * the error code returned by the service is retriable, this will be invoked for each response returned by the service. * * @param context The current state of the execution, including the SDK and HTTP requests and the current HTTP response. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to * give data to future lifecycle methods. * @return The potentially-modified HTTP response that should be given to the unmarshaller. Must not be null. */ default Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { return context.responseBody(); } /** * Read the finalized HTTP response as it will be given to the unmarshaller to be converted into an {@link SdkResponse}. * * <p>Note: Unlike many other lifecycle methods, this one may be invoked multiple times. If the {@link RetryPolicy} determines * the error code returned by the service is retriable, this will be invoked for each response returned by the service. * * @param context The current state of the execution, including the SDK and HTTP requests as well as the (potentially * modified by other interceptors) HTTP response. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to * give data to future lifecycle methods. */ default void beforeUnmarshalling(Context.BeforeUnmarshalling context, ExecutionAttributes executionAttributes) { } /** * Read the {@link SdkResponse} as it was returned by the unmarshaller, before it is modified by other interceptors. * {@link #afterExecution} should be used in most circumstances for reading the SDK response because it includes * modifications made by other interceptors. * * @param context The current state of the execution, including the SDK and HTTP requests and the HTTP response. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to * give data to future lifecycle methods. */ default void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { } /** * Modify the {@link SdkResponse} before it is returned by the client. * * @param context The current state of the execution, including the SDK and HTTP requests as well as the SDK and HTTP * response. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to * give data to future lifecycle methods. * @return The potentially-modified SDK response that should be returned by the client. Must not be null. */ default SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) { return context.response(); } /** * Read the finalized {@link SdkResponse} as it will be returned by the client invocation. * * @param context The current state of the execution, including the SDK and HTTP requests as well as the SDK and HTTP * response. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to * give data to future lifecycle methods. */ default void afterExecution(Context.AfterExecution context, ExecutionAttributes executionAttributes) { } /** * Modify the exception before it is thrown. * * <p>This will only be invoked if the entire execution fails. If a retriable error happens (according to the * {@link RetryPolicy}) and a subsequent retry succeeds, this method will not be invoked. * * @param context The context associated with the execution that failed. An SDK request will always be available, but * depending on the time at which the failure happened, the HTTP request, HTTP response and SDK response may * not be available. This also includes the exception that triggered the failure. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to * give data to future lifecycle methods. * @return the modified Exception */ default Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) { return context.exception(); } /** * Invoked when any error happens during an execution that prevents the request from succeeding. This could be due to an * error returned by a service call, a request timeout or even another interceptor raising an exception. The provided * exception will be thrown by the service client. * * <p>This will only be invoked if the entire execution fails. If a retriable error happens (according to the * {@link RetryPolicy}) and a subsequent retry succeeds, this method will not be invoked. * * @param context The context associated with the execution that failed. An SDK request will always be available, but * depending on the time at which the failure happened, the HTTP request, HTTP response and SDK response may * not be available. This also includes the exception that triggered the failure. * @param executionAttributes A mutable set of attributes scoped to one specific request/response cycle that can be used to * give data to future lifecycle methods. */ default void onExecutionFailure(Context.FailedExecution context, ExecutionAttributes executionAttributes) { } }
2,090
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/interceptor/InterceptorContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.interceptor; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Optional; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An SDK-internal implementation of {@link Context.AfterExecution} and its parent interfaces. */ @SdkProtectedApi public final class InterceptorContext implements Context.AfterExecution, Context.ModifyHttpRequest, ToCopyableBuilder<InterceptorContext.Builder, InterceptorContext> { private final SdkRequest request; private final SdkHttpRequest httpRequest; private final Optional<RequestBody> requestBody; private final SdkHttpResponse httpResponse; private final Optional<InputStream> responseBody; private final SdkResponse response; private final Optional<AsyncRequestBody> asyncRequestBody; private final Optional<Publisher<ByteBuffer>> responsePublisher; private InterceptorContext(Builder builder) { this.request = Validate.paramNotNull(builder.request, "request"); this.httpRequest = builder.httpRequest; this.requestBody = builder.requestBody; this.httpResponse = builder.httpResponse; this.responseBody = builder.responseBody; this.response = builder.response; this.asyncRequestBody = builder.asyncRequestBody; this.responsePublisher = builder.responsePublisher; } public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return new Builder(this); } @Override public SdkRequest request() { return request; } @Override public Optional<RequestBody> requestBody() { return requestBody; } @Override public Optional<AsyncRequestBody> asyncRequestBody() { return asyncRequestBody; } @Override public Optional<Publisher<ByteBuffer>> responsePublisher() { return responsePublisher; } @Override public SdkHttpRequest httpRequest() { return httpRequest; } @Override public SdkHttpResponse httpResponse() { return httpResponse; } @Override public Optional<InputStream> responseBody() { return responseBody; } @Override public SdkResponse response() { return response; } @NotThreadSafe @SdkPublicApi public static final class Builder implements CopyableBuilder<Builder, InterceptorContext> { private SdkRequest request; private SdkHttpRequest httpRequest; private Optional<RequestBody> requestBody = Optional.empty(); private SdkHttpResponse httpResponse; private Optional<InputStream> responseBody = Optional.empty(); private SdkResponse response; private Optional<AsyncRequestBody> asyncRequestBody = Optional.empty(); private Optional<Publisher<ByteBuffer>> responsePublisher = Optional.empty(); private Builder() { super(); } private Builder(InterceptorContext context) { this.request = context.request; this.httpRequest = context.httpRequest; this.requestBody = context.requestBody; this.httpResponse = context.httpResponse; this.responseBody = context.responseBody; this.response = context.response; this.asyncRequestBody = context.asyncRequestBody; this.responsePublisher = context.responsePublisher; } public Builder request(SdkRequest request) { this.request = request; return this; } public Builder httpRequest(SdkHttpRequest httpRequest) { this.httpRequest = httpRequest; return this; } public Builder requestBody(RequestBody requestBody) { this.requestBody = Optional.ofNullable(requestBody); return this; } public Builder httpResponse(SdkHttpResponse httpResponse) { this.httpResponse = httpResponse; return this; } public Builder responseBody(InputStream responseBody) { this.responseBody = Optional.ofNullable(responseBody); return this; } public Builder response(SdkResponse response) { this.response = response; return this; } public Builder asyncRequestBody(AsyncRequestBody asyncRequestBody) { this.asyncRequestBody = Optional.ofNullable(asyncRequestBody); return this; } public Builder responsePublisher(Publisher<ByteBuffer> responsePublisher) { this.responsePublisher = Optional.ofNullable(responsePublisher); return this; } @Override public InterceptorContext build() { return new InterceptorContext(this); } } }
2,091
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/interceptor/SdkInternalExecutionAttribute.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.interceptor; import java.util.Map; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkProtocolMetadata; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.interceptor.trait.HttpChecksum; import software.amazon.awssdk.core.interceptor.trait.HttpChecksumRequired; import software.amazon.awssdk.core.internal.interceptor.trait.RequestCompression; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.endpoints.EndpointProvider; import software.amazon.awssdk.http.SdkHttpExecutionAttributes; 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.utils.AttributeMap; /** * Attributes that can be applied to all sdk requests. Only generated code from the SDK clients should set these values. */ @SdkProtectedApi public final class SdkInternalExecutionAttribute extends SdkExecutionAttribute { /** * The key to indicate if the request is for a full duplex operation ie., request and response are sent/received * at the same time. */ public static final ExecutionAttribute<Boolean> IS_FULL_DUPLEX = new ExecutionAttribute<>("IsFullDuplex"); /** * If true, indicates that this is an event streaming request being sent over RPC, and therefore the serialized * request object is encapsulated as an event of type {@code initial-request}. */ public static final ExecutionAttribute<Boolean> HAS_INITIAL_REQUEST_EVENT = new ExecutionAttribute<>( "HasInitialRequestEvent"); public static final ExecutionAttribute<HttpChecksumRequired> HTTP_CHECKSUM_REQUIRED = new ExecutionAttribute<>("HttpChecksumRequired"); /** * Whether host prefix injection has been disabled on the client. * See {@link software.amazon.awssdk.core.client.config.SdkAdvancedClientOption#DISABLE_HOST_PREFIX_INJECTION} */ public static final ExecutionAttribute<Boolean> DISABLE_HOST_PREFIX_INJECTION = new ExecutionAttribute<>("DisableHostPrefixInjection"); /** * Key to indicate if the Http Checksums that are valid for an operation. */ public static final ExecutionAttribute<HttpChecksum> HTTP_CHECKSUM = new ExecutionAttribute<>("HttpChecksum"); /** * The SDK HTTP attributes that can be passed to the HTTP client */ public static final ExecutionAttribute<SdkHttpExecutionAttributes> SDK_HTTP_EXECUTION_ATTRIBUTES = new ExecutionAttribute<>("SdkHttpExecutionAttributes"); public static final ExecutionAttribute<Boolean> IS_NONE_AUTH_TYPE_REQUEST = new ExecutionAttribute<>("IsNoneAuthTypeRequest"); /** * The endpoint provider used to resolve the destination endpoint for a request. */ public static final ExecutionAttribute<EndpointProvider> ENDPOINT_PROVIDER = new ExecutionAttribute<>("EndpointProvider"); /** * The resolved endpoint as computed by the client's configured {@link EndpointProvider}. */ public static final ExecutionAttribute<Endpoint> RESOLVED_ENDPOINT = new ExecutionAttribute<>("ResolvedEndpoint"); /** * The values of client context params declared for this service. Client contet params are one possible source of inputs into * the endpoint provider for the client. */ public static final ExecutionAttribute<AttributeMap> CLIENT_CONTEXT_PARAMS = new ExecutionAttribute<>("ClientContextParams"); /** * Whether the endpoint on the request is the result of Endpoint Discovery. */ public static final ExecutionAttribute<Boolean> IS_DISCOVERED_ENDPOINT = new ExecutionAttribute<>("IsDiscoveredEndpoint"); /** * The auth scheme provider used to resolve the auth scheme for a request. */ public static final ExecutionAttribute<AuthSchemeProvider> AUTH_SCHEME_RESOLVER = new ExecutionAttribute<>("AuthSchemeProvider"); /** * The auth schemes available for a request. */ public static final ExecutionAttribute<Map<String, AuthScheme<?>>> AUTH_SCHEMES = new ExecutionAttribute<>("AuthSchemes"); /** * The {@link IdentityProviders} for a request. */ public static final ExecutionAttribute<IdentityProviders> IDENTITY_PROVIDERS = new ExecutionAttribute<>("IdentityProviders"); /** * The selected auth scheme for a request. */ public static final ExecutionAttribute<SelectedAuthScheme<?>> SELECTED_AUTH_SCHEME = new ExecutionAttribute<>("SelectedAuthScheme"); /** * The supported compression algorithms for an operation, and whether the operation is streaming or not. */ public static final ExecutionAttribute<RequestCompression> REQUEST_COMPRESSION = new ExecutionAttribute<>("RequestCompression"); /** * The key under which the protocol metadata is stored. */ public static final ExecutionAttribute<SdkProtocolMetadata> PROTOCOL_METADATA = new ExecutionAttribute<>("ProtocolMetadata"); /** * The backing attribute for RESOLVED_CHECKSUM_SPECS. * This holds the real ChecksumSpecs value, and is used to map to the ChecksumAlgorithm signer property * in the SELECTED_AUTH_SCHEME execution attribute. */ static final ExecutionAttribute<ChecksumSpecs> INTERNAL_RESOLVED_CHECKSUM_SPECS = new ExecutionAttribute<>("InternalResolvedChecksumSpecs"); private SdkInternalExecutionAttribute() { } }
2,092
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/interceptor/SdkExecutionAttribute.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.interceptor; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32C; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA1; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA256; import static software.amazon.awssdk.http.auth.aws.internal.signer.util.ChecksumUtil.checksumHeaderName; import java.net.URI; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.checksums.spi.ChecksumAlgorithm; import software.amazon.awssdk.core.ClientType; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.ServiceConfiguration; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.checksums.ChecksumValidation; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignedRequest; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.ImmutableMap; /** * Contains attributes attached to the execution. This information is available to {@link ExecutionInterceptor}s and * {@link Signer}s. */ @SdkPublicApi public class SdkExecutionAttribute { /** * Handler context key for advanced configuration. */ public static final ExecutionAttribute<ServiceConfiguration> SERVICE_CONFIG = new ExecutionAttribute<>("ServiceConfig"); /** * The key under which the service name is stored. */ public static final ExecutionAttribute<String> SERVICE_NAME = new ExecutionAttribute<>("ServiceName"); /** * The key under which the time offset (for clock skew correction) is stored. */ public static final ExecutionAttribute<Integer> TIME_OFFSET = new ExecutionAttribute<>("TimeOffset"); public static final ExecutionAttribute<ClientType> CLIENT_TYPE = new ExecutionAttribute<>("ClientType"); public static final ExecutionAttribute<String> OPERATION_NAME = new ExecutionAttribute<>("OperationName"); /** * The {@link MetricCollector} associated with the overall API call. */ public static final ExecutionAttribute<MetricCollector> API_CALL_METRIC_COLLECTOR = new ExecutionAttribute<>( "ApiCallMetricCollector"); /** * The {@link MetricCollector} associated with the current, ongoing API call attempt. This is not set until the actual * internal API call attempt starts. */ public static final ExecutionAttribute<MetricCollector> API_CALL_ATTEMPT_METRIC_COLLECTOR = new ExecutionAttribute<>("ApiCallAttemptMetricCollector"); /** * If true indicates that the configured endpoint of the client is a value that was supplied as an override and not * generated from regional metadata. */ public static final ExecutionAttribute<Boolean> ENDPOINT_OVERRIDDEN = new ExecutionAttribute<>("EndpointOverridden"); /** * This is the endpointOverride (if {@link #ENDPOINT_OVERRIDDEN} is true), otherwise the endpoint generated from regional * metadata. */ public static final ExecutionAttribute<URI> CLIENT_ENDPOINT = new ExecutionAttribute<>("EndpointOverride"); /** * If the client signer value has been overridden. */ public static final ExecutionAttribute<Boolean> SIGNER_OVERRIDDEN = new ExecutionAttribute<>("SignerOverridden"); /** * @deprecated This attribute is used for: * - Set profile file of service endpoint builder docdb, nepture, rds * This has been replaced with {@code PROFILE_FILE_SUPPLIER.get()}. */ @Deprecated public static final ExecutionAttribute<ProfileFile> PROFILE_FILE = new ExecutionAttribute<>("ProfileFile"); public static final ExecutionAttribute<Supplier<ProfileFile>> PROFILE_FILE_SUPPLIER = new ExecutionAttribute<>("ProfileFileSupplier"); public static final ExecutionAttribute<String> PROFILE_NAME = new ExecutionAttribute<>("ProfileName"); /** * The checksum algorithm is resolved based on the Request member. * The RESOLVED_CHECKSUM_SPECS holds the final checksum which will be used for checksum computation. */ public static final ExecutionAttribute<ChecksumSpecs> RESOLVED_CHECKSUM_SPECS = ExecutionAttribute.mappedBuilder("ResolvedChecksumSpecs", () -> SdkInternalExecutionAttribute.INTERNAL_RESOLVED_CHECKSUM_SPECS, () -> SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME) .readMapping(SdkExecutionAttribute::signerChecksumReadMapping) .writeMapping(SdkExecutionAttribute::signerChecksumWriteMapping) .build(); /** * The Algorithm used for checksum validation of a response. */ public static final ExecutionAttribute<Algorithm> HTTP_CHECKSUM_VALIDATION_ALGORITHM = new ExecutionAttribute<>( "HttpChecksumValidationAlgorithm"); /** * Provides the status of {@link ChecksumValidation} performed on the response. */ public static final ExecutionAttribute<ChecksumValidation> HTTP_RESPONSE_CHECKSUM_VALIDATION = new ExecutionAttribute<>( "HttpResponseChecksumValidation"); private static final ImmutableMap<ChecksumAlgorithm, Algorithm> ALGORITHM_MAP = ImmutableMap.of( SHA256, Algorithm.SHA256, SHA1, Algorithm.SHA1, CRC32, Algorithm.CRC32, CRC32C, Algorithm.CRC32C ); private static final ImmutableMap<Algorithm, ChecksumAlgorithm> CHECKSUM_ALGORITHM_MAP = ImmutableMap.of( Algorithm.SHA256, SHA256, Algorithm.SHA1, SHA1, Algorithm.CRC32, CRC32, Algorithm.CRC32C, CRC32C ); protected SdkExecutionAttribute() { } /** * Map from the SelectedAuthScheme and the backing ChecksumSpecs value to a new value for ChecksumSpecs. */ private static <T extends Identity> ChecksumSpecs signerChecksumReadMapping(ChecksumSpecs checksumSpecs, SelectedAuthScheme<T> authScheme) { if (checksumSpecs == null || authScheme == null) { return checksumSpecs; } ChecksumAlgorithm checksumAlgorithm = authScheme.authSchemeOption().signerProperty(AwsV4FamilyHttpSigner.CHECKSUM_ALGORITHM); return ChecksumSpecs.builder() .algorithm(checksumAlgorithm != null ? ALGORITHM_MAP.get(checksumAlgorithm) : null) .isRequestStreaming(checksumSpecs.isRequestStreaming()) .isRequestChecksumRequired(checksumSpecs.isRequestChecksumRequired()) .isValidationEnabled(checksumSpecs.isValidationEnabled()) .headerName(checksumAlgorithm != null ? checksumHeaderName(checksumAlgorithm) : null) .responseValidationAlgorithms(checksumSpecs.responseValidationAlgorithms()) .build(); } /** * Map from ChecksumSpecs to a SelectedAuthScheme with the CHECKSUM_ALGORITHM signer property set. */ private static <T extends Identity> SelectedAuthScheme<?> signerChecksumWriteMapping(SelectedAuthScheme<T> authScheme, ChecksumSpecs checksumSpecs) { ChecksumAlgorithm checksumAlgorithm = checksumSpecs == null ? null : CHECKSUM_ALGORITHM_MAP.get(checksumSpecs.algorithm()); if (authScheme == null) { // This is an unusual use-case. // Let's assume they're setting the checksum-algorithm so that they can call the signer directly. If that's true, // then it doesn't really matter what we store other than the checksum-algorithm. return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()), new UnsetHttpSigner(), AuthSchemeOption.builder() .schemeId("unset") .putSignerProperty(AwsV4FamilyHttpSigner.CHECKSUM_ALGORITHM, checksumAlgorithm) .build()); } return new SelectedAuthScheme<>(authScheme.identity(), authScheme.signer(), authScheme.authSchemeOption() .copy(o -> o.putSignerProperty(AwsV4FamilyHttpSigner.CHECKSUM_ALGORITHM, checksumAlgorithm))); } private static class UnsetIdentity implements Identity { } private static class UnsetHttpSigner implements HttpSigner<UnsetIdentity> { @Override public SignedRequest sign(SignRequest<? extends UnsetIdentity> request) { throw new IllegalStateException("A signer was not configured."); } @Override public CompletableFuture<AsyncSignedRequest> signAsync(AsyncSignRequest<? extends UnsetIdentity> request) { return CompletableFutureUtils.failedFuture(new IllegalStateException("A signer was not configured.")); } } }
2,093
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/interceptor/ExecutionAttributes.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.interceptor; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A mutable collection of {@link ExecutionAttribute}s that can be modified by {@link ExecutionInterceptor}s in order to save and * retrieve information specific to the current execution. * * This is useful for sharing data between {@link ExecutionInterceptor} method calls specific to a particular execution. */ @SdkPublicApi @NotThreadSafe public class ExecutionAttributes implements ToCopyableBuilder<ExecutionAttributes.Builder, ExecutionAttributes> { private final Map<ExecutionAttribute<?>, Object> attributes; public ExecutionAttributes() { this.attributes = new HashMap<>(32); } protected ExecutionAttributes(Map<? extends ExecutionAttribute<?>, ?> attributes) { this.attributes = new HashMap<>(attributes); } /** * Retrieve the current value of the provided attribute in this collection of attributes. This will return null if the value * is not set. */ public <U> U getAttribute(ExecutionAttribute<U> attribute) { return attribute.storage().get(attributes); } /** * Retrieve the collection of attributes. */ public Map<ExecutionAttribute<?>, Object> getAttributes() { return Collections.unmodifiableMap(attributes); } /** * Retrieve the Optional current value of the provided attribute in this collection of attributes. * This will return Optional Value. */ public <U> Optional<U> getOptionalAttribute(ExecutionAttribute<U> attribute) { return Optional.ofNullable(getAttribute(attribute)); } /** * Update or set the provided attribute in this collection of attributes. */ public <U> ExecutionAttributes putAttribute(ExecutionAttribute<U> attribute, U value) { attribute.storage().set(attributes, value); return this; } /** * Set the provided attribute in this collection of attributes if it does not already exist in the collection. */ public <U> ExecutionAttributes putAttributeIfAbsent(ExecutionAttribute<U> attribute, U value) { attribute.storage().setIfAbsent(attributes, value); return this; } /** * Merge attributes of a higher precedence into the current lower precedence collection. */ public ExecutionAttributes merge(ExecutionAttributes lowerPrecedenceExecutionAttributes) { Map<ExecutionAttribute<?>, Object> copiedAttributes = new HashMap<>(this.attributes); lowerPrecedenceExecutionAttributes.getAttributes().forEach(copiedAttributes::putIfAbsent); return new ExecutionAttributes(copiedAttributes); } /** * Add the provided attributes to this attribute, if the provided attribute does not exist. */ public void putAbsentAttributes(ExecutionAttributes lowerPrecedenceExecutionAttributes) { if (lowerPrecedenceExecutionAttributes != null) { lowerPrecedenceExecutionAttributes.getAttributes().forEach(attributes::putIfAbsent); } } public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return new ExecutionAttributes.Builder(this); } public ExecutionAttributes copy() { return toBuilder().build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || !(o instanceof ExecutionAttributes)) { return false; } ExecutionAttributes that = (ExecutionAttributes) o; return attributes != null ? attributes.equals(that.attributes) : that.attributes == null; } @Override public int hashCode() { return attributes != null ? attributes.hashCode() : 0; } @Override public String toString() { return ToString.builder("ExecutionAttributes") .add("attributes", attributes.keySet()) .build(); } public static ExecutionAttributes unmodifiableExecutionAttributes(ExecutionAttributes attributes) { return new UnmodifiableExecutionAttributes(attributes); } private static class UnmodifiableExecutionAttributes extends ExecutionAttributes { UnmodifiableExecutionAttributes(ExecutionAttributes executionAttributes) { super(executionAttributes.attributes); } @Override public <U> ExecutionAttributes putAttribute(ExecutionAttribute<U> attribute, U value) { throw new UnsupportedOperationException(); } @Override public <U> ExecutionAttributes putAttributeIfAbsent(ExecutionAttribute<U> attribute, U value) { throw new UnsupportedOperationException(); } } /** * TODO: We should deprecate this builder - execution attributes are mutable - why do we need a builder? We can just use * copy() if it's because of {@link #unmodifiableExecutionAttributes(ExecutionAttributes)}. */ public static final class Builder implements CopyableBuilder<ExecutionAttributes.Builder, ExecutionAttributes> { private final Map<ExecutionAttribute<?>, Object> executionAttributes = new HashMap<>(32); private Builder() { } private Builder(ExecutionAttributes source) { this.executionAttributes.putAll(source.attributes); } /** * Add a mapping between the provided key and value. */ public <T> ExecutionAttributes.Builder put(ExecutionAttribute<T> key, T value) { Validate.notNull(key, "Key to set must not be null."); key.storage().set(executionAttributes, value); return this; } /** * Adds all the attributes from the map provided. */ public ExecutionAttributes.Builder putAll(Map<? extends ExecutionAttribute<?>, ?> attributes) { attributes.forEach(this::unsafePut); return this; } /** * There is no way to make this safe without runtime checks, which we can't do because we don't have the class of T. * This will just throw an exception at runtime if the types don't match up. */ @SuppressWarnings("unchecked") private <T> void unsafePut(ExecutionAttribute<T> key, Object value) { key.storage().set(executionAttributes, (T) value); } @Override public ExecutionAttributes build() { return new ExecutionAttributes(executionAttributes); } } }
2,094
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/interceptor
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/interceptor/trait/HttpChecksum.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.interceptor.trait; import java.util.Arrays; import java.util.List; import java.util.Objects; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public class HttpChecksum { private final boolean requestChecksumRequired; private final String requestAlgorithm; private final String requestValidationMode; private final boolean isRequestStreaming; private final List<String> responseAlgorithms; private HttpChecksum(Builder builder) { this.requestChecksumRequired = builder.requestChecksumRequired; this.requestAlgorithm = builder.requestAlgorithm; this.requestValidationMode = builder.requestValidationMode; this.responseAlgorithms = builder.responseAlgorithms; this.isRequestStreaming = builder.isRequestStreaming; } public boolean isRequestChecksumRequired() { return requestChecksumRequired; } public String requestAlgorithm() { return requestAlgorithm; } public List<String> responseAlgorithms() { return responseAlgorithms; } public String requestValidationMode() { return requestValidationMode; } public boolean isRequestStreaming() { return isRequestStreaming; } public static Builder builder() { return new Builder(); } public static final class Builder { private boolean requestChecksumRequired; private String requestAlgorithm; private String requestValidationMode; private List<String> responseAlgorithms; private boolean isRequestStreaming; public Builder requestChecksumRequired(boolean requestChecksumRequired) { this.requestChecksumRequired = requestChecksumRequired; return this; } public Builder requestAlgorithm(String requestAlgorithm) { this.requestAlgorithm = requestAlgorithm; return this; } public Builder requestValidationMode(String requestValidationMode) { this.requestValidationMode = requestValidationMode; return this; } public Builder responseAlgorithms(List<String> responseAlgorithms) { this.responseAlgorithms = responseAlgorithms; return this; } public Builder responseAlgorithms(String... responseAlgorithms) { if (responseAlgorithms != null) { this.responseAlgorithms = Arrays.asList(responseAlgorithms); } return this; } public Builder isRequestStreaming(boolean isRequestStreaming) { this.isRequestStreaming = isRequestStreaming; return this; } public HttpChecksum build() { return new HttpChecksum(this); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } HttpChecksum that = (HttpChecksum) o; return requestChecksumRequired == that.requestChecksumRequired && isRequestStreaming == that.isRequestStreaming && Objects.equals(requestAlgorithm, that.requestAlgorithm) && Objects.equals(requestValidationMode, that.requestValidationMode) && Objects.equals(responseAlgorithms, that.responseAlgorithms); } @Override public int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + (requestChecksumRequired ? 1 : 0); hashCode = 31 * hashCode + (isRequestStreaming ? 1 : 0); hashCode = 31 * hashCode + Objects.hashCode(requestAlgorithm); hashCode = 31 * hashCode + Objects.hashCode(requestValidationMode); hashCode = 31 * hashCode + Objects.hashCode(responseAlgorithms); return hashCode; } }
2,095
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/interceptor
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/interceptor/trait/HttpChecksumRequired.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.interceptor.trait; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public class HttpChecksumRequired { private HttpChecksumRequired() { } public static HttpChecksumRequired create() { return new HttpChecksumRequired(); } }
2,096
0
Create_ds/aws-sdk-java-v2/core/metrics-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/metrics-spi/src/test/java/software/amazon/awssdk/metrics/LoggingMetricPublisherTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics; import static org.apache.logging.log4j.Level.DEBUG; import static org.apache.logging.log4j.Level.INFO; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.core.LogEvent; import org.junit.jupiter.api.Test; import org.slf4j.event.Level; import software.amazon.awssdk.metrics.LoggingMetricPublisher.Format; import software.amazon.awssdk.metrics.internal.DefaultMetricCollection; import software.amazon.awssdk.metrics.internal.DefaultMetricRecord; import software.amazon.awssdk.testutils.LogCaptor; class LoggingMetricPublisherTest { private static final SdkMetric<Integer> TEST_METRIC = SdkMetric.create("LoggingMetricPublisherTest", Integer.class, MetricLevel.INFO, MetricCategory.CORE); @Test void testDefaultConfiguration() { MetricCollection qux = metrics("qux"); MetricCollection baz = metrics("baz"); MetricCollection bar = metrics("bar", baz); MetricCollection foo = metrics("foo", bar, qux); LoggingMetricPublisher publisher = LoggingMetricPublisher.create(); try (LogCaptor logCaptor = LogCaptor.create()) { publisher.publish(foo); List<LogEvent> events = logCaptor.loggedEvents(); assertLogged(events, INFO, "Metrics published: %s", foo); assertThat(events).isEmpty(); } } @Test void testPrettyFormat() { MetricCollection qux = metrics("qux"); MetricCollection baz = metrics("baz"); MetricCollection bar = metrics("bar", baz); MetricCollection foo = metrics("foo", bar, qux); String guid = Integer.toHexString(foo.hashCode()); LoggingMetricPublisher publisher = LoggingMetricPublisher.create(Level.DEBUG, Format.PRETTY); try (LogCaptor logCaptor = LogCaptor.create()) { publisher.publish(foo); List<LogEvent> events = logCaptor.loggedEvents(); assertLogged(events, DEBUG, "[%s] foo", guid); assertLogged(events, DEBUG, "[%s] β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”", guid); assertLogged(events, DEBUG, "[%s] β”‚ LoggingMetricPublisherTest=1 β”‚", guid); assertLogged(events, DEBUG, "[%s] β”‚ LoggingMetricPublisherTest=2 β”‚", guid); assertLogged(events, DEBUG, "[%s] β”‚ LoggingMetricPublisherTest=3 β”‚", guid); assertLogged(events, DEBUG, "[%s] β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜", guid); assertLogged(events, DEBUG, "[%s] bar", guid); assertLogged(events, DEBUG, "[%s] β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”", guid); assertLogged(events, DEBUG, "[%s] β”‚ LoggingMetricPublisherTest=1 β”‚", guid); assertLogged(events, DEBUG, "[%s] β”‚ LoggingMetricPublisherTest=2 β”‚", guid); assertLogged(events, DEBUG, "[%s] β”‚ LoggingMetricPublisherTest=3 β”‚", guid); assertLogged(events, DEBUG, "[%s] β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜", guid); assertLogged(events, DEBUG, "[%s] baz", guid); assertLogged(events, DEBUG, "[%s] β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”", guid); assertLogged(events, DEBUG, "[%s] β”‚ LoggingMetricPublisherTest=1 β”‚", guid); assertLogged(events, DEBUG, "[%s] β”‚ LoggingMetricPublisherTest=2 β”‚", guid); assertLogged(events, DEBUG, "[%s] β”‚ LoggingMetricPublisherTest=3 β”‚", guid); assertLogged(events, DEBUG, "[%s] β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜", guid); assertLogged(events, DEBUG, "[%s] qux", guid); assertLogged(events, DEBUG, "[%s] β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”", guid); assertLogged(events, DEBUG, "[%s] β”‚ LoggingMetricPublisherTest=1 β”‚", guid); assertLogged(events, DEBUG, "[%s] β”‚ LoggingMetricPublisherTest=2 β”‚", guid); assertLogged(events, DEBUG, "[%s] β”‚ LoggingMetricPublisherTest=3 β”‚", guid); assertLogged(events, DEBUG, "[%s] β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜", guid); assertThat(events).isEmpty(); } } private static MetricCollection metrics(String name, MetricCollection... children) { Integer[] values = {1, 2, 3}; Map<SdkMetric<?>, List<MetricRecord<?>>> recordMap = new HashMap<>(); List<MetricRecord<?>> records = Stream.of(values).map(v -> new DefaultMetricRecord<>(TEST_METRIC, v)).collect(Collectors.toList()); recordMap.put(TEST_METRIC, records); return new DefaultMetricCollection(name, recordMap, Arrays.asList(children)); } private static void assertLogged(List<LogEvent> events, org.apache.logging.log4j.Level level, String message, Object... args) { assertThat(events).withFailMessage("Expecting events to not be empty").isNotEmpty(); LogEvent event = events.remove(0); String msg = event.getMessage().getFormattedMessage(); assertThat(msg).isEqualTo(String.format(message, args)); assertThat(event.getLevel()).isEqualTo(level); } }
2,097
0
Create_ds/aws-sdk-java-v2/core/metrics-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/metrics-spi/src/test/java/software/amazon/awssdk/metrics/MetricLevelTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; public class MetricLevelTest { @Test public void allLevelsAreCorrect() { assertThat(MetricLevel.TRACE.includesLevel(MetricLevel.TRACE)).isTrue(); assertThat(MetricLevel.TRACE.includesLevel(MetricLevel.INFO)).isTrue(); assertThat(MetricLevel.TRACE.includesLevel(MetricLevel.ERROR)).isTrue(); } @Test public void infoLevelsAreCorrect() { assertThat(MetricLevel.INFO.includesLevel(MetricLevel.TRACE)).isFalse(); assertThat(MetricLevel.INFO.includesLevel(MetricLevel.INFO)).isTrue(); assertThat(MetricLevel.INFO.includesLevel(MetricLevel.ERROR)).isTrue(); } @Test public void errorLevelsAreCorrect() { assertThat(MetricLevel.ERROR.includesLevel(MetricLevel.TRACE)).isFalse(); assertThat(MetricLevel.ERROR.includesLevel(MetricLevel.INFO)).isFalse(); assertThat(MetricLevel.ERROR.includesLevel(MetricLevel.ERROR)).isTrue(); } }
2,098
0
Create_ds/aws-sdk-java-v2/core/metrics-spi/src/test/java/software/amazon/awssdk/metrics
Create_ds/aws-sdk-java-v2/core/metrics-spi/src/test/java/software/amazon/awssdk/metrics/internal/DefaultSdkMetricTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.metrics.MetricCategory; import software.amazon.awssdk.metrics.MetricLevel; import software.amazon.awssdk.metrics.SdkMetric; public class DefaultSdkMetricTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void methodSetup() { DefaultSdkMetric.clearDeclaredMetrics(); } @Test public void testOf_variadicOverload_createdProperly() { SdkMetric<Integer> event = SdkMetric.create("event", Integer.class, MetricLevel.INFO, MetricCategory.CORE); assertThat(event.categories()).containsExactly(MetricCategory.CORE); assertThat(event.name()).isEqualTo("event"); assertThat(event.valueClass()).isEqualTo(Integer.class); } @Test public void testOf_setOverload_createdProperly() { SdkMetric<Integer> event = SdkMetric.create("event", Integer.class, MetricLevel.INFO, Stream.of(MetricCategory.CORE) .collect(Collectors.toSet())); assertThat(event.categories()).containsExactly(MetricCategory.CORE); assertThat(event.name()).isEqualTo("event"); assertThat(event.valueClass()).isEqualTo(Integer.class); } @Test public void testOf_variadicOverload_c1Null_throws() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("must not contain null elements"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, (MetricCategory) null); } @Test public void testOf_variadicOverload_c1NotNull_cnNull_doesNotThrow() { SdkMetric.create("event", Integer.class, MetricLevel.INFO, MetricCategory.CORE, null); } @Test public void testOf_variadicOverload_cnContainsNull_throws() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("must not contain null elements"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, MetricCategory.CORE, new MetricCategory[]{null }); } @Test public void testOf_setOverload_null_throws() { thrown.expect(NullPointerException.class); thrown.expectMessage("object is null"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, (Set<MetricCategory>) null); } @Test public void testOf_setOverload_nullElement_throws() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("categories must not contain null elements"); SdkMetric.create("event", Integer.class, MetricLevel.INFO, Stream.of((MetricCategory) null).collect(Collectors.toSet())); } @Test public void testOf_namePreviouslyUsed_throws() { String fooName = "metricEvent"; thrown.expect(IllegalArgumentException.class); thrown.expectMessage(fooName + " has already been created"); SdkMetric.create(fooName, Integer.class, MetricLevel.INFO, MetricCategory.CORE); SdkMetric.create(fooName, Integer.class, MetricLevel.INFO, MetricCategory.CORE); } @Test public void testOf_namePreviouslyUsed_differentArgs_throws() { String fooName = "metricEvent"; thrown.expect(IllegalArgumentException.class); thrown.expectMessage(fooName + " has already been created"); SdkMetric.create(fooName, Integer.class, MetricLevel.INFO, MetricCategory.CORE); SdkMetric.create(fooName, Long.class, MetricLevel.INFO, MetricCategory.HTTP_CLIENT); } @Test public void testOf_namePreviouslyUsed_doesNotReplaceExisting() { String fooName = "fooMetric"; thrown.expect(IllegalArgumentException.class); thrown.expectMessage(fooName + " has already been created"); SdkMetric.create(fooName, Integer.class, MetricLevel.INFO, MetricCategory.CORE); try { SdkMetric.create(fooName, Long.class, MetricLevel.INFO, MetricCategory.HTTP_CLIENT); } finally { SdkMetric<?> fooMetric = DefaultSdkMetric.declaredEvents() .stream() .filter(e -> e.name().equals(fooName)) .findFirst() .get(); assertThat(fooMetric.name()).isEqualTo(fooName); assertThat(fooMetric.valueClass()).isEqualTo(Integer.class); assertThat(fooMetric.categories()).containsExactly(MetricCategory.CORE); } } }
2,099