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/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/async/EmptySubscription.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.async;
import java.util.concurrent.atomic.AtomicBoolean;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* A NoOp implementation of {@link Subscription} interface.
*
* This subscription calls {@link Subscriber#onComplete()} on first request for data and then terminates the subscription.
*/
@SdkProtectedApi
public final class EmptySubscription implements Subscription {
private final AtomicBoolean isTerminated = new AtomicBoolean(false);
private final Subscriber subscriber;
public EmptySubscription(Subscriber subscriber) {
this.subscriber = subscriber;
}
@Override
public void request(long n) {
if (isTerminated()) {
return;
}
if (n <= 0) {
throw new IllegalArgumentException("Non-positive request signals are illegal");
}
if (terminate()) {
subscriber.onComplete();
}
}
@Override
public void cancel() {
terminate();
}
private boolean terminate() {
return isTerminated.compareAndSet(false, true);
}
private boolean isTerminated() {
return isTerminated.get();
}
}
| 1,800 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/async/ResponsesSubscription.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.async;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* An implementation of the {@link Subscription} interface that can be used to signal and cancel demand for
* paginated response pages.
*
* @param <ResponseT> The type of a single response page
*/
@SdkProtectedApi
public final class ResponsesSubscription<ResponseT> extends PaginationSubscription<ResponseT> {
private ResponsesSubscription(BuilderImpl builder) {
super(builder);
}
/**
* Create a builder for creating a {@link ResponsesSubscription}.
*/
public static Builder builder() {
return new BuilderImpl();
}
@Override
protected void handleRequests() {
if (!hasNextPage()) {
completeSubscription();
return;
}
synchronized (this) {
if (outstandingRequests.get() <= 0) {
stopTask();
return;
}
}
if (!isTerminated()) {
outstandingRequests.getAndDecrement();
nextPageFetcher.nextPage(currentPage)
.whenComplete(((response, error) -> {
if (response != null) {
currentPage = response;
subscriber.onNext(response);
handleRequests();
}
if (error != null) {
subscriber.onError(error);
cleanup();
}
}));
}
}
public interface Builder extends PaginationSubscription.Builder<ResponsesSubscription, Builder> {
@Override
ResponsesSubscription build();
}
private static final class BuilderImpl extends PaginationSubscription.BuilderImpl<ResponsesSubscription, Builder>
implements Builder {
@Override
public ResponsesSubscription build() {
return new ResponsesSubscription(this);
}
}
}
| 1,801 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/async/PaginatedItemsPublisher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.async;
import java.util.Iterator;
import java.util.function.Function;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.internal.pagination.async.ItemsSubscription;
/**
* A publisher to request for a stream of paginated items. The class can be used to request data for paginated items
* across multiple pages.
*
* @param <ResponseT> The type of a single response page
* @param <ItemT> The type of paginated member in a response page
*/
@SdkProtectedApi
public final class PaginatedItemsPublisher<ResponseT, ItemT> implements SdkPublisher<ItemT> {
private final AsyncPageFetcher<ResponseT> nextPageFetcher;
private final Function<ResponseT, Iterator<ItemT>> getIteratorFunction;
private final boolean isLastPage;
private PaginatedItemsPublisher(BuilderImpl builder) {
this.nextPageFetcher = builder.nextPageFetcher;
this.getIteratorFunction = builder.iteratorFunction;
this.isLastPage = builder.isLastPage;
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public void subscribe(Subscriber<? super ItemT> subscriber) {
subscriber.onSubscribe(isLastPage ? new EmptySubscription(subscriber)
: ItemsSubscription.builder()
.subscriber(subscriber)
.nextPageFetcher(nextPageFetcher)
.iteratorFunction(getIteratorFunction)
.build());
}
public interface Builder {
Builder nextPageFetcher(AsyncPageFetcher nextPageFetcher);
Builder iteratorFunction(Function iteratorFunction);
Builder isLastPage(boolean isLastPage);
PaginatedItemsPublisher build();
}
private static final class BuilderImpl implements Builder {
private AsyncPageFetcher nextPageFetcher;
private Function iteratorFunction;
private boolean isLastPage;
@Override
public Builder nextPageFetcher(AsyncPageFetcher nextPageFetcher) {
this.nextPageFetcher = nextPageFetcher;
return this;
}
@Override
public Builder iteratorFunction(Function iteratorFunction) {
this.iteratorFunction = iteratorFunction;
return this;
}
@Override
public Builder isLastPage(boolean isLastPage) {
this.isLastPage = isLastPage;
return this;
}
@Override
public PaginatedItemsPublisher build() {
return new PaginatedItemsPublisher(this);
}
}
}
| 1,802 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/async/AsyncPageFetcher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.async;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Interface to deal with async paginated responses.
* @param <ResponseT> Type of Response
*/
@SdkProtectedApi
public interface AsyncPageFetcher<ResponseT> {
/**
* Returns a boolean value indicating if a next page is available.
*
* @param oldPage last page sent by service in a paginated operation
* @return True if there is a next page available. Otherwise false.
*/
boolean hasNextPage(ResponseT oldPage);
/**
* Method that uses the information in #oldPage and returns a
* completable future for the next page. This method makes service calls.
*
* @param oldPage last page sent by service in a paginated operation
* @return A CompletableFuture that can be used to get the next response page
*/
CompletableFuture<ResponseT> nextPage(ResponseT oldPage);
}
| 1,803 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/sync/SyncPageFetcher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.sync;
import software.amazon.awssdk.annotations.SdkProtectedApi;
@SdkProtectedApi
public interface SyncPageFetcher<ResponseT> {
/**
* Returns a boolean value indicating if a next page is available.
*
* @param oldPage last page sent by service in a paginated operation
* @return True if there is a next page available. Otherwise false.
*/
boolean hasNextPage(ResponseT oldPage);
/**
* Method that uses the information in #oldPage and returns the
* next page if available by making a service call.
*
* @param oldPage last page sent by service in a paginated operation
* @return the next page if available. Otherwise returns null.
*/
ResponseT nextPage(ResponseT oldPage);
}
| 1,804 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/sync/PaginatedItemsIterable.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.sync;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Iterable for the paginated items. This class can be used through iterate through
* all the items across multiple pages until there is no more response from the service.
*
* @param <ResponseT> The type of a single response page
* @param <ItemT> The type of paginated member in a response page
*/
@SdkProtectedApi
public final class PaginatedItemsIterable<ResponseT, ItemT> implements SdkIterable<ItemT> {
private final SdkIterable<ResponseT> pagesIterable;
private final Function<ResponseT, Iterator<ItemT>> getItemIterator;
private PaginatedItemsIterable(BuilderImpl<ResponseT, ItemT> builder) {
this.pagesIterable = builder.pagesIterable;
this.getItemIterator = builder.itemIteratorFunction;
}
public static <R, T> Builder<R, T> builder() {
return new BuilderImpl<>();
}
@Override
public Iterator<ItemT> iterator() {
return new ItemsIterator(pagesIterable.iterator());
}
private class ItemsIterator implements Iterator<ItemT> {
private final Iterator<ResponseT> pagesIterator;
private Iterator<ItemT> singlePageItemsIterator;
ItemsIterator(final Iterator<ResponseT> pagesIterator) {
this.pagesIterator = pagesIterator;
this.singlePageItemsIterator = pagesIterator.hasNext() ? getItemIterator.apply(pagesIterator.next())
: Collections.emptyIterator();
}
@Override
public boolean hasNext() {
while (!hasMoreItems() && pagesIterator.hasNext()) {
singlePageItemsIterator = getItemIterator.apply(pagesIterator.next());
}
if (hasMoreItems()) {
return true;
}
return false;
}
@Override
public ItemT next() {
if (!hasNext()) {
throw new NoSuchElementException("No more elements left");
}
return singlePageItemsIterator.next();
}
private boolean hasMoreItems() {
return singlePageItemsIterator.hasNext();
}
}
public interface Builder<ResponseT, ItemT> {
Builder<ResponseT, ItemT> pagesIterable(SdkIterable<ResponseT> sdkIterable);
Builder<ResponseT, ItemT> itemIteratorFunction(Function<ResponseT, Iterator<ItemT>> itemIteratorFunction);
PaginatedItemsIterable<ResponseT, ItemT> build();
}
private static final class BuilderImpl<ResponseT, ItemT> implements Builder<ResponseT, ItemT> {
private SdkIterable<ResponseT> pagesIterable;
private Function<ResponseT, Iterator<ItemT>> itemIteratorFunction;
private BuilderImpl() {
}
@Override
public Builder<ResponseT, ItemT> pagesIterable(SdkIterable<ResponseT> pagesIterable) {
this.pagesIterable = pagesIterable;
return this;
}
@Override
public Builder<ResponseT, ItemT> itemIteratorFunction(Function<ResponseT, Iterator<ItemT>> itemIteratorFunction) {
this.itemIteratorFunction = itemIteratorFunction;
return this;
}
@Override
public PaginatedItemsIterable<ResponseT, ItemT> build() {
return new PaginatedItemsIterable<>(this);
}
}
}
| 1,805 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/sync/SdkIterable.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.sync;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A custom iterable used in paginated responses.
*
* This interface has a default stream() method which creates a stream from
* spliterator method.
*
* @param <T> the type of elements returned by the iterator
*/
@SdkPublicApi
public interface SdkIterable<T> extends Iterable<T> {
default Stream<T> stream() {
return StreamSupport.stream(spliterator(), false);
}
}
| 1,806 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/sync/PaginatedResponsesIterator.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.core.pagination.sync;
import java.util.Iterator;
import java.util.NoSuchElementException;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Iterator for all response pages in a paginated operation.
*
* This class is used to iterate through all the pages of an operation.
* SDK makes service calls to retrieve the next page when next() method is called.
*
* @param <ResponseT> The type of a single response page
*/
@SdkProtectedApi
public final class PaginatedResponsesIterator<ResponseT> implements Iterator<ResponseT> {
private final SyncPageFetcher<ResponseT> nextPageFetcher;
// This is null when the object is created. It gets initialized in next() method
// where SDK make service calls.
private ResponseT oldResponse;
private PaginatedResponsesIterator(BuilderImpl builder) {
this.nextPageFetcher = builder.nextPageFetcher;
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public boolean hasNext() {
return oldResponse == null || nextPageFetcher.hasNextPage(oldResponse);
}
@Override
public ResponseT next() {
if (!hasNext()) {
throw new NoSuchElementException("No more pages left");
}
oldResponse = nextPageFetcher.nextPage(oldResponse);
return oldResponse;
}
public interface Builder {
Builder nextPageFetcher(SyncPageFetcher nextPageFetcher);
PaginatedResponsesIterator build();
}
private static final class BuilderImpl implements Builder {
private SyncPageFetcher nextPageFetcher;
protected BuilderImpl() {
}
@Override
public Builder nextPageFetcher(SyncPageFetcher nextPageFetcher) {
this.nextPageFetcher = nextPageFetcher;
return this;
}
@Override
public PaginatedResponsesIterator build() {
return new PaginatedResponsesIterator(this);
}
}
}
| 1,807 |
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/retry/RetryUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.http.HttpStatusCode;
@SdkProtectedApi
public final class RetryUtils {
private RetryUtils() {
}
/**
* Returns true if the specified exception is a request entity too large error.
*
* @param exception The exception to test.
* @return True if the exception resulted from a request entity too large error message from a service, otherwise false.
*/
public static boolean isRequestEntityTooLargeException(SdkException exception) {
return isServiceException(exception) && toServiceException(exception).statusCode() == HttpStatusCode.REQUEST_TOO_LONG;
}
public static boolean isServiceException(SdkException e) {
return e instanceof SdkServiceException;
}
public static SdkServiceException toServiceException(SdkException e) {
if (!(e instanceof SdkServiceException)) {
throw new IllegalStateException("Received non-SdkServiceException where one was expected.", e);
}
return (SdkServiceException) e;
}
/**
* Returns true if the specified exception is a clock skew error.
*
* @param exception The exception to test.
* @return True if the exception resulted from a clock skews error message from a service, otherwise false.
*/
public static boolean isClockSkewException(SdkException exception) {
return isServiceException(exception) && toServiceException(exception).isClockSkewException();
}
/**
* Returns true if the specified exception is a throttling error.
*
* @param exception The exception to test.
* @return True if the exception resulted from a throttling error message from a service, otherwise false.
*/
public static boolean isThrottlingException(SdkException exception) {
return isServiceException(exception) && toServiceException(exception).isThrottlingException();
}
}
| 1,808 |
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/retry/RetryPolicy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry;
import java.util.Objects;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ToBuilderIgnoreField;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting;
import software.amazon.awssdk.core.retry.backoff.BackoffStrategy;
import software.amazon.awssdk.core.retry.conditions.AndRetryCondition;
import software.amazon.awssdk.core.retry.conditions.MaxNumberOfRetriesCondition;
import software.amazon.awssdk.core.retry.conditions.RetryCondition;
import software.amazon.awssdk.core.retry.conditions.TokenBucketRetryCondition;
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;
/**
* Interface for specifying a retry policy to use when evaluating whether or not a request should be retried. The
* {@link #builder()}} can be used to construct a retry policy from SDK provided policies or policies that directly implement
* {@link BackoffStrategy} and/or {@link RetryCondition}. This is configured on a client via
* {@link ClientOverrideConfiguration.Builder#retryPolicy}.
*
* When using the {@link #builder()} the SDK will use default values for fields that are not provided. The default number of
* retries and condition is based on the current {@link RetryMode}.
*
* @see RetryCondition for a list of SDK provided retry condition strategies
* @see BackoffStrategy for a list of SDK provided backoff strategies
*/
@Immutable
@SdkPublicApi
public final class RetryPolicy implements ToCopyableBuilder<RetryPolicy.Builder, RetryPolicy> {
private final boolean additionalRetryConditionsAllowed;
private final RetryMode retryMode;
private final BackoffStrategy backoffStrategy;
private final BackoffStrategy throttlingBackoffStrategy;
private final Integer numRetries;
private final RetryCondition retryCondition;
private final RetryCondition retryCapacityCondition;
private final RetryCondition aggregateRetryCondition;
private Boolean fastFailRateLimiting;
private RetryPolicy(BuilderImpl builder) {
this.additionalRetryConditionsAllowed = builder.additionalRetryConditionsAllowed;
this.retryMode = builder.retryMode;
this.backoffStrategy = builder.backoffStrategy;
this.throttlingBackoffStrategy = builder.throttlingBackoffStrategy;
this.numRetries = builder.numRetries;
this.retryCondition = builder.retryCondition;
this.retryCapacityCondition = builder.retryCapacityCondition;
this.aggregateRetryCondition = generateAggregateRetryCondition();
this.fastFailRateLimiting = builder.isFastFailRateLimiting();
validateFastFailRateLimiting();
}
/**
* Create a {@link RetryPolicy} using the {@link RetryMode#defaultRetryMode()} defaults.
*/
public static RetryPolicy defaultRetryPolicy() {
return forRetryMode(RetryMode.defaultRetryMode());
}
/**
* Create a {@link RetryPolicy} using the provided {@link RetryMode} defaults.
*/
public static RetryPolicy forRetryMode(RetryMode retryMode) {
return RetryPolicy.builder(retryMode).build();
}
/**
* Create a {@link RetryPolicy} that will NEVER retry.
*/
public static RetryPolicy none() {
return RetryPolicy.builder()
.numRetries(0)
.backoffStrategy(BackoffStrategy.none())
.throttlingBackoffStrategy(BackoffStrategy.none())
.retryCondition(RetryCondition.none())
.additionalRetryConditionsAllowed(false)
.build();
}
/**
* Create a {@link RetryPolicy.Builder} populated with the defaults from the {@link RetryMode#defaultRetryMode()}.
*/
public static Builder builder() {
return new BuilderImpl(RetryMode.defaultRetryMode());
}
/**
* Create a {@link RetryPolicy.Builder} populated with the defaults from the provided {@link RetryMode}.
*/
public static Builder builder(RetryMode retryMode) {
Validate.paramNotNull(retryMode, "The retry mode cannot be set as null. If you don't want to set the retry mode,"
+ " please use the other builder method without setting retry mode, and the default retry"
+ " mode will be used.");
return new BuilderImpl(retryMode);
}
/**
* Retrieve the {@link RetryMode} that was used to determine the defaults for this retry policy.
*/
public RetryMode retryMode() {
return retryMode;
}
/**
* When using {@link RetryMode#ADAPTIVE} retry mode, this controls the client should immediately fail the request when not
* enough capacity is immediately available from the rate limiter to execute the request, instead of waiting for capacity
* to be available.
*/
public Boolean isFastFailRateLimiting() {
return fastFailRateLimiting;
}
/**
* Returns true if service-specific conditions are allowed on this policy (e.g. more conditions may be added by the SDK if
* they are recommended).
*/
public boolean additionalRetryConditionsAllowed() {
return additionalRetryConditionsAllowed;
}
/**
* Retrieve the retry condition that aggregates the {@link Builder#retryCondition(RetryCondition)},
* {@link Builder#numRetries(Integer)} and {@link Builder#retryCapacityCondition(RetryCondition)} configured on the builder.
*/
public RetryCondition aggregateRetryCondition() {
return aggregateRetryCondition;
}
/**
* Retrieve the {@link Builder#retryCondition(RetryCondition)} configured on the builder.
*/
public RetryCondition retryCondition() {
return retryCondition;
}
/**
* Retrieve the {@link Builder#backoffStrategy(BackoffStrategy)} configured on the builder.
*/
public BackoffStrategy backoffStrategy() {
return backoffStrategy;
}
/**
* Retrieve the {@link Builder#throttlingBackoffStrategy(BackoffStrategy)} configured on the builder.
*/
public BackoffStrategy throttlingBackoffStrategy() {
return throttlingBackoffStrategy;
}
/**
* Retrieve the {@link Builder#numRetries(Integer)} configured on the builder.
*/
public Integer numRetries() {
return numRetries;
}
private RetryCondition generateAggregateRetryCondition() {
RetryCondition aggregate = AndRetryCondition.create(MaxNumberOfRetriesCondition.create(numRetries),
retryCondition);
if (retryCapacityCondition != null) {
return AndRetryCondition.create(aggregate, retryCapacityCondition);
}
return aggregate;
}
@Override
@ToBuilderIgnoreField("retryMode")
public Builder toBuilder() {
return builder(retryMode).additionalRetryConditionsAllowed(additionalRetryConditionsAllowed)
.numRetries(numRetries)
.retryCondition(retryCondition)
.backoffStrategy(backoffStrategy)
.throttlingBackoffStrategy(throttlingBackoffStrategy)
.retryCapacityCondition(retryCapacityCondition)
.fastFailRateLimiting(fastFailRateLimiting);
}
@Override
public String toString() {
return ToString.builder("RetryPolicy")
.add("additionalRetryConditionsAllowed", additionalRetryConditionsAllowed)
.add("aggregateRetryCondition", aggregateRetryCondition)
.add("backoffStrategy", backoffStrategy)
.add("throttlingBackoffStrategy", throttlingBackoffStrategy)
.add("fastFailRateLimiting", fastFailRateLimiting)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RetryPolicy that = (RetryPolicy) o;
if (additionalRetryConditionsAllowed != that.additionalRetryConditionsAllowed) {
return false;
}
if (!aggregateRetryCondition.equals(that.aggregateRetryCondition)) {
return false;
}
if (!backoffStrategy.equals(that.backoffStrategy)) {
return false;
}
if (!throttlingBackoffStrategy.equals(that.throttlingBackoffStrategy)) {
return false;
}
return Objects.equals(fastFailRateLimiting, that.fastFailRateLimiting);
}
@Override
public int hashCode() {
int result = aggregateRetryCondition.hashCode();
result = 31 * result + Boolean.hashCode(additionalRetryConditionsAllowed);
result = 31 * result + backoffStrategy.hashCode();
result = 31 * result + throttlingBackoffStrategy.hashCode();
result = 31 * result + Objects.hashCode(fastFailRateLimiting);
return result;
}
private void validateFastFailRateLimiting() {
if (fastFailRateLimiting == null) {
return;
}
Validate.isTrue(RetryMode.ADAPTIVE == retryMode,
"FastFailRateLimiting is enabled, but this setting is only valid for the ADAPTIVE retry mode. The "
+ "configured mode is %s.", retryMode.name());
}
public interface Builder extends CopyableBuilder<Builder, RetryPolicy> {
/**
* Configure whether further conditions can be added to this policy after it is created. This may include service-
* specific retry conditions that may not otherwise be covered by the {@link RetryCondition#defaultRetryCondition()}.
*
* <p>
* By default, this is true.
*/
Builder additionalRetryConditionsAllowed(boolean additionalRetryConditionsAllowed);
/**
* @see #additionalRetryConditionsAllowed(boolean)
*/
boolean additionalRetryConditionsAllowed();
/**
* Configure the backoff strategy that should be used for waiting in between retry attempts. If the retry is because of
* throttling reasons, the {@link #throttlingBackoffStrategy(BackoffStrategy)} is used instead.
*/
Builder backoffStrategy(BackoffStrategy backoffStrategy);
/**
* @see #backoffStrategy(BackoffStrategy)
*/
BackoffStrategy backoffStrategy();
/**
* Configure the backoff strategy that should be used for waiting in between retry attempts after a throttling error
* is encountered. If the retry is not because of throttling reasons, the {@link #backoffStrategy(BackoffStrategy)} is
* used instead.
*/
Builder throttlingBackoffStrategy(BackoffStrategy backoffStrategy);
/**
* @see #throttlingBackoffStrategy(BackoffStrategy)
*/
BackoffStrategy throttlingBackoffStrategy();
/**
* Configure the condition under which the request should be retried.
*
* <p>
* While this can be any interface that implements {@link RetryCondition}, it is encouraged to use
* {@link #numRetries(Integer)} when attempting to limit the number of times the SDK will retry an attempt or the
* {@link #retryCapacityCondition(RetryCondition)} when attempting to configure the throttling of retries. This guidance
* is because the SDK uses the {@link #aggregateRetryCondition()} when determining whether or not to retry a request,
* and the {@code aggregateRetryCondition} includes the {@code numRetries} and {@code retryCapacityCondition} in its
* determination.
*/
Builder retryCondition(RetryCondition retryCondition);
/**
* @see #retryCondition(RetryCondition)
*/
RetryCondition retryCondition();
/**
* Configure the {@link RetryCondition} that should be used to throttle the number of retries attempted by the SDK client
* as a whole.
*
* <p>
* While any {@link RetryCondition} (or null) can be used, by convention these conditions are usually stateful and work
* globally for the whole client to limit the overall capacity of the client to execute retries.
*
* <p>
* By default the {@link TokenBucketRetryCondition} is used. This can be disabled by setting the value to {@code null}
* (not {@code RetryPolicy#none()}, which would completely disable retries).
*/
Builder retryCapacityCondition(RetryCondition retryCapacityCondition);
/**
* @see #retryCapacityCondition(RetryCondition)
*/
RetryCondition retryCapacityCondition();
/**
* Configure the maximum number of times that a single request should be retried, assuming it fails for a retryable error.
*/
Builder numRetries(Integer numRetries);
/**
* @see #numRetries(Integer)
*/
Integer numRetries();
/**
* Whether the client should immediately fail the request when not enough capacity is immediately available from the
* rate limiter to execute the request, instead of waiting for capacity to be available.
*
* @param fastFailRateLimiting Whether to fast fail.
*/
Builder fastFailRateLimiting(Boolean fastFailRateLimiting);
/**
* Whether the client should immediately fail the request when not enough capacity is immediately available from the
* rate limiter to execute the request, instead of waiting for capacity to be available.
*/
Boolean isFastFailRateLimiting();
@Override
RetryPolicy build();
}
/**
* Builder for a {@link RetryPolicy}.
*/
private static final class BuilderImpl implements Builder {
private final RetryMode retryMode;
private boolean additionalRetryConditionsAllowed;
private Integer numRetries;
private BackoffStrategy backoffStrategy;
private BackoffStrategy throttlingBackoffStrategy;
private RetryCondition retryCondition;
private RetryCondition retryCapacityCondition;
private Boolean fastFailRateLimiting;
private BuilderImpl(RetryMode retryMode) {
this.retryMode = retryMode;
this.numRetries = SdkDefaultRetrySetting.maxAttempts(retryMode) - 1;
this.additionalRetryConditionsAllowed = true;
this.backoffStrategy = BackoffStrategy.defaultStrategy(retryMode);
this.throttlingBackoffStrategy = BackoffStrategy.defaultThrottlingStrategy(retryMode);
this.retryCondition = RetryCondition.defaultRetryCondition();
this.retryCapacityCondition = TokenBucketRetryCondition.forRetryMode(retryMode);
}
@Override
public Builder additionalRetryConditionsAllowed(boolean additionalRetryConditionsAllowed) {
this.additionalRetryConditionsAllowed = additionalRetryConditionsAllowed;
return this;
}
public void setadditionalRetryConditionsAllowed(boolean additionalRetryConditionsAllowed) {
additionalRetryConditionsAllowed(additionalRetryConditionsAllowed);
}
@Override
public boolean additionalRetryConditionsAllowed() {
return additionalRetryConditionsAllowed;
}
@Override
public Builder numRetries(Integer numRetries) {
this.numRetries = numRetries;
return this;
}
public void setNumRetries(Integer numRetries) {
numRetries(numRetries);
}
@Override
public Integer numRetries() {
return numRetries;
}
@Override
public Builder fastFailRateLimiting(Boolean fastFailRateLimiting) {
this.fastFailRateLimiting = fastFailRateLimiting;
return this;
}
@Override
public Boolean isFastFailRateLimiting() {
return fastFailRateLimiting;
}
@Override
public Builder backoffStrategy(BackoffStrategy backoffStrategy) {
this.backoffStrategy = backoffStrategy;
return this;
}
public void setBackoffStrategy(BackoffStrategy backoffStrategy) {
backoffStrategy(backoffStrategy);
}
@Override
public BackoffStrategy backoffStrategy() {
return backoffStrategy;
}
@Override
public Builder throttlingBackoffStrategy(BackoffStrategy throttlingBackoffStrategy) {
this.throttlingBackoffStrategy = throttlingBackoffStrategy;
return this;
}
@Override
public BackoffStrategy throttlingBackoffStrategy() {
return throttlingBackoffStrategy;
}
public void setThrottlingBackoffStrategy(BackoffStrategy throttlingBackoffStrategy) {
this.throttlingBackoffStrategy = throttlingBackoffStrategy;
}
@Override
public Builder retryCondition(RetryCondition retryCondition) {
this.retryCondition = retryCondition;
return this;
}
public void setRetryCondition(RetryCondition retryCondition) {
retryCondition(retryCondition);
}
@Override
public RetryCondition retryCondition() {
return retryCondition;
}
@Override
public Builder retryCapacityCondition(RetryCondition retryCapacityCondition) {
this.retryCapacityCondition = retryCapacityCondition;
return this;
}
public void setRetryCapacityCondition(RetryCondition retryCapacityCondition) {
retryCapacityCondition(retryCapacityCondition);
}
@Override
public RetryCondition retryCapacityCondition() {
return this.retryCapacityCondition;
}
@Override
public RetryPolicy build() {
return new RetryPolicy(this);
}
}
}
| 1,809 |
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/retry/RetryMode.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.retry.conditions.TokenBucketRetryCondition;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.utils.OptionalUtils;
import software.amazon.awssdk.utils.StringUtils;
/**
* A retry mode is a collection of retry behaviors encoded under a single value. For example, the {@link #LEGACY} retry mode will
* retry up to three times, and the {@link #STANDARD} will retry up to two times.
*
* <p>
* While the {@link #LEGACY} retry mode is specific to Java, the {@link #STANDARD} retry mode is standardized across all of the
* AWS SDKs.
*
* <p>
* The retry mode can be configured:
* <ol>
* <li>Directly on a client via {@link ClientOverrideConfiguration.Builder#retryPolicy(RetryMode)}.</li>
* <li>Directly on a client via a combination of {@link RetryPolicy#builder(RetryMode)} or
* {@link RetryPolicy#forRetryMode(RetryMode)}, and {@link ClientOverrideConfiguration.Builder#retryPolicy(RetryPolicy)}</li>
* <li>On a configuration profile via the "retry_mode" profile file property.</li>
* <li>Globally via the "aws.retryMode" system property.</li>
* <li>Globally via the "AWS_RETRY_MODE" environment variable.</li>
* </ol>
*/
@SdkPublicApi
public enum RetryMode {
/**
* The LEGACY retry mode, specific to the Java SDK, and characterized by:
* <ol>
* <li>Up to 3 retries, or more for services like DynamoDB (which has up to 8).</li>
* <li>Zero token are subtracted from the {@link TokenBucketRetryCondition} when throttling exceptions are encountered.
* </li>
* </ol>
*
* <p>
* This is the retry mode that is used when no other mode is configured.
*/
LEGACY,
/**
* The STANDARD retry mode, shared by all AWS SDK implementations, and characterized by:
* <ol>
* <li>Up to 2 retries, regardless of service.</li>
* <li>Throttling exceptions are treated the same as other exceptions for the purposes of the
* {@link TokenBucketRetryCondition}.</li>
* </ol>
*/
STANDARD,
/**
* Adaptive retry mode builds on {@code STANDARD} mode.
* <p>
* Adaptive retry mode dynamically limits the rate of AWS requests to maximize success rate. This may be at the
* expense of request latency. Adaptive retry mode is not recommended when predictable latency is important.
* <p>
* <b>Warning:</b> Adaptive retry mode assumes that the client is working against a single resource (e.g. one
* DynamoDB Table or one S3 Bucket). If you use a single client for multiple resources, throttling or outages
* associated with one resource will result in increased latency and failures when accessing all other resources via
* the same client. When using adaptive retry mode, we recommend using a single client per resource.
*
* @see RetryPolicy#isFastFailRateLimiting()
*/
ADAPTIVE,
;
/**
* Retrieve the default retry mode by consulting the locations described in {@link RetryMode}, or LEGACY if no value is
* configured.
*/
public static RetryMode defaultRetryMode() {
return resolver().resolve();
}
/**
* Create a {@link Resolver} that allows customizing the variables used during determination of a {@link RetryMode}.
*/
public static Resolver resolver() {
return new Resolver();
}
/**
* Allows customizing the variables used during determination of a {@link RetryMode}. Created via {@link #resolver()}.
*/
public static class Resolver {
private static final RetryMode SDK_DEFAULT_RETRY_MODE = LEGACY;
private Supplier<ProfileFile> profileFile;
private String profileName;
private RetryMode defaultRetryMode;
private Resolver() {
}
/**
* Configure the profile file that should be used when determining the {@link RetryMode}. The supplier is only consulted
* if a higher-priority determinant (e.g. environment variables) does not find the setting.
*/
public Resolver profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
/**
* Configure the profile file name should be used when determining the {@link RetryMode}.
*/
public Resolver profileName(String profileName) {
this.profileName = profileName;
return this;
}
/**
* Configure the {@link RetryMode} that should be used if the mode is not specified anywhere else.
*/
public Resolver defaultRetryMode(RetryMode defaultRetryMode) {
this.defaultRetryMode = defaultRetryMode;
return this;
}
/**
* Resolve which retry mode should be used, based on the configured values.
*/
public RetryMode resolve() {
return OptionalUtils.firstPresent(Resolver.fromSystemSettings(), () -> fromProfileFile(profileFile, profileName))
.orElseGet(this::fromDefaultMode);
}
private static Optional<RetryMode> fromSystemSettings() {
return SdkSystemSetting.AWS_RETRY_MODE.getStringValue()
.flatMap(Resolver::fromString);
}
private static Optional<RetryMode> fromProfileFile(Supplier<ProfileFile> profileFile, String profileName) {
profileFile = profileFile != null ? profileFile : ProfileFile::defaultProfileFile;
profileName = profileName != null ? profileName : ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow();
return profileFile.get()
.profile(profileName)
.flatMap(p -> p.property(ProfileProperty.RETRY_MODE))
.flatMap(Resolver::fromString);
}
private static Optional<RetryMode> fromString(String string) {
if (string == null || string.isEmpty()) {
return Optional.empty();
}
switch (StringUtils.lowerCase(string)) {
case "legacy":
return Optional.of(LEGACY);
case "standard":
return Optional.of(STANDARD);
case "adaptive":
return Optional.of(ADAPTIVE);
default:
throw new IllegalStateException("Unsupported retry policy mode configured: " + string);
}
}
private RetryMode fromDefaultMode() {
return defaultRetryMode != null ? defaultRetryMode : SDK_DEFAULT_RETRY_MODE;
}
}
}
| 1,810 |
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/retry/RetryPolicyContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Contains useful information about a failed request that can be used to make retry and backoff decisions. See {@link
* RetryPolicy}.
*/
@Immutable
@SdkPublicApi
public final class RetryPolicyContext implements ToCopyableBuilder<RetryPolicyContext.Builder, RetryPolicyContext> {
private final SdkRequest originalRequest;
private final SdkHttpFullRequest request;
private final SdkException exception;
private final ExecutionAttributes executionAttributes;
private final int retriesAttempted;
private final Integer httpStatusCode;
private RetryPolicyContext(Builder builder) {
this.originalRequest = builder.originalRequest;
this.request = builder.request;
this.exception = builder.exception;
this.executionAttributes = builder.executionAttributes;
this.retriesAttempted = builder.retriesAttempted;
this.httpStatusCode = builder.httpStatusCode;
}
public static Builder builder() {
return new Builder();
}
/**
* @return The original request passed to the client method for an operation.
*/
public SdkRequest originalRequest() {
return this.originalRequest;
}
/**
* @return The marshalled request.
*/
public SdkHttpFullRequest request() {
return this.request;
}
/**
* @return The last seen exception for the request.
*/
public SdkException exception() {
return this.exception;
}
/**
* @return Mutable execution context.
*/
public ExecutionAttributes executionAttributes() {
return this.executionAttributes;
}
/**
* @return Number of retries attempted thus far.
*/
public int retriesAttempted() {
return this.retriesAttempted;
}
/**
* @return The total number of requests made thus far.
*/
public int totalRequests() {
return this.retriesAttempted + 1;
}
/**
* @return HTTP status code of response. May be null if no response was received from the service.
*/
public Integer httpStatusCode() {
return this.httpStatusCode;
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
@SdkPublicApi
public static final class Builder implements CopyableBuilder<Builder, RetryPolicyContext> {
private SdkRequest originalRequest;
private SdkHttpFullRequest request;
private SdkException exception;
private ExecutionAttributes executionAttributes;
private int retriesAttempted;
private Integer httpStatusCode;
private Builder() {
}
private Builder(RetryPolicyContext copy) {
this.originalRequest = copy.originalRequest;
this.request = copy.request;
this.exception = copy.exception;
this.executionAttributes = copy.executionAttributes;
this.retriesAttempted = copy.retriesAttempted;
this.httpStatusCode = copy.httpStatusCode;
}
public Builder originalRequest(SdkRequest originalRequest) {
this.originalRequest = originalRequest;
return this;
}
public Builder request(SdkHttpFullRequest request) {
this.request = request;
return this;
}
public Builder exception(SdkException exception) {
this.exception = exception;
return this;
}
public Builder executionAttributes(ExecutionAttributes executionAttributes) {
this.executionAttributes = executionAttributes;
return this;
}
public Builder retriesAttempted(int retriesAttempted) {
this.retriesAttempted = retriesAttempted;
return this;
}
public Builder httpStatusCode(Integer httpStatusCode) {
this.httpStatusCode = httpStatusCode;
return this;
}
@Override
public RetryPolicyContext build() {
return new RetryPolicyContext(this);
}
}
}
| 1,811 |
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/retry/ClockSkew.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.internal.http.HttpClientDependencies;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.utils.DateUtils;
import software.amazon.awssdk.utils.Logger;
/**
* Utility methods for checking and reacting to the current client-side clock being different from the service-side clock.
*/
@ThreadSafe
@SdkProtectedApi
public final class ClockSkew {
private static final Logger log = Logger.loggerFor(ClockSkew.class);
/**
* When we get an error that may be due to a clock skew error, and our clock is different than the service clock, this is
* the difference threshold beyond which we will recommend a clock skew adjustment.
*/
private static final Duration CLOCK_SKEW_ADJUST_THRESHOLD = Duration.ofMinutes(4);
private ClockSkew() {
}
/**
* Determine whether the request-level client time was sufficiently skewed from the server time as to possibly cause a
* clock skew error.
*/
public static boolean isClockSkewed(Instant clientTime, Instant serverTime) {
Duration requestClockSkew = getClockSkew(clientTime, serverTime);
return requestClockSkew.abs().compareTo(CLOCK_SKEW_ADJUST_THRESHOLD) >= 0;
}
/**
* Calculate the time skew between a client and server date. This value has the same semantics of
* {@link HttpClientDependencies#timeOffset()}. Positive values imply the client clock is "fast" and negative values imply
* the client clock is "slow".
*/
public static Duration getClockSkew(Instant clientTime, Instant serverTime) {
if (clientTime == null || serverTime == null) {
// If we do not have a client or server time, 0 is the safest skew to apply
return Duration.ZERO;
}
return Duration.between(serverTime, clientTime);
}
/**
* Get the server time from the service response, or empty if the time could not be determined.
*/
public static Optional<Instant> getServerTime(SdkHttpResponse serviceResponse) {
Optional<String> responseDateHeader = serviceResponse.firstMatchingHeader("Date");
if (responseDateHeader.isPresent()) {
String serverDate = responseDateHeader.get();
log.debug(() -> "Reported service date: " + serverDate);
try {
return Optional.of(DateUtils.parseRfc822Date(serverDate));
} catch (RuntimeException e) {
log.warn(() -> "Unable to parse clock skew offset from response: " + serverDate, e);
return Optional.empty();
}
}
log.debug(() -> "Service did not return a Date header, so clock skew adjustments will not be applied.");
return Optional.empty();
}
}
| 1,812 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/backoff/EqualJitterBackoffStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.backoff;
import static software.amazon.awssdk.utils.NumericUtils.min;
import static software.amazon.awssdk.utils.Validate.isNotNegative;
import java.time.Duration;
import java.util.Random;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Backoff strategy that uses equal jitter for computing the delay before the next retry. An equal jitter
* backoff strategy will first compute an exponential delay based on the current number of retries, base delay
* and max delay. The final computed delay before the next retry will keep half of this computed delay plus
* a random delay computed as a random number between 0 and half of the exponential delay plus one.
*
* For example, using a base delay of 100, a max backoff time of 10000 an exponential delay of 400 is computed
* for a second retry attempt. The final computed delay before the next retry will be half of the computed exponential
* delay, in this case 200, plus a random number between 0 and 201. Therefore the range for delay would be between
* 200 and 401.
*
* This is in contrast to {@link FullJitterBackoffStrategy} where the final computed delay before the next retry will be
* between 0 and the computed exponential delay.
*/
@SdkPublicApi
public final class EqualJitterBackoffStrategy implements BackoffStrategy,
ToCopyableBuilder<EqualJitterBackoffStrategy.Builder,
EqualJitterBackoffStrategy> {
private static final Duration BASE_DELAY_CEILING = Duration.ofMillis(Integer.MAX_VALUE); // Around 24 days
private static final Duration MAX_BACKOFF_CEILING = Duration.ofMillis(Integer.MAX_VALUE); // Around 24 days
private final Duration baseDelay;
private final Duration maxBackoffTime;
private final Random random;
private EqualJitterBackoffStrategy(BuilderImpl builder) {
this(builder.baseDelay, builder.maxBackoffTime, new Random());
}
EqualJitterBackoffStrategy(final Duration baseDelay, final Duration maxBackoffTime, final Random random) {
this.baseDelay = min(isNotNegative(baseDelay, "baseDelay"), BASE_DELAY_CEILING);
this.maxBackoffTime = min(isNotNegative(maxBackoffTime, "maxBackoffTime"), MAX_BACKOFF_CEILING);
this.random = random;
}
@Override
public Duration computeDelayBeforeNextRetry(RetryPolicyContext context) {
int ceil = calculateExponentialDelay(context.retriesAttempted(), baseDelay, maxBackoffTime);
return Duration.ofMillis((ceil / 2) + random.nextInt((ceil / 2) + 1));
}
@Override
public Builder toBuilder() {
return builder().baseDelay(baseDelay).maxBackoffTime(maxBackoffTime);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder extends CopyableBuilder<EqualJitterBackoffStrategy.Builder, EqualJitterBackoffStrategy> {
Builder baseDelay(Duration baseDelay);
Duration baseDelay();
Builder maxBackoffTime(Duration maxBackoffTime);
Duration maxBackoffTime();
@Override
EqualJitterBackoffStrategy build();
}
private static final class BuilderImpl implements Builder {
private Duration baseDelay;
private Duration maxBackoffTime;
private BuilderImpl() {
}
@Override
public Builder baseDelay(Duration baseDelay) {
this.baseDelay = baseDelay;
return this;
}
public void setBaseDelay(Duration baseDelay) {
baseDelay(baseDelay);
}
@Override
public Duration baseDelay() {
return baseDelay;
}
@Override
public Builder maxBackoffTime(Duration maxBackoffTime) {
this.maxBackoffTime = maxBackoffTime;
return this;
}
public void setMaxBackoffTime(Duration maxBackoffTime) {
maxBackoffTime(maxBackoffTime);
}
@Override
public Duration maxBackoffTime() {
return maxBackoffTime;
}
@Override
public EqualJitterBackoffStrategy build() {
return new EqualJitterBackoffStrategy(this);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EqualJitterBackoffStrategy that = (EqualJitterBackoffStrategy) o;
if (!baseDelay.equals(that.baseDelay)) {
return false;
}
return maxBackoffTime.equals(that.maxBackoffTime);
}
@Override
public int hashCode() {
int result = baseDelay.hashCode();
result = 31 * result + maxBackoffTime.hashCode();
return result;
}
@Override
public String toString() {
return ToString.builder("EqualJitterBackoffStrategy")
.add("baseDelay", baseDelay)
.add("maxBackoffTime", maxBackoffTime)
.build();
}
}
| 1,813 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/backoff/FullJitterBackoffStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.backoff;
import static software.amazon.awssdk.utils.NumericUtils.min;
import static software.amazon.awssdk.utils.Validate.isNotNegative;
import java.time.Duration;
import java.util.Random;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Backoff strategy that uses a full jitter strategy for computing the next backoff delay. A full jitter
* strategy will always compute a new random delay between 0 and the computed exponential backoff for each
* subsequent request.
*
* For example, using a base delay of 100, a max backoff time of 10000 an exponential delay of 400 is computed
* for a second retry attempt. The final computed delay before the next retry will then be in the range of 0 to 400.
*
* This is in contrast to {@link EqualJitterBackoffStrategy} that computes a new random delay where the final
* computed delay before the next retry will be at least half of the computed exponential delay.
*/
@SdkPublicApi
public final class FullJitterBackoffStrategy implements BackoffStrategy,
ToCopyableBuilder<FullJitterBackoffStrategy.Builder,
FullJitterBackoffStrategy> {
private static final Duration BASE_DELAY_CEILING = Duration.ofMillis(Integer.MAX_VALUE); // Around 24 days
private static final Duration MAX_BACKOFF_CEILING = Duration.ofMillis(Integer.MAX_VALUE); // Around 24 days
private final Duration baseDelay;
private final Duration maxBackoffTime;
private final Random random;
private FullJitterBackoffStrategy(BuilderImpl builder) {
this(builder.baseDelay, builder.maxBackoffTime, new Random());
}
FullJitterBackoffStrategy(final Duration baseDelay, final Duration maxBackoffTime, final Random random) {
this.baseDelay = min(isNotNegative(baseDelay, "baseDelay"), BASE_DELAY_CEILING);
this.maxBackoffTime = min(isNotNegative(maxBackoffTime, "maxBackoffTime"), MAX_BACKOFF_CEILING);
this.random = random;
}
@Override
public Duration computeDelayBeforeNextRetry(RetryPolicyContext context) {
int ceil = calculateExponentialDelay(context.retriesAttempted(), baseDelay, maxBackoffTime);
// Minimum of 1 ms (consistent with BackoffStrategy.none()'s behavior)
return Duration.ofMillis(random.nextInt(ceil) + 1L);
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder extends CopyableBuilder<Builder, FullJitterBackoffStrategy> {
Builder baseDelay(Duration baseDelay);
Duration baseDelay();
Builder maxBackoffTime(Duration maxBackoffTime);
Duration maxBackoffTime();
@Override
FullJitterBackoffStrategy build();
}
private static final class BuilderImpl implements Builder {
private Duration baseDelay;
private Duration maxBackoffTime;
private BuilderImpl() {
}
private BuilderImpl(FullJitterBackoffStrategy strategy) {
this.baseDelay = strategy.baseDelay;
this.maxBackoffTime = strategy.maxBackoffTime;
}
@Override
public Builder baseDelay(Duration baseDelay) {
this.baseDelay = baseDelay;
return this;
}
public void setBaseDelay(Duration baseDelay) {
baseDelay(baseDelay);
}
@Override
public Duration baseDelay() {
return baseDelay;
}
@Override
public Builder maxBackoffTime(Duration maxBackoffTime) {
this.maxBackoffTime = maxBackoffTime;
return this;
}
public void setMaxBackoffTime(Duration maxBackoffTime) {
maxBackoffTime(maxBackoffTime);
}
@Override
public Duration maxBackoffTime() {
return maxBackoffTime;
}
@Override
public FullJitterBackoffStrategy build() {
return new FullJitterBackoffStrategy(this);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FullJitterBackoffStrategy that = (FullJitterBackoffStrategy) o;
if (!baseDelay.equals(that.baseDelay)) {
return false;
}
return maxBackoffTime.equals(that.maxBackoffTime);
}
@Override
public int hashCode() {
int result = baseDelay.hashCode();
result = 31 * result + maxBackoffTime.hashCode();
return result;
}
@Override
public String toString() {
return ToString.builder("FullJitterBackoffStrategy")
.add("baseDelay", baseDelay)
.add("maxBackoffTime", maxBackoffTime)
.build();
}
}
| 1,814 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/backoff/BackoffStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.backoff;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
@SdkPublicApi
@FunctionalInterface
public interface BackoffStrategy {
/**
* Max permitted retry times. To prevent exponentialDelay from overflow, there must be 2 ^ retriesAttempted
* <= 2 ^ 31 - 1, which means retriesAttempted <= 30, so that is the ceil for retriesAttempted.
*/
int RETRIES_ATTEMPTED_CEILING = (int) Math.floor(Math.log(Integer.MAX_VALUE) / Math.log(2));
/**
* Compute the delay before the next retry request. This strategy is only consulted when there will be a next retry.
*
* @param context Context about the state of the last request and information about the number of requests made.
* @return Amount of time in milliseconds to wait before the next attempt. Must be non-negative (can be zero).
*/
Duration computeDelayBeforeNextRetry(RetryPolicyContext context);
default int calculateExponentialDelay(int retriesAttempted, Duration baseDelay, Duration maxBackoffTime) {
int cappedRetries = Math.min(retriesAttempted, RETRIES_ATTEMPTED_CEILING);
return (int) Math.min(baseDelay.multipliedBy(1L << cappedRetries).toMillis(), maxBackoffTime.toMillis());
}
static BackoffStrategy defaultStrategy() {
return defaultStrategy(RetryMode.defaultRetryMode());
}
static BackoffStrategy defaultStrategy(RetryMode retryMode) {
return FullJitterBackoffStrategy.builder()
.baseDelay(SdkDefaultRetrySetting.baseDelay(retryMode))
.maxBackoffTime(SdkDefaultRetrySetting.MAX_BACKOFF)
.build();
}
static BackoffStrategy defaultThrottlingStrategy() {
return defaultThrottlingStrategy(RetryMode.defaultRetryMode());
}
static BackoffStrategy defaultThrottlingStrategy(RetryMode retryMode) {
switch (retryMode) {
case LEGACY:
return EqualJitterBackoffStrategy.builder()
.baseDelay(SdkDefaultRetrySetting.throttledBaseDelay(retryMode))
.maxBackoffTime(SdkDefaultRetrySetting.MAX_BACKOFF)
.build();
case ADAPTIVE:
case STANDARD:
return FullJitterBackoffStrategy.builder()
.baseDelay(SdkDefaultRetrySetting.throttledBaseDelay(retryMode))
.maxBackoffTime(SdkDefaultRetrySetting.MAX_BACKOFF)
.build();
default:
throw new IllegalStateException("Unsupported RetryMode: " + retryMode);
}
}
static BackoffStrategy none() {
return FixedDelayBackoffStrategy.create(Duration.ofMillis(1));
}
}
| 1,815 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/backoff/FixedDelayBackoffStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.backoff;
import static software.amazon.awssdk.utils.Validate.isNotNegative;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
/**
* Simple backoff strategy that always uses a fixed delay for the delay before the next retry attempt.
*/
@SdkPublicApi
public final class FixedDelayBackoffStrategy implements BackoffStrategy {
private final Duration fixedBackoff;
private FixedDelayBackoffStrategy(Duration fixedBackoff) {
this.fixedBackoff = isNotNegative(fixedBackoff, "fixedBackoff");
}
@Override
public Duration computeDelayBeforeNextRetry(RetryPolicyContext context) {
return fixedBackoff;
}
public static FixedDelayBackoffStrategy create(Duration fixedBackoff) {
return new FixedDelayBackoffStrategy(fixedBackoff);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FixedDelayBackoffStrategy that = (FixedDelayBackoffStrategy) o;
return fixedBackoff.equals(that.fixedBackoff);
}
@Override
public int hashCode() {
return fixedBackoff.hashCode();
}
@Override
public String toString() {
return ToString.builder("FixedDelayBackoffStrategy")
.add("fixedBackoff", fixedBackoff)
.build();
}
}
| 1,816 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/TokenBucketRetryCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.conditions;
import static software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting.TOKEN_BUCKET_SIZE;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.internal.capacity.TokenBucket;
import software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* A {@link RetryCondition} that limits the number of retries made by the SDK using a token bucket algorithm. "Tokens" are
* acquired from the bucket whenever {@link #shouldRetry} returns true, and are released to the bucket whenever
* {@link #requestSucceeded} or {@link #requestWillNotBeRetried} are invoked.
*
* <p>
* If "tokens" cannot be acquired from the bucket, it means too many requests have failed and the request will not be allowed
* to retry until we start to see initial non-retried requests succeed via {@link #requestSucceeded(RetryPolicyContext)}.
*
* <p>
* This prevents the client from holding the calling thread to retry when it's likely that it will fail anyway.
*
* <p>
* This is currently included in the default {@link RetryPolicy#aggregateRetryCondition()}, but can be disabled by setting the
* {@link RetryPolicy.Builder#retryCapacityCondition} to null.
*/
@SdkPublicApi
public class TokenBucketRetryCondition implements RetryCondition {
private static final Logger log = Logger.loggerFor(TokenBucketRetryCondition.class);
private static final ExecutionAttribute<Capacity> LAST_ACQUIRED_CAPACITY =
new ExecutionAttribute<>("TokenBucketRetryCondition.LAST_ACQUIRED_CAPACITY");
private static final ExecutionAttribute<Integer> RETRY_COUNT_OF_LAST_CAPACITY_ACQUISITION =
new ExecutionAttribute<>("TokenBucketRetryCondition.RETRY_COUNT_OF_LAST_CAPACITY_ACQUISITION");
private final TokenBucket capacity;
private final TokenBucketExceptionCostFunction exceptionCostFunction;
private TokenBucketRetryCondition(Builder builder) {
this.capacity = new TokenBucket(Validate.notNull(builder.tokenBucketSize, "tokenBucketSize"));
this.exceptionCostFunction = Validate.notNull(builder.exceptionCostFunction, "exceptionCostFunction");
}
/**
* Create a condition using the {@link RetryMode#defaultRetryMode()}. This is equivalent to
* {@code forRetryMode(RetryMode.defaultRetryMode())}.
*
* <p>
* For more detailed control, see {@link #builder()}.
*/
public static TokenBucketRetryCondition create() {
return forRetryMode(RetryMode.defaultRetryMode());
}
/**
* Create a condition using the configured {@link RetryMode}. The {@link RetryMode#LEGACY} does not subtract tokens from
* the token bucket when throttling exceptions are encountered. The {@link RetryMode#STANDARD} treats throttling and non-
* throttling exceptions as the same cost.
*
* <p>
* For more detailed control, see {@link #builder()}.
*/
public static TokenBucketRetryCondition forRetryMode(RetryMode retryMode) {
return TokenBucketRetryCondition.builder()
.tokenBucketSize(TOKEN_BUCKET_SIZE)
.exceptionCostFunction(SdkDefaultRetrySetting.tokenCostFunction(retryMode))
.build();
}
/**
* Create a builder that allows fine-grained control over the token policy of this condition.
*/
public static Builder builder() {
return new Builder();
}
/**
* If {@link #shouldRetry(RetryPolicyContext)} returned true for the provided execution, this method returns the
* {@link Capacity} consumed by the request.
*/
public static Optional<Capacity> getCapacityForExecution(ExecutionAttributes attributes) {
return Optional.ofNullable(attributes.getAttribute(LAST_ACQUIRED_CAPACITY));
}
/**
* Retrieve the number of tokens currently available in the token bucket. This is a volatile snapshot of the current value.
* See {@link #getCapacityForExecution(ExecutionAttributes)} to see how much capacity was left in the bucket after a specific
* execution was considered.
*/
public int tokensAvailable() {
return capacity.currentCapacity();
}
@Override
public boolean shouldRetry(RetryPolicyContext context) {
int costOfFailure = exceptionCostFunction.apply(context.exception());
Validate.isTrue(costOfFailure >= 0, "Cost of failure must not be negative, but was " + costOfFailure);
Optional<Capacity> capacity = this.capacity.tryAcquire(costOfFailure);
capacity.ifPresent(c -> {
context.executionAttributes().putAttribute(LAST_ACQUIRED_CAPACITY, c);
context.executionAttributes().putAttribute(RETRY_COUNT_OF_LAST_CAPACITY_ACQUISITION,
context.retriesAttempted());
log.trace(() -> "Successfully acquired token bucket capacity to retry this request. "
+ "Acquired: " + c.capacityAcquired + ". Remaining: " + c.capacityRemaining);
});
boolean hasCapacity = capacity.isPresent();
if (!hasCapacity) {
log.debug(() -> "This request will not be retried because the client has experienced too many recent call failures.");
}
return hasCapacity;
}
@Override
public void requestWillNotBeRetried(RetryPolicyContext context) {
Integer lastAcquisitionRetryCount = context.executionAttributes().getAttribute(RETRY_COUNT_OF_LAST_CAPACITY_ACQUISITION);
if (lastAcquisitionRetryCount != null && context.retriesAttempted() == lastAcquisitionRetryCount) {
// We said yes to "should-retry", but something else caused it not to retry
Capacity lastAcquiredCapacity = context.executionAttributes().getAttribute(LAST_ACQUIRED_CAPACITY);
Validate.validState(lastAcquiredCapacity != null, "Last acquired capacity should not be null.");
capacity.release(lastAcquiredCapacity.capacityAcquired());
}
}
@Override
public void requestSucceeded(RetryPolicyContext context) {
Capacity lastAcquiredCapacity = context.executionAttributes().getAttribute(LAST_ACQUIRED_CAPACITY);
if (lastAcquiredCapacity == null || lastAcquiredCapacity.capacityAcquired() == 0) {
capacity.release(1);
} else {
capacity.release(lastAcquiredCapacity.capacityAcquired());
}
}
@Override
public String toString() {
return ToString.builder("TokenBucketRetryCondition")
.add("capacity", capacity.currentCapacity() + "/" + capacity.maxCapacity())
.add("exceptionCostFunction", exceptionCostFunction)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TokenBucketRetryCondition that = (TokenBucketRetryCondition) o;
if (!capacity.equals(that.capacity)) {
return false;
}
return exceptionCostFunction.equals(that.exceptionCostFunction);
}
@Override
public int hashCode() {
int result = capacity.hashCode();
result = 31 * result + exceptionCostFunction.hashCode();
return result;
}
/**
* Configure and create a {@link TokenBucketRetryCondition}.
*/
public static final class Builder {
private Integer tokenBucketSize;
private TokenBucketExceptionCostFunction exceptionCostFunction;
/**
* Create using {@link TokenBucketRetryCondition#builder()}.
*/
private Builder() {
}
/**
* Specify the maximum number of tokens in the token bucket. This is also used as the initial value for the number of
* tokens in the bucket.
*/
public Builder tokenBucketSize(int tokenBucketSize) {
this.tokenBucketSize = tokenBucketSize;
return this;
}
/**
* Configure a {@link TokenBucketExceptionCostFunction} that is used to calculate the number of tokens that should be
* taken out of the bucket for each specific exception. These tokens will be returned in case of successful retries.
*/
public Builder exceptionCostFunction(TokenBucketExceptionCostFunction exceptionCostFunction) {
this.exceptionCostFunction = exceptionCostFunction;
return this;
}
/**
* Build a {@link TokenBucketRetryCondition} using the provided configuration.
*/
public TokenBucketRetryCondition build() {
return new TokenBucketRetryCondition(this);
}
}
/**
* The number of tokens in the token bucket after a specific token acquisition succeeds. This can be retrieved via
* {@link #getCapacityForExecution(ExecutionAttributes)}.
*/
public static final class Capacity {
private final int capacityAcquired;
private final int capacityRemaining;
private Capacity(Builder builder) {
this.capacityAcquired = Validate.notNull(builder.capacityAcquired, "capacityAcquired");
this.capacityRemaining = Validate.notNull(builder.capacityRemaining, "capacityRemaining");
}
public static Builder builder() {
return new Builder();
}
/**
* The number of tokens acquired by the last token acquisition.
*/
public int capacityAcquired() {
return capacityAcquired;
}
/**
* The number of tokens in the token bucket.
*/
public int capacityRemaining() {
return capacityRemaining;
}
public static class Builder {
private Integer capacityAcquired;
private Integer capacityRemaining;
private Builder() {
}
public Builder capacityAcquired(Integer capacityAcquired) {
this.capacityAcquired = capacityAcquired;
return this;
}
public Builder capacityRemaining(Integer capacityRemaining) {
this.capacityRemaining = capacityRemaining;
return this;
}
public Capacity build() {
return new Capacity(this);
}
}
}
}
| 1,817 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/AndRetryCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.conditions;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Composite {@link RetryCondition} that evaluates to true when all contained retry conditions evaluate to true.
*/
@SdkPublicApi
public final class AndRetryCondition implements RetryCondition {
private final Set<RetryCondition> conditions = new LinkedHashSet<>();
private AndRetryCondition(RetryCondition... conditions) {
Collections.addAll(this.conditions, Validate.notEmpty(conditions, "%s cannot be empty.", "conditions"));
}
public static AndRetryCondition create(RetryCondition... conditions) {
return new AndRetryCondition(conditions);
}
/**
* @return True if all conditions are true, false otherwise.
*/
@Override
public boolean shouldRetry(RetryPolicyContext context) {
return conditions.stream().allMatch(r -> r.shouldRetry(context));
}
@Override
public void requestWillNotBeRetried(RetryPolicyContext context) {
conditions.forEach(c -> c.requestWillNotBeRetried(context));
}
@Override
public void requestSucceeded(RetryPolicyContext context) {
conditions.forEach(c -> c.requestSucceeded(context));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AndRetryCondition that = (AndRetryCondition) o;
return conditions.equals(that.conditions);
}
@Override
public int hashCode() {
return conditions.hashCode();
}
@Override
public String toString() {
return ToString.builder("AndRetryCondition")
.add("conditions", conditions)
.build();
}
}
| 1,818 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/SdkRetryCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.conditions;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting;
import software.amazon.awssdk.core.retry.RetryUtils;
/**
* Contains predefined {@link RetryCondition} provided by SDK.
*/
@SdkProtectedApi
public final class SdkRetryCondition {
public static final RetryCondition DEFAULT = OrRetryCondition.create(
RetryOnStatusCodeCondition.create(SdkDefaultRetrySetting.RETRYABLE_STATUS_CODES),
RetryOnExceptionsCondition.create(SdkDefaultRetrySetting.RETRYABLE_EXCEPTIONS),
c -> RetryUtils.isClockSkewException(c.exception()),
c -> RetryUtils.isThrottlingException(c.exception()));
public static final RetryCondition NONE = MaxNumberOfRetriesCondition.create(0);
private SdkRetryCondition() {
}
}
| 1,819 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/TokenBucketExceptionCostFunction.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.conditions;
import java.util.function.Function;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.internal.retry.DefaultTokenBucketExceptionCostFunction;
/**
* A function used by {@link TokenBucketRetryCondition} to determine how many tokens should be removed from the bucket when an
* exception is encountered. This can be implemented directly, or using the helper methods provided by the {@link #builder()}.
*/
@SdkPublicApi
@FunctionalInterface
@ThreadSafe
public interface TokenBucketExceptionCostFunction extends Function<SdkException, Integer> {
/**
* Create an exception cost function using exception type matchers built into the SDK. This interface may be implemented
* directly, or created via a builder.
*/
static Builder builder() {
return new DefaultTokenBucketExceptionCostFunction.Builder();
}
/**
* A helper that can be used to assign exception costs to specific exception types, created via {@link #builder()}.
*/
@NotThreadSafe
interface Builder {
/**
* Specify the number of tokens that should be removed from the token bucket when throttling exceptions (e.g. HTTP status
* code 429) are encountered.
*/
Builder throttlingExceptionCost(int cost);
/**
* Specify the number of tokens that should be removed from the token bucket when no other exception type in this
* function is matched. This field is required.
*/
Builder defaultExceptionCost(int cost);
/**
* Create a {@link TokenBucketExceptionCostFunction} using the values configured on this builder.
*/
TokenBucketExceptionCostFunction build();
}
}
| 1,820 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/RetryOnThrottlingCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.conditions;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.core.retry.RetryUtils;
import software.amazon.awssdk.utils.ToString;
/**
* A {@link RetryCondition} that will return true if the provided exception seems to be due to a throttling error from the
* service to the client.
*/
@SdkPublicApi
public final class RetryOnThrottlingCondition implements RetryCondition {
private RetryOnThrottlingCondition() {
}
public static RetryOnThrottlingCondition create() {
return new RetryOnThrottlingCondition();
}
@Override
public boolean shouldRetry(RetryPolicyContext context) {
return RetryUtils.isThrottlingException(context.exception());
}
@Override
public String toString() {
return ToString.create("RetryOnThrottlingCondition");
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
return o != null && getClass() == o.getClass();
}
@Override
public int hashCode() {
return 0;
}
}
| 1,821 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/RetryCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.conditions;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
@SdkPublicApi
@FunctionalInterface
public interface RetryCondition {
/**
* Determine whether a request should or should not be retried.
*
* @param context Context about the state of the last request and information about the number of requests made.
* @return True if the request should be retried, false if not.
*/
boolean shouldRetry(RetryPolicyContext context);
/**
* Called by the SDK to notify this condition that the provided request will not be retried, because some retry condition
* determined that it shouldn't be retried.
*/
default void requestWillNotBeRetried(RetryPolicyContext context) {
}
/**
* Called by the SDK to notify this condition that the provided request succeeded. This method is invoked even if the
* execution never failed before ({@link RetryPolicyContext#retriesAttempted()} is zero).
*/
default void requestSucceeded(RetryPolicyContext context) {
}
static RetryCondition defaultRetryCondition() {
return OrRetryCondition.create(
RetryOnStatusCodeCondition.create(SdkDefaultRetrySetting.RETRYABLE_STATUS_CODES),
RetryOnExceptionsCondition.create(SdkDefaultRetrySetting.RETRYABLE_EXCEPTIONS),
RetryOnClockSkewCondition.create(),
RetryOnThrottlingCondition.create());
}
/**
* A retry condition that will NEVER allow retries.
*/
static RetryCondition none() {
return MaxNumberOfRetriesCondition.create(0);
}
}
| 1,822 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/RetryOnClockSkewCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.conditions;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.core.retry.RetryUtils;
import software.amazon.awssdk.utils.ToString;
/**
* A {@link RetryCondition} that will return true if the provided exception seems to be due to a clock skew between the
* client and service.
*/
@SdkPublicApi
public final class RetryOnClockSkewCondition implements RetryCondition {
private RetryOnClockSkewCondition() {
}
public static RetryOnClockSkewCondition create() {
return new RetryOnClockSkewCondition();
}
@Override
public boolean shouldRetry(RetryPolicyContext context) {
return RetryUtils.isClockSkewException(context.exception());
}
@Override
public String toString() {
return ToString.create("RetryOnClockSkewCondition");
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
return o != null && getClass() == o.getClass();
}
@Override
public int hashCode() {
return 0;
}
}
| 1,823 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/RetryOnStatusCodeCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.conditions;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Retry condition implementation that retries if the HTTP status code matches one of the provided status codes.
*/
@SdkPublicApi
public final class RetryOnStatusCodeCondition implements RetryCondition {
private final Set<Integer> statusCodesToRetryOn;
private RetryOnStatusCodeCondition(Set<Integer> statusCodesToRetryOn) {
this.statusCodesToRetryOn = new HashSet<>(
Validate.paramNotNull(statusCodesToRetryOn, "statusCodesToRetryOn"));
}
/**
* @param context Context about the state of the last request and information about the number of requests made.
* @return True if the HTTP status code matches one of the provided status codes. False if it doesn't match or the request
* failed for reasons other than an exceptional HTTP response (i.e. IOException).
*/
@Override
public boolean shouldRetry(RetryPolicyContext context) {
return Optional.ofNullable(context.httpStatusCode()).map(s ->
statusCodesToRetryOn.stream().anyMatch(code -> code.equals(s))).orElse(false);
}
public static RetryOnStatusCodeCondition create(Set<Integer> statusCodesToRetryOn) {
return new RetryOnStatusCodeCondition(statusCodesToRetryOn);
}
public static RetryOnStatusCodeCondition create(Integer... statusCodesToRetryOn) {
return new RetryOnStatusCodeCondition(Arrays.stream(statusCodesToRetryOn).collect(Collectors.toSet()));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RetryOnStatusCodeCondition that = (RetryOnStatusCodeCondition) o;
return statusCodesToRetryOn.equals(that.statusCodesToRetryOn);
}
@Override
public int hashCode() {
return statusCodesToRetryOn.hashCode();
}
@Override
public String toString() {
return ToString.builder("RetryOnStatusCodeCondition")
.add("statusCodesToRetryOn", statusCodesToRetryOn)
.build();
}
}
| 1,824 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/RetryOnExceptionsCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.conditions;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
/**
* Retry condition implementation that retries if the exception or the cause of the exception matches the classes defined.
*/
@SdkPublicApi
public final class RetryOnExceptionsCondition implements RetryCondition {
private final Set<Class<? extends Exception>> exceptionsToRetryOn;
/**
* @param exceptionsToRetryOn Exception classes to retry on.
*/
private RetryOnExceptionsCondition(Set<Class<? extends Exception>> exceptionsToRetryOn) {
this.exceptionsToRetryOn = new HashSet<>(exceptionsToRetryOn);
}
/**
* @param context Context about the state of the last request and information about the number of requests made.
* @return True if the exception class or the cause of the exception matches one of the exceptions supplied at
* initialization time.
*/
@Override
public boolean shouldRetry(RetryPolicyContext context) {
SdkException exception = context.exception();
if (exception == null) {
return false;
}
Predicate<Class<? extends Exception>> isRetryableException =
ex -> ex.isAssignableFrom(exception.getClass());
Predicate<Class<? extends Exception>> hasRetryableCause =
ex -> exception.getCause() != null && ex.isAssignableFrom(exception.getCause().getClass());
return exceptionsToRetryOn.stream().anyMatch(isRetryableException.or(hasRetryableCause));
}
/**
* @param exceptionsToRetryOn Exception classes to retry on.
*/
public static RetryOnExceptionsCondition create(Set<Class<? extends Exception>> exceptionsToRetryOn) {
return new RetryOnExceptionsCondition(exceptionsToRetryOn);
}
/**
* @param exceptionsToRetryOn Exception classes to retry on.
*/
public static RetryOnExceptionsCondition create(Class<? extends Exception>... exceptionsToRetryOn) {
return new RetryOnExceptionsCondition(Arrays.stream(exceptionsToRetryOn).collect(Collectors.toSet()));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RetryOnExceptionsCondition that = (RetryOnExceptionsCondition) o;
return exceptionsToRetryOn.equals(that.exceptionsToRetryOn);
}
@Override
public int hashCode() {
return exceptionsToRetryOn.hashCode();
}
@Override
public String toString() {
return ToString.builder("RetryOnExceptionsCondition")
.add("exceptionsToRetryOn", exceptionsToRetryOn)
.build();
}
}
| 1,825 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/OrRetryCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.conditions;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
/**
* Composite retry condition that evaluates to true if any containing condition evaluates to true.
*/
@SdkPublicApi
public final class OrRetryCondition implements RetryCondition {
private final Set<RetryCondition> conditions = new LinkedHashSet<>();
private OrRetryCondition(RetryCondition... conditions) {
Collections.addAll(this.conditions, conditions);
}
public static OrRetryCondition create(RetryCondition... conditions) {
return new OrRetryCondition(conditions);
}
/**
* @return True if any condition returns true. False otherwise.
*/
@Override
public boolean shouldRetry(RetryPolicyContext context) {
return conditions.stream().anyMatch(r -> r.shouldRetry(context));
}
@Override
public void requestWillNotBeRetried(RetryPolicyContext context) {
conditions.forEach(c -> c.requestWillNotBeRetried(context));
}
@Override
public void requestSucceeded(RetryPolicyContext context) {
conditions.forEach(c -> c.requestSucceeded(context));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrRetryCondition that = (OrRetryCondition) o;
return conditions.equals(that.conditions);
}
@Override
public int hashCode() {
return conditions.hashCode();
}
@Override
public String toString() {
return ToString.builder("OrRetryCondition")
.add("conditions", conditions)
.build();
}
}
| 1,826 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/retry/conditions/MaxNumberOfRetriesCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry.conditions;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.internal.retry.SdkDefaultRetrySetting;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Simple retry condition that allows retries up to a certain max number of retries.
*/
@SdkPublicApi
public final class MaxNumberOfRetriesCondition implements RetryCondition {
private final int maxNumberOfRetries;
private MaxNumberOfRetriesCondition(int maxNumberOfRetries) {
this.maxNumberOfRetries = Validate.isNotNegative(maxNumberOfRetries, "maxNumberOfRetries");
}
public static MaxNumberOfRetriesCondition create(int maxNumberOfRetries) {
return new MaxNumberOfRetriesCondition(maxNumberOfRetries);
}
public static MaxNumberOfRetriesCondition forRetryMode(RetryMode retryMode) {
return create(SdkDefaultRetrySetting.maxAttempts(retryMode));
}
@Override
public boolean shouldRetry(RetryPolicyContext context) {
return context.retriesAttempted() < maxNumberOfRetries;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MaxNumberOfRetriesCondition that = (MaxNumberOfRetriesCondition) o;
return maxNumberOfRetries == that.maxNumberOfRetries;
}
@Override
public int hashCode() {
return maxNumberOfRetries;
}
@Override
public String toString() {
return ToString.builder("MaxNumberOfRetriesCondition")
.add("maxNumberOfRetries", maxNumberOfRetries)
.build();
}
}
| 1,827 |
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/util/SdkAutoConstructList.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import java.util.List;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* A list that was auto constructed by the SDK.
* <p>
* The main purpose of this class is to help distinguish explicitly empty lists
* set on requests by the user, as some services may treat {@code null} or
* missing lists and empty list members differently. As such, this class should
* not be used directly by the user.
*
* @param <T> The element type.
*/
@SdkProtectedApi
public interface SdkAutoConstructList<T> extends List<T> {
}
| 1,828 |
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/util/DefaultSdkAutoConstructMap.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Default implementation of {@link SdkAutoConstructMap}.
* <p>
* This is an empty, unmodifiable map.
*
* @param <K> The key type.
* @param <V> The value type.
*/
@SdkProtectedApi
public final class DefaultSdkAutoConstructMap<K, V> implements SdkAutoConstructMap<K, V> {
private static final DefaultSdkAutoConstructMap INSTANCE = new DefaultSdkAutoConstructMap();
private final Map<K, V> impl = Collections.emptyMap();
private DefaultSdkAutoConstructMap() {
}
@SuppressWarnings("unchecked")
public static <K, V> DefaultSdkAutoConstructMap<K, V> getInstance() {
return (DefaultSdkAutoConstructMap<K, V>) INSTANCE;
}
@Override
public int size() {
return impl.size();
}
@Override
public boolean isEmpty() {
return impl.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return impl.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return impl.containsValue(value);
}
@Override
public V get(Object key) {
return impl.get(key);
}
@Override
public V put(K key, V value) {
return impl.put(key, value);
}
@Override
public V remove(Object key) {
return impl.get(key);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
impl.putAll(m);
}
@Override
public void clear() {
impl.clear();
}
@Override
public Set<K> keySet() {
return impl.keySet();
}
@Override
public Collection<V> values() {
return impl.values();
}
@Override
public Set<Entry<K, V>> entrySet() {
return impl.entrySet();
}
@Override
public boolean equals(Object o) {
return impl.equals(o);
}
@Override
public int hashCode() {
return impl.hashCode();
}
@Override
public String toString() {
return impl.toString();
}
}
| 1,829 |
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/util/DefaultSdkAutoConstructList.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Default implementation of {@link SdkAutoConstructList}.
* <p>
* This is an empty, unmodifiable list.
*
* @param <T> The element type.
*/
@SdkProtectedApi
public final class DefaultSdkAutoConstructList<T> implements SdkAutoConstructList<T> {
private static final DefaultSdkAutoConstructList INSTANCE = new DefaultSdkAutoConstructList();
private final List impl = Collections.emptyList();
private DefaultSdkAutoConstructList() {
}
@SuppressWarnings("unchecked")
public static <T> DefaultSdkAutoConstructList<T> getInstance() {
return (DefaultSdkAutoConstructList<T>) INSTANCE;
}
@Override
public int size() {
return impl.size();
}
@Override
public boolean isEmpty() {
return impl.isEmpty();
}
@Override
public boolean contains(Object o) {
return impl.contains(o);
}
@Override
public Iterator<T> iterator() {
return impl.iterator();
}
@Override
public Object[] toArray() {
return impl.toArray();
}
@Override
public <T1> T1[] toArray(T1[] a) {
return (T1[]) impl.toArray(a);
}
@Override
public boolean add(T t) {
return impl.add(t);
}
@Override
public boolean remove(Object o) {
return impl.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return impl.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends T> c) {
return impl.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends T> c) {
return impl.addAll(index, c);
}
@Override
public boolean removeAll(Collection<?> c) {
return impl.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return impl.retainAll(c);
}
@Override
public void clear() {
impl.clear();
}
@Override
public T get(int index) {
return (T) impl.get(index);
}
@Override
public T set(int index, T element) {
return (T) impl.set(index, element);
}
@Override
public void add(int index, T element) {
impl.add(index, element);
}
@Override
public T remove(int index) {
return (T) impl.remove(index);
}
@Override
public int indexOf(Object o) {
return impl.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return impl.lastIndexOf(o);
}
@Override
public ListIterator<T> listIterator() {
return impl.listIterator();
}
@Override
public ListIterator<T> listIterator(int index) {
return impl.listIterator(index);
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
return impl.subList(fromIndex, toIndex);
}
@Override
public boolean equals(Object o) {
return impl.equals(o);
}
@Override
public int hashCode() {
return impl.hashCode();
}
@Override
public String toString() {
return impl.toString();
}
}
| 1,830 |
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/util/SdkAutoConstructMap.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* A map that was auto constructed by the SDK.
* <p>
* The main purpose of this class is to help distinguish explicitly empty maps
* set on requests by the user, as some services may treat {@code null} or
* missing maps and empty map members differently. As such, this class should
* not be used directly by the user.
*
* @param <K> The key type.
* @param <V> The value type.
*/
@SdkProtectedApi
public interface SdkAutoConstructMap<K, V> extends Map<K, V> {
}
| 1,831 |
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/util/IdempotentUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import java.util.UUID;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
/**
* Utility class to manage idempotency token
*/
@SdkProtectedApi
public final class IdempotentUtils {
private static Supplier<String> generator = () -> UUID.randomUUID().toString();
private IdempotentUtils() {
}
/**
* @deprecated By {@link #getGenerator()}
*/
@Deprecated
@SdkProtectedApi
public static String resolveString(String token) {
return token != null ? token : generator.get();
}
@SdkProtectedApi
public static Supplier<String> getGenerator() {
return generator;
}
@SdkTestInternalApi
public static void setGenerator(Supplier<String> newGenerator) {
generator = newGenerator;
}
}
| 1,832 |
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/util/SdkUserAgent.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import java.util.Optional;
import java.util.jar.JarInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.JavaSystemSetting;
import software.amazon.awssdk.utils.StringUtils;
/**
* Utility class for accessing AWS SDK versioning information.
*/
@ThreadSafe
@SdkProtectedApi
public final class SdkUserAgent {
private static final String UA_STRING = "aws-sdk-{platform}/{version} {os.name}/{os.version} {java.vm.name}/{java.vm"
+ ".version} Java/{java.version}{language.and.region}{additional.languages} "
+ "vendor/{java.vendor}";
/** Disallowed characters in the user agent token: @see <a href="https://tools.ietf.org/html/rfc7230#section-3.2.6">RFC 7230</a> */
private static final String UA_DENYLIST_REGEX = "[() ,/:;<=>?@\\[\\]{}\\\\]";
/** Shared logger for any issues while loading version information. */
private static final Logger log = LoggerFactory.getLogger(SdkUserAgent.class);
private static final String UNKNOWN = "unknown";
private static volatile SdkUserAgent instance;
private static final String[] USER_AGENT_SEARCH = {
"{platform}",
"{version}",
"{os.name}",
"{os.version}",
"{java.vm.name}",
"{java.vm.version}",
"{java.version}",
"{java.vendor}",
"{additional.languages}",
"{language.and.region}"
};
/** User Agent info. */
private String userAgent;
private SdkUserAgent() {
initializeUserAgent();
}
public static SdkUserAgent create() {
if (instance == null) {
synchronized (SdkUserAgent.class) {
if (instance == null) {
instance = new SdkUserAgent();
}
}
}
return instance;
}
/**
* @return Returns the User Agent string to be used when communicating with
* the AWS services. The User Agent encapsulates SDK, Java, OS and
* region information.
*/
public String userAgent() {
return userAgent;
}
/**
* Initializes the user agent string by loading a template from
* {@code InternalConfig} and filling in the detected version/platform
* info.
*/
private void initializeUserAgent() {
userAgent = getUserAgent();
}
@SdkTestInternalApi
String getUserAgent() {
Optional<String> language = JavaSystemSetting.USER_LANGUAGE.getStringValue();
Optional<String> region = JavaSystemSetting.USER_REGION.getStringValue();
String languageAndRegion = "";
if (language.isPresent() && region.isPresent()) {
languageAndRegion = " (" + sanitizeInput(language.get()) + "_" + sanitizeInput(region.get()) + ")";
}
return StringUtils.replaceEach(UA_STRING, USER_AGENT_SEARCH, new String[] {
"java",
VersionInfo.SDK_VERSION,
sanitizeInput(JavaSystemSetting.OS_NAME.getStringValue().orElse(null)),
sanitizeInput(JavaSystemSetting.OS_VERSION.getStringValue().orElse(null)),
sanitizeInput(JavaSystemSetting.JAVA_VM_NAME.getStringValue().orElse(null)),
sanitizeInput(JavaSystemSetting.JAVA_VM_VERSION.getStringValue().orElse(null)),
sanitizeInput(JavaSystemSetting.JAVA_VERSION.getStringValue().orElse(null)),
sanitizeInput(JavaSystemSetting.JAVA_VENDOR.getStringValue().orElse(null)),
getAdditionalJvmLanguages(),
languageAndRegion,
});
}
/**
* Replace any spaces, parentheses in the input with underscores.
*
* @param input the input
* @return the input with spaces replaced by underscores
*/
private static String sanitizeInput(String input) {
return input == null ? UNKNOWN : input.replaceAll(UA_DENYLIST_REGEX, "_");
}
private static String getAdditionalJvmLanguages() {
return concat(concat("", scalaVersion(), " "), kotlinVersion(), " ");
}
/**
* Attempt to determine if Scala is on the classpath and if so what version is in use.
* Does this by looking for a known Scala class (scala.util.Properties) and then calling
* a static method on that class via reflection to determine the versionNumberString.
*
* @return Scala version if any, else empty string
*/
private static String scalaVersion() {
String scalaVersion = "";
try {
Class<?> scalaProperties = Class.forName("scala.util.Properties");
scalaVersion = "scala";
String version = (String) scalaProperties.getMethod("versionNumberString").invoke(null);
scalaVersion = concat(scalaVersion, version, "/");
} catch (ClassNotFoundException e) {
//Ignore
} catch (Exception e) {
if (log.isTraceEnabled()) {
log.trace("Exception attempting to get Scala version.", e);
}
}
return scalaVersion;
}
/**
* Attempt to determine if Kotlin is on the classpath and if so what version is in use.
* Does this by looking for a known Kotlin class (kotlin.Unit) and then loading the Manifest
* from that class' JAR to determine the Kotlin version.
*
* @return Kotlin version if any, else empty string
*/
private static String kotlinVersion() {
String kotlinVersion = "";
JarInputStream kotlinJar = null;
try {
Class<?> kotlinUnit = Class.forName("kotlin.Unit");
kotlinVersion = "kotlin";
kotlinJar = new JarInputStream(kotlinUnit.getProtectionDomain().getCodeSource().getLocation().openStream());
String version = kotlinJar.getManifest().getMainAttributes().getValue("Implementation-Version");
kotlinVersion = concat(kotlinVersion, version, "/");
} catch (ClassNotFoundException e) {
//Ignore
} catch (Exception e) {
if (log.isTraceEnabled()) {
log.trace("Exception attempting to get Kotlin version.", e);
}
} finally {
IoUtils.closeQuietly(kotlinJar, log);
}
return kotlinVersion;
}
private static String concat(String prefix, String suffix, String separator) {
return suffix != null && !suffix.isEmpty() ? prefix + separator + suffix : prefix;
}
}
| 1,833 |
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/util/PaginatorUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import java.util.Collection;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
@SdkProtectedApi
public final class PaginatorUtils {
private PaginatorUtils() {
}
/**
* Checks if the output token is available.
*
* @param outputToken the output token to check
* @param <T> the type of the output token
* @return true if the output token is non-null or non-empty if the output token is a String or map or Collection type
*/
public static <T> boolean isOutputTokenAvailable(T outputToken) {
if (outputToken == null) {
return false;
}
if (outputToken instanceof String) {
return !((String) outputToken).isEmpty();
}
if (outputToken instanceof Map) {
return !((Map) outputToken).isEmpty();
}
if (outputToken instanceof Collection) {
return !((Collection) outputToken).isEmpty();
}
return true;
}
}
| 1,834 |
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/traits/JsonValueTrait.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Trait that indicates a String member is a JSON document. This can influence how it is marshalled/unmarshalled. For example,
* a string bound to the header with this trait applied will be Base64 encoded.
*/
@SdkProtectedApi
public final class JsonValueTrait implements Trait {
private JsonValueTrait() {
}
public static JsonValueTrait create() {
return new JsonValueTrait();
}
}
| 1,835 |
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/traits/LocationTrait.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.protocol.MarshallLocation;
/**
* Trait to include metadata about the marshalling/unmarshalling location (i.e. headers/payload/etc).
*/
@SdkProtectedApi
public final class LocationTrait implements Trait {
private final MarshallLocation location;
private final String locationName;
private final String unmarshallLocationName;
private LocationTrait(Builder builder) {
this.location = builder.location;
this.locationName = builder.locationName;
this.unmarshallLocationName = builder.unmarshallLocationName == null ?
builder.locationName : builder.unmarshallLocationName;
}
/**
* @return Location of member (i.e. headers/query/path/payload).
*/
public MarshallLocation location() {
return location;
}
/**
* @return Location name of member. I.E. the header or query param name, or the JSON field name, etc.
*/
public String locationName() {
return locationName;
}
/**
* @return Location name for unmarshalling. This is only needed for the legacy EC2 protocol which has
* different serialization/deserialization for the same fields.
*/
public String unmarshallLocationName() {
return unmarshallLocationName;
}
/**
* @return Builder instance.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link LocationTrait}.
*/
public static final class Builder {
private MarshallLocation location;
private String locationName;
private String unmarshallLocationName;
private Builder() {
}
public Builder location(MarshallLocation location) {
this.location = location;
return this;
}
public Builder locationName(String locationName) {
this.locationName = locationName;
return this;
}
public Builder unmarshallLocationName(String unmarshallLocationName) {
this.unmarshallLocationName = unmarshallLocationName;
return this;
}
public LocationTrait build() {
return new LocationTrait(this);
}
}
}
| 1,836 |
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/traits/PayloadTrait.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Trait that indicates a member is the 'payload' member.
*/
@SdkProtectedApi
public final class PayloadTrait implements Trait {
private PayloadTrait() {
}
public static PayloadTrait create() {
return new PayloadTrait();
}
}
| 1,837 |
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/traits/DefaultValueTrait.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.util.IdempotentUtils;
/**
* Trait that supplies a default value when none is present for a given field.
*/
@SdkProtectedApi
public final class DefaultValueTrait implements Trait {
private final Supplier<?> defaultValueSupplier;
private DefaultValueTrait(Supplier<?> defaultValueSupplier) {
this.defaultValueSupplier = defaultValueSupplier;
}
/**
* If the value is null then the default value supplier is used to get a default
* value for the field. Otherwise 'val' is returned.
*
* @param val Value to resolve.
* @return Resolved value.
*/
public Object resolveValue(Object val) {
return val != null ? val : defaultValueSupplier.get();
}
/**
* Creates a new {@link DefaultValueTrait} with a custom {@link Supplier}.
*
* @param supplier Supplier of default value for the field.
* @return New trait instance.
*/
public static DefaultValueTrait create(Supplier<?> supplier) {
return new DefaultValueTrait(supplier);
}
/**
* Creates a precanned {@link DefaultValueTrait} using the idempotency token generation which
* creates a new UUID if a field is null. This is used when the 'idempotencyToken' trait in the service
* model is present.
*
* @return New trait instance.
*/
public static DefaultValueTrait idempotencyToken() {
return new DefaultValueTrait(IdempotentUtils.getGenerator());
}
}
| 1,838 |
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/traits/XmlAttributesTrait.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.Pair;
/**
* Trait to include the xml attributes such as "xmlns:xsi" or "xsi:type".
*/
@SdkProtectedApi
public final class XmlAttributesTrait implements Trait {
private Map<String, AttributeAccessors> attributes;
private XmlAttributesTrait(Pair<String, AttributeAccessors>... attributePairs) {
attributes = new LinkedHashMap<>();
for (Pair<String, AttributeAccessors> pair : attributePairs) {
attributes.put(pair.left(), pair.right());
}
attributes = Collections.unmodifiableMap(attributes);
}
public static XmlAttributesTrait create(Pair<String, AttributeAccessors>... pairs) {
return new XmlAttributesTrait(pairs);
}
public Map<String, AttributeAccessors> attributes() {
return attributes;
}
public static final class AttributeAccessors {
private final Function<Object, String> attributeGetter;
private AttributeAccessors(Builder builder) {
this.attributeGetter = builder.attributeGetter;
}
public static Builder builder() {
return new Builder();
}
/**
* @return the attribute Getter method
*/
public Function<Object, String> attributeGetter() {
return attributeGetter;
}
public static final class Builder {
private Function<Object, String> attributeGetter;
private Builder() {
}
public Builder attributeGetter(Function<Object, String> attributeGetter) {
this.attributeGetter = attributeGetter;
return this;
}
public AttributeAccessors build() {
return new AttributeAccessors(this);
}
}
}
}
| 1,839 |
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/traits/Trait.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkField;
/**
* Marker interface for traits that contain additional metadata about {@link SdkField}s.
*/
@SdkProtectedApi
public interface Trait {
}
| 1,840 |
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/traits/RequiredTrait.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Trait that indicates a value must be provided for a member.
*/
@SdkProtectedApi
public final class RequiredTrait implements Trait {
private RequiredTrait() {
}
public static RequiredTrait create() {
return new RequiredTrait();
}
}
| 1,841 |
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/traits/TimestampFormatTrait.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.DateUtils;
/**
* Trait that indicates a different format should be used for marshalling/unmarshalling timestamps. If not present
* the protocol will determine the default format to use based on the location (i.e. for JSON protocol headers are ISO8601
* but timestamps in the payload are epoch seconds with millisecond decimal precision).
*/
@SdkProtectedApi
public final class TimestampFormatTrait implements Trait {
private final Format format;
private TimestampFormatTrait(Format timestampFormat) {
this.format = timestampFormat;
}
/**
* @return Format to use.
*/
public Format format() {
return format;
}
public static TimestampFormatTrait create(Format timestampFormat) {
return new TimestampFormatTrait(timestampFormat);
}
/**
* Enum of the timestamp formats we currently support.
*/
public enum Format {
/**
* See {@link DateUtils#parseIso8601Date(String)}
*/
ISO_8601,
/**
* See {@link DateUtils#parseRfc1123Date(String)}
*/
RFC_822,
/**
* See {@link DateUtils#parseUnixTimestampInstant(String)}
*/
UNIX_TIMESTAMP,
/**
* See {@link DateUtils#parseUnixTimestampMillisInstant(String)}. This is only used by the CBOR protocol currently.
*/
UNIX_TIMESTAMP_MILLIS;
/**
* Creates a timestamp format enum from the string defined in the model.
*
* @param strFormat String format.
* @return Format enum.
*/
public static Format fromString(String strFormat) {
switch (strFormat) {
case "iso8601":
return ISO_8601;
case "rfc822":
return RFC_822;
case "unixTimestamp":
return UNIX_TIMESTAMP;
// UNIX_TIMESTAMP_MILLIS does not have a defined string format so intentionally omitted here.
default:
throw new RuntimeException("Unknown timestamp format - " + strFormat);
}
}
}
}
| 1,842 |
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/traits/ListTrait.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkField;
/**
* Trait that includes additional metadata about List members.
*/
@SdkProtectedApi
public final class ListTrait implements Trait {
private final String memberLocationName;
private final SdkField memberFieldInfo;
private final boolean isFlattened;
private ListTrait(Builder builder) {
this.memberLocationName = builder.memberLocationName;
this.memberFieldInfo = builder.memberFieldInfo;
this.isFlattened = builder.isFlattened;
}
/**
* Location name of member, this is typically only used for XML based protocols which use separate
* tags for each item. This is not used for JSON and JSON-like protocols.
*
* @return Member location name.
*/
// TODO remove this
public String memberLocationName() {
return memberLocationName;
}
/**
* @return Metadata about the items this list contains. May be further nested in the case of complex nested containers.
*/
public SdkField memberFieldInfo() {
return memberFieldInfo;
}
/**
* @return Whether the list should be marshalled/unmarshalled as a 'flattened' list. This only applies to Query/XML protocols.
*/
public boolean isFlattened() {
return isFlattened;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private String memberLocationName;
private SdkField memberFieldInfo;
private boolean isFlattened;
private Builder() {
}
public Builder memberLocationName(String memberLocationName) {
this.memberLocationName = memberLocationName;
return this;
}
public Builder memberFieldInfo(SdkField memberFieldInfo) {
this.memberFieldInfo = memberFieldInfo;
return this;
}
public Builder isFlattened(boolean isFlattened) {
this.isFlattened = isFlattened;
return this;
}
public ListTrait build() {
return new ListTrait(this);
}
}
}
| 1,843 |
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/traits/XmlAttributeTrait.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Trait to indicate this is an Xml attribute.
*/
@SdkProtectedApi
public final class XmlAttributeTrait implements Trait {
private XmlAttributeTrait() {
}
public static XmlAttributeTrait create() {
return new XmlAttributeTrait();
}
}
| 1,844 |
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/traits/MapTrait.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.traits;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkField;
/**
* Trait that includes additional metadata for Map members.
*/
@SdkProtectedApi
public final class MapTrait implements Trait {
private final String keyLocationName;
private final String valueLocationName;
private final SdkField valueFieldInfo;
private final boolean isFlattened;
private MapTrait(Builder builder) {
this.keyLocationName = builder.keyLocationName;
this.valueLocationName = builder.valueLocationName;
this.valueFieldInfo = builder.valueFieldInfo;
this.isFlattened = builder.isFlattened;
}
/**
* @return Location name of key. Used only for XML based protocols.
*/
public String keyLocationName() {
return keyLocationName;
}
/**
* @return Location name of value. Used only for XML based protocols.
*/
public String valueLocationName() {
return valueLocationName;
}
/**
* @return Additional metadata for the map value types. May be further nested in the case of complex containers.
*/
public SdkField valueFieldInfo() {
return valueFieldInfo;
}
/**
* @return Whether the map should be marshalled/unmarshalled as a 'flattened' map. This only applies to Query/XML protocols.
*/
public boolean isFlattened() {
return isFlattened;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private String keyLocationName;
private String valueLocationName;
private SdkField valueFieldInfo;
private boolean isFlattened;
private Builder() {
}
public Builder keyLocationName(String keyLocationName) {
this.keyLocationName = keyLocationName;
return this;
}
public Builder valueLocationName(String valueLocationName) {
this.valueLocationName = valueLocationName;
return this;
}
public Builder valueFieldInfo(SdkField valueFieldInfo) {
this.valueFieldInfo = valueFieldInfo;
return this;
}
public Builder isFlattened(boolean isFlattened) {
this.isFlattened = isFlattened;
return this;
}
public MapTrait build() {
return new MapTrait(this);
}
}
}
| 1,845 |
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/endpointdiscovery/EndpointDiscoveryRefreshCache.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.endpointdiscovery;
import java.net.URI;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import software.amazon.awssdk.annotations.SdkProtectedApi;
@SdkProtectedApi
public final class EndpointDiscoveryRefreshCache {
private final Map<String, EndpointDiscoveryEndpoint> cache = new ConcurrentHashMap<>();
private final EndpointDiscoveryCacheLoader client;
private EndpointDiscoveryRefreshCache(EndpointDiscoveryCacheLoader client) {
this.client = client;
}
public static EndpointDiscoveryRefreshCache create(EndpointDiscoveryCacheLoader client) {
return new EndpointDiscoveryRefreshCache(client);
}
/**
* Abstract method to be implemented by each service to handle retrieving
* endpoints from a cache. Each service must handle converting a request
* object into the relevant cache key.
*
* @return The endpoint to use for this request
*/
public URI get(String accessKey, EndpointDiscoveryRequest request) {
String key = accessKey;
// Support null (anonymous credentials) by mapping to empty-string. The backing cache does not support null.
if (key == null) {
key = "";
}
if (request.cacheKey().isPresent()) {
key = key + ":" + request.cacheKey().get();
}
EndpointDiscoveryEndpoint endpoint = cache.get(key);
if (endpoint == null) {
if (request.required()) {
return cache.computeIfAbsent(key, k -> getAndJoin(request)).endpoint();
} else {
EndpointDiscoveryEndpoint tempEndpoint = EndpointDiscoveryEndpoint.builder()
.endpoint(request.defaultEndpoint())
.expirationTime(Instant.now().plusSeconds(60))
.build();
EndpointDiscoveryEndpoint previousValue = cache.putIfAbsent(key, tempEndpoint);
if (previousValue != null) {
// Someone else primed the cache. Use that endpoint (which may be temporary).
return previousValue.endpoint();
} else {
// We primed the cache with the temporary endpoint. Kick off discovery in the background.
refreshCacheAsync(request, key);
}
return tempEndpoint.endpoint();
}
}
if (endpoint.expirationTime().isBefore(Instant.now())) {
cache.put(key, endpoint.toBuilder().expirationTime(Instant.now().plusSeconds(60)).build());
refreshCacheAsync(request, key);
}
return endpoint.endpoint();
}
private EndpointDiscoveryEndpoint getAndJoin(EndpointDiscoveryRequest request) {
try {
return discoverEndpoint(request).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw EndpointDiscoveryFailedException.create(e);
} catch (ExecutionException e) {
throw EndpointDiscoveryFailedException.create(e.getCause());
}
}
private void refreshCacheAsync(EndpointDiscoveryRequest request, String key) {
discoverEndpoint(request).thenApply(v -> cache.put(key, v));
}
public CompletableFuture<EndpointDiscoveryEndpoint> discoverEndpoint(EndpointDiscoveryRequest request) {
return client.discoverEndpoint(request);
}
public void evict(String key) {
cache.remove(key);
}
}
| 1,846 |
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/endpointdiscovery/EndpointDiscoveryCacheLoader.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.endpointdiscovery;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.exception.SdkClientException;
@SdkProtectedApi
public interface EndpointDiscoveryCacheLoader {
CompletableFuture<EndpointDiscoveryEndpoint> discoverEndpoint(EndpointDiscoveryRequest endpointDiscoveryRequest);
default URI toUri(String address, URI defaultEndpoint) {
try {
return new URI(defaultEndpoint.getScheme(), address, defaultEndpoint.getPath(), defaultEndpoint.getFragment());
} catch (URISyntaxException e) {
throw SdkClientException.builder().message("Unable to construct discovered endpoint").cause(e).build();
}
}
}
| 1,847 |
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/endpointdiscovery/EndpointDiscoveryFailedException.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.endpointdiscovery;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.utils.Validate;
/**
* This exception is thrown when the SDK was unable to retrieve an endpoint from AWS. The cause describes what specific part of
* the endpoint discovery process failed.
*/
@SdkPublicApi
public class EndpointDiscoveryFailedException extends SdkClientException {
private static final long serialVersionUID = 1L;
private EndpointDiscoveryFailedException(Builder b) {
super(b);
Validate.paramNotNull(b.cause(), "cause");
}
public static Builder builder() {
return new BuilderImpl();
}
public static EndpointDiscoveryFailedException create(Throwable cause) {
return builder().message("Failed when retrieving a required endpoint from AWS.")
.cause(cause)
.build();
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
public interface Builder extends SdkClientException.Builder {
@Override
Builder message(String message);
@Override
Builder cause(Throwable cause);
@Override
Builder writableStackTrace(Boolean writableStackTrace);
@Override
EndpointDiscoveryFailedException build();
}
protected static final class BuilderImpl extends SdkClientException.BuilderImpl implements Builder {
protected BuilderImpl() {
}
protected BuilderImpl(EndpointDiscoveryFailedException 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 EndpointDiscoveryFailedException build() {
return new EndpointDiscoveryFailedException(this);
}
}
}
| 1,848 |
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/endpointdiscovery/EndpointDiscoveryEndpoint.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.endpointdiscovery;
import java.net.URI;
import java.time.Instant;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
@SdkInternalApi
public final class EndpointDiscoveryEndpoint implements
ToCopyableBuilder<EndpointDiscoveryEndpoint.Builder, EndpointDiscoveryEndpoint> {
private final URI endpoint;
private final Instant expirationTime;
private EndpointDiscoveryEndpoint(BuilderImpl builder) {
this.endpoint = builder.endpoint;
this.expirationTime = builder.expirationTime;
}
public URI endpoint() {
return endpoint;
}
public Instant expirationTime() {
return expirationTime;
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public Builder toBuilder() {
return builder().endpoint(endpoint).expirationTime(expirationTime);
}
public interface Builder extends CopyableBuilder<Builder, EndpointDiscoveryEndpoint> {
Builder endpoint(URI endpoint);
Builder expirationTime(Instant expirationTime);
@Override
EndpointDiscoveryEndpoint build();
}
private static final class BuilderImpl implements Builder {
private URI endpoint;
private Instant expirationTime;
private BuilderImpl() {
}
@Override
public Builder endpoint(URI endpoint) {
this.endpoint = endpoint;
return this;
}
public void setEndpoint(URI endpoint) {
endpoint(endpoint);
}
@Override
public Builder expirationTime(Instant expirationTime) {
this.expirationTime = expirationTime;
return this;
}
public void setExpirationTime(Instant expirationTime) {
expirationTime(expirationTime);
}
@Override
public EndpointDiscoveryEndpoint build() {
return new EndpointDiscoveryEndpoint(this);
}
}
}
| 1,849 |
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/endpointdiscovery/EndpointDiscoveryRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.endpointdiscovery;
import java.net.URI;
import java.util.Map;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.RequestOverrideConfiguration;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
@SdkProtectedApi
public final class EndpointDiscoveryRequest
implements ToCopyableBuilder<EndpointDiscoveryRequest.Builder, EndpointDiscoveryRequest> {
private final RequestOverrideConfiguration requestOverrideConfiguration;
private final String operationName;
private final Map<String, String> identifiers;
private final String cacheKey;
private final boolean required;
private final URI defaultEndpoint;
private EndpointDiscoveryRequest(BuilderImpl builder) {
this.requestOverrideConfiguration = builder.requestOverrideConfiguration;
this.operationName = builder.operationName;
this.identifiers = builder.identifiers;
this.cacheKey = builder.cacheKey;
this.required = builder.required;
this.defaultEndpoint = builder.defaultEndpoint;
}
public Optional<RequestOverrideConfiguration> overrideConfiguration() {
return Optional.ofNullable(requestOverrideConfiguration);
}
public Optional<String> operationName() {
return Optional.ofNullable(operationName);
}
public Optional<Map<String, String>> identifiers() {
return Optional.ofNullable(identifiers);
}
public Optional<String> cacheKey() {
return Optional.ofNullable(cacheKey);
}
public boolean required() {
return required;
}
public URI defaultEndpoint() {
return defaultEndpoint;
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
/**
* Builder interface for constructing a {@link EndpointDiscoveryRequest}.
*/
public interface Builder extends CopyableBuilder<Builder, EndpointDiscoveryRequest> {
/**
* The request override configuration to be used with the endpoint discovery request.
*/
Builder overrideConfiguration(RequestOverrideConfiguration overrideConfiguration);
/**
* The name of the operation being used in the customer's request.
*
* @param operationName The name of the operation.
* @return Returns a reference to this object so that method calls can be chained together.
*/
Builder operationName(String operationName);
/**
* Specifies a map containing a set identifiers mapped to the name of the field in the request.
*
* @param identifiers A map of identifiers for the request.
* @return Returns a reference to this object so that method calls can be chained together.
*/
Builder identifiers(Map<String, String> identifiers);
/**
* The cache key to use for a given cache entry.
*
* @param cacheKey A cache key.
* @return Returns a reference to this object so that method calls can be chained together.
*/
Builder cacheKey(String cacheKey);
/**
* Whether or not endpoint discovery is required for this request.
*
* @param required boolean specifying if endpoint discovery is required.
* @return Returns a reference to this object so that method calls can be chained together.
*/
Builder required(boolean required);
/**
* The default endpoint for a request.
* @param defaultEndpoint {@link URI} of the default endpoint
* @return Returns a reference to this object so that method calls can be chained together.
*/
Builder defaultEndpoint(URI defaultEndpoint);
}
static class BuilderImpl implements Builder {
private RequestOverrideConfiguration requestOverrideConfiguration;
private String operationName;
private Map<String, String> identifiers;
private String cacheKey;
private boolean required = false;
private URI defaultEndpoint;
private BuilderImpl() {
}
private BuilderImpl(EndpointDiscoveryRequest request) {
this.requestOverrideConfiguration = request.requestOverrideConfiguration;
this.operationName = request.operationName;
this.identifiers = request.identifiers;
this.cacheKey = request.cacheKey;
this.required = request.required;
this.defaultEndpoint = request.defaultEndpoint;
}
@Override
public Builder overrideConfiguration(RequestOverrideConfiguration overrideConfiguration) {
this.requestOverrideConfiguration = overrideConfiguration;
return this;
}
@Override
public Builder operationName(String operationName) {
this.operationName = operationName;
return this;
}
@Override
public Builder identifiers(Map<String, String> identifiers) {
this.identifiers = identifiers;
return this;
}
@Override
public Builder cacheKey(String cacheKey) {
this.cacheKey = cacheKey;
return this;
}
@Override
public Builder required(boolean required) {
this.required = required;
return this;
}
@Override
public Builder defaultEndpoint(URI defaultEndpoint) {
this.defaultEndpoint = defaultEndpoint;
return this;
}
@Override
public EndpointDiscoveryRequest build() {
return new EndpointDiscoveryRequest(this);
}
}
}
| 1,850 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/endpointdiscovery | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/endpointdiscovery/providers/SystemPropertiesEndpointDiscoveryProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.endpointdiscovery.providers;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.utils.ToString;
/**
* {@link EndpointDiscoveryProvider} implementation that loads endpoint discovery from the AWS_ENABLE_ENDPOINT_DISCOVERY
* system property or environment variable.
*/
@SdkPublicApi
public final class SystemPropertiesEndpointDiscoveryProvider implements EndpointDiscoveryProvider {
private SystemPropertiesEndpointDiscoveryProvider() {
}
public static SystemPropertiesEndpointDiscoveryProvider create() {
return new SystemPropertiesEndpointDiscoveryProvider();
}
@Override
public boolean resolveEndpointDiscovery() {
return SdkSystemSetting
.AWS_ENDPOINT_DISCOVERY_ENABLED.getBooleanValue()
.orElseThrow(
() -> SdkClientException.builder()
.message("No endpoint discovery setting set.")
.build());
}
@Override
public String toString() {
return ToString.create("SystemPropertiesEndpointDiscoveryProvider");
}
}
| 1,851 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/endpointdiscovery | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/endpointdiscovery/providers/EndpointDiscoveryProviderChain.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.endpointdiscovery.providers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkProtectedApi;
@SdkProtectedApi
public class EndpointDiscoveryProviderChain implements EndpointDiscoveryProvider {
private static final Logger log = LoggerFactory.getLogger(EndpointDiscoveryProviderChain.class);
private final List<EndpointDiscoveryProvider> providers;
public EndpointDiscoveryProviderChain(EndpointDiscoveryProvider... providers) {
this.providers = new ArrayList<>(providers.length);
Collections.addAll(this.providers, providers);
}
@Override
public boolean resolveEndpointDiscovery() {
for (EndpointDiscoveryProvider provider : providers) {
try {
return provider.resolveEndpointDiscovery();
} catch (Exception e) {
log.debug("Unable to load endpoint discovery from {}:{}", provider.toString(), e.getMessage());
}
}
return false;
}
}
| 1,852 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/endpointdiscovery | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/endpointdiscovery/providers/EndpointDiscoveryProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.endpointdiscovery.providers;
import software.amazon.awssdk.annotations.SdkInternalApi;
@FunctionalInterface
@SdkInternalApi
public interface EndpointDiscoveryProvider {
/**
* Returns whether or not endpoint discovery is enabled.
*
* @return whether endpoint discovery is enabled.
*/
boolean resolveEndpointDiscovery();
}
| 1,853 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/endpointdiscovery | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/endpointdiscovery/providers/ProfileEndpointDiscoveryProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.endpointdiscovery.providers;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.utils.ToString;
@SdkInternalApi
public class ProfileEndpointDiscoveryProvider implements EndpointDiscoveryProvider {
private final Supplier<ProfileFile> profileFile;
private final String profileName;
private ProfileEndpointDiscoveryProvider(Supplier<ProfileFile> profileFile, String profileName) {
this.profileFile = profileFile;
this.profileName = profileName;
}
public static ProfileEndpointDiscoveryProvider create() {
return new ProfileEndpointDiscoveryProvider(ProfileFile::defaultProfileFile,
ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow());
}
public static ProfileEndpointDiscoveryProvider create(Supplier<ProfileFile> profileFile, String profileName) {
return new ProfileEndpointDiscoveryProvider(profileFile, profileName);
}
@Override
public boolean resolveEndpointDiscovery() {
return profileFile.get()
.profile(profileName)
.map(p -> p.properties().get(ProfileProperty.ENDPOINT_DISCOVERY_ENABLED))
.map(Boolean::parseBoolean)
.orElseThrow(() -> SdkClientException.builder()
.message("No endpoint discovery setting provided in profile: " +
profileName)
.build());
}
@Override
public String toString() {
return ToString.create("ProfileEndpointDiscoveryProvider");
}
}
| 1,854 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/endpointdiscovery | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/endpointdiscovery/providers/DefaultEndpointDiscoveryProviderChain.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.endpointdiscovery.providers;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
@SdkProtectedApi
public class DefaultEndpointDiscoveryProviderChain extends EndpointDiscoveryProviderChain {
public DefaultEndpointDiscoveryProviderChain() {
this(ProfileFile::defaultProfileFile,
ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow());
}
public DefaultEndpointDiscoveryProviderChain(SdkClientConfiguration clientConfiguration) {
this(clientConfiguration.option(SdkClientOption.PROFILE_FILE_SUPPLIER),
clientConfiguration.option(SdkClientOption.PROFILE_NAME));
}
private DefaultEndpointDiscoveryProviderChain(Supplier<ProfileFile> profileFile, String profileName) {
super(SystemPropertiesEndpointDiscoveryProvider.create(),
ProfileEndpointDiscoveryProvider.create(profileFile, profileName));
}
}
| 1,855 |
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/async/DrainingSubscriber.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Requests elements from a subscriber until the subscription is completed.
*/
@SdkProtectedApi
public class DrainingSubscriber<T> implements Subscriber<T> {
@Override
public void onSubscribe(Subscription subscription) {
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(T t) {
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
}
| 1,856 |
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/async/AsyncRequestBodyFromInputStreamConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async;
import java.io.InputStream;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Configuration options for {@link AsyncRequestBody#fromInputStream(AsyncRequestBodyFromInputStreamConfiguration)}
* to configure how the SDK should create an {@link AsyncRequestBody} from an {@link InputStream}.
*/
@SdkPublicApi
public final class AsyncRequestBodyFromInputStreamConfiguration
implements ToCopyableBuilder<AsyncRequestBodyFromInputStreamConfiguration.Builder,
AsyncRequestBodyFromInputStreamConfiguration> {
private final InputStream inputStream;
private final Long contentLength;
private final ExecutorService executor;
private final Integer maxReadLimit;
private AsyncRequestBodyFromInputStreamConfiguration(DefaultBuilder builder) {
this.inputStream = Validate.paramNotNull(builder.inputStream, "inputStream");
this.contentLength = Validate.isNotNegativeOrNull(builder.contentLength, "contentLength");
this.maxReadLimit = Validate.isPositiveOrNull(builder.maxReadLimit, "maxReadLimit");
this.executor = Validate.paramNotNull(builder.executor, "executor");
}
/**
* @return the provided {@link InputStream}.
*/
public InputStream inputStream() {
return inputStream;
}
/**
* @return the provided content length.
*/
public Long contentLength() {
return contentLength;
}
/**
* @return the provided {@link ExecutorService}.
*/
public ExecutorService executor() {
return executor;
}
/**
* @return the provided max read limit used to mark and reset the {@link InputStream}).
*/
public Integer maxReadLimit() {
return maxReadLimit;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AsyncRequestBodyFromInputStreamConfiguration that = (AsyncRequestBodyFromInputStreamConfiguration) o;
if (!Objects.equals(inputStream, that.inputStream)) {
return false;
}
if (!Objects.equals(contentLength, that.contentLength)) {
return false;
}
if (!Objects.equals(executor, that.executor)) {
return false;
}
return Objects.equals(maxReadLimit, that.maxReadLimit);
}
@Override
public int hashCode() {
int result = inputStream != null ? inputStream.hashCode() : 0;
result = 31 * result + (contentLength != null ? contentLength.hashCode() : 0);
result = 31 * result + (executor != null ? executor.hashCode() : 0);
result = 31 * result + (maxReadLimit != null ? maxReadLimit.hashCode() : 0);
return result;
}
/**
* Create a {@link Builder}, used to create a {@link AsyncRequestBodyFromInputStreamConfiguration}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
@Override
public AsyncRequestBodyFromInputStreamConfiguration.Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<AsyncRequestBodyFromInputStreamConfiguration.Builder,
AsyncRequestBodyFromInputStreamConfiguration> {
/**
* Configures the InputStream.
*
* @param inputStream the InputStream
* @return This object for method chaining.
*/
Builder inputStream(InputStream inputStream);
/**
* Configures the length of the provided {@link InputStream}
* @param contentLength the content length
* @return This object for method chaining.
*/
Builder contentLength(Long contentLength);
/**
* Configures the {@link ExecutorService} to perform the blocking data reads.
*
* @param executor the executor
* @return This object for method chaining.
*/
Builder executor(ExecutorService executor);
/**
* Configures max read limit used to mark and reset the {@link InputStream}. This will have no
* effect if the stream doesn't support mark and reset.
*
* <p>
* By default, it is 128 KiB.
*
* @param maxReadLimit the max read limit
* @return This object for method chaining.
* @see InputStream#mark(int)
*/
Builder maxReadLimit(Integer maxReadLimit);
}
private static final class DefaultBuilder implements Builder {
private InputStream inputStream;
private Long contentLength;
private ExecutorService executor;
private Integer maxReadLimit;
private DefaultBuilder(AsyncRequestBodyFromInputStreamConfiguration asyncRequestBodyFromInputStreamConfiguration) {
this.inputStream = asyncRequestBodyFromInputStreamConfiguration.inputStream;
this.contentLength = asyncRequestBodyFromInputStreamConfiguration.contentLength;
this.executor = asyncRequestBodyFromInputStreamConfiguration.executor;
this.maxReadLimit = asyncRequestBodyFromInputStreamConfiguration.maxReadLimit;
}
private DefaultBuilder() {
}
public Builder inputStream(InputStream inputStream) {
this.inputStream = inputStream;
return this;
}
public Builder contentLength(Long contentLength) {
this.contentLength = contentLength;
return this;
}
public Builder executor(ExecutorService executor) {
this.executor = executor;
return this;
}
public Builder maxReadLimit(Integer maxReadLimit) {
this.maxReadLimit = maxReadLimit;
return this;
}
@Override
public AsyncRequestBodyFromInputStreamConfiguration build() {
return new AsyncRequestBodyFromInputStreamConfiguration(this);
}
}
}
| 1,857 |
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/async/AsyncResponseTransformerUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.async.listener.AsyncResponseTransformerListener;
import software.amazon.awssdk.utils.Pair;
@SdkProtectedApi
public final class AsyncResponseTransformerUtils {
private AsyncResponseTransformerUtils() {
}
/**
* Wrap a {@link AsyncResponseTransformer} and associate it with a future that is completed upon end-of-stream, regardless of
* whether the transformer is configured to complete its future upon end-of-response or end-of-stream.
*/
public static <ResponseT, ResultT> Pair<AsyncResponseTransformer<ResponseT, ResultT>, CompletableFuture<Void>>
wrapWithEndOfStreamFuture(AsyncResponseTransformer<ResponseT, ResultT> responseTransformer) {
CompletableFuture<Void> future = new CompletableFuture<>();
AsyncResponseTransformer<ResponseT, ResultT> wrapped = AsyncResponseTransformerListener.wrap(
responseTransformer,
new AsyncResponseTransformerListener<ResponseT>() {
@Override
public void transformerExceptionOccurred(Throwable t) {
future.completeExceptionally(t);
}
@Override
public void subscriberOnError(Throwable t) {
future.completeExceptionally(t);
}
@Override
public void subscriberOnComplete() {
future.complete(null);
}
});
return Pair.of(wrapped, future);
}
}
| 1,858 |
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/async/EmptyPublisher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkProtectedApi;
@SdkProtectedApi
public class EmptyPublisher<T> implements Publisher<T> {
private static final Subscription SUBSCRIPTION = new Subscription() {
@Override
public void request(long l) {
}
@Override
public void cancel() {
}
};
@Override
public void subscribe(Subscriber<? super T> subscriber) {
subscriber.onSubscribe(SUBSCRIPTION);
subscriber.onComplete();
}
}
| 1,859 |
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/async/BlockingInputStreamAsyncRequestBody.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.exception.NonRetryableException;
import software.amazon.awssdk.core.internal.io.SdkLengthAwareInputStream;
import software.amazon.awssdk.core.internal.util.NoopSubscription;
import software.amazon.awssdk.utils.async.InputStreamConsumingPublisher;
/**
* An implementation of {@link AsyncRequestBody} that allows performing a blocking write of an input stream to a downstream
* service.
*
* <p>See {@link AsyncRequestBody#forBlockingInputStream(Long)}.
*/
@SdkPublicApi
public final class BlockingInputStreamAsyncRequestBody implements AsyncRequestBody {
private final InputStreamConsumingPublisher delegate = new InputStreamConsumingPublisher();
private final CountDownLatch subscribedLatch = new CountDownLatch(1);
private final AtomicBoolean subscribeCalled = new AtomicBoolean(false);
private final Long contentLength;
private final Duration subscribeTimeout;
BlockingInputStreamAsyncRequestBody(Long contentLength) {
this(contentLength, Duration.ofSeconds(10));
}
BlockingInputStreamAsyncRequestBody(Long contentLength, Duration subscribeTimeout) {
this.contentLength = contentLength;
this.subscribeTimeout = subscribeTimeout;
}
@Override
public Optional<Long> contentLength() {
return Optional.ofNullable(contentLength);
}
/**
* Block the calling thread and write the provided input stream to the downstream service.
*
* <p>This method will block the calling thread immediately. This means that this request body should usually be passed to
* the SDK before this method is called.
*
* <p>This method will return the amount of data written when the entire input stream has been written. This will throw an
* exception if writing the input stream has failed.
*
* <p>You can invoke {@link #cancel()} to cancel any blocked write calls to the downstream service (and mark the stream as
* failed).
*/
public long writeInputStream(InputStream inputStream) {
try {
waitForSubscriptionIfNeeded();
if (contentLength != null) {
return delegate.doBlockingWrite(new SdkLengthAwareInputStream(inputStream, contentLength));
}
return delegate.doBlockingWrite(inputStream);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
delegate.cancel();
throw new RuntimeException(e);
}
}
/**
* Cancel any running write (and mark the stream as failed).
*/
public void cancel() {
delegate.cancel();
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
if (subscribeCalled.compareAndSet(false, true)) {
delegate.subscribe(s);
subscribedLatch.countDown();
} else {
s.onSubscribe(new NoopSubscription(s));
s.onError(NonRetryableException.create("A retry was attempted, but AsyncRequestBody.forBlockingInputStream does not "
+ "support retries. Consider using AsyncRequestBody.fromInputStream with an "
+ "input stream that supports mark/reset to get retry support."));
}
}
private void waitForSubscriptionIfNeeded() throws InterruptedException {
long timeoutSeconds = subscribeTimeout.getSeconds();
if (!subscribedLatch.await(timeoutSeconds, TimeUnit.SECONDS)) {
throw new IllegalStateException("The service request was not made within " + timeoutSeconds + " seconds of "
+ "doBlockingWrite being invoked. Make sure to invoke the service request "
+ "BEFORE invoking doBlockingWrite if your caller is single-threaded.");
}
}
}
| 1,860 |
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/async/AsyncRequestBody.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.FileRequestBodyConfiguration;
import software.amazon.awssdk.core.internal.async.ByteBuffersAsyncRequestBody;
import software.amazon.awssdk.core.internal.async.FileAsyncRequestBody;
import software.amazon.awssdk.core.internal.async.InputStreamWithExecutorAsyncRequestBody;
import software.amazon.awssdk.core.internal.async.SplittingPublisher;
import software.amazon.awssdk.core.internal.util.Mimetype;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.Validate;
/**
* Interface to allow non-blocking streaming of request content. This follows the reactive streams pattern where this interface is
* the {@link Publisher} of data (specifically {@link ByteBuffer} chunks) and the HTTP client is the Subscriber of the data (i.e.
* to write that data on the wire).
*
* <p>
* {@link #subscribe(Subscriber)} should be implemented to tie this publisher to a subscriber. Ideally each call to subscribe
* should reproduce the content (i.e if you are reading from a file each subscribe call should produce a
* {@link org.reactivestreams.Subscription} that reads the file fully). This allows for automatic retries to be performed in the
* SDK. If the content is not reproducible, an exception may be thrown from any subsequent {@link #subscribe(Subscriber)} calls.
* </p>
*
* <p>
* It is important to only send the number of chunks that the subscriber requests to avoid out of memory situations. The
* subscriber does it's own buffering so it's usually not needed to buffer in the publisher. Additional permits for chunks will be
* notified via the {@link org.reactivestreams.Subscription#request(long)} method.
* </p>
*
* @see FileAsyncRequestBody
* @see ByteBuffersAsyncRequestBody
*/
@SdkPublicApi
public interface AsyncRequestBody extends SdkPublisher<ByteBuffer> {
/**
* @return The content length of the data being produced.
*/
Optional<Long> contentLength();
/**
* @return The content type of the data being produced.
*/
default String contentType() {
return Mimetype.MIMETYPE_OCTET_STREAM;
}
/**
* Creates an {@link AsyncRequestBody} the produces data from the input ByteBuffer publisher. The data is delivered when the
* publisher publishes the data.
*
* @param publisher Publisher of source data
* @return Implementation of {@link AsyncRequestBody} that produces data send by the publisher
*/
static AsyncRequestBody fromPublisher(Publisher<ByteBuffer> publisher) {
return new AsyncRequestBody() {
/**
* Returns empty optional as size of the each bytebuffer sent is unknown
*/
@Override
public Optional<Long> contentLength() {
return Optional.empty();
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
publisher.subscribe(s);
}
};
}
/**
* Creates an {@link AsyncRequestBody} that produces data from the contents of a file. See
* {@link FileAsyncRequestBody#builder} to create a customized body implementation.
*
* @param path Path to file to read from.
* @return Implementation of {@link AsyncRequestBody} that reads data from the specified file.
* @see FileAsyncRequestBody
*/
static AsyncRequestBody fromFile(Path path) {
return FileAsyncRequestBody.builder().path(path).build();
}
/**
* Creates an {@link AsyncRequestBody} that produces data from the contents of a file. See
* {@link #fromFile(FileRequestBodyConfiguration)} to create a customized body implementation.
*
* @param file The file to read from.
* @return Implementation of {@link AsyncRequestBody} that reads data from the specified file.
*/
static AsyncRequestBody fromFile(File file) {
return FileAsyncRequestBody.builder().path(file.toPath()).build();
}
/**
* Creates an {@link AsyncRequestBody} that produces data from the contents of a file.
*
* @param configuration configuration for how the SDK should read the file
* @return Implementation of {@link AsyncRequestBody} that reads data from the specified file.
*/
static AsyncRequestBody fromFile(FileRequestBodyConfiguration configuration) {
Validate.notNull(configuration, "configuration");
return FileAsyncRequestBody.builder()
.path(configuration.path())
.position(configuration.position())
.chunkSizeInBytes(configuration.chunkSizeInBytes())
.numBytesToRead(configuration.numBytesToRead())
.build();
}
/**
* Creates an {@link AsyncRequestBody} that produces data from the contents of a file.
*
* <p>
* This is a convenience method that creates an instance of the {@link FileRequestBodyConfiguration} builder,
* avoiding the need to create one manually via {@link FileRequestBodyConfiguration#builder()}.
*
* @param configuration configuration for how the SDK should read the file
* @return Implementation of {@link AsyncRequestBody} that reads data from the specified file.
*/
static AsyncRequestBody fromFile(Consumer<FileRequestBodyConfiguration.Builder> configuration) {
Validate.notNull(configuration, "configuration");
return fromFile(FileRequestBodyConfiguration.builder().applyMutation(configuration).build());
}
/**
* Creates an {@link AsyncRequestBody} that uses a single string as data.
*
* @param string The string to provide.
* @param cs The {@link Charset} to use.
* @return Implementation of {@link AsyncRequestBody} that uses the specified string.
* @see ByteBuffersAsyncRequestBody
*/
static AsyncRequestBody fromString(String string, Charset cs) {
return ByteBuffersAsyncRequestBody.from(Mimetype.MIMETYPE_TEXT_PLAIN + "; charset=" + cs.name(),
string.getBytes(cs));
}
/**
* Creates an {@link AsyncRequestBody} that uses a single string as data with UTF_8 encoding.
*
* @param string The string to send.
* @return Implementation of {@link AsyncRequestBody} that uses the specified string.
* @see #fromString(String, Charset)
*/
static AsyncRequestBody fromString(String string) {
return fromString(string, StandardCharsets.UTF_8);
}
/**
* Creates an {@link AsyncRequestBody} from a byte array. This will copy the contents of the byte array to prevent
* modifications to the provided byte array from being reflected in the {@link AsyncRequestBody}.
*
* @param bytes The bytes to send to the service.
* @return AsyncRequestBody instance.
*/
static AsyncRequestBody fromBytes(byte[] bytes) {
byte[] clonedBytes = bytes.clone();
return ByteBuffersAsyncRequestBody.from(clonedBytes);
}
/**
* Creates an {@link AsyncRequestBody} from a byte array <b>without</b> copying the contents of the byte array. This
* introduces concurrency risks, allowing: (1) the caller to modify the byte array stored in this {@code AsyncRequestBody}
* implementation AND (2) any users of {@link #fromBytesUnsafe(byte[])} to modify the byte array passed into this
* {@code AsyncRequestBody} implementation.
*
* <p>As the method name implies, this is unsafe. Use {@link #fromBytes(byte[])} unless you're sure you know the risks.
*
* @param bytes The bytes to send to the service.
* @return AsyncRequestBody instance.
*/
static AsyncRequestBody fromBytesUnsafe(byte[] bytes) {
return ByteBuffersAsyncRequestBody.from(bytes);
}
/**
* Creates an {@link AsyncRequestBody} from a {@link ByteBuffer}. This will copy the contents of the {@link ByteBuffer} to
* prevent modifications to the provided {@link ByteBuffer} from being reflected in the {@link AsyncRequestBody}.
* <p>
* <b>NOTE:</b> This method ignores 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 AsyncRequestBody instance.
*/
static AsyncRequestBody fromByteBuffer(ByteBuffer byteBuffer) {
ByteBuffer immutableCopy = BinaryUtils.immutableCopyOf(byteBuffer);
immutableCopy.rewind();
return ByteBuffersAsyncRequestBody.of((long) immutableCopy.remaining(), immutableCopy);
}
/**
* Creates an {@link AsyncRequestBody} from the remaining readable bytes from a {@link ByteBuffer}. This will copy the
* remaining contents of the {@link ByteBuffer} to prevent modifications to the provided {@link ByteBuffer} from being
* reflected in the {@link AsyncRequestBody}.
* <p> Unlike {@link #fromByteBuffer(ByteBuffer)}, this method respects the current read position of the buffer and reads
* only the remaining bytes.
*
* @param byteBuffer ByteBuffer to send to the service.
* @return AsyncRequestBody instance.
*/
static AsyncRequestBody fromRemainingByteBuffer(ByteBuffer byteBuffer) {
ByteBuffer immutableCopy = BinaryUtils.immutableCopyOfRemaining(byteBuffer);
return ByteBuffersAsyncRequestBody.of((long) immutableCopy.remaining(), immutableCopy);
}
/**
* Creates an {@link AsyncRequestBody} from a {@link ByteBuffer} <b>without</b> copying the contents of the
* {@link ByteBuffer}. This introduces concurrency risks, allowing the caller to modify the {@link ByteBuffer} stored in this
* {@code AsyncRequestBody} implementation.
* <p>
* <b>NOTE:</b> This method ignores the current read position. Use {@link #fromRemainingByteBufferUnsafe(ByteBuffer)} if you
* need it to copy only the remaining readable bytes.
*
* <p>As the method name implies, this is unsafe. Use {@link #fromByteBuffer(ByteBuffer)}} unless you're sure you know the
* risks.
*
* @param byteBuffer ByteBuffer to send to the service.
* @return AsyncRequestBody instance.
*/
static AsyncRequestBody fromByteBufferUnsafe(ByteBuffer byteBuffer) {
ByteBuffer readOnlyBuffer = byteBuffer.asReadOnlyBuffer();
readOnlyBuffer.rewind();
return ByteBuffersAsyncRequestBody.of((long) readOnlyBuffer.remaining(), readOnlyBuffer);
}
/**
* Creates an {@link AsyncRequestBody} from a {@link ByteBuffer} <b>without</b> copying the contents of the
* {@link ByteBuffer}. This introduces concurrency risks, allowing the caller to modify the {@link ByteBuffer} stored in this
* {@code AsyncRequestBody} implementation.
* <p>Unlike {@link #fromByteBufferUnsafe(ByteBuffer)}, this method respects the current read position of
* the buffer and reads only the remaining bytes.
*
* <p>As the method name implies, this is unsafe. Use {@link #fromByteBuffer(ByteBuffer)}} unless you're sure you know the
* risks.
*
* @param byteBuffer ByteBuffer to send to the service.
* @return AsyncRequestBody instance.
*/
static AsyncRequestBody fromRemainingByteBufferUnsafe(ByteBuffer byteBuffer) {
ByteBuffer readOnlyBuffer = byteBuffer.asReadOnlyBuffer();
return ByteBuffersAsyncRequestBody.of((long) readOnlyBuffer.remaining(), readOnlyBuffer);
}
/**
* Creates an {@link AsyncRequestBody} from a {@link ByteBuffer} array. This will copy the contents of each {@link ByteBuffer}
* to prevent modifications to any provided {@link ByteBuffer} from being reflected in the {@link AsyncRequestBody}.
* <p>
* <b>NOTE:</b> This method ignores the current read position of each {@link ByteBuffer}. Use
* {@link #fromRemainingByteBuffers(ByteBuffer...)} if you need it to copy only the remaining readable bytes.
*
* @param byteBuffers ByteBuffer array to send to the service.
* @return AsyncRequestBody instance.
*/
static AsyncRequestBody fromByteBuffers(ByteBuffer... byteBuffers) {
ByteBuffer[] immutableCopy = Arrays.stream(byteBuffers)
.map(BinaryUtils::immutableCopyOf)
.peek(ByteBuffer::rewind)
.toArray(ByteBuffer[]::new);
return ByteBuffersAsyncRequestBody.of(immutableCopy);
}
/**
* Creates an {@link AsyncRequestBody} from a {@link ByteBuffer} array. This will copy the remaining contents of each
* {@link ByteBuffer} to prevent modifications to any provided {@link ByteBuffer} from being reflected in the
* {@link AsyncRequestBody}.
* <p>Unlike {@link #fromByteBufferUnsafe(ByteBuffer)},
* this method respects the current read position of each buffer and reads only the remaining bytes.
*
* @param byteBuffers ByteBuffer array to send to the service.
* @return AsyncRequestBody instance.
*/
static AsyncRequestBody fromRemainingByteBuffers(ByteBuffer... byteBuffers) {
ByteBuffer[] immutableCopy = Arrays.stream(byteBuffers)
.map(BinaryUtils::immutableCopyOfRemaining)
.peek(ByteBuffer::rewind)
.toArray(ByteBuffer[]::new);
return ByteBuffersAsyncRequestBody.of(immutableCopy);
}
/**
* Creates an {@link AsyncRequestBody} from a {@link ByteBuffer} array <b>without</b> copying the contents of each
* {@link ByteBuffer}. This introduces concurrency risks, allowing the caller to modify any {@link ByteBuffer} stored in this
* {@code AsyncRequestBody} implementation.
* <p>
* <b>NOTE:</b> This method ignores the current read position of each {@link ByteBuffer}. Use
* {@link #fromRemainingByteBuffers(ByteBuffer...)} if you need it to copy only the remaining readable bytes.
*
* <p>As the method name implies, this is unsafe. Use {@link #fromByteBuffers(ByteBuffer...)} unless you're sure you know the
* risks.
*
* @param byteBuffers ByteBuffer array to send to the service.
* @return AsyncRequestBody instance.
*/
static AsyncRequestBody fromByteBuffersUnsafe(ByteBuffer... byteBuffers) {
ByteBuffer[] readOnlyBuffers = Arrays.stream(byteBuffers)
.map(ByteBuffer::asReadOnlyBuffer)
.peek(ByteBuffer::rewind)
.toArray(ByteBuffer[]::new);
return ByteBuffersAsyncRequestBody.of(readOnlyBuffers);
}
/**
* Creates an {@link AsyncRequestBody} from a {@link ByteBuffer} array <b>without</b> copying the contents of each
* {@link ByteBuffer}. This introduces concurrency risks, allowing the caller to modify any {@link ByteBuffer} stored in this
* {@code AsyncRequestBody} implementation.
* <p>Unlike {@link #fromByteBuffersUnsafe(ByteBuffer...)},
* this method respects the current read position of each buffer and reads only the remaining bytes.
*
* <p>As the method name implies, this is unsafe. Use {@link #fromByteBuffers(ByteBuffer...)} unless you're sure you know the
* risks.
*
* @param byteBuffers ByteBuffer array to send to the service.
* @return AsyncRequestBody instance.
*/
static AsyncRequestBody fromRemainingByteBuffersUnsafe(ByteBuffer... byteBuffers) {
ByteBuffer[] readOnlyBuffers = Arrays.stream(byteBuffers)
.map(ByteBuffer::asReadOnlyBuffer)
.toArray(ByteBuffer[]::new);
return ByteBuffersAsyncRequestBody.of(readOnlyBuffers);
}
/**
* Creates an {@link AsyncRequestBody} from an {@link InputStream}.
*
* <p>An {@link ExecutorService} is required in order to perform the blocking data reads, to prevent blocking the
* non-blocking event loop threads owned by the SDK.
*/
static AsyncRequestBody fromInputStream(InputStream inputStream, Long contentLength, ExecutorService executor) {
return fromInputStream(b -> b.inputStream(inputStream).contentLength(contentLength).executor(executor));
}
/**
* Creates an {@link AsyncRequestBody} from an {@link InputStream} with the provided
* {@link AsyncRequestBodySplitConfiguration}.
*/
static AsyncRequestBody fromInputStream(AsyncRequestBodyFromInputStreamConfiguration configuration) {
Validate.notNull(configuration, "configuration");
return new InputStreamWithExecutorAsyncRequestBody(configuration);
}
/**
* This is a convenience method that passes an instance of the {@link AsyncRequestBodyFromInputStreamConfiguration} builder,
* avoiding the need to create one manually via {@link AsyncRequestBodyFromInputStreamConfiguration#builder()}.
*
* @see #fromInputStream(AsyncRequestBodyFromInputStreamConfiguration)
*/
static AsyncRequestBody fromInputStream(Consumer<AsyncRequestBodyFromInputStreamConfiguration.Builder> configuration) {
Validate.notNull(configuration, "configuration");
return fromInputStream(AsyncRequestBodyFromInputStreamConfiguration.builder().applyMutation(configuration).build());
}
/**
* Creates a {@link BlockingInputStreamAsyncRequestBody} to use for writing an input stream to the downstream service.
*
* <p><b>Example Usage</b>
*
* <p>
* {@snippet :
* S3AsyncClient s3 = S3AsyncClient.create(); // Use one client for your whole application!
*
* byte[] dataToSend = "Hello".getBytes(StandardCharsets.UTF_8);
* InputStream streamToSend = new ByteArrayInputStream();
* long streamToSendLength = dataToSend.length();
*
* // Start the operation
* BlockingInputStreamAsyncRequestBody body =
* AsyncRequestBody.forBlockingInputStream(streamToSendLength);
* CompletableFuture<PutObjectResponse> responseFuture =
* s3.putObject(r -> r.bucket("bucketName").key("key"), body);
*
* // Write the input stream to the running operation
* body.writeInputStream(streamToSend);
*
* // Wait for the service to respond.
* PutObjectResponse response = responseFuture.join();
* }
*/
static BlockingInputStreamAsyncRequestBody forBlockingInputStream(Long contentLength) {
return new BlockingInputStreamAsyncRequestBody(contentLength);
}
/**
* Creates a {@link BlockingOutputStreamAsyncRequestBody} to use for writing to the downstream service as if it's an output
* stream. Retries are not supported for this request body.
*
* <p>The caller is responsible for calling {@link OutputStream#close()} on the
* {@link BlockingOutputStreamAsyncRequestBody#outputStream()} when writing is complete.
*
* <p><b>Example Usage</b>
* <p>
* {@snippet :
* S3AsyncClient s3 = S3AsyncClient.create(); // Use one client for your whole application!
*
* byte[] dataToSend = "Hello".getBytes(StandardCharsets.UTF_8);
* long lengthOfDataToSend = dataToSend.length();
*
* // Start the operation
* BlockingInputStreamAsyncRequestBody body =
* AsyncRequestBody.forBlockingOutputStream(lengthOfDataToSend);
* CompletableFuture<PutObjectResponse> responseFuture =
* s3.putObject(r -> r.bucket("bucketName").key("key"), body);
*
* // Write the input stream to the running operation
* try (CancellableOutputStream outputStream = body.outputStream()) {
* outputStream.write(dataToSend);
* }
*
* // Wait for the service to respond.
* PutObjectResponse response = responseFuture.join();
* }
*/
static BlockingOutputStreamAsyncRequestBody forBlockingOutputStream(Long contentLength) {
return new BlockingOutputStreamAsyncRequestBody(contentLength);
}
/**
* Creates an {@link AsyncRequestBody} with no content.
*
* @return AsyncRequestBody instance.
*/
static AsyncRequestBody empty() {
return fromBytes(new byte[0]);
}
/**
* Converts this {@link AsyncRequestBody} to a publisher of {@link AsyncRequestBody}s, each of which publishes a specific
* portion of the original data, based on the provided {@link AsyncRequestBodySplitConfiguration}. The default chunk size
* is 2MB and the default buffer size is 8MB.
*
* <p>
* By default, if content length of this {@link AsyncRequestBody} is present, each divided {@link AsyncRequestBody} is
* delivered to the subscriber right after it's initialized. On the other hand, if content length is null, it is sent after
* the entire content for that chunk is buffered. In this case, the configured {@code maxMemoryUsageInBytes} must be larger
* than or equal to {@code chunkSizeInBytes}. Note that this behavior may be different if a specific implementation of this
* interface overrides this method.
*
* @see AsyncRequestBodySplitConfiguration
*/
default SdkPublisher<AsyncRequestBody> split(AsyncRequestBodySplitConfiguration splitConfiguration) {
Validate.notNull(splitConfiguration, "splitConfiguration");
return new SplittingPublisher(this, splitConfiguration);
}
/**
* This is a convenience method that passes an instance of the {@link AsyncRequestBodySplitConfiguration} builder,
* avoiding the need to create one manually via {@link AsyncRequestBodySplitConfiguration#builder()}.
*
* @see #split(AsyncRequestBodySplitConfiguration)
*/
default SdkPublisher<AsyncRequestBody> split(Consumer<AsyncRequestBodySplitConfiguration.Builder> splitConfiguration) {
Validate.notNull(splitConfiguration, "splitConfiguration");
return split(AsyncRequestBodySplitConfiguration.builder().applyMutation(splitConfiguration).build());
}
}
| 1,861 |
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/async/AsyncResponseTransformer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async;
import java.io.File;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.FileTransformerConfiguration;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.internal.async.ByteArrayAsyncResponseTransformer;
import software.amazon.awssdk.core.internal.async.FileAsyncResponseTransformer;
import software.amazon.awssdk.core.internal.async.InputStreamResponseTransformer;
import software.amazon.awssdk.core.internal.async.PublisherAsyncResponseTransformer;
import software.amazon.awssdk.utils.Validate;
/**
* Callback interface to handle a streaming asynchronous response.
* <p>
* <h2>Synchronization</h2>
* <p>
* All operations, including those called on the {@link org.reactivestreams.Subscriber} of the stream are guaranteed to be
* synchronized externally; i.e. no two methods on this interface or on the {@link org.reactivestreams.Subscriber} will be
* invoked concurrently. It is <b>not</b> guaranteed that the methods will being invoked by the same thread.
* <p>
* <h2>Invocation Order</h2>
* <p>
* The methods are called in the following order:
* <ul>
* <li>
* {@link #prepare()}: This method is always called first. Implementations should use this to setup or perform any
* cleanup necessary. <b>Note that this will be called upon each request attempt</b>. If the {@link CompletableFuture}
* returned from the previous invocation has already been completed, the implementation should return a new instance.
* </li>
* <li>
* {@link #onResponse}: If the response was received successfully, this method is called next.
* </li>
* <li>
* {@link #onStream(SdkPublisher)}: Called after {@code onResponse}. This is always invoked, even if the service
* operation response does not contain a body. If the response does not have a body, then the {@link SdkPublisher} will
* complete the subscription without signaling any elements.
* </li>
* <li>
* {@link #exceptionOccurred(Throwable)}: If there is an error sending the request. This method is called before {@link
* org.reactivestreams.Subscriber#onError(Throwable)}.
* </li>
* <li>
* {@link org.reactivestreams.Subscriber#onError(Throwable)}: If an error is encountered while the {@code Publisher} is
* publishing to a {@link org.reactivestreams.Subscriber}.
* </li>
* </ul>
* <p>
* <h2>Retries</h2>
* <p>
* The transformer has the ability to trigger retries at any time by completing the {@link CompletableFuture} with an
* exception that is deemed retryable by the configured {@link software.amazon.awssdk.core.retry.RetryPolicy}.
*
* @param <ResponseT> POJO response type.
* @param <ResultT> Type this response handler produces. I.E. the type you are transforming the response into.
*/
@SdkPublicApi
public interface AsyncResponseTransformer<ResponseT, ResultT> {
/**
* Initial call to enable any setup required before the response is handled.
* <p>
* Note that this will be called for each request attempt, up to the number of retries allowed by the configured {@link
* software.amazon.awssdk.core.retry.RetryPolicy}.
* <p>
* This method is guaranteed to be called before the request is executed, and before {@link #onResponse(Object)} is
* signaled.
*
* @return The future holding the transformed response.
*/
CompletableFuture<ResultT> prepare();
/**
* Called when the unmarshalled response object is ready.
*
* @param response The unmarshalled response.
*/
void onResponse(ResponseT response);
/**
* Called when the response stream is ready.
*
* @param publisher The publisher.
*/
void onStream(SdkPublisher<ByteBuffer> publisher);
/**
* Called when an error is encountered while making the request or receiving the response.
* Implementations should free up any resources in this method. This method may be called
* multiple times during the lifecycle of a request if automatic retries are enabled.
*
* @param error Error that occurred.
*/
void exceptionOccurred(Throwable error);
/**
* Creates an {@link AsyncResponseTransformer} that writes all the content to the given file. In the event of an error,
* the SDK will attempt to delete the file (whatever has been written to it so far). If the file already exists, an
* exception will be thrown.
*
* @param path Path to file to write to.
* @param <ResponseT> Pojo Response type.
* @return AsyncResponseTransformer instance.
* @see #toFile(Path, FileTransformerConfiguration)
*/
static <ResponseT> AsyncResponseTransformer<ResponseT, ResponseT> toFile(Path path) {
return new FileAsyncResponseTransformer<>(path);
}
/**
* Creates an {@link AsyncResponseTransformer} that writes all the content to the given file with the specified {@link
* FileTransformerConfiguration}.
*
* @param path Path to file to write to.
* @param config configuration for the transformer
* @param <ResponseT> Pojo Response type.
* @return AsyncResponseTransformer instance.
* @see FileTransformerConfiguration
*/
static <ResponseT> AsyncResponseTransformer<ResponseT, ResponseT> toFile(Path path, FileTransformerConfiguration config) {
return new FileAsyncResponseTransformer<>(path, config);
}
/**
* This is a convenience method that creates an instance of the {@link FileTransformerConfiguration} builder,
* avoiding the need to create one manually via {@link FileTransformerConfiguration#builder()}.
*
* @see #toFile(Path, FileTransformerConfiguration)
*/
static <ResponseT> AsyncResponseTransformer<ResponseT, ResponseT> toFile(
Path path, Consumer<FileTransformerConfiguration.Builder> config) {
Validate.paramNotNull(config, "config");
return new FileAsyncResponseTransformer<>(path, FileTransformerConfiguration.builder().applyMutation(config).build());
}
/**
* Creates an {@link AsyncResponseTransformer} that writes all the content to the given file. In the event of an error,
* the SDK will attempt to delete the file (whatever has been written to it so far). If the file already exists, an
* exception will be thrown.
*
* @param file File to write to.
* @param <ResponseT> Pojo Response type.
* @return AsyncResponseTransformer instance.
*/
static <ResponseT> AsyncResponseTransformer<ResponseT, ResponseT> toFile(File file) {
return toFile(file.toPath());
}
/**
* Creates an {@link AsyncResponseTransformer} that writes all the content to the given file with the specified {@link
* FileTransformerConfiguration}.
*
* @param file File to write to.
* @param config configuration for the transformer
* @param <ResponseT> Pojo Response type.
* @return AsyncResponseTransformer instance.
* @see FileTransformerConfiguration
*/
static <ResponseT> AsyncResponseTransformer<ResponseT, ResponseT> toFile(File file, FileTransformerConfiguration config) {
return new FileAsyncResponseTransformer<>(file.toPath(), config);
}
/**
* This is a convenience method that creates an instance of the {@link FileTransformerConfiguration} builder,
* avoiding the need to create one manually via {@link FileTransformerConfiguration#builder()}.
*
* @see #toFile(File, FileTransformerConfiguration)
*/
static <ResponseT> AsyncResponseTransformer<ResponseT, ResponseT> toFile(
File file, Consumer<FileTransformerConfiguration.Builder> config) {
Validate.paramNotNull(config, "config");
return new FileAsyncResponseTransformer<>(file.toPath(), FileTransformerConfiguration.builder()
.applyMutation(config)
.build());
}
/**
* Creates an {@link AsyncResponseTransformer} that writes all content to a byte array.
*
* @param <ResponseT> Pojo response type.
* @return AsyncResponseTransformer instance.
*/
static <ResponseT> AsyncResponseTransformer<ResponseT, ResponseBytes<ResponseT>> toBytes() {
return new ByteArrayAsyncResponseTransformer<>();
}
/**
* Creates an {@link AsyncResponseTransformer} that publishes the response body content through a {@link ResponsePublisher},
* which is an {@link SdkPublisher} that also contains a reference to the {@link SdkResponse} returned by the service.
* <p>
* When this transformer is used with an async client, the {@link CompletableFuture} that the client returns will be completed
* once the {@link SdkResponse} is available and the response body <i>begins</i> streaming. This behavior differs from some
* other transformers, like {@link #toFile(Path)} and {@link #toBytes()}, which only have their {@link CompletableFuture}
* completed after the entire response body has finished streaming.
* <p>
* You are responsible for subscribing to this publisher and managing the associated back-pressure. Therefore, this
* transformer is only recommended for advanced use cases.
* <p>
* Example usage:
* <pre>
* {@code
* CompletableFuture<ResponsePublisher<GetObjectResponse>> responseFuture =
* s3AsyncClient.getObject(getObjectRequest, AsyncResponseTransformer.toPublisher());
* ResponsePublisher<GetObjectResponse> responsePublisher = responseFuture.join();
* System.out.println(responsePublisher.response());
* CompletableFuture<Void> drainPublisherFuture = responsePublisher.subscribe(System.out::println);
* drainPublisherFuture.join();
* }
* </pre>
*
* @param <ResponseT> Pojo response type.
* @return AsyncResponseTransformer instance.
*/
static <ResponseT extends SdkResponse> AsyncResponseTransformer<ResponseT, ResponsePublisher<ResponseT>> toPublisher() {
return new PublisherAsyncResponseTransformer<>();
}
/**
* Creates an {@link AsyncResponseTransformer} that allows reading the response body content as an
* {@link InputStream}.
* <p>
* When this transformer is used with an async client, the {@link CompletableFuture} that the client returns will
* be completed once the {@link SdkResponse} is available and the response body <i>begins</i> streaming. This
* behavior differs from some other transformers, like {@link #toFile(Path)} and {@link #toBytes()}, which only
* have their {@link CompletableFuture} completed after the entire response body has finished streaming.
* <p>
* You are responsible for performing blocking reads from this input stream and closing the stream when you are
* finished.
* <p>
* Example usage:
* <pre>
* {@code
* CompletableFuture<ResponseInputStream<GetObjectResponse>> responseFuture =
* s3AsyncClient.getObject(getObjectRequest, AsyncResponseTransformer.toBlockingInputStream());
* try (ResponseInputStream<GetObjectResponse> responseStream = responseFuture.join()) {
* responseStream.transferTo(System.out); // BLOCKS the calling thread
* }
* }
* </pre>
*/
static <ResponseT extends SdkResponse>
AsyncResponseTransformer<ResponseT, ResponseInputStream<ResponseT>> toBlockingInputStream() {
return new InputStreamResponseTransformer<>();
}
}
| 1,862 |
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/async/ResponsePublisher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async;
import java.nio.ByteBuffer;
import java.util.Objects;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* An {@link SdkPublisher} that publishes response body content and also contains a reference to the {@link SdkResponse} returned
* by the service.
*
* @param <ResponseT> Pojo response type.
* @see AsyncResponseTransformer#toPublisher()
*/
@SdkPublicApi
public final class ResponsePublisher<ResponseT extends SdkResponse> implements SdkPublisher<ByteBuffer> {
private final ResponseT response;
private final SdkPublisher<ByteBuffer> publisher;
public ResponsePublisher(ResponseT response, SdkPublisher<ByteBuffer> publisher) {
this.response = Validate.paramNotNull(response, "response");
this.publisher = Validate.paramNotNull(publisher, "publisher");
}
/**
* @return the unmarshalled response object from the service.
*/
public ResponseT response() {
return response;
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
publisher.subscribe(subscriber);
}
@Override
public String toString() {
return ToString.builder("ResponsePublisher")
.add("response", response)
.add("publisher", publisher)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ResponsePublisher<?> that = (ResponsePublisher<?>) o;
if (!Objects.equals(response, that.response)) {
return false;
}
return Objects.equals(publisher, that.publisher);
}
@Override
public int hashCode() {
int result = response != null ? response.hashCode() : 0;
result = 31 * result + (publisher != null ? publisher.hashCode() : 0);
return result;
}
}
| 1,863 |
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/async/SdkPublisher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.async.AddingTrailingDataSubscriber;
import software.amazon.awssdk.utils.async.BufferingSubscriber;
import software.amazon.awssdk.utils.async.EventListeningSubscriber;
import software.amazon.awssdk.utils.async.FilteringSubscriber;
import software.amazon.awssdk.utils.async.FlatteningSubscriber;
import software.amazon.awssdk.utils.async.LimitingSubscriber;
import software.amazon.awssdk.utils.async.SequentialSubscriber;
import software.amazon.awssdk.utils.internal.MappingSubscriber;
/**
* Interface that is implemented by the Async auto-paginated responses.
*/
@SdkPublicApi
public interface SdkPublisher<T> extends Publisher<T> {
/**
* Adapts a {@link Publisher} to {@link SdkPublisher}.
*
* @param toAdapt {@link Publisher} to adapt.
* @param <T> Type of object being published.
* @return SdkPublisher
*/
static <T> SdkPublisher<T> adapt(Publisher<T> toAdapt) {
return toAdapt::subscribe;
}
/**
* Filters published events to just those that are instances of the given class. This changes the type of
* publisher to the type specified in the {@link Class}.
*
* @param clzz Class to filter to. Includes subtypes of the class.
* @param <U> Type of class to filter to.
* @return New publisher, filtered to the given class.
*/
default <U extends T> SdkPublisher<U> filter(Class<U> clzz) {
return filter(clzz::isInstance).map(clzz::cast);
}
/**
* Filters published events to just those that match the given predicate. Unlike {@link #filter(Class)}, this method
* does not change the type of the {@link Publisher}.
*
* @param predicate Predicate to match events.
* @return New publisher, filtered to just the events that match the predicate.
*/
default SdkPublisher<T> filter(Predicate<T> predicate) {
return subscriber -> subscribe(new FilteringSubscriber<>(subscriber, predicate));
}
/**
* Perform a mapping on the published events. Returns a new publisher of the mapped events. Typically this method will
* change the type of the publisher.
*
* @param mapper Mapping function to apply.
* @param <U> Type being mapped to.
* @return New publisher with events mapped according to the given function.
*/
default <U> SdkPublisher<U> map(Function<T, U> mapper) {
return subscriber -> subscribe(MappingSubscriber.create(subscriber, mapper));
}
/**
* Performs a mapping on the published events and creates a new publisher that emits the mapped events one by one.
*
* @param mapper Mapping function that produces an {@link Iterable} of new events to be flattened.
* @param <U> Type of flattened event being mapped to.
* @return New publisher of flattened events.
*/
default <U> SdkPublisher<U> flatMapIterable(Function<T, Iterable<U>> mapper) {
return subscriber -> map(mapper).subscribe(new FlatteningSubscriber<>(subscriber));
}
/**
* Buffers the events into lists of the given buffer size. Note that the last batch of events may be less than
* the buffer size.
*
* @param bufferSize Number of events to buffer before delivering downstream.
* @return New publisher of buffered events.
*/
default SdkPublisher<List<T>> buffer(int bufferSize) {
return subscriber -> subscribe(new BufferingSubscriber<>(subscriber, bufferSize));
}
/**
* Limit the number of published events and cancel the subscription after that limit has been reached. The limit
* may never be reached if the downstream publisher doesn't have many events to publish. Once it reaches the limit,
* subsequent requests will be ignored.
*
* @param limit Number of events to publish.
* @return New publisher that will only publish up to the specified number of events.
*/
default SdkPublisher<T> limit(int limit) {
return subscriber -> subscribe(new LimitingSubscriber<>(subscriber, limit));
}
/**
* Creates a new publisher that emits trailing events provided by {@code trailingDataSupplier} in addition to the
* published events.
*
* @param trailingDataSupplier supplier to provide the trailing data
* @return New publisher that will publish additional events
*/
default SdkPublisher<T> addTrailingData(Supplier<Iterable<T>> trailingDataSupplier) {
return subscriber -> subscribe(new AddingTrailingDataSubscriber<T>(subscriber, trailingDataSupplier));
}
/**
* Add a callback that will be invoked after this publisher invokes {@link Subscriber#onComplete()}.
*
* @param afterOnComplete The logic that should be run immediately after onComplete.
* @return New publisher that invokes the requested callback.
*/
default SdkPublisher<T> doAfterOnComplete(Runnable afterOnComplete) {
return subscriber -> subscribe(new EventListeningSubscriber<>(subscriber, afterOnComplete, null, null));
}
/**
* Add a callback that will be invoked after this publisher invokes {@link Subscriber#onError(Throwable)}.
*
* @param afterOnError The logic that should be run immediately after onError.
* @return New publisher that invokes the requested callback.
*/
default SdkPublisher<T> doAfterOnError(Consumer<Throwable> afterOnError) {
return subscriber -> subscribe(new EventListeningSubscriber<>(subscriber, null, afterOnError, null));
}
/**
* Add a callback that will be invoked after this publisher invokes {@link Subscription#cancel()}.
*
* @param afterOnCancel The logic that should be run immediately after cancellation of the subscription.
* @return New publisher that invokes the requested callback.
*/
default SdkPublisher<T> doAfterOnCancel(Runnable afterOnCancel) {
return subscriber -> subscribe(new EventListeningSubscriber<>(subscriber, null, null, afterOnCancel));
}
/**
* Subscribes to the publisher with the given {@link Consumer}. This consumer will be called for each event
* published. There is no backpressure using this method if the Consumer dispatches processing asynchronously. If more
* control over backpressure is required, consider using {@link #subscribe(Subscriber)}.
*
* @param consumer Consumer to process event.
* @return CompletableFuture that will be notified when all events have been consumed or if an error occurs.
*/
default CompletableFuture<Void> subscribe(Consumer<T> consumer) {
CompletableFuture<Void> future = new CompletableFuture<>();
subscribe(new SequentialSubscriber<>(consumer, future));
return future;
}
}
| 1,864 |
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/async/AsyncRequestBodySplitConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Configuration options for {@link AsyncRequestBody#split} to configure how the SDK
* should split an {@link SdkPublisher}.
*/
@SdkPublicApi
public final class AsyncRequestBodySplitConfiguration implements ToCopyableBuilder<AsyncRequestBodySplitConfiguration.Builder,
AsyncRequestBodySplitConfiguration> {
private static final long DEFAULT_CHUNK_SIZE = 2 * 1024 * 1024L;
private static final long DEFAULT_BUFFER_SIZE = DEFAULT_CHUNK_SIZE * 4;
private static final AsyncRequestBodySplitConfiguration DEFAULT_CONFIG = builder()
.bufferSizeInBytes(DEFAULT_BUFFER_SIZE)
.chunkSizeInBytes(DEFAULT_CHUNK_SIZE)
.build();
private final Long chunkSizeInBytes;
private final Long bufferSizeInBytes;
private AsyncRequestBodySplitConfiguration(DefaultBuilder builder) {
this.chunkSizeInBytes = Validate.isPositiveOrNull(builder.chunkSizeInBytes, "chunkSizeInBytes");
this.bufferSizeInBytes = Validate.isPositiveOrNull(builder.bufferSizeInBytes, "bufferSizeInBytes");
}
public static AsyncRequestBodySplitConfiguration defaultConfiguration() {
return DEFAULT_CONFIG;
}
/**
* The configured chunk size for each divided {@link AsyncRequestBody}.
*/
public Long chunkSizeInBytes() {
return chunkSizeInBytes;
}
/**
* The configured maximum buffer size the SDK will use to buffer the content from the source {@link SdkPublisher}.
*/
public Long bufferSizeInBytes() {
return bufferSizeInBytes;
}
/**
* Create a {@link Builder}, used to create a {@link AsyncRequestBodySplitConfiguration}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AsyncRequestBodySplitConfiguration that = (AsyncRequestBodySplitConfiguration) o;
if (!Objects.equals(chunkSizeInBytes, that.chunkSizeInBytes)) {
return false;
}
return Objects.equals(bufferSizeInBytes, that.bufferSizeInBytes);
}
@Override
public int hashCode() {
int result = chunkSizeInBytes != null ? chunkSizeInBytes.hashCode() : 0;
result = 31 * result + (bufferSizeInBytes != null ? bufferSizeInBytes.hashCode() : 0);
return result;
}
@Override
public AsyncRequestBodySplitConfiguration.Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<AsyncRequestBodySplitConfiguration.Builder,
AsyncRequestBodySplitConfiguration> {
/**
* Configures the size for each divided chunk. The last chunk may be smaller than the configured size. The default value
* is 2MB.
*
* @param chunkSizeInBytes the chunk size in bytes
* @return This object for method chaining.
*/
Builder chunkSizeInBytes(Long chunkSizeInBytes);
/**
* The maximum buffer size the SDK will use to buffer the content from the source {@link SdkPublisher}. The default value
* is 8MB.
*
* @param bufferSizeInBytes the buffer size in bytes
* @return This object for method chaining.
*/
Builder bufferSizeInBytes(Long bufferSizeInBytes);
}
private static final class DefaultBuilder implements Builder {
private Long chunkSizeInBytes;
private Long bufferSizeInBytes;
private DefaultBuilder(AsyncRequestBodySplitConfiguration asyncRequestBodySplitConfiguration) {
this.chunkSizeInBytes = asyncRequestBodySplitConfiguration.chunkSizeInBytes;
this.bufferSizeInBytes = asyncRequestBodySplitConfiguration.bufferSizeInBytes;
}
private DefaultBuilder() {
}
@Override
public Builder chunkSizeInBytes(Long chunkSizeInBytes) {
this.chunkSizeInBytes = chunkSizeInBytes;
return this;
}
@Override
public Builder bufferSizeInBytes(Long bufferSizeInBytes) {
this.bufferSizeInBytes = bufferSizeInBytes;
return this;
}
@Override
public AsyncRequestBodySplitConfiguration build() {
return new AsyncRequestBodySplitConfiguration(this);
}
}
}
| 1,865 |
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/async/BlockingOutputStreamAsyncRequestBody.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.exception.NonRetryableException;
import software.amazon.awssdk.core.internal.util.NoopSubscription;
import software.amazon.awssdk.utils.CancellableOutputStream;
import software.amazon.awssdk.utils.async.OutputStreamPublisher;
/**
* An implementation of {@link AsyncRequestBody} that allows performing a blocking write of an output stream to a downstream
* service.
*
* <p>The caller is responsible for calling {@link OutputStream#close()} on the {@link #outputStream()} when writing is
* complete.
*
* @see AsyncRequestBody#forBlockingOutputStream(Long)
*/
@SdkPublicApi
public final class BlockingOutputStreamAsyncRequestBody implements AsyncRequestBody {
private final OutputStreamPublisher delegate = new OutputStreamPublisher();
private final CountDownLatch subscribedLatch = new CountDownLatch(1);
private final AtomicBoolean subscribeCalled = new AtomicBoolean(false);
private final Long contentLength;
private final Duration subscribeTimeout;
BlockingOutputStreamAsyncRequestBody(Long contentLength) {
this(contentLength, Duration.ofSeconds(10));
}
BlockingOutputStreamAsyncRequestBody(Long contentLength, Duration subscribeTimeout) {
this.contentLength = contentLength;
this.subscribeTimeout = subscribeTimeout;
}
/**
* Return an output stream to which blocking writes can be made to the downstream service.
*
* <p>This method will block the calling thread until the SDK is connected to the service. This means that this request body
* should usually be passed to the SDK before this method is called.
*
* <p>You can invoke {@link CancellableOutputStream#cancel()} to cancel any blocked write calls to the downstream service
* (and mark the stream as failed).
*/
public CancellableOutputStream outputStream() {
waitForSubscriptionIfNeeded();
return delegate;
}
@Override
public Optional<Long> contentLength() {
return Optional.ofNullable(contentLength);
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
if (subscribeCalled.compareAndSet(false, true)) {
delegate.subscribe(s);
subscribedLatch.countDown();
} else {
s.onSubscribe(new NoopSubscription(s));
s.onError(NonRetryableException.create("A retry was attempted, but AsyncRequestBody.forBlockingOutputStream does not "
+ "support retries."));
}
}
private void waitForSubscriptionIfNeeded() {
try {
long timeoutSeconds = subscribeTimeout.getSeconds();
if (!subscribedLatch.await(timeoutSeconds, TimeUnit.SECONDS)) {
throw new IllegalStateException("The service request was not made within " + timeoutSeconds + " seconds of "
+ "outputStream being invoked. Make sure to invoke the service request "
+ "BEFORE invoking outputStream if your caller is single-threaded.");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while waiting for subscription.", e);
}
}
}
| 1,866 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/async | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/async/listener/AsyncResponseTransformerListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async.listener;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
/**
* Listener interface that invokes callbacks associated with a {@link AsyncResponseTransformer} and any resulting {@link
* SdkPublisher} and {@link Subscriber}.
*
* @see PublisherListener
* @see SubscriberListener
*/
@SdkProtectedApi
public interface AsyncResponseTransformerListener<ResponseT> extends PublisherListener<ByteBuffer> {
/**
* Invoked before {@link AsyncResponseTransformer#onResponse(Object)}
*/
default void transformerOnResponse(ResponseT response) {
}
/**
* Invoked before {@link AsyncResponseTransformer#onStream(SdkPublisher)}
*/
default void transformerOnStream(SdkPublisher<ByteBuffer> publisher) {
}
/**
* Invoked before {@link AsyncResponseTransformer#exceptionOccurred(Throwable)}
*/
default void transformerExceptionOccurred(Throwable t) {
}
/**
* Wrap a {@link AsyncResponseTransformer} with a new one that will notify a {@link AsyncResponseTransformerListener} of
* important events occurring.
*/
static <ResponseT, ResultT> AsyncResponseTransformer<ResponseT, ResultT> wrap(
AsyncResponseTransformer<ResponseT, ResultT> delegate,
AsyncResponseTransformerListener<ResponseT> listener) {
return new NotifyingAsyncResponseTransformer<>(delegate, listener);
}
@SdkInternalApi
final class NotifyingAsyncResponseTransformer<ResponseT, ResultT> implements AsyncResponseTransformer<ResponseT, ResultT> {
private static final Logger log = Logger.loggerFor(NotifyingAsyncResponseTransformer.class);
private final AsyncResponseTransformer<ResponseT, ResultT> delegate;
private final AsyncResponseTransformerListener<ResponseT> listener;
NotifyingAsyncResponseTransformer(AsyncResponseTransformer<ResponseT, ResultT> delegate,
AsyncResponseTransformerListener<ResponseT> listener) {
this.delegate = Validate.notNull(delegate, "delegate");
this.listener = Validate.notNull(listener, "listener");
}
@Override
public CompletableFuture<ResultT> prepare() {
return delegate.prepare();
}
@Override
public void onResponse(ResponseT response) {
invoke(() -> listener.transformerOnResponse(response), "transformerOnResponse");
delegate.onResponse(response);
}
@Override
public void onStream(SdkPublisher<ByteBuffer> publisher) {
invoke(() -> listener.transformerOnStream(publisher), "transformerOnStream");
delegate.onStream(PublisherListener.wrap(publisher, listener));
}
@Override
public void exceptionOccurred(Throwable error) {
invoke(() -> listener.transformerExceptionOccurred(error), "transformerExceptionOccurred");
delegate.exceptionOccurred(error);
}
static void invoke(Runnable runnable, String callbackName) {
try {
runnable.run();
} catch (Exception e) {
log.error(() -> callbackName + " callback failed. This exception will be dropped.", e);
}
}
}
}
| 1,867 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/async | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/async/listener/SubscriberListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async.listener;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
/**
* Listener interface that invokes callbacks associated with a {@link Subscriber}.
*
* @see AsyncResponseTransformerListener
* @see PublisherListener
*/
@SdkProtectedApi
public interface SubscriberListener<T> {
/**
* Invoked before {@link Subscriber#onNext(Object)}
*/
default void subscriberOnNext(T t) {
}
/**
* Invoked before {@link Subscriber#onComplete()}
*/
default void subscriberOnComplete() {
}
/**
* Invoked before {@link Subscriber#onError(Throwable)}
*/
default void subscriberOnError(Throwable t) {
}
/**
* Invoked before {@link Subscription#cancel()}
*/
default void subscriptionCancel() {
}
/**
* Wrap a {@link Subscriber} with a new one that will notify a {@link SubscriberListener} of important events occurring.
*/
static <T> Subscriber<T> wrap(Subscriber<? super T> delegate, SubscriberListener<? super T> listener) {
return new NotifyingSubscriber<>(delegate, listener);
}
@SdkInternalApi
final class NotifyingSubscriber<T> implements Subscriber<T> {
private static final Logger log = Logger.loggerFor(NotifyingSubscriber.class);
private final Subscriber<? super T> delegate;
private final SubscriberListener<? super T> listener;
NotifyingSubscriber(Subscriber<? super T> delegate,
SubscriberListener<? super T> listener) {
this.delegate = Validate.notNull(delegate, "delegate");
this.listener = Validate.notNull(listener, "listener");
}
@Override
public void onSubscribe(Subscription s) {
delegate.onSubscribe(new NotifyingSubscription(s));
}
@Override
public void onNext(T t) {
invoke(() -> listener.subscriberOnNext(t), "subscriberOnNext");
delegate.onNext(t);
}
@Override
public void onError(Throwable t) {
invoke(() -> listener.subscriberOnError(t), "subscriberOnError");
delegate.onError(t);
}
@Override
public void onComplete() {
invoke(listener::subscriberOnComplete, "subscriberOnComplete");
delegate.onComplete();
}
static void invoke(Runnable runnable, String callbackName) {
try {
runnable.run();
} catch (Exception e) {
log.error(() -> callbackName + " callback failed. This exception will be dropped.", e);
}
}
@SdkInternalApi
final class NotifyingSubscription implements Subscription {
private final Subscription delegateSubscription;
NotifyingSubscription(Subscription delegateSubscription) {
this.delegateSubscription = Validate.notNull(delegateSubscription, "delegateSubscription");
}
@Override
public void request(long n) {
delegateSubscription.request(n);
}
@Override
public void cancel() {
invoke(listener::subscriptionCancel, "subscriptionCancel");
delegateSubscription.cancel();
}
}
}
}
| 1,868 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/async | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/async/listener/AsyncRequestBodyListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async.listener;
import java.nio.ByteBuffer;
import java.util.Optional;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
/**
* Listener interface that invokes callbacks associated with a {@link AsyncRequestBody} and any resulting {@link Subscriber}.
*
* @see PublisherListener
* @see SubscriberListener
*/
@SdkProtectedApi
public interface AsyncRequestBodyListener extends PublisherListener<ByteBuffer> {
/**
* Wrap a {@link AsyncRequestBody} with a new one that will notify a {@link AsyncRequestBodyListener} of important events
* occurring.
*/
static AsyncRequestBody wrap(AsyncRequestBody delegate, AsyncRequestBodyListener listener) {
return new NotifyingAsyncRequestBody(delegate, listener);
}
@SdkInternalApi
final class NotifyingAsyncRequestBody implements AsyncRequestBody {
private static final Logger log = Logger.loggerFor(NotifyingAsyncRequestBody.class);
private final AsyncRequestBody delegate;
private final AsyncRequestBodyListener listener;
NotifyingAsyncRequestBody(AsyncRequestBody delegate, AsyncRequestBodyListener listener) {
this.delegate = Validate.notNull(delegate, "delegate");
this.listener = Validate.notNull(listener, "listener");
}
@Override
public Optional<Long> contentLength() {
return delegate.contentLength();
}
@Override
public String contentType() {
return delegate.contentType();
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
invoke(() -> listener.publisherSubscribe(s), "publisherSubscribe");
delegate.subscribe(SubscriberListener.wrap(s, listener));
}
static void invoke(Runnable runnable, String callbackName) {
try {
runnable.run();
} catch (Exception e) {
log.error(() -> callbackName + " callback failed. This exception will be dropped.", e);
}
}
}
}
| 1,869 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/async | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/async/listener/PublisherListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.async.listener;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
/**
* Listener interface that invokes callbacks associated with a {@link Publisher} and any resulting {@link Subscriber}.
*
* @see AsyncResponseTransformerListener
* @see SubscriberListener
*/
@SdkProtectedApi
public interface PublisherListener<T> extends SubscriberListener<T> {
/**
* Invoked before {@link Publisher#subscribe(Subscriber)}
*/
default void publisherSubscribe(Subscriber<? super T> subscriber) {
}
/**
* Wrap a {@link SdkPublisher} with a new one that will notify a {@link PublisherListener} of important events occurring.
*/
static <T> SdkPublisher<T> wrap(SdkPublisher<T> delegate, PublisherListener<T> listener) {
return new NotifyingPublisher<>(delegate, listener);
}
@SdkInternalApi
final class NotifyingPublisher<T> implements SdkPublisher<T> {
private static final Logger log = Logger.loggerFor(NotifyingPublisher.class);
private final SdkPublisher<T> delegate;
private final PublisherListener<T> listener;
NotifyingPublisher(SdkPublisher<T> delegate,
PublisherListener<T> listener) {
this.delegate = Validate.notNull(delegate, "delegate");
this.listener = Validate.notNull(listener, "listener");
}
@Override
public void subscribe(Subscriber<? super T> s) {
invoke(() -> listener.publisherSubscribe(s), "publisherSubscribe");
delegate.subscribe(SubscriberListener.wrap(s, listener));
}
static void invoke(Runnable runnable, String callbackName) {
try {
runnable.run();
} catch (Exception e) {
log.error(() -> callbackName + " callback failed. This exception will be dropped.", e);
}
}
}
}
| 1,870 |
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/io/SdkInputStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.io;
import java.io.IOException;
import java.io.InputStream;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.exception.AbortedException;
import software.amazon.awssdk.core.internal.io.Releasable;
import software.amazon.awssdk.utils.IoUtils;
/**
* Base class for AWS Java SDK specific {@link InputStream}.
*/
@SdkProtectedApi
public abstract class SdkInputStream extends InputStream implements Releasable {
/**
* Returns the underlying input stream, if any, from the subclass; or null
* if there is no underlying input stream.
*/
protected abstract InputStream getWrappedInputStream();
/**
* Aborts with subclass specific abortion logic executed if needed.
* Note the interrupted status of the thread is cleared by this method.
* @throws AbortedException if found necessary.
*/
protected final void abortIfNeeded() {
if (Thread.currentThread().isInterrupted()) {
try {
abort(); // execute subclass specific abortion logic
} catch (IOException e) {
LoggerFactory.getLogger(getClass()).debug("FYI", e);
}
throw AbortedException.builder().build();
}
}
/**
* Can be used to provide abortion logic prior to throwing the
* AbortedException. No-op by default.
*/
protected void abort() throws IOException {
// no-op by default, but subclass such as S3ObjectInputStream may override
}
/**
* WARNING: Subclass that overrides this method must NOT call
* super.release() or else it would lead to infinite loop.
* <p>
* {@inheritDoc}
*/
@Override
public void release() {
// Don't call IOUtils.release(in, null) or else could lead to infinite loop
IoUtils.closeQuietly(this, null);
InputStream in = getWrappedInputStream();
if (in instanceof Releasable) {
// This allows any underlying stream that has the close operation
// disabled to be truly released
Releasable r = (Releasable) in;
r.release();
}
}
}
| 1,871 |
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/io/ResettableInputStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.exception.SdkClientException;
/**
* A mark-and-resettable input stream that can be used on files or file input
* streams.
*
* In particular, a {@link ResettableInputStream} allows the close operation to
* be disabled via {@link #disableClose()} (to avoid accidentally being closed).
* This is necessary when such input stream needs to be marked-and-reset
* multiple times but only as long as the stream has not been closed.
* <p>
* The creator of this input stream should therefore always call
* {@link #release()} in a finally block to truly release the underlying
* resources.
*
* @see ReleasableInputStream
*/
@NotThreadSafe
@SdkProtectedApi
public class ResettableInputStream extends ReleasableInputStream {
private static final Logger log = LoggerFactory.getLogger(ResettableInputStream.class);
private final File file; // null if the file is not known
private FileInputStream fis; // never null
private FileChannel fileChannel; // never null
/**
* Marked position of the file; default to zero.
*/
private long markPos;
/**
* @param file
* must not be null. Upon successful construction the the file
* will be opened with an input stream automatically marked at
* the starting position of the given file.
* <p>
* Note the creation of a {@link ResettableInputStream} would
* entail physically opening a file. If the opened file is meant
* to be closed only (in a finally block) by the very same code
* block that created it, then it is necessary that the release
* method must not be called while the execution is made in other
* stack frames.
*
* In such case, as other stack frames may inadvertently or
* indirectly call the close method of the stream, the creator of
* the stream would need to explicitly disable the accidental
* closing via {@link ResettableInputStream#disableClose()}, so
* that the release method becomes the only way to truly close
* the opened file.
*/
public ResettableInputStream(File file) throws IOException {
this(new FileInputStream(file), file);
}
/**
* <p>
* Note the creation of a {@link ResettableInputStream} would entail
* physically opening a file. If the opened file is meant to be closed only
* (in a finally block) by the very same code block that created it, then it
* is necessary that the release method must not be called while the
* execution is made in other stack frames.
*
* In such case, as other stack frames may inadvertently or indirectly call
* the close method of the stream, the creator of the stream would need to
* explicitly disable the accidental closing via
* {@link ResettableInputStream#disableClose()}, so that the release method
* becomes the only way to truly close the opened file.
*
* @param fis
* file input stream; must not be null. Upon successful
* construction the input stream will be automatically marked at
* the current position of the given file input stream.
*/
public ResettableInputStream(FileInputStream fis) throws IOException {
this(fis, null);
}
/**
* @param file
* can be null if not known
*/
private ResettableInputStream(FileInputStream fis, File file) throws IOException {
super(fis);
this.file = file;
this.fis = fis;
this.fileChannel = fis.getChannel();
this.markPos = fileChannel.position();
}
/**
* Convenient factory method to construct a new resettable input stream for
* the given file, converting any IOException into SdkClientException.
* <p>
* Note the creation of a {@link ResettableInputStream} would entail
* physically opening a file. If the opened file is meant to be closed only
* (in a finally block) by the very same code block that created it, then it
* is necessary that the release method must not be called while the
* execution is made in other stack frames.
*
* In such case, as other stack frames may inadvertently or indirectly call
* the close method of the stream, the creator of the stream would need to
* explicitly disable the accidental closing via
* {@link ResettableInputStream#disableClose()}, so that the release method
* becomes the only way to truly close the opened file.
*/
public static ResettableInputStream newResettableInputStream(File file) {
return newResettableInputStream(file, null);
}
/**
* Convenient factory method to construct a new resettable input stream for
* the given file, converting any IOException into SdkClientException
* with the given error message.
* <p>
* Note the creation of a {@link ResettableInputStream} would entail
* physically opening a file. If the opened file is meant to be closed only
* (in a finally block) by the very same code block that created it, then it
* is necessary that the release method must not be called while the
* execution is made in other stack frames.
*
* In such case, as other stack frames may inadvertently or indirectly call
* the close method of the stream, the creator of the stream would need to
* explicitly disable the accidental closing via
* {@link ResettableInputStream#disableClose()}, so that the release method
* becomes the only way to truly close the opened file.
*/
public static ResettableInputStream newResettableInputStream(File file,
String errmsg) {
try {
return new ResettableInputStream(file);
} catch (IOException e) {
throw errmsg == null
? SdkClientException.builder().cause(e).build()
: SdkClientException.builder().message(errmsg).cause(e).build();
}
}
/**
* Convenient factory method to construct a new resettable input stream for
* the given file input stream, converting any IOException into
* SdkClientException.
* <p>
* Note the creation of a {@link ResettableInputStream} would entail
* physically opening a file. If the opened file is meant to be closed only
* (in a finally block) by the very same code block that created it, then it
* is necessary that the release method must not be called while the
* execution is made in other stack frames.
*
* In such case, as other stack frames may inadvertently or indirectly call
* the close method of the stream, the creator of the stream would need to
* explicitly disable the accidental closing via
* {@link ResettableInputStream#disableClose()}, so that the release method
* becomes the only way to truly close the opened file.
*/
public static ResettableInputStream newResettableInputStream(
FileInputStream fis) {
return newResettableInputStream(fis, null);
}
/**
* Convenient factory method to construct a new resettable input stream for
* the given file input stream, converting any IOException into
* SdkClientException with the given error message.
* <p>
* Note the creation of a {@link ResettableInputStream} would entail
* physically opening a file. If the opened file is meant to be closed only
* (in a finally block) by the very same code block that created it, then it
* is necessary that the release method must not be called while the
* execution is made in other stack frames.
*
* In such case, as other stack frames may inadvertently or indirectly call
* the close method of the stream, the creator of the stream would need to
* explicitly disable the accidental closing via
* {@link ResettableInputStream#disableClose()}, so that the release method
* becomes the only way to truly close the opened file.
*/
public static ResettableInputStream newResettableInputStream(
FileInputStream fis, String errmsg) {
try {
return new ResettableInputStream(fis);
} catch (IOException e) {
throw SdkClientException.builder().message(errmsg).cause(e).build();
}
}
@Override
public final boolean markSupported() {
return true;
}
/**
* Marks the current position in this input stream. A subsequent call to
* the <code>reset</code> method repositions this stream at the last marked
* position so that subsequent reads re-read the same bytes.
* This method works as long as the underlying file has not been closed.
* <p>
* Note the creation of a {@link ResettableInputStream} would entail
* physically opening a file. If the opened file is meant to be closed only
* (in a finally block) by the very same code block that created it, then it
* is necessary that the release method must not be called while the
* execution is made in other stack frames.
*
* In such case, as other stack frames may inadvertently or indirectly call
* the close method of the stream, the creator of the stream would need to
* explicitly disable the accidental closing via
* {@link ResettableInputStream#disableClose()}, so that the release method
* becomes the only way to truly close the opened file.
*
* @param ignored
* ignored
*/
@Override
public void mark(int ignored) {
abortIfNeeded();
try {
markPos = fileChannel.position();
} catch (IOException e) {
throw SdkClientException.builder().message("Failed to mark the file position").cause(e).build();
}
if (log.isTraceEnabled()) {
log.trace("File input stream marked at position " + markPos);
}
}
/**
* Repositions this stream to the position at the time the
* <code>mark</code> method was last called on this input stream.
* This method works as long as the underlying file has not been closed.
* <p>
* Note the creation of a {@link ResettableInputStream} would entail
* physically opening a file. If the opened file is meant to be closed only
* (in a finally block) by the very same code block that created it, then it
* is necessary that the release method must not be called while the
* execution is made in other stack frames.
*
* In such case, as other stack frames may inadvertently or indirectly call
* the close method of the stream, the creator of the stream would need to
* explicitly disable the accidental closing via
* {@link ResettableInputStream#disableClose()}, so that the release method
* becomes the only way to truly close the opened file.
*/
@Override
public void reset() throws IOException {
abortIfNeeded();
fileChannel.position(markPos);
if (log.isTraceEnabled()) {
log.trace("Reset to position " + markPos);
}
}
@Override
public int available() throws IOException {
abortIfNeeded();
return fis.available();
}
@Override
public int read() throws IOException {
abortIfNeeded();
return fis.read();
}
@Override
public long skip(long n) throws IOException {
abortIfNeeded();
return fis.skip(n);
}
@Override
public int read(byte[] arg0, int arg1, int arg2) throws IOException {
abortIfNeeded();
return fis.read(arg0, arg1, arg2);
}
/**
* Returns the underlying file, if known; or null if not;
*/
public File getFile() {
return file;
}
}
| 1,872 |
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/io/SdkDigestInputStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.io;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.internal.io.Releasable;
import software.amazon.awssdk.utils.IoUtils;
/**
* Base class for AWS Java SDK specific {@link DigestInputStream}.
*/
@SdkProtectedApi
public class SdkDigestInputStream extends DigestInputStream implements Releasable {
private static final int SKIP_BUF_SIZE = 2 * 1024;
private final SdkChecksum sdkChecksum;
public SdkDigestInputStream(InputStream stream, MessageDigest digest, SdkChecksum sdkChecksum) {
super(stream, digest);
this.sdkChecksum = sdkChecksum;
}
public SdkDigestInputStream(InputStream stream, MessageDigest digest) {
this(stream, digest, null) ;
}
// https://github.com/aws/aws-sdk-java/issues/232
/**
* Skips over and discards <code>n</code> bytes of data from this input
* stream, while taking the skipped bytes into account for digest
* calculation. The <code>skip</code> method may, for a variety of reasons,
* end up skipping over some smaller number of bytes, possibly
* <code>0</code>. This may result from any of a number of conditions;
* reaching end of file before <code>n</code> bytes have been skipped is
* only one possibility. The actual number of bytes skipped is returned. If
* <code>n</code> is negative, no bytes are skipped.
*
* <p>
* The <code>skip</code> method of this class creates a byte array and then
* repeatedly reads into it until <code>n</code> bytes have been read or the
* end of the stream has been reached. Subclasses are encouraged to provide
* a more efficient implementation of this method. For instance, the
* implementation may depend on the ability to seek.
*
* @param n
* the number of bytes to be skipped.
* @return the actual number of bytes skipped.
* @exception IOException
* if the stream does not support seek, or if some other I/O
* error occurs.
*/
@Override
public final long skip(final long n) throws IOException {
if (n <= 0) {
return n;
}
byte[] b = new byte[(int) Math.min(SKIP_BUF_SIZE, n)];
long m = n; // remaining number of bytes to read
while (m > 0) {
int len = read(b, 0, (int) Math.min(m, b.length));
if (len == -1) {
return n - m;
}
m -= len;
}
assert (m == 0);
return n;
}
@Override
public final void release() {
// Don't call IOUtils.release(in, null) or else could lead to infinite loop
IoUtils.closeQuietly(this, null);
if (in instanceof Releasable) {
// This allows any underlying stream that has the close operation
// disabled to be truly released
Releasable r = (Releasable) in;
r.release();
}
}
/**
* {@inheritdoc}
*/
@Override
public int read() throws IOException {
int ch = in.read();
if (ch != -1) {
digest.update((byte) ch);
if (sdkChecksum != null) {
sdkChecksum.update((byte) ch);
}
}
return ch;
}
/**
* {@inheritdoc}
*/
@Override
public int read(byte[] b, int off, int len) throws IOException {
int result = in.read(b, off, len);
if (result != -1) {
digest.update(b, off, result);
if (sdkChecksum != null) {
sdkChecksum.update(b, off, result);
}
}
return result;
}
}
| 1,873 |
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/io/ReleasableInputStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.io;
import java.io.FileInputStream;
import java.io.InputStream;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.internal.io.Releasable;
import software.amazon.awssdk.utils.Logger;
/**
* An input stream that can have the close operation disabled (to avoid
* accidentally being closed). This is necessary, for example, when an input
* stream needs to be marked-and-reset multiple times but only as long as the
* input stream has not been closed. To survive not being accidentally closed,
* the close method can be disabled via {@link #disableClose()}.
* <p>
* The creator of this input stream should therefore always call
* {@link #release()} in a finally block to truly release the underlying
* resources.
*
* @see Releasable
* @see ResettableInputStream
*/
@NotThreadSafe
@SdkProtectedApi
public class ReleasableInputStream extends SdkFilterInputStream {
private static final Logger log = Logger.loggerFor(ReleasableInputStream.class);
/**
* True if the close method is disabled; false otherwise. Default is false.
* In case the close method is disabled, caller would be responsible to
* release resources via {@link #release()}.
*/
private boolean closeDisabled;
/**
* This constructor is not meant to be used directly. Use
* {@link #wrap(InputStream)} instead.
*/
protected ReleasableInputStream(InputStream is) {
super(is);
}
/**
* Wraps the given input stream into a {@link ReleasableInputStream} if
* necessary. Note if the given input stream is a {@link FileInputStream}, a
* {@link ResettableInputStream} which is a specific subclass of
* {@link ReleasableInputStream} will be returned.
*/
public static ReleasableInputStream wrap(InputStream is) {
if (is instanceof ReleasableInputStream) {
return (ReleasableInputStream) is; // already wrapped
}
if (is instanceof FileInputStream) {
return ResettableInputStream.newResettableInputStream((FileInputStream) is);
}
return new ReleasableInputStream(is);
}
/**
* If {@link #closeDisabled} is false, closes this input stream and releases
* any system resources associated with the stream. Otherwise, this method
* does nothing.
*/
@Override
public final void close() {
if (!closeDisabled) {
doRelease();
}
}
/**
* Closes the underlying stream file and releases any system resources associated.
*/
@Override
public final void release() {
doRelease();
}
/**
* Used to truly release the underlying resources.
*/
private void doRelease() {
try {
in.close();
} catch (Exception ex) {
log.debug(() -> "Ignore failure in closing the input stream", ex);
}
if (in instanceof Releasable) {
// This allows any underlying stream that has the close operation
// disabled to be truly released
Releasable r = (Releasable) in;
r.release();
}
abortIfNeeded();
}
/**
* Returns true if the close method has been disabled; false otherwise. Once
* the close method is disabled, caller would be responsible to release
* resources via {@link #release()}.
*/
public final boolean isCloseDisabled() {
return closeDisabled;
}
/**
* Used to disable the close method. Once the close method is disabled,
* caller would be responsible to release resources via {@link #release()}.
*/
public final <T extends ReleasableInputStream> T disableClose() {
this.closeDisabled = true;
@SuppressWarnings("unchecked")
T t = (T) this;
return t;
}
}
| 1,874 |
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/io/SdkFilterInputStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.io;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.exception.AbortedException;
import software.amazon.awssdk.core.internal.io.Releasable;
import software.amazon.awssdk.utils.IoUtils;
/**
* Base class for AWS Java SDK specific {@link FilterInputStream}.
*/
@SdkProtectedApi
public class SdkFilterInputStream extends FilterInputStream implements Releasable {
protected SdkFilterInputStream(InputStream in) {
super(in);
}
/**
* Aborts with subclass specific abortion logic executed if needed.
* Note the interrupted status of the thread is cleared by this method.
*
* @throws AbortedException if found necessary.
*/
protected final void abortIfNeeded() {
if (Thread.currentThread().isInterrupted()) {
abort(); // execute subclass specific abortion logic
throw AbortedException.builder().build();
}
}
/**
* Can be used to provide abortion logic prior to throwing the
* AbortedException. No-op by default.
*/
protected void abort() {
// no-op by default, but subclass such as S3ObjectInputStream may override
}
@Override
public int read() throws IOException {
abortIfNeeded();
return in.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
abortIfNeeded();
return in.read(b, off, len);
}
@Override
public long skip(long n) throws IOException {
abortIfNeeded();
return in.skip(n);
}
@Override
public int available() throws IOException {
abortIfNeeded();
return in.available();
}
@Override
public void close() throws IOException {
in.close();
abortIfNeeded();
}
@Override
public synchronized void mark(int readlimit) {
abortIfNeeded();
in.mark(readlimit);
}
@Override
public synchronized void reset() throws IOException {
abortIfNeeded();
in.reset();
}
@Override
public boolean markSupported() {
abortIfNeeded();
return in.markSupported();
}
@Override
public void release() {
// Don't call IOUtils.release(in, null) or else could lead to infinite loop
IoUtils.closeQuietly(this, null);
if (in instanceof Releasable) {
// This allows any underlying stream that has the close operation
// disabled to be truly released
Releasable r = (Releasable) in;
r.release();
}
}
}
| 1,875 |
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/runtime/TypeConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.runtime;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* A utilities class used by generated clients to easily convert between nested types, such as lists and maps.
*/
@SdkProtectedApi
public final class TypeConverter {
private TypeConverter() {
}
/**
* Null-safely convert between types by applying a function.
*/
public static <T, U> U convert(T toConvert, Function<? super T, ? extends U> converter) {
if (toConvert == null) {
return null;
}
return converter.apply(toConvert);
}
/**
* Null-safely convert between two lists by applying a function to each value.
*/
public static <T, U> List<U> convert(List<T> toConvert, Function<? super T, ? extends U> converter) {
if (toConvert == null) {
return null;
}
List<U> result = toConvert.stream().map(converter).collect(Collectors.toList());
return Collections.unmodifiableList(result);
}
/**
* Null-safely convert between two maps by applying a function to each key and value. A predicate is also specified to filter
* the results, in case the mapping function were to generate duplicate keys, etc.
*/
public static <T1, T2, U1, U2> Map<U1, U2> convert(Map<T1, T2> toConvert,
Function<? super T1, ? extends U1> keyConverter,
Function<? super T2, ? extends U2> valueConverter,
BiPredicate<U1, U2> resultFilter) {
if (toConvert == null) {
return null;
}
Map<U1, U2> result = toConvert.entrySet().stream()
.map(e -> new SimpleImmutableEntry<>(keyConverter.apply(e.getKey()),
valueConverter.apply(e.getValue())))
.filter(p -> resultFilter.test(p.getKey(), p.getValue()))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
return Collections.unmodifiableMap(result);
}
}
| 1,876 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/runtime | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/runtime/transform/StreamingRequestMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.runtime.transform;
import static software.amazon.awssdk.http.Header.CONTENT_TYPE;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.internal.transform.AbstractStreamingRequestMarshaller;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.StringUtils;
/**
* Augments a {@link Marshaller} to add contents for a streamed request.
*
* @param <T> Type of POJO being marshalled.
*/
@SdkProtectedApi
public final class StreamingRequestMarshaller<T> extends AbstractStreamingRequestMarshaller<T> {
private final RequestBody requestBody;
private StreamingRequestMarshaller(Builder builder) {
super(builder);
this.requestBody = builder.requestBody;
}
public static Builder builder() {
return new Builder();
}
@Override
public SdkHttpFullRequest marshall(T in) {
SdkHttpFullRequest.Builder marshalled = delegateMarshaller.marshall(in).toBuilder();
marshalled.contentStreamProvider(requestBody.contentStreamProvider());
String contentType = marshalled.firstMatchingHeader(CONTENT_TYPE)
.orElse(null);
if (StringUtils.isEmpty(contentType)) {
marshalled.putHeader(CONTENT_TYPE, requestBody.contentType());
}
// Currently, SDK always require content length in RequestBody. So we always
// send Content-Length header for sync APIs
// This change will be useful if SDK relaxes the content-length requirement in RequestBody
addHeaders(marshalled, requestBody.optionalContentLength(), requiresLength, transferEncoding, useHttp2);
return marshalled.build();
}
/**
* Builder class to build {@link StreamingRequestMarshaller} object.
*/
public static final class Builder extends AbstractStreamingRequestMarshaller.Builder<Builder> {
private RequestBody requestBody;
/**
* @param requestBody {@link RequestBody} representing the HTTP payload
* @return This object for method chaining
*/
public Builder requestBody(RequestBody requestBody) {
this.requestBody = requestBody;
return this;
}
public <T> StreamingRequestMarshaller<T> build() {
return new StreamingRequestMarshaller<>(this);
}
}
}
| 1,877 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/runtime | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/runtime/transform/Marshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.runtime.transform;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* Interface to marshall a POJO into a {@link SdkHttpFullRequest}.
*
* @param <InputT> Type to marshall.
*/
@SdkProtectedApi
public interface Marshaller<InputT> {
/**
* Marshalls the given POJO into a {@link SdkHttpFullRequest}.
*
* @param in POJO type.
* @return Marshalled {@link SdkHttpFullRequest}.
*/
SdkHttpFullRequest marshall(InputT in);
}
| 1,878 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/runtime | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/runtime/transform/AsyncStreamingRequestMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.runtime.transform;
import static software.amazon.awssdk.http.Header.CONTENT_TYPE;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.internal.transform.AbstractStreamingRequestMarshaller;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.StringUtils;
/**
* Augments a {@link Marshaller} to add contents for an async streamed request.
*
* @param <T> Type of POJO being marshalled.
*/
@SdkProtectedApi
public final class AsyncStreamingRequestMarshaller<T> extends AbstractStreamingRequestMarshaller<T> {
private final AsyncRequestBody asyncRequestBody;
private AsyncStreamingRequestMarshaller(Builder builder) {
super(builder);
this.asyncRequestBody = builder.asyncRequestBody;
}
public static Builder builder() {
return new Builder();
}
@Override
public SdkHttpFullRequest marshall(T in) {
SdkHttpFullRequest.Builder marshalled = delegateMarshaller.marshall(in).toBuilder();
String contentType = marshalled.firstMatchingHeader(CONTENT_TYPE).orElse(null);
if (StringUtils.isEmpty(contentType)) {
marshalled.putHeader(CONTENT_TYPE, asyncRequestBody.contentType());
}
addHeaders(marshalled, asyncRequestBody.contentLength(), requiresLength, transferEncoding, useHttp2);
return marshalled.build();
}
/**
* Builder class to build {@link AsyncStreamingRequestMarshaller} object.
*/
public static final class Builder extends AbstractStreamingRequestMarshaller.Builder<Builder> {
private AsyncRequestBody asyncRequestBody;
/**
* @param asyncRequestBody {@link AsyncRequestBody} representing the HTTP payload
* @return This object for method chaining
*/
public Builder asyncRequestBody(AsyncRequestBody asyncRequestBody) {
this.asyncRequestBody = asyncRequestBody;
return this;
}
public <T> AsyncStreamingRequestMarshaller<T> build() {
return new AsyncStreamingRequestMarshaller<>(this);
}
}
}
| 1,879 |
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/internal/SdkInternalTestAdvancedClientOption.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import java.net.URI;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.core.client.builder.SdkClientBuilder;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.client.config.SdkClientOption;
/**
* Options of {@link SdkAdvancedClientOption} that <b>must not be used</b> outside of tests that are stored in this project.
* Changes to this class <b>are not guaranteed to be backwards compatible</b>.
*/
@SdkInternalApi
public class SdkInternalTestAdvancedClientOption<T> extends SdkAdvancedClientOption<T> {
/**
* By default, the SDK handles endpoints specified via {@link SdkClientBuilder#endpointOverride(URI)} differently than
* endpoints generated from a specific region. For example, endpoint discovery is not supported in some cases when endpoint
* overrides are used.
*
* When this option is set, the {@link SdkClientOption#ENDPOINT_OVERRIDDEN} is forced to this value. Because of the way this
* is implemented, the client configuration must be configured *after* the {@code endpointOverride} is configured.
*/
@SdkTestInternalApi
public static final SdkInternalTestAdvancedClientOption<Boolean> ENDPOINT_OVERRIDDEN_OVERRIDE =
new SdkInternalTestAdvancedClientOption<>(Boolean.class);
protected SdkInternalTestAdvancedClientOption(Class<T> valueClass) {
super(valueClass);
}
}
| 1,880 |
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/internal/InternalCoreExecutionAttribute.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
/**
* Attributes that can be applied to all sdk requests. These attributes are only used internally by the core to
* handle executions through the pipeline.
*/
@SdkInternalApi
public final class InternalCoreExecutionAttribute extends SdkExecutionAttribute {
/**
* The key to store the execution attempt number that is used by handlers in the async request pipeline to help
* regulate their behavior.
*/
public static final ExecutionAttribute<Integer> EXECUTION_ATTEMPT =
new ExecutionAttribute<>("SdkInternalExecutionAttempt");
private InternalCoreExecutionAttribute() {
}
}
| 1,881 |
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/handler/BaseSyncClientHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.handler;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.Response;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.handler.ClientExecutionParams;
import software.amazon.awssdk.core.client.handler.SyncClientHandler;
import software.amazon.awssdk.core.exception.AbortedException;
import software.amazon.awssdk.core.exception.NonRetryableException;
import software.amazon.awssdk.core.exception.RetryableException;
import software.amazon.awssdk.core.http.ExecutionContext;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.InterceptorContext;
import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient;
import software.amazon.awssdk.core.internal.http.CombinedResponseHandler;
import software.amazon.awssdk.core.internal.http.InterruptMonitor;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.metrics.MetricCollector;
@SdkInternalApi
public abstract class BaseSyncClientHandler extends BaseClientHandler implements SyncClientHandler {
private final AmazonSyncHttpClient client;
protected BaseSyncClientHandler(SdkClientConfiguration clientConfiguration,
AmazonSyncHttpClient client) {
super(clientConfiguration);
this.client = client;
}
@Override
public <InputT extends SdkRequest, OutputT extends SdkResponse, ReturnT> ReturnT execute(
ClientExecutionParams<InputT, OutputT> executionParams,
ResponseTransformer<OutputT, ReturnT> responseTransformer) {
return measureApiCallSuccess(executionParams, () -> {
// Running beforeExecution interceptors and modifyRequest interceptors.
ExecutionContext executionContext = invokeInterceptorsAndCreateExecutionContext(executionParams);
CombinedResponseHandler<ReturnT> streamingCombinedResponseHandler =
createStreamingCombinedResponseHandler(executionParams, responseTransformer, executionContext);
return doExecute(executionParams, executionContext, streamingCombinedResponseHandler);
});
}
@Override
public <InputT extends SdkRequest, OutputT extends SdkResponse> OutputT execute(
ClientExecutionParams<InputT, OutputT> executionParams) {
return measureApiCallSuccess(executionParams, () -> {
// Running beforeExecution interceptors and modifyRequest interceptors.
ExecutionContext executionContext = invokeInterceptorsAndCreateExecutionContext(executionParams);
HttpResponseHandler<Response<OutputT>> combinedResponseHandler =
createCombinedResponseHandler(executionParams, executionContext);
return doExecute(executionParams, executionContext, combinedResponseHandler);
});
}
@Override
public void close() {
client.close();
}
/**
* Invoke the request using the http client. Assumes credentials (or lack thereof) have been
* configured in the OldExecutionContext beforehand.
**/
private <OutputT> OutputT invoke(SdkClientConfiguration clientConfiguration,
SdkHttpFullRequest request,
SdkRequest originalRequest,
ExecutionContext executionContext,
HttpResponseHandler<Response<OutputT>> responseHandler) {
return client.requestExecutionBuilder()
.request(request)
.originalRequest(originalRequest)
.executionContext(executionContext)
.httpClientDependencies(c -> c.clientConfiguration(clientConfiguration))
.execute(responseHandler);
}
private <InputT extends SdkRequest, OutputT extends SdkResponse, ReturnT> CombinedResponseHandler<ReturnT>
createStreamingCombinedResponseHandler(ClientExecutionParams<InputT, OutputT> executionParams,
ResponseTransformer<OutputT, ReturnT> responseTransformer,
ExecutionContext executionContext) {
if (executionParams.getCombinedResponseHandler() != null) {
// There is no support for catching errors in a body for streaming responses
throw new IllegalArgumentException("A streaming 'responseTransformer' may not be used when a "
+ "'combinedResponseHandler' has been specified in a "
+ "ClientExecutionParams object.");
}
HttpResponseHandler<OutputT> decoratedResponseHandlers =
decorateResponseHandlers(executionParams.getResponseHandler(), executionContext);
HttpResponseHandler<ReturnT> httpResponseHandler =
new HttpResponseHandlerAdapter<>(decoratedResponseHandlers, responseTransformer);
return new CombinedResponseHandler<>(httpResponseHandler, executionParams.getErrorResponseHandler());
}
private <InputT extends SdkRequest, OutputT extends SdkResponse> HttpResponseHandler<Response<OutputT>>
createCombinedResponseHandler(ClientExecutionParams<InputT, OutputT> executionParams,
ExecutionContext executionContext) {
validateCombinedResponseHandler(executionParams);
HttpResponseHandler<Response<OutputT>> combinedResponseHandler;
if (executionParams.getCombinedResponseHandler() != null) {
combinedResponseHandler = decorateSuccessResponseHandlers(executionParams.getCombinedResponseHandler(),
executionContext);
} else {
HttpResponseHandler<OutputT> decoratedResponseHandlers =
decorateResponseHandlers(executionParams.getResponseHandler(), executionContext);
combinedResponseHandler = new CombinedResponseHandler<>(decoratedResponseHandlers,
executionParams.getErrorResponseHandler());
}
return combinedResponseHandler;
}
private <InputT extends SdkRequest, OutputT, ReturnT> ReturnT doExecute(
ClientExecutionParams<InputT, OutputT> executionParams,
ExecutionContext executionContext,
HttpResponseHandler<Response<ReturnT>> responseHandler) {
InputT inputT = (InputT) executionContext.interceptorContext().request();
InterceptorContext sdkHttpFullRequestContext = finalizeSdkHttpFullRequest(executionParams,
executionContext,
inputT,
resolveRequestConfiguration(
executionParams));
SdkHttpFullRequest marshalled = (SdkHttpFullRequest) sdkHttpFullRequestContext.httpRequest();
// Ensure that the signing configuration is still valid after the
// request has been potentially transformed.
validateSigningConfiguration(marshalled, executionContext.signer());
// TODO Pass requestBody as separate arg to invoke
Optional<RequestBody> requestBody = sdkHttpFullRequestContext.requestBody();
if (requestBody.isPresent()) {
marshalled = marshalled.toBuilder()
.contentStreamProvider(requestBody.get().contentStreamProvider())
.build();
}
SdkClientConfiguration clientConfiguration = resolveRequestConfiguration(executionParams);
return invoke(clientConfiguration,
marshalled,
inputT,
executionContext,
responseHandler);
}
private <T> T measureApiCallSuccess(ClientExecutionParams<?, ?> executionParams, Supplier<T> thingToMeasureSuccessOf) {
try {
T result = thingToMeasureSuccessOf.get();
reportApiCallSuccess(executionParams, true);
return result;
} catch (Exception e) {
reportApiCallSuccess(executionParams, false);
throw e;
}
}
private void reportApiCallSuccess(ClientExecutionParams<?, ?> executionParams, boolean value) {
MetricCollector metricCollector = executionParams.getMetricCollector();
if (metricCollector != null) {
metricCollector.reportMetric(CoreMetric.API_CALL_SUCCESSFUL, value);
}
}
private static class HttpResponseHandlerAdapter<ReturnT, OutputT extends SdkResponse>
implements HttpResponseHandler<ReturnT> {
private final HttpResponseHandler<OutputT> httpResponseHandler;
private final ResponseTransformer<OutputT, ReturnT> responseTransformer;
private HttpResponseHandlerAdapter(HttpResponseHandler<OutputT> httpResponseHandler,
ResponseTransformer<OutputT, ReturnT> responseTransformer) {
this.httpResponseHandler = httpResponseHandler;
this.responseTransformer = responseTransformer;
}
@Override
public ReturnT handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception {
OutputT resp = httpResponseHandler.handle(response, executionAttributes);
return transformResponse(resp, response.content().orElseGet(AbortableInputStream::createEmpty));
}
@Override
public boolean needsConnectionLeftOpen() {
return responseTransformer.needsConnectionLeftOpen();
}
private ReturnT transformResponse(OutputT resp, AbortableInputStream inputStream) throws Exception {
try {
InterruptMonitor.checkInterrupted();
ReturnT result = responseTransformer.transform(resp, inputStream);
InterruptMonitor.checkInterrupted();
return result;
} catch (RetryableException | InterruptedException | AbortedException e) {
throw e;
} catch (Exception e) {
InterruptMonitor.checkInterrupted();
throw NonRetryableException.builder().cause(e).build();
}
}
}
}
| 1,882 |
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/handler/BaseClientHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.handler;
import java.net.URI;
import java.time.Duration;
import java.util.Optional;
import java.util.function.BiFunction;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.CredentialType;
import software.amazon.awssdk.core.Response;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.client.handler.ClientExecutionParams;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.http.ExecutionContext;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptorChain;
import software.amazon.awssdk.core.interceptor.InterceptorContext;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.core.internal.InternalCoreExecutionAttribute;
import software.amazon.awssdk.core.internal.io.SdkLengthAwareInputStream;
import software.amazon.awssdk.core.internal.util.MetricUtils;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.StringUtils;
@SdkInternalApi
public abstract class BaseClientHandler {
private SdkClientConfiguration clientConfiguration;
protected BaseClientHandler(SdkClientConfiguration clientConfiguration) {
this.clientConfiguration = clientConfiguration;
}
/**
* Finalize {@link SdkHttpFullRequest} by running beforeMarshalling, afterMarshalling,
* modifyHttpRequest, modifyHttpContent and modifyAsyncHttpContent interceptors
*/
static <InputT extends SdkRequest, OutputT> InterceptorContext finalizeSdkHttpFullRequest(
ClientExecutionParams<InputT, OutputT> executionParams,
ExecutionContext executionContext, InputT inputT,
SdkClientConfiguration clientConfiguration) {
runBeforeMarshallingInterceptors(executionContext);
Pair<SdkHttpFullRequest, Duration> measuredMarshall = MetricUtils.measureDuration(() ->
executionParams.getMarshaller().marshall(inputT));
executionContext.metricCollector().reportMetric(CoreMetric.MARSHALLING_DURATION, measuredMarshall.right());
SdkHttpFullRequest request = measuredMarshall.left();
request = modifyEndpointHostIfNeeded(request, clientConfiguration, executionParams);
addHttpRequest(executionContext, request);
runAfterMarshallingInterceptors(executionContext);
return runModifyHttpRequestAndHttpContentInterceptors(executionContext);
}
private static void runBeforeMarshallingInterceptors(ExecutionContext executionContext) {
executionContext.interceptorChain().beforeMarshalling(executionContext.interceptorContext(),
executionContext.executionAttributes());
}
/**
* Modifies the given {@link SdkHttpFullRequest} with new host if host prefix is enabled and set.
*/
private static SdkHttpFullRequest modifyEndpointHostIfNeeded(SdkHttpFullRequest originalRequest,
SdkClientConfiguration clientConfiguration,
ClientExecutionParams executionParams) {
if (executionParams.discoveredEndpoint() != null) {
URI discoveredEndpoint = executionParams.discoveredEndpoint();
executionParams.putExecutionAttribute(SdkInternalExecutionAttribute.IS_DISCOVERED_ENDPOINT, true);
return originalRequest.toBuilder().host(discoveredEndpoint.getHost()).port(discoveredEndpoint.getPort()).build();
}
Boolean disableHostPrefixInjection = clientConfiguration.option(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION);
if ((disableHostPrefixInjection != null && disableHostPrefixInjection.equals(Boolean.TRUE)) ||
StringUtils.isEmpty(executionParams.hostPrefixExpression())) {
return originalRequest;
}
return originalRequest.toBuilder()
.host(executionParams.hostPrefixExpression() + originalRequest.host())
.build();
}
private static void addHttpRequest(ExecutionContext executionContext, SdkHttpFullRequest request) {
InterceptorContext interceptorContext = executionContext.interceptorContext();
Optional<ContentStreamProvider> contentStreamProvider = request.contentStreamProvider();
if (contentStreamProvider.isPresent()) {
interceptorContext = interceptorContext.copy(b -> b.httpRequest(request)
.requestBody(getBody(request)));
} else {
interceptorContext = interceptorContext.copy(b -> b.httpRequest(request));
}
executionContext.interceptorContext(interceptorContext);
}
private static RequestBody getBody(SdkHttpFullRequest request) {
Optional<ContentStreamProvider> contentStreamProviderOptional = request.contentStreamProvider();
if (contentStreamProviderOptional.isPresent()) {
Optional<String> contentLengthOptional = request.firstMatchingHeader("Content-Length");
long contentLength = Long.parseLong(contentLengthOptional.orElse("0"));
String contentType = request.firstMatchingHeader("Content-Type").orElse("");
// Enforce the content length specified only if it was present on the request (and not the default).
ContentStreamProvider streamProvider = contentStreamProviderOptional.get();
if (contentLengthOptional.isPresent()) {
ContentStreamProvider toWrap = contentStreamProviderOptional.get();
streamProvider = () -> new SdkLengthAwareInputStream(toWrap.newStream(), contentLength);
}
return RequestBody.fromContentProvider(streamProvider,
contentLength,
contentType);
}
return null;
}
private static void runAfterMarshallingInterceptors(ExecutionContext executionContext) {
executionContext.interceptorChain().afterMarshalling(executionContext.interceptorContext(),
executionContext.executionAttributes());
}
private static InterceptorContext runModifyHttpRequestAndHttpContentInterceptors(ExecutionContext executionContext) {
InterceptorContext interceptorContext =
executionContext.interceptorChain().modifyHttpRequestAndHttpContent(executionContext.interceptorContext(),
executionContext.executionAttributes());
executionContext.interceptorContext(interceptorContext);
return interceptorContext;
}
/**
* Run afterUnmarshalling and modifyResponse interceptors.
*/
private static <OutputT extends SdkResponse> BiFunction<OutputT, SdkHttpFullResponse, OutputT>
runAfterUnmarshallingInterceptors(ExecutionContext context) {
return (input, httpFullResponse) -> {
// Update interceptor context to include response
InterceptorContext interceptorContext =
context.interceptorContext().copy(b -> b.response(input));
context.interceptorChain().afterUnmarshalling(interceptorContext, context.executionAttributes());
interceptorContext = context.interceptorChain().modifyResponse(interceptorContext, context.executionAttributes());
// Store updated context
context.interceptorContext(interceptorContext);
return (OutputT) interceptorContext.response();
};
}
private static <OutputT extends SdkResponse> BiFunction<OutputT, SdkHttpFullResponse, OutputT>
attachHttpResponseToResult() {
return ((response, httpFullResponse) -> (OutputT) response.toBuilder().sdkHttpResponse(httpFullResponse).build());
}
// This method is only called from tests, since the subclasses in aws-core override it.
protected <InputT extends SdkRequest, OutputT extends SdkResponse> ExecutionContext
invokeInterceptorsAndCreateExecutionContext(
ClientExecutionParams<InputT, OutputT> params) {
SdkClientConfiguration clientConfiguration = resolveRequestConfiguration(params);
SdkRequest originalRequest = params.getInput();
ExecutionAttributes executionAttributes = params.executionAttributes();
executionAttributes
.putAttribute(InternalCoreExecutionAttribute.EXECUTION_ATTEMPT, 1)
.putAttribute(SdkExecutionAttribute.SERVICE_CONFIG,
clientConfiguration.option(SdkClientOption.SERVICE_CONFIGURATION))
.putAttribute(SdkExecutionAttribute.SERVICE_NAME, clientConfiguration.option(SdkClientOption.SERVICE_NAME))
.putAttribute(SdkExecutionAttribute.PROFILE_FILE,
clientConfiguration.option(SdkClientOption.PROFILE_FILE_SUPPLIER) != null ?
clientConfiguration.option(SdkClientOption.PROFILE_FILE_SUPPLIER).get() : null)
.putAttribute(SdkExecutionAttribute.PROFILE_FILE_SUPPLIER,
clientConfiguration.option(SdkClientOption.PROFILE_FILE_SUPPLIER))
.putAttribute(SdkExecutionAttribute.PROFILE_NAME, clientConfiguration.option(SdkClientOption.PROFILE_NAME));
ExecutionInterceptorChain interceptorChain =
new ExecutionInterceptorChain(clientConfiguration.option(SdkClientOption.EXECUTION_INTERCEPTORS));
InterceptorContext interceptorContext = InterceptorContext.builder()
.request(originalRequest)
.build();
interceptorChain.beforeExecution(interceptorContext, executionAttributes);
interceptorContext = interceptorChain.modifyRequest(interceptorContext, executionAttributes);
MetricCollector metricCollector = resolveMetricCollector(params);
return ExecutionContext.builder()
.interceptorChain(interceptorChain)
.interceptorContext(interceptorContext)
.executionAttributes(executionAttributes)
.signer(clientConfiguration.option(SdkAdvancedClientOption.SIGNER))
.metricCollector(metricCollector)
.build();
}
protected boolean isCalculateCrc32FromCompressedData() {
return clientConfiguration.option(SdkClientOption.CRC32_FROM_COMPRESSED_DATA_ENABLED);
}
protected void validateSigningConfiguration(SdkHttpRequest request, Signer signer) {
if (signer == null) {
return;
}
if (signer.credentialType() != CredentialType.TOKEN) {
return;
}
URI endpoint = request.getUri();
if (!"https".equals(endpoint.getScheme())) {
throw SdkClientException.create("Cannot use bearer token signer with a plaintext HTTP endpoint: " + endpoint);
}
}
protected SdkClientConfiguration resolveRequestConfiguration(ClientExecutionParams<?, ?> params) {
SdkClientConfiguration config = params.requestConfiguration();
if (config != null) {
return config;
}
return clientConfiguration;
}
/**
* Decorate response handlers by running after unmarshalling Interceptors and adding http response metadata.
*/
<OutputT extends SdkResponse> HttpResponseHandler<OutputT> decorateResponseHandlers(
HttpResponseHandler<OutputT> delegate, ExecutionContext executionContext) {
return resultTransformationResponseHandler(delegate, responseTransformations(executionContext));
}
<OutputT extends SdkResponse> HttpResponseHandler<Response<OutputT>> decorateSuccessResponseHandlers(
HttpResponseHandler<Response<OutputT>> delegate, ExecutionContext executionContext) {
return successTransformationResponseHandler(delegate, responseTransformations(executionContext));
}
<OutputT extends SdkResponse> HttpResponseHandler<Response<OutputT>> successTransformationResponseHandler(
HttpResponseHandler<Response<OutputT>> responseHandler,
BiFunction<OutputT, SdkHttpFullResponse, OutputT> successTransformer) {
return (response, executionAttributes) -> {
Response<OutputT> delegateResponse = responseHandler.handle(response, executionAttributes);
if (delegateResponse.isSuccess()) {
return delegateResponse.toBuilder()
.response(successTransformer.apply(delegateResponse.response(), response))
.build();
} else {
return delegateResponse;
}
};
}
<OutputT extends SdkResponse> HttpResponseHandler<OutputT> resultTransformationResponseHandler(
HttpResponseHandler<OutputT> responseHandler,
BiFunction<OutputT, SdkHttpFullResponse, OutputT> successTransformer) {
return (response, executionAttributes) -> {
OutputT delegateResponse = responseHandler.handle(response, executionAttributes);
return successTransformer.apply(delegateResponse, response);
};
}
static void validateCombinedResponseHandler(ClientExecutionParams<?, ?> executionParams) {
if (executionParams.getCombinedResponseHandler() != null) {
if (executionParams.getResponseHandler() != null) {
throw new IllegalArgumentException("Only one of 'combinedResponseHandler' and 'responseHandler' may "
+ "be specified in a ClientExecutionParams object");
}
if (executionParams.getErrorResponseHandler() != null) {
throw new IllegalArgumentException("Only one of 'combinedResponseHandler' and 'errorResponseHandler' "
+ "may be specified in a ClientExecutionParams object");
}
}
}
/**
* Returns the composition of 'runAfterUnmarshallingInterceptors' and 'attachHttpResponseToResult' response
* transformations as a single transformation that should be applied to all responses.
*/
private static <T extends SdkResponse> BiFunction<T, SdkHttpFullResponse, T>
responseTransformations(ExecutionContext executionContext) {
return composeResponseFunctions(runAfterUnmarshallingInterceptors(executionContext),
attachHttpResponseToResult());
}
/**
* Composes two functions passing the result of the first function as the first argument of the second function
* and the same second argument to both functions. This is used by response transformers to chain together and
* pass through a persistent SdkHttpFullResponse object as a second arg turning them effectively into a single
* response transformer.
* <p>
* So given f1(x, y) and f2(x, y) where x is typically OutputT and y is typically SdkHttpFullResponse the composed
* function would be f12(x, y) = f2(f1(x, y), y).
*/
private static <T, R> BiFunction<T, R, T> composeResponseFunctions(BiFunction<T, R, T> function1,
BiFunction<T, R, T> function2) {
return (x, y) -> function2.apply(function1.apply(x, y), y);
}
private MetricCollector resolveMetricCollector(ClientExecutionParams<?, ?> params) {
MetricCollector metricCollector = params.getMetricCollector();
if (metricCollector == null) {
metricCollector = MetricCollector.create("ApiCall");
}
return metricCollector;
}
}
| 1,883 |
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/handler/BaseAsyncClientHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.handler;
import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.Response;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.handler.AsyncClientHandler;
import software.amazon.awssdk.core.client.handler.ClientExecutionParams;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.http.Crc32Validation;
import software.amazon.awssdk.core.http.ExecutionContext;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.InterceptorContext;
import software.amazon.awssdk.core.internal.InternalCoreExecutionAttribute;
import software.amazon.awssdk.core.internal.http.AmazonAsyncHttpClient;
import software.amazon.awssdk.core.internal.http.IdempotentAsyncResponseHandler;
import software.amazon.awssdk.core.internal.http.TransformingAsyncResponseHandler;
import software.amazon.awssdk.core.internal.http.async.AsyncAfterTransmissionInterceptorCallingResponseHandler;
import software.amazon.awssdk.core.internal.http.async.AsyncResponseHandler;
import software.amazon.awssdk.core.internal.http.async.AsyncStreamingResponseHandler;
import software.amazon.awssdk.core.internal.http.async.CombinedResponseAsyncHttpResponseHandler;
import software.amazon.awssdk.core.internal.util.ThrowableUtils;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import software.amazon.awssdk.utils.Logger;
@SdkInternalApi
public abstract class BaseAsyncClientHandler extends BaseClientHandler implements AsyncClientHandler {
private static final Logger log = Logger.loggerFor(BaseAsyncClientHandler.class);
private final AmazonAsyncHttpClient client;
private final Function<SdkHttpFullResponse, SdkHttpFullResponse> crc32Validator;
protected BaseAsyncClientHandler(SdkClientConfiguration clientConfiguration,
AmazonAsyncHttpClient client) {
super(clientConfiguration);
this.client = client;
this.crc32Validator = response -> Crc32Validation.validate(isCalculateCrc32FromCompressedData(), response);
}
@Override
public <InputT extends SdkRequest, OutputT extends SdkResponse> CompletableFuture<OutputT> execute(
ClientExecutionParams<InputT, OutputT> executionParams) {
return measureApiCallSuccess(executionParams, () -> {
// Running beforeExecution interceptors and modifyRequest interceptors.
ExecutionContext executionContext = invokeInterceptorsAndCreateExecutionContext(executionParams);
TransformingAsyncResponseHandler<Response<OutputT>> combinedResponseHandler =
createCombinedResponseHandler(executionParams, executionContext);
return doExecute(executionParams, executionContext, combinedResponseHandler);
});
}
@Override
public <InputT extends SdkRequest, OutputT extends SdkResponse, ReturnT> CompletableFuture<ReturnT> execute(
ClientExecutionParams<InputT, OutputT> executionParams,
AsyncResponseTransformer<OutputT, ReturnT> asyncResponseTransformer) {
return measureApiCallSuccess(executionParams, () -> {
if (executionParams.getCombinedResponseHandler() != null) {
// There is no support for catching errors in a body for streaming responses. Our codegen must never
// attempt to do this.
throw new IllegalArgumentException("A streaming 'asyncResponseTransformer' may not be used when a "
+ "'combinedResponseHandler' has been specified in a "
+ "ClientExecutionParams object.");
}
ExecutionAttributes executionAttributes = executionParams.executionAttributes();
executionAttributes.putAttribute(InternalCoreExecutionAttribute.EXECUTION_ATTEMPT, 1);
AsyncStreamingResponseHandler<OutputT, ReturnT> asyncStreamingResponseHandler =
new AsyncStreamingResponseHandler<>(asyncResponseTransformer);
// For streaming requests, prepare() should be called as early as possible to avoid NPE in client
// See https://github.com/aws/aws-sdk-java-v2/issues/1268. We do this with a wrapper that caches the prepare
// result until the execution attempt number changes. This guarantees that prepare is only called once per
// execution.
TransformingAsyncResponseHandler<ReturnT> wrappedAsyncStreamingResponseHandler =
IdempotentAsyncResponseHandler.create(
asyncStreamingResponseHandler,
() -> executionAttributes.getAttribute(InternalCoreExecutionAttribute.EXECUTION_ATTEMPT),
Integer::equals);
wrappedAsyncStreamingResponseHandler.prepare();
// Running beforeExecution interceptors and modifyRequest interceptors.
ExecutionContext context = invokeInterceptorsAndCreateExecutionContext(executionParams);
HttpResponseHandler<OutputT> decoratedResponseHandlers =
decorateResponseHandlers(executionParams.getResponseHandler(), context);
asyncStreamingResponseHandler.responseHandler(decoratedResponseHandlers);
TransformingAsyncResponseHandler<? extends SdkException> errorHandler =
resolveErrorResponseHandler(executionParams.getErrorResponseHandler(), context, crc32Validator);
TransformingAsyncResponseHandler<Response<ReturnT>> combinedResponseHandler =
new CombinedResponseAsyncHttpResponseHandler<>(wrappedAsyncStreamingResponseHandler, errorHandler);
return doExecute(executionParams, context, combinedResponseHandler);
});
}
private <InputT extends SdkRequest, OutputT extends SdkResponse> TransformingAsyncResponseHandler<Response<OutputT>>
createCombinedResponseHandler(ClientExecutionParams<InputT, OutputT> executionParams,
ExecutionContext executionContext) {
/* Decorate and combine provided response handlers into a single decorated response handler */
validateCombinedResponseHandler(executionParams);
TransformingAsyncResponseHandler<Response<OutputT>> combinedResponseHandler;
if (executionParams.getCombinedResponseHandler() == null) {
combinedResponseHandler = createDecoratedHandler(executionParams.getResponseHandler(),
executionParams.getErrorResponseHandler(),
executionContext);
} else {
combinedResponseHandler = createDecoratedHandler(executionParams.getCombinedResponseHandler(),
executionContext);
}
return combinedResponseHandler;
}
/**
* Combines and decorates separate success and failure response handlers into a single combined response handler
* that handles both cases and produces a {@link Response} object that wraps the result. The handlers are
* decorated with additional behavior (such as CRC32 validation).
*/
private <OutputT extends SdkResponse> TransformingAsyncResponseHandler<Response<OutputT>> createDecoratedHandler(
HttpResponseHandler<OutputT> successHandler,
HttpResponseHandler<? extends SdkException> errorHandler,
ExecutionContext executionContext) {
HttpResponseHandler<OutputT> decoratedResponseHandlers =
decorateResponseHandlers(successHandler, executionContext);
TransformingAsyncResponseHandler<OutputT> decoratedSuccessHandler =
new AsyncResponseHandler<>(decoratedResponseHandlers,
crc32Validator,
executionContext.executionAttributes());
TransformingAsyncResponseHandler<? extends SdkException> decoratedErrorHandler =
resolveErrorResponseHandler(errorHandler, executionContext, crc32Validator);
return new CombinedResponseAsyncHttpResponseHandler<>(decoratedSuccessHandler, decoratedErrorHandler);
}
/**
* Decorates a combined response handler with additional behavior (such as CRC32 validation).
*/
private <OutputT extends SdkResponse> TransformingAsyncResponseHandler<Response<OutputT>> createDecoratedHandler(
HttpResponseHandler<Response<OutputT>> combinedResponseHandler,
ExecutionContext executionContext) {
HttpResponseHandler<Response<OutputT>> decoratedResponseHandlers =
decorateSuccessResponseHandlers(combinedResponseHandler, executionContext);
return new AsyncResponseHandler<>(decoratedResponseHandlers,
crc32Validator,
executionContext.executionAttributes());
}
private <InputT extends SdkRequest, OutputT extends SdkResponse, ReturnT> CompletableFuture<ReturnT> doExecute(
ClientExecutionParams<InputT, OutputT> executionParams,
ExecutionContext executionContext,
TransformingAsyncResponseHandler<Response<ReturnT>> asyncResponseHandler) {
try {
InputT inputT = (InputT) executionContext.interceptorContext().request();
// Running beforeMarshalling, afterMarshalling and modifyHttpRequest, modifyHttpContent,
// modifyAsyncHttpContent interceptors
InterceptorContext finalizeSdkHttpRequestContext = finalizeSdkHttpFullRequest(executionParams,
executionContext,
inputT,
resolveRequestConfiguration(
executionParams));
SdkHttpFullRequest marshalled = (SdkHttpFullRequest) finalizeSdkHttpRequestContext.httpRequest();
// Ensure that the signing configuration is still valid after the
// request has been potentially transformed.
try {
validateSigningConfiguration(marshalled, executionContext.signer());
} catch (Exception e) {
return CompletableFutureUtils.failedFuture(e);
}
Optional<RequestBody> requestBody = finalizeSdkHttpRequestContext.requestBody();
// For non-streaming requests, RequestBody can be modified in the interceptors. eg:
// CreateMultipartUploadRequestInterceptor
if (!finalizeSdkHttpRequestContext.asyncRequestBody().isPresent() && requestBody.isPresent()) {
marshalled = marshalled.toBuilder()
.contentStreamProvider(requestBody.get().contentStreamProvider())
.build();
}
SdkClientConfiguration clientConfiguration = resolveRequestConfiguration(executionParams);
CompletableFuture<ReturnT> invokeFuture =
invoke(clientConfiguration,
marshalled,
finalizeSdkHttpRequestContext.asyncRequestBody().orElse(null),
inputT,
executionContext,
new AsyncAfterTransmissionInterceptorCallingResponseHandler<>(asyncResponseHandler,
executionContext));
CompletableFuture<ReturnT> exceptionTranslatedFuture = invokeFuture.handle((resp, err) -> {
if (err != null) {
throw ThrowableUtils.failure(err);
}
return resp;
});
return CompletableFutureUtils.forwardExceptionTo(exceptionTranslatedFuture, invokeFuture);
} catch (Throwable t) {
runAndLogError(
log.logger(),
"Error thrown from TransformingAsyncResponseHandler#onError, ignoring.",
() -> asyncResponseHandler.onError(t));
return CompletableFutureUtils.failedFuture(ThrowableUtils.asSdkException(t));
}
}
@Override
public void close() {
client.close();
}
/**
* Error responses are never streaming so we always use {@link AsyncResponseHandler}.
*
* @return Async handler for error responses.
*/
private TransformingAsyncResponseHandler<? extends SdkException> resolveErrorResponseHandler(
HttpResponseHandler<? extends SdkException> errorHandler,
ExecutionContext executionContext,
Function<SdkHttpFullResponse, SdkHttpFullResponse> responseAdapter) {
return new AsyncResponseHandler<>(errorHandler,
responseAdapter,
executionContext.executionAttributes());
}
/**
* Invoke the request using the http client. Assumes credentials (or lack thereof) have been
* configured in the ExecutionContext beforehand.
**/
private <InputT extends SdkRequest, OutputT> CompletableFuture<OutputT> invoke(
SdkClientConfiguration clientConfiguration,
SdkHttpFullRequest request,
AsyncRequestBody requestProvider,
InputT originalRequest,
ExecutionContext executionContext,
TransformingAsyncResponseHandler<Response<OutputT>> responseHandler) {
return client.requestExecutionBuilder()
.requestProvider(requestProvider)
.request(request)
.originalRequest(originalRequest)
.executionContext(executionContext)
.httpClientDependencies(c -> c.clientConfiguration(clientConfiguration))
.execute(responseHandler);
}
private <T> CompletableFuture<T> measureApiCallSuccess(ClientExecutionParams<?, ?> executionParams,
Supplier<CompletableFuture<T>> apiCall) {
try {
CompletableFuture<T> apiCallResult = apiCall.get();
CompletableFuture<T> outputFuture =
apiCallResult.whenComplete((r, t) -> reportApiCallSuccess(executionParams, t == null));
// Preserve cancellations on the output future, by passing cancellations of the output future to the api call future.
CompletableFutureUtils.forwardExceptionTo(outputFuture, apiCallResult);
return outputFuture;
} catch (Exception e) {
reportApiCallSuccess(executionParams, false);
return CompletableFutureUtils.failedFuture(e);
}
}
private void reportApiCallSuccess(ClientExecutionParams<?, ?> executionParams, boolean value) {
MetricCollector metricCollector = executionParams.getMetricCollector();
if (metricCollector != null) {
metricCollector.reportMetric(CoreMetric.API_CALL_SUCCESSFUL, value);
}
}
}
| 1,884 |
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/metrics/SdkErrorType.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.metrics;
import java.io.IOException;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException;
import software.amazon.awssdk.core.exception.ApiCallTimeoutException;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.retry.RetryUtils;
/**
* General categories of errors that can be encountered when making an API call attempt.
* <p>
* This class is <b>NOT</b> intended to fully distinguish the details of every error that is possible to encounter when making
* an API call attempt; for example, it is not a replacement for detailed logs. Instead, the categories are intentionally
* broad to make it easy at-a-glance what is causing issues with requests, and to help direct further investigation.
*/
@SdkInternalApi
public enum SdkErrorType {
/**
* The service responded with a throttling error.
*/
THROTTLING("Throttling"),
/**
* The service responded with an error other than {@link #THROTTLING}.
*/
SERVER_ERROR("ServerError"),
/**
* A clientside timeout occurred, either an attempt level timeout, or API call level.
*/
CONFIGURED_TIMEOUT("ConfiguredTimeout"),
/**
* An I/O error.
*/
IO("IO"),
/**
* Catch-all type for errors that don't fit into the other categories.
*/
OTHER("Other"),
;
private final String name;
SdkErrorType(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
public static SdkErrorType fromException(Throwable e) {
if (e instanceof IOException) {
return IO;
}
if (e instanceof SdkException) {
SdkException sdkError = (SdkException) e;
if (sdkError instanceof ApiCallTimeoutException || sdkError instanceof ApiCallAttemptTimeoutException) {
return CONFIGURED_TIMEOUT;
}
if (RetryUtils.isThrottlingException(sdkError)) {
return THROTTLING;
}
if (e instanceof SdkServiceException) {
return SERVER_ERROR;
}
}
return OTHER;
}
}
| 1,885 |
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/signer/SigningMethod.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.signer;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public enum SigningMethod {
PROTOCOL_STREAMING_SIGNING_AUTH,
UNSIGNED_PAYLOAD,
PROTOCOL_BASED_UNSIGNED,
HEADER_BASED_AUTH;
} | 1,886 |
0 | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/pagination | Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/internal/pagination/async/ItemsSubscription.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pagination.async;
import java.util.Iterator;
import java.util.function.Function;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.pagination.async.PaginationSubscription;
/**
* An implementation of the {@link Subscription} interface that can be used to signal and cancel demand for
* paginated items across pages
*
* @param <ResponseT> The type of a single response page
* @param <ItemT> The type of paginated member in a response page
*/
@SdkInternalApi
public final class ItemsSubscription<ResponseT, ItemT> extends PaginationSubscription<ResponseT> {
private final Function<ResponseT, Iterator<ItemT>> getIteratorFunction;
private volatile Iterator<ItemT> singlePageItemsIterator;
private ItemsSubscription(BuilderImpl builder) {
super(builder);
this.getIteratorFunction = builder.iteratorFunction;
}
/**
* Create a builder for creating a {@link ItemsSubscription}.
*/
public static Builder builder() {
return new BuilderImpl();
}
@Override
protected void handleRequests() {
if (!hasMoreItems() && !hasNextPage()) {
completeSubscription();
return;
}
synchronized (this) {
if (outstandingRequests.get() <= 0) {
stopTask();
return;
}
}
if (!isTerminated()) {
/**
* Current page is null only the first time the method is called.
* Once initialized, current page will never be null
*/
if (currentPage == null || (!hasMoreItems() && hasNextPage())) {
fetchNextPage();
} else if (hasMoreItems()) {
sendNextElement();
// All valid cases are covered above. Throw an exception if any combination is missed
} else {
throw new IllegalStateException("Execution should have not reached here");
}
}
}
private void fetchNextPage() {
nextPageFetcher.nextPage(currentPage)
.whenComplete(((response, error) -> {
if (response != null) {
currentPage = response;
singlePageItemsIterator = getIteratorFunction.apply(response);
sendNextElement();
}
if (error != null) {
subscriber.onError(error);
cleanup();
}
}));
}
/**
* Calls onNext and calls the recursive method.
*/
private void sendNextElement() {
if (singlePageItemsIterator.hasNext()) {
subscriber.onNext(singlePageItemsIterator.next());
outstandingRequests.getAndDecrement();
}
handleRequests();
}
private boolean hasMoreItems() {
return singlePageItemsIterator != null && singlePageItemsIterator.hasNext();
}
public interface Builder extends PaginationSubscription.Builder<ItemsSubscription, Builder> {
Builder iteratorFunction(Function iteratorFunction);
@Override
ItemsSubscription build();
}
private static final class BuilderImpl extends PaginationSubscription.BuilderImpl<ItemsSubscription, Builder>
implements Builder {
private Function iteratorFunction;
@Override
public Builder iteratorFunction(Function iteratorFunction) {
this.iteratorFunction = iteratorFunction;
return this;
}
@Override
public ItemsSubscription build() {
return new ItemsSubscription(this);
}
}
}
| 1,887 |
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/retry/ClockSkewAdjuster.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry;
import java.time.Duration;
import java.time.Instant;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.internal.http.HttpClientDependencies;
import software.amazon.awssdk.core.retry.ClockSkew;
import software.amazon.awssdk.core.retry.RetryUtils;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.utils.Logger;
/**
* Suggests a clock skew adjustment that should be applied to future requests.
*/
@ThreadSafe
@SdkInternalApi
public final class ClockSkewAdjuster {
private static final Logger log = Logger.loggerFor(ClockSkewAdjuster.class);
/**
* Returns true if the clock should be adjusted for future requests.
*/
public boolean shouldAdjust(SdkException exception) {
return RetryUtils.isClockSkewException(exception);
}
/**
* Returns the recommended clock adjustment that should be used for future requests (in seconds). The result has the same
* semantics of {@link HttpClientDependencies#timeOffset()}. Positive values imply the client clock is "fast" and negative
* values imply the client clock is "slow".
*/
public Integer getAdjustmentInSeconds(SdkHttpResponse response) {
Instant now = Instant.now();
Instant serverTime = ClockSkew.getServerTime(response).orElse(null);
Duration skew = ClockSkew.getClockSkew(now, serverTime);
try {
return Math.toIntExact(skew.getSeconds());
} catch (ArithmeticException e) {
log.warn(() -> "The clock skew between the client and server was too large to be compensated for (" + now +
" versus " + serverTime + ").");
return 0;
}
}
} | 1,888 |
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/retry/RateLimitingTokenBucket.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry;
import java.util.OptionalDouble;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.core.exception.SdkClientException;
@SdkInternalApi
public class RateLimitingTokenBucket {
private static final double MIN_FILL_RATE = 0.5;
private static final double MIN_CAPACITY = 1.0;
private static final double SMOOTH = 0.8;
private static final double BETA = 0.7;
private static final double SCALE_CONSTANT = 0.4;
private final Clock clock;
private Double fillRate;
private Double maxCapacity;
private double currentCapacity;
private Double lastTimestamp;
private boolean enabled;
private double measuredTxRate;
private double lastTxRateBucket;
private long requestCount;
private double lastMaxRate;
private double lastThrottleTime;
private double timeWindow;
public interface Clock {
double time();
}
public RateLimitingTokenBucket() {
clock = new DefaultClock();
initialize();
}
@SdkTestInternalApi
RateLimitingTokenBucket(Clock clock) {
this.clock = clock;
initialize();
}
/**
*
* Acquire tokens from the bucket. If the bucket contains enough capacity
* to satisfy the request, this method will return immediately, otherwise
* the method will block the calling thread until enough tokens are refilled.
* <p>
* <pre>
* _TokenBucketAcquire(amount)
* # Client side throttling is not enabled until we see a throttling error.
* if not enabled
* return
*
* _TokenBucketRefill()
* # Next see if we have enough capacity for the requested amount.
* if amount <= current_capacity
* current_capacity = current_capacity - amount
* else
* sleep((amount - current_capacity) / fill_rate)
* current_capacity = current_capacity - amount
* return
* </pre>
* <p>
* This is equivalent to {@code acquire(amount, false)}.
*
* @param amount The amount of tokens to acquire.
*
* @return Whether the amount was successfully acquired.
*/
public boolean acquire(double amount) {
return acquire(amount, false);
}
/**
*
* Acquire tokens from the bucket. If the bucket contains enough capacity
* to satisfy the request, this method will return immediately. Otherwise,
* the behavior depends on the value of {@code fastFail}. If it is {@code
* true}, then it will return {@code false} immediately, signaling that
* enough capacity could not be acquired. Otherwise if {@code fastFail} is
* {@code false}, then it will wait the required amount of time to fill the
* bucket with enough tokens to satisfy {@code amount}.
* <pre>
* _TokenBucketAcquire(amount)
* # Client side throttling is not enabled until we see a throttling error.
* if not enabled
* return
*
* _TokenBucketRefill()
* # Next see if we have enough capacity for the requested amount.
* if amount <= current_capacity
* current_capacity = current_capacity - amount
* else
* sleep((amount - current_capacity) / fill_rate)
* current_capacity = current_capacity - amount
* return
* </pre>
*
* @param amount The amount of tokens to acquire.
* @param fastFail Whether this method should return immediately instead
* of waiting if {@code amount} exceeds the current
* capacity.
*
* @return Whether the amount was successfully acquired.
*/
public boolean acquire(double amount, boolean fastFail) {
OptionalDouble waitTime = acquireNonBlocking(amount, fastFail);
if (!waitTime.isPresent()) {
return false;
}
double t = waitTime.getAsDouble();
if (t > 0.0) {
sleep(t);
}
return true;
}
/**
* Acquire capacity from the rate limiter without blocking the call.
* <p>
* This method returns an {@code OptionalDouble} whose value, or its absence correspond to the following states:
* <ul>
* <li>Empty - If the value is not present, then the call fast failed, and no capacity was acquired.</li>
* <li>Present - if the value is present, then the value is the time in seconds that caller must wait before
* executing the request to be within the rate imposed by the rate limiter./li>
* </ul>
*
* @return The amount of time in seconds to wait before proceeding.
*/
public OptionalDouble acquireNonBlocking(double amount, boolean fastFail) {
double waitTime = 0.0;
synchronized (this) {
// If rate limiting is not enabled, we technically have an uncapped limit
if (!enabled) {
return OptionalDouble.of(0.0);
}
refill();
double originalCapacity = currentCapacity;
double unfulfilled = tryAcquireCapacity(amount);
if (unfulfilled > 0.0 && fastFail) {
currentCapacity = originalCapacity;
return OptionalDouble.empty();
}
// If all the tokens couldn't be acquired immediately, wait enough
// time to fill the remainder.
if (unfulfilled > 0) {
waitTime = unfulfilled / fillRate;
}
}
return OptionalDouble.of(waitTime);
}
/**
*
* @param amount The amount of capacity to acquire from the bucket.
* @return The unfulfilled amount.
*/
double tryAcquireCapacity(double amount) {
double result;
if (amount <= currentCapacity) {
result = 0;
} else {
result = amount - currentCapacity;
}
currentCapacity = currentCapacity - amount;
return result;
}
private void initialize() {
fillRate = null;
maxCapacity = null;
currentCapacity = 0.0;
lastTimestamp = null;
enabled = false;
measuredTxRate = 0.0;
lastTxRateBucket = Math.floor(clock.time());
requestCount = 0;
lastMaxRate = 0.0;
lastThrottleTime = clock.time();
}
/**
* <pre>
* _TokenBucketRefill()
* timestamp = time()
* if last_timestamp is unset
* last_timestamp = timestamp
* return
* fill_amount = (timestamp - last_timestamp) * fill_rate
* current_capacity = min(max_capacity, current_capacity + fill_amount)
* last_timestamp = timestamp
* </pre>
*/
// Package private for testing
synchronized void refill() {
double timestamp = clock.time();
if (lastTimestamp == null) {
lastTimestamp = timestamp;
return;
}
double fillAmount = (timestamp - lastTimestamp) * fillRate;
currentCapacity = Math.min(maxCapacity, currentCapacity + fillAmount);
lastTimestamp = timestamp;
}
/**
* <pre>
* _TokenBucketUpdateRate(new_rps)
* # Refill based on our current rate before we update to the new fill rate.
* _TokenBucketRefill()
* fill_rate = max(new_rps, MIN_FILL_RATE)
* max_capacity = max(new_rps, MIN_CAPACITY)
* # When we scale down we can't have a current capacity that exceeds our
* # max_capacity.
* current_capacity = min(current_capacity, max_capacity)
* </pre>
*/
private synchronized void updateRate(double newRps) {
refill();
fillRate = Math.max(newRps, MIN_FILL_RATE);
maxCapacity = Math.max(newRps, MIN_CAPACITY);
currentCapacity = Math.min(currentCapacity, maxCapacity);
}
/**
* <pre>
* t = time()
* time_bucket = floor(t * 2) / 2
* request_count = request_count + 1
* if time_bucket > last_tx_rate_bucket
* current_rate = request_count / (time_bucket - last_tx_rate_bucket)
* measured_tx_rate = (current_rate * SMOOTH) + (measured_tx_rate * (1 - SMOOTH))
* request_count = 0
* last_tx_rate_bucket = time_bucket
* </pre>
*/
private synchronized void updateMeasuredRate() {
double t = clock.time();
double timeBucket = Math.floor(t * 2) / 2;
requestCount = requestCount + 1;
if (timeBucket > lastTxRateBucket) {
double currentRate = requestCount / (timeBucket - lastTxRateBucket);
measuredTxRate = (currentRate * SMOOTH) + (measuredTxRate * (1 - SMOOTH));
requestCount = 0;
lastTxRateBucket = timeBucket;
}
}
synchronized void enable() {
enabled = true;
}
/**
* <pre>
* _UpdateClientSendingRate(response)
* _UpdateMeasuredRate()
*
* if IsThrottlingError(response)
* if not enabled
* rate_to_use = measured_tx_rate
* else
* rate_to_use = min(measured_tx_rate, fill_rate)
*
* # The fill_rate is from the token bucket.
* last_max_rate = rate_to_use
* _CalculateTimeWindow()
* last_throttle_time = time()
* calculated_rate = _CUBICThrottle(rate_to_use)
* TokenBucketEnable()
* else
* _CalculateTimeWindow()
* calculated_rate = _CUBICSuccess(time())
*
* new_rate = min(calculated_rate, 2 * measured_tx_rate)
* _TokenBucketUpdateRate(new_rate)
* </pre>
*/
public synchronized void updateClientSendingRate(boolean throttlingResponse) {
updateMeasuredRate();
double calculatedRate;
if (throttlingResponse) {
double rateToUse;
if (!enabled) {
rateToUse = measuredTxRate;
} else {
rateToUse = Math.min(measuredTxRate, fillRate);
}
lastMaxRate = rateToUse;
calculateTimeWindow();
lastThrottleTime = clock.time();
calculatedRate = cubicThrottle(rateToUse);
enable();
} else {
calculateTimeWindow();
calculatedRate = cubicSuccess(clock.time());
}
double newRate = Math.min(calculatedRate, 2 * measuredTxRate);
updateRate(newRate);
}
/**
* <pre>
* _CalculateTimeWindow()
* # This is broken out into a separate calculation because it only
* # gets updated when last_max_rate change so it can be cached.
* _time_window = ((last_max_rate * (1 - BETA)) / SCALE_CONSTANT) ^ (1 / 3)
* </pre>
*/
// Package private for testing
synchronized void calculateTimeWindow() {
timeWindow = Math.pow((lastMaxRate * (1 - BETA)) / SCALE_CONSTANT, 1.0 / 3);
}
/**
* Sleep for a given amount of seconds.
*
* @param seconds The amount of time to sleep in seconds.
*/
void sleep(double seconds) {
long millisToSleep = (long) (seconds * 1000);
try {
Thread.sleep(millisToSleep);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw SdkClientException.create("Sleep interrupted", ie);
}
}
/**
* <pre>
* _CUBICThrottle(rate_to_use)
* calculated_rate = rate_to_use * BETA
* return calculated_rate
* </pre>
*/
// Package private for testing
double cubicThrottle(double rateToUse) {
double calculatedRate = rateToUse * BETA;
return calculatedRate;
}
/**
* <pre>
* _CUBICSuccess(timestamp)
* dt = timestamp - last_throttle_time
* calculated_rate = (SCALE_CONSTANT * ((dt - _time_window) ^ 3)) + last_max_rate
* return calculated_rate
* </pre>
*/
// Package private for testing
synchronized double cubicSuccess(double timestamp) {
double dt = timestamp - lastThrottleTime;
double calculatedRate = SCALE_CONSTANT * Math.pow(dt - timeWindow, 3) + lastMaxRate;
return calculatedRate;
}
static class DefaultClock implements Clock {
@Override
public double time() {
long timeMillis = System.nanoTime();
return timeMillis / 1000000000.;
}
}
@SdkTestInternalApi
synchronized void setLastMaxRate(double lastMaxRate) {
this.lastMaxRate = lastMaxRate;
}
@SdkTestInternalApi
synchronized void setLastThrottleTime(double lastThrottleTime) {
this.lastThrottleTime = lastThrottleTime;
}
@SdkTestInternalApi
synchronized double getMeasuredTxRate() {
return measuredTxRate;
}
@SdkTestInternalApi
synchronized double getFillRate() {
return fillRate;
}
@SdkTestInternalApi
synchronized void setCurrentCapacity(double currentCapacity) {
this.currentCapacity = currentCapacity;
}
@SdkTestInternalApi
synchronized double getCurrentCapacity() {
return currentCapacity;
}
@SdkTestInternalApi
synchronized void setFillRate(double fillRate) {
this.fillRate = fillRate;
}
}
| 1,889 |
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/retry/DefaultTokenBucketExceptionCostFunction.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.retry.RetryUtils;
import software.amazon.awssdk.core.retry.conditions.TokenBucketExceptionCostFunction;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public class DefaultTokenBucketExceptionCostFunction implements TokenBucketExceptionCostFunction {
private final Integer throttlingExceptionCost;
private final int defaultExceptionCost;
private DefaultTokenBucketExceptionCostFunction(Builder builder) {
this.throttlingExceptionCost = builder.throttlingExceptionCost;
this.defaultExceptionCost = Validate.paramNotNull(builder.defaultExceptionCost, "defaultExceptionCost");
}
@Override
public Integer apply(SdkException e) {
if (throttlingExceptionCost != null && RetryUtils.isThrottlingException(e)) {
return throttlingExceptionCost;
}
return defaultExceptionCost;
}
@Override
public String toString() {
return ToString.builder("TokenBucketExceptionCostCalculator")
.add("throttlingExceptionCost", throttlingExceptionCost)
.add("defaultExceptionCost", defaultExceptionCost)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultTokenBucketExceptionCostFunction that = (DefaultTokenBucketExceptionCostFunction) o;
if (defaultExceptionCost != that.defaultExceptionCost) {
return false;
}
return throttlingExceptionCost != null ?
throttlingExceptionCost.equals(that.throttlingExceptionCost) :
that.throttlingExceptionCost == null;
}
@Override
public int hashCode() {
int result = throttlingExceptionCost != null ? throttlingExceptionCost.hashCode() : 0;
result = 31 * result + defaultExceptionCost;
return result;
}
public static final class Builder implements TokenBucketExceptionCostFunction.Builder {
private Integer throttlingExceptionCost;
private Integer defaultExceptionCost;
@Override
public TokenBucketExceptionCostFunction.Builder throttlingExceptionCost(int cost) {
this.throttlingExceptionCost = cost;
return this;
}
@Override
public TokenBucketExceptionCostFunction.Builder defaultExceptionCost(int cost) {
this.defaultExceptionCost = cost;
return this;
}
@Override
public TokenBucketExceptionCostFunction build() {
return new DefaultTokenBucketExceptionCostFunction(this);
}
}
}
| 1,890 |
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/retry/SdkDefaultRetrySetting.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.retry;
import static java.util.Collections.unmodifiableSet;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.util.HashSet;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException;
import software.amazon.awssdk.core.exception.RetryableException;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.conditions.TokenBucketExceptionCostFunction;
import software.amazon.awssdk.http.HttpStatusCode;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class SdkDefaultRetrySetting {
public static final class Legacy {
private static final int MAX_ATTEMPTS = 4;
private static final Duration BASE_DELAY = Duration.ofMillis(100);
private static final Duration THROTTLED_BASE_DELAY = Duration.ofMillis(500);
private static final int THROTTLE_EXCEPTION_TOKEN_COST = 0;
private static final int DEFAULT_EXCEPTION_TOKEN_COST = 5;
public static final TokenBucketExceptionCostFunction COST_FUNCTION =
TokenBucketExceptionCostFunction.builder()
.throttlingExceptionCost(THROTTLE_EXCEPTION_TOKEN_COST)
.defaultExceptionCost(DEFAULT_EXCEPTION_TOKEN_COST)
.build();
}
public static final class Standard {
private static final int MAX_ATTEMPTS = 3;
private static final Duration BASE_DELAY = Duration.ofMillis(100);
private static final Duration THROTTLED_BASE_DELAY = Duration.ofSeconds(1);
private static final int THROTTLE_EXCEPTION_TOKEN_COST = 5;
private static final int DEFAULT_EXCEPTION_TOKEN_COST = 5;
public static final TokenBucketExceptionCostFunction COST_FUNCTION =
TokenBucketExceptionCostFunction.builder()
.throttlingExceptionCost(THROTTLE_EXCEPTION_TOKEN_COST)
.defaultExceptionCost(DEFAULT_EXCEPTION_TOKEN_COST)
.build();
}
public static final int TOKEN_BUCKET_SIZE = 500;
public static final Duration MAX_BACKOFF = Duration.ofSeconds(20);
public static final Set<Integer> RETRYABLE_STATUS_CODES;
public static final Set<Class<? extends Exception>> RETRYABLE_EXCEPTIONS;
static {
Set<Integer> retryableStatusCodes = new HashSet<>();
retryableStatusCodes.add(HttpStatusCode.INTERNAL_SERVER_ERROR);
retryableStatusCodes.add(HttpStatusCode.BAD_GATEWAY);
retryableStatusCodes.add(HttpStatusCode.SERVICE_UNAVAILABLE);
retryableStatusCodes.add(HttpStatusCode.GATEWAY_TIMEOUT);
RETRYABLE_STATUS_CODES = unmodifiableSet(retryableStatusCodes);
Set<Class<? extends Exception>> retryableExceptions = new HashSet<>();
retryableExceptions.add(RetryableException.class);
retryableExceptions.add(IOException.class);
retryableExceptions.add(UncheckedIOException.class);
retryableExceptions.add(ApiCallAttemptTimeoutException.class);
RETRYABLE_EXCEPTIONS = unmodifiableSet(retryableExceptions);
}
private SdkDefaultRetrySetting() {
}
public static Integer maxAttempts(RetryMode retryMode) {
Integer maxAttempts = SdkSystemSetting.AWS_MAX_ATTEMPTS.getIntegerValue().orElse(null);
if (maxAttempts == null) {
switch (retryMode) {
case LEGACY:
maxAttempts = Legacy.MAX_ATTEMPTS;
break;
case ADAPTIVE:
case STANDARD:
maxAttempts = Standard.MAX_ATTEMPTS;
break;
default:
throw new IllegalStateException("Unsupported RetryMode: " + retryMode);
}
}
Validate.isPositive(maxAttempts, "Maximum attempts must be positive, but was " + maxAttempts);
return maxAttempts;
}
public static TokenBucketExceptionCostFunction tokenCostFunction(RetryMode retryMode) {
switch (retryMode) {
case LEGACY:
return Legacy.COST_FUNCTION;
case ADAPTIVE:
case STANDARD:
return Standard.COST_FUNCTION;
default:
throw new IllegalStateException("Unsupported RetryMode: " + retryMode);
}
}
public static Integer defaultMaxAttempts() {
return maxAttempts(RetryMode.defaultRetryMode());
}
public static Duration baseDelay(RetryMode retryMode) {
switch (retryMode) {
case LEGACY:
return Legacy.BASE_DELAY;
case ADAPTIVE:
case STANDARD:
return Standard.BASE_DELAY;
default:
throw new IllegalStateException("Unsupported RetryMode: " + retryMode);
}
}
public static Duration throttledBaseDelay(RetryMode retryMode) {
switch (retryMode) {
case LEGACY:
return Legacy.THROTTLED_BASE_DELAY;
case ADAPTIVE:
case STANDARD:
return Standard.THROTTLED_BASE_DELAY;
default:
throw new IllegalStateException("Unsupported RetryMode: " + retryMode);
}
}
}
| 1,891 |
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/util/ClassLoaderHelper.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public final class ClassLoaderHelper {
private ClassLoaderHelper() {
}
private static Class<?> loadClassViaClasses(String fqcn, Class<?>[] classes) {
if (classes == null) {
return null;
}
for (Class<?> clzz: classes) {
if (clzz == null) {
continue;
}
ClassLoader loader = clzz.getClassLoader();
if (loader != null) {
try {
return loader.loadClass(fqcn);
} catch (ClassNotFoundException e) {
// move on to try the next class loader
}
}
}
return null;
}
private static Class<?> loadClassViaContext(String fqcn) {
ClassLoader loader = contextClassLoader();
try {
return loader == null ? null : loader.loadClass(fqcn);
} catch (ClassNotFoundException e) {
// Ignored.
}
return null;
}
/**
* Loads the class via the optionally specified classes in the order of
* their specification, and if not found, via the context class loader of
* the current thread, and if not found, from the caller class loader as the
* last resort.
*
* @param fqcn
* fully qualified class name of the target class to be loaded
* @param classes
* class loader providers
* @return the class loaded; never null
*
* @throws ClassNotFoundException
* if failed to load the class
*/
public static Class<?> loadClass(String fqcn, Class<?>... classes) throws ClassNotFoundException {
return loadClass(fqcn, true, classes);
}
/**
* If classesFirst is false, loads the class via the context class
* loader of the current thread, and if not found, via the class loaders of
* the optionally specified classes in the order of their specification, and
* if not found, from the caller class loader as the
* last resort.
* <p>
* If classesFirst is true, loads the class via the optionally
* specified classes in the order of their specification, and if not found,
* via the context class loader of the current thread, and if not found,
* from the caller class loader as the last resort.
*
* @param fqcn
* fully qualified class name of the target class to be loaded
* @param classesFirst
* true if the class loaders of the optionally specified classes
* take precedence over the context class loader of the current
* thread; false if the opposite is true.
* @param classes
* class loader providers
* @return the class loaded; never null
*
* @throws ClassNotFoundException if failed to load the class
*/
public static Class<?> loadClass(String fqcn, boolean classesFirst,
Class<?>... classes) throws ClassNotFoundException {
Class<?> target = null;
if (classesFirst) {
target = loadClassViaClasses(fqcn, classes);
if (target == null) {
target = loadClassViaContext(fqcn);
}
} else {
target = loadClassViaContext(fqcn);
if (target == null) {
target = loadClassViaClasses(fqcn, classes);
}
}
return target == null ? Class.forName(fqcn) : target;
}
/**
* Attempt to get the current thread's class loader and fallback to the system classloader if null
* @return a {@link ClassLoader} or null if none found
*/
private static ClassLoader contextClassLoader() {
ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();
if (threadClassLoader != null) {
return threadClassLoader;
}
return ClassLoader.getSystemClassLoader();
}
/**
* Attempt to get class loader that loads the classes and fallback to the thread context classloader if null.
*
* @param classes the classes
* @return a {@link ClassLoader} or null if none found
*/
public static ClassLoader classLoader(Class<?>... classes) {
if (classes != null) {
for (Class clzz : classes) {
ClassLoader classLoader = clzz.getClassLoader();
if (classLoader != null) {
return classLoader;
}
}
}
return contextClassLoader();
}
}
| 1,892 |
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/util/FakeIoException.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import java.io.IOException;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Used for simulating an IOException for test purposes.
*/
@SdkInternalApi
public class FakeIoException extends IOException {
private static final long serialVersionUID = 1L;
public FakeIoException(String message) {
super(message);
}
}
| 1,893 |
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/util/CapacityManager.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Manages capacity of a finite resource. Capacity can be acquired and
* released.
*/
@SdkInternalApi
public class CapacityManager {
private final int maxCapacity;
private final Object lock = new Object();
private volatile int availableCapacity;
/**
* Creates a CapacityManager.
*
* @param maxCapacity maximum capacity of this resource.
* available capacity will initially be set to this value.
* if a negative value is provided the capacity manager will operate in a no-op
* passthrough mode in which all acquire calls will return true.
*/
public CapacityManager(final int maxCapacity) {
this.maxCapacity = maxCapacity;
this.availableCapacity = maxCapacity;
}
/**
* Attempts to acquire a single capacity unit.
* If acquired, capacity will be consumed from the available pool.
* @return true if capacity can be acquired, false if not
*/
public boolean acquire() {
return acquire(1);
}
/**
* Attempts to acquire a given amount of capacity.
* If acquired, capacity will be consumed from the available pool.
*
* @param capacity capacity to acquire
* @return true if capacity can be acquired, false if not
* @throws IllegalArgumentException if given capacity is negative
*/
public boolean acquire(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("capacity to acquire cannot be negative");
}
if (availableCapacity < 0) {
return true;
}
synchronized (lock) {
if (availableCapacity - capacity >= 0) {
availableCapacity -= capacity;
return true;
} else {
return false;
}
}
}
/**
* Releases a single unit of capacity back to the pool, making it available
* to consumers.
*/
public void release() {
release(1);
}
/**
* Releases a given amount of capacity back to the pool, making it available
* to consumers.
*
* @param capacity capacity to release
* @throws IllegalArgumentException if given capacity is negative
*/
public void release(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("capacity to release cannot be negative");
}
// in the common 'good' case where we have our full capacity available we can
// short circuit going any further and avoid unnecessary locking.
if (availableCapacity >= 0 && availableCapacity != maxCapacity) {
synchronized (lock) {
availableCapacity = Math.min((availableCapacity + capacity), maxCapacity);
}
}
}
/**
* Returns the currently consumed capacity.
*
* @return consumed capacity
*/
public int consumedCapacity() {
return (availableCapacity < 0) ? 0 : (maxCapacity - availableCapacity);
}
/**
* Returns the currently available capacity.
*
* @return available capacity
*/
public int availableCapacity() {
return availableCapacity;
}
}
| 1,894 |
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/util/Crc32ChecksumValidatingInputStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import java.io.IOException;
import java.io.InputStream;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.exception.Crc32MismatchException;
import software.amazon.awssdk.core.io.SdkFilterInputStream;
/**
* Wraps the provided input stream with a {@link Crc32ChecksumCalculatingInputStream} and after the stream is closed
* will validate the calculated checksum against the actual checksum.
*/
@SdkInternalApi
public class Crc32ChecksumValidatingInputStream extends SdkFilterInputStream {
private final long expectedChecksum;
/**
* @param in Input stream to content.
* @param expectedChecksum Expected CRC32 checksum returned by the service.
*/
public Crc32ChecksumValidatingInputStream(InputStream in, long expectedChecksum) {
super(new Crc32ChecksumCalculatingInputStream(in));
this.expectedChecksum = expectedChecksum;
}
/**
* Closes the underlying stream and validates the calculated checksum against the expected.
*
* @throws Crc32MismatchException If the calculated CRC32 checksum does not match the expected.
*/
@Override
public void close() throws IOException {
try {
validateChecksum();
} finally {
super.close();
}
}
private void validateChecksum() throws Crc32MismatchException {
long actualChecksum = ((Crc32ChecksumCalculatingInputStream) in).getCrc32Checksum();
if (expectedChecksum != actualChecksum) {
throw Crc32MismatchException.builder()
.message(String.format("Expected %d as the Crc32 checksum but the actual " +
"calculated checksum was %d", expectedChecksum, actualChecksum))
.build();
}
}
}
| 1,895 |
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/util/UnreliableFilterInputStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.ToString;
/**
* An internal class used solely for the purpose of testing via failure
* injection.
*/
@SdkInternalApi
public class UnreliableFilterInputStream extends FilterInputStream {
// True to throw a FakeIOException; false to throw a RuntimeException
private final boolean isFakeIoException;
/**
* Max number of errors that can be triggered.
*/
private int maxNumErrors = 1;
/**
* Current number of errors that have been triggered.
*/
private int currNumErrors;
private int bytesReadBeforeException = 100;
private int marked;
private int position;
private int resetCount; // number of times the reset method has been called
/**
* used to control whether an exception would be thrown based on the reset
* recurrence; not applicable if set to zero. For example, if
* resetIntervalBeforeException == n, the exception can only be thrown
* before the n_th reset (or after the n_th minus 1 reset), 2n_th reset (or
* after the 2n_th minus 1) reset), etc.
*/
private int resetIntervalBeforeException;
public UnreliableFilterInputStream(InputStream in, boolean isFakeIoException) {
super(in);
this.isFakeIoException = isFakeIoException;
}
@Override
public int read() throws IOException {
int read = super.read();
if (read != -1) {
position++;
}
triggerError();
return read;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
triggerError();
int read = super.read(b, off, len);
position += read;
triggerError();
return read;
}
@Override
public void mark(int readlimit) {
super.mark(readlimit);
marked = position;
}
@Override
public void reset() throws IOException {
resetCount++;
super.reset();
position = marked;
}
private void triggerError() throws FakeIoException {
if (currNumErrors >= maxNumErrors) {
return;
}
if (position >= bytesReadBeforeException) {
if (resetIntervalBeforeException > 0
&& resetCount % resetIntervalBeforeException != (resetIntervalBeforeException - 1)) {
return;
}
currNumErrors++;
if (isFakeIoException) {
throw new FakeIoException("Fake IO error " + currNumErrors
+ " on UnreliableFileInputStream: " + this);
} else {
throw new RuntimeException("Injected runtime error " + currNumErrors
+ " on UnreliableFileInputStream: " + this);
}
}
}
public int getCurrNumErrors() {
return currNumErrors;
}
public int getMaxNumErrors() {
return maxNumErrors;
}
public UnreliableFilterInputStream withMaxNumErrors(int maxNumErrors) {
this.maxNumErrors = maxNumErrors;
return this;
}
public UnreliableFilterInputStream withBytesReadBeforeException(
int bytesReadBeforeException) {
this.bytesReadBeforeException = bytesReadBeforeException;
return this;
}
public int getBytesReadBeforeException() {
return bytesReadBeforeException;
}
/**
* @param resetIntervalBeforeException
* used to control whether an exception would be thrown based on
* the reset recurrence; not applicable if set to zero. For
* example, if resetIntervalBeforeException == n, the exception
* can only be thrown before the n_th reset (or after the n_th
* minus 1 reset), 2n_th reset (or after the 2n_th minus 1)
* reset), etc.
*/
public UnreliableFilterInputStream withResetIntervalBeforeException(
int resetIntervalBeforeException) {
this.resetIntervalBeforeException = resetIntervalBeforeException;
return this;
}
public int getResetIntervalBeforeException() {
return resetIntervalBeforeException;
}
public int getMarked() {
return marked;
}
public int getPosition() {
return position;
}
public boolean isFakeIoException() {
return isFakeIoException;
}
public int getResetCount() {
return resetCount;
}
@Override
public String toString() {
return ToString.builder("UnreliableFilterInputStream")
.add("isFakeIoException", isFakeIoException)
.add("maxNumErrors", maxNumErrors)
.add("currNumErrors", currNumErrors)
.add("bytesReadBeforeException", bytesReadBeforeException)
.add("marked", marked)
.add("position", position)
.add("resetCount", resetCount)
.add("resetIntervalBeforeException", resetIntervalBeforeException)
.toString();
}
}
| 1,896 |
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/util/ChunkContentUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.exception.SdkClientException;
@SdkInternalApi
public final class ChunkContentUtils {
public static final String HEADER_COLON_SEPARATOR = ":";
public static final String ZERO_BYTE = "0";
public static final String CRLF = "\r\n";
public static final String LAST_CHUNK = ZERO_BYTE + CRLF;
public static final long LAST_CHUNK_LEN = LAST_CHUNK.length();
private ChunkContentUtils() {
}
/**
* The chunk format is: chunk-size CRLF chunk-data CRLF.
*
* @param originalContentLength Original Content length.
* @return the length of this chunk
*/
public static long calculateChunkLength(long originalContentLength) {
if (originalContentLength == 0) {
return 0;
}
return Long.toHexString(originalContentLength).length()
+ CRLF.length()
+ originalContentLength
+ CRLF.length();
}
/**
* Calculates the content length for data that is divided into chunks.
*
* @param originalLength original content length.
* @param chunkSize chunk size
* @return Content length of the trailer that will be appended at the end.
*/
public static long calculateStreamContentLength(long originalLength, long chunkSize) {
if (originalLength < 0 || chunkSize == 0) {
throw new IllegalArgumentException(originalLength + ", " + chunkSize + "Args <= 0 not expected");
}
long maxSizeChunks = originalLength / chunkSize;
long remainingBytes = originalLength % chunkSize;
long allChunks = maxSizeChunks * calculateChunkLength(chunkSize);
long remainingInChunk = remainingBytes > 0 ? calculateChunkLength(remainingBytes) : 0;
// last byte is composed of a "0" and "\r\n"
long lastByteSize = 1 + (long) CRLF.length();
return allChunks + remainingInChunk + lastByteSize;
}
/**
* Calculates the content length for a given algorithm and header name.
*
* @param algorithm Algorithm used.
* @param headerName Header name.
* @return Content length of the trailer that will be appended at the end.
*/
public static long calculateChecksumTrailerLength(Algorithm algorithm, String headerName) {
return headerName.length()
+ HEADER_COLON_SEPARATOR.length()
+ algorithm.base64EncodedLength().longValue()
+ CRLF.length()
+ CRLF.length();
}
/**
* Creates Chunk encoded checksum trailer for a computedChecksum which is in Base64 encoded.
* @param computedChecksum Base64 encoded computed checksum.
* @param trailerHeader Header for the checksum data in the trailer.
* @return Chunk encoded checksum trailer with given header.
*/
public static ByteBuffer createChecksumTrailer(String computedChecksum, String trailerHeader) {
StringBuilder headerBuilder = new StringBuilder(trailerHeader)
.append(HEADER_COLON_SEPARATOR)
.append(computedChecksum)
.append(CRLF)
.append(CRLF);
return ByteBuffer.wrap(headerBuilder.toString().getBytes(StandardCharsets.UTF_8));
}
/**
* Creates ChunkEncoded data for an given chunk data.
* @param chunkData chunk data that needs to be converted to chunk encoded format.
* @param isLastByte if true then additional CRLF will not be appended.
* @return Chunk encoded format of a given data.
*/
public static ByteBuffer createChunk(ByteBuffer chunkData, boolean isLastByte) {
int chunkLength = chunkData.remaining();
StringBuilder chunkHeader = new StringBuilder(Integer.toHexString(chunkLength));
chunkHeader.append(CRLF);
try {
byte[] header = chunkHeader.toString().getBytes(StandardCharsets.UTF_8);
byte[] trailer = !isLastByte ? CRLF.getBytes(StandardCharsets.UTF_8)
: "".getBytes(StandardCharsets.UTF_8);
ByteBuffer chunkFormattedBuffer = ByteBuffer.allocate(header.length + chunkLength + trailer.length);
chunkFormattedBuffer.put(header).put(chunkData).put(trailer);
chunkFormattedBuffer.flip();
return chunkFormattedBuffer;
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to create chunked data. " + e.getMessage())
.cause(e)
.build();
}
}
} | 1,897 |
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/util/Crc32ChecksumCalculatingInputStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.io.SdkFilterInputStream;
/**
* Simple InputStream wrapper that examines the wrapped stream's contents as
* they are read and calculates and CRC32 checksum.
*/
@SdkInternalApi
public class Crc32ChecksumCalculatingInputStream extends SdkFilterInputStream {
/** The CRC32 being calculated by this input stream. */
private CRC32 crc32;
public Crc32ChecksumCalculatingInputStream(InputStream in) {
super(in);
crc32 = new CRC32();
}
public long getCrc32Checksum() {
return crc32.getValue();
}
/**
* Resets the wrapped input stream and the CRC32 computation.
*
* @see java.io.InputStream#reset()
*/
@Override
public synchronized void reset() throws IOException {
abortIfNeeded();
crc32.reset();
in.reset();
}
/**
* @see java.io.InputStream#read()
*/
@Override
public int read() throws IOException {
abortIfNeeded();
int ch = in.read();
if (ch != -1) {
crc32.update(ch);
}
return ch;
}
/**
* @see java.io.InputStream#read(byte[], int, int)
*/
@Override
public int read(byte[] b, int off, int len) throws IOException {
abortIfNeeded();
int result = in.read(b, off, len);
if (result != -1) {
crc32.update(b, off, result);
}
return result;
}
}
| 1,898 |
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/util/ThrowableUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.util;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.exception.AbortedException;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkException;
/**
* Utility for use with errors or exceptions.
*/
@SdkInternalApi
public final class ThrowableUtils {
private ThrowableUtils() {
}
/**
* Returns the root cause of the given cause, or null if the given
* cause is null. If the root cause is over 1000 level deep, the
* original cause will be returned defensively as this is heuristically
* considered a circular reference, however unlikely.
*/
public static Throwable getRootCause(Throwable orig) {
if (orig == null) {
return orig;
}
Throwable t = orig;
// defend against (malicious?) circularity
for (int i = 0; i < 1000; i++) {
Throwable cause = t.getCause();
if (cause == null) {
return t;
}
t = cause;
}
// Too bad. Return the original exception.
LoggerFactory.getLogger(ThrowableUtils.class).debug("Possible circular reference detected on {}: [{}]",
orig.getClass(),
orig);
return orig;
}
/**
* Used to help perform common throw-up with minimal wrapping.
*/
public static RuntimeException failure(Throwable t) {
if (t instanceof RuntimeException) {
return (RuntimeException) t;
}
if (t instanceof Error) {
throw (Error) t;
}
return t instanceof InterruptedException
? AbortedException.builder().cause(t).build()
: SdkClientException.builder().cause(t).build();
}
/**
* Same as {@link #failure(Throwable)}, but the given errmsg will be used if
* it was wrapped as either an {@link SdkClientException} or
* {@link AbortedException}.
*/
public static RuntimeException failure(Throwable t, String errmsg) {
if (t instanceof RuntimeException) {
return (RuntimeException) t;
}
if (t instanceof Error) {
throw (Error) t;
}
return t instanceof InterruptedException
? AbortedException.builder().message(errmsg).cause(t).build()
: SdkClientException.builder().message(errmsg).cause(t).build();
}
/**
* Wraps the given {@code Throwable} in {@link SdkException} if necessary.
*/
public static SdkException asSdkException(Throwable t) {
if (t instanceof SdkException) {
return (SdkException) t;
}
return SdkClientException.builder().cause(t).build();
}
}
| 1,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.