index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
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(); } }
2,100
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> { }
2,101
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(); } }
2,102
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(); } }
2,103
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> { }
2,104
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; } }
2,105
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; } }
2,106
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; } }
2,107
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(); } }
2,108
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); } } }
2,109
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(); } }
2,110
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()); } }
2,111
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); } } } }
2,112
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 { }
2,113
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(); } }
2,114
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); } } } }
2,115
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); } } }
2,116
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(); } }
2,117
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); } } }
2,118
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); } }
2,119
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(); } } }
2,120
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); } } }
2,121
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); } } }
2,122
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); } } }
2,123
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"); } }
2,124
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; } }
2,125
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(); }
2,126
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"); } }
2,127
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)); } }
2,128
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() { } }
2,129
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); } } }
2,130
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); } }
2,131
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(); } }
2,132
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."); } } }
2,133
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()); } }
2,134
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<>(); } }
2,135
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; } }
2,136
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; } }
2,137
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); } } }
2,138
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); } } }
2,139
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); } } } }
2,140
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(); } } } }
2,141
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); } } } }
2,142
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); } } } }
2,143
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(); } } }
2,144
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; } }
2,145
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; } }
2,146
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; } }
2,147
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(); } } }
2,148
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); } }
2,149
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); } } }
2,150
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); }
2,151
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); } } }
2,152
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); } }
2,153
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() { } }
2,154
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(); } } } }
2,155
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; } }
2,156
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); } } }
2,157
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; } }
2,158
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; }
2,159
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); } } }
2,160
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; } } }
2,161
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 &lt;= 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 &lt;= 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; } }
2,162
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); } } }
2,163
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); } } }
2,164
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(); } }
2,165
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); } }
2,166
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; } }
2,167
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(); } } }
2,168
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(); } }
2,169
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(); } } }
2,170
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; } }
2,171
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(); } }
2,172
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/NoopSubscription.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; /** An implementation of {@link org.reactivestreams.Subscription} that does nothing. * <p> * Useful in situations where a {@link org.reactivestreams.Publisher} needs to * signal {@code exceptionOccurred} or {@code onComplete} immediately after * {@code subscribe()} but but it needs to signal{@code onSubscription} first. */ @SdkInternalApi public final class NoopSubscription implements Subscription { private final Subscriber<?> subscriber; public NoopSubscription(Subscriber<?> subscriber) { this.subscriber = subscriber; } @Override public void request(long l) { if (l < 1) { subscriber.onError(new IllegalArgumentException("Demand must be positive!")); } } @Override public void cancel() { } }
2,173
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/HttpChecksumResolver.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.util.ArrayList; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.interceptor.trait.HttpChecksum; /** * Class to resolve the different Checksums specs from ExecutionAttributes. */ @SdkInternalApi public final class HttpChecksumResolver { private HttpChecksumResolver() { } public static ChecksumSpecs getResolvedChecksumSpecs(ExecutionAttributes executionAttributes) { ChecksumSpecs checksumSpecs = executionAttributes.getAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS); if (checksumSpecs != null) { return checksumSpecs; } return resolveChecksumSpecs(executionAttributes); } public static ChecksumSpecs resolveChecksumSpecs(ExecutionAttributes executionAttributes) { HttpChecksum httpChecksumTraitInOperation = executionAttributes.getAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM); if (httpChecksumTraitInOperation == null) { return null; } boolean hasRequestValidation = hasRequestValidationMode(httpChecksumTraitInOperation); String requestAlgorithm = httpChecksumTraitInOperation.requestAlgorithm(); String checksumHeaderName = requestAlgorithm != null ? HttpChecksumUtils.httpChecksumHeader(requestAlgorithm) : null; List<Algorithm> responseValidationAlgorithms = getResponseValidationAlgorithms(httpChecksumTraitInOperation); return ChecksumSpecs.builder() .algorithm(Algorithm.fromValue(httpChecksumTraitInOperation.requestAlgorithm())) .headerName(checksumHeaderName) .responseValidationAlgorithms(responseValidationAlgorithms) .isValidationEnabled(hasRequestValidation) .isRequestChecksumRequired(httpChecksumTraitInOperation.isRequestChecksumRequired()) .isRequestStreaming(httpChecksumTraitInOperation.isRequestStreaming()) .build(); } private static boolean hasRequestValidationMode(HttpChecksum httpChecksum) { return httpChecksum.requestValidationMode() != null; } private static List<Algorithm> getResponseValidationAlgorithms(HttpChecksum httpChecksumTraitInOperation) { List<String> responseAlgorithms = httpChecksumTraitInOperation.responseAlgorithms(); if (responseAlgorithms != null && !responseAlgorithms.isEmpty()) { List<Algorithm> responseValidationAlgorithms = new ArrayList<>(responseAlgorithms.size()); for (String algorithmName : responseAlgorithms) { responseValidationAlgorithms.add(Algorithm.fromValue(algorithmName)); } return responseValidationAlgorithms; } return null; } }
2,174
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/HttpChecksumUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 static software.amazon.awssdk.core.HttpChecksumConstant.SIGNING_METHOD; import static software.amazon.awssdk.core.HttpChecksumConstant.X_AMZ_TRAILER; import static software.amazon.awssdk.core.internal.util.HttpChecksumResolver.getResolvedChecksumSpecs; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.ClientType; import software.amazon.awssdk.core.HttpChecksumConstant; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.internal.signer.SigningMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.StringUtils; @SdkInternalApi public final class HttpChecksumUtils { private static final int CHECKSUM_BUFFER_SIZE = 16 * 1024; private HttpChecksumUtils() { } /** * @param algorithmName Checksum Algorithm Name * @return Http Checksum header for a given Algorithm. */ public static String httpChecksumHeader(String algorithmName) { return String.format("%s-%s", HttpChecksumConstant.HTTP_CHECKSUM_HEADER_PREFIX, StringUtils.lowerCase(algorithmName)); } /** * The header based Checksum is computed only if following criteria is met * - Flexible checksum is not already computed. * - * - HeaderChecksumSpecs are defined. * - Unsigned Payload request. */ public static boolean isStreamingUnsignedPayload(SdkHttpRequest sdkHttpRequest, ExecutionAttributes executionAttributes, ChecksumSpecs headerChecksumSpecs, boolean isContentStreaming) { SigningMethod signingMethodUsed = executionAttributes.getAttribute(SIGNING_METHOD); String protocol = sdkHttpRequest.protocol(); if (isHeaderBasedSigningAuth(signingMethodUsed, protocol)) { return false; } return isUnsignedPayload(signingMethodUsed, protocol, isContentStreaming) && headerChecksumSpecs.isRequestStreaming(); } public static boolean isHeaderBasedSigningAuth(SigningMethod signingMethodUsed, String protocol) { switch (signingMethodUsed) { case HEADER_BASED_AUTH: { return true; } case PROTOCOL_BASED_UNSIGNED: { return "http".equals(protocol); } default: { return false; } } } /** * @param signingMethod Signing Method. * @param protocol The http/https protocol. * @return true if Payload signing is resolved to Unsigned payload. */ public static boolean isUnsignedPayload(SigningMethod signingMethod, String protocol, boolean isContentStreaming) { switch (signingMethod) { case UNSIGNED_PAYLOAD: return true; case PROTOCOL_STREAMING_SIGNING_AUTH: return "https".equals(protocol) || !isContentStreaming; case PROTOCOL_BASED_UNSIGNED: return "https".equals(protocol); default: return false; } } /** * Computes the Checksum of the data in the given input stream and returns it as an array of bytes. * * @param is InputStream for which checksum needs to be calculated. * @param algorithm algorithm that will be used to compute the checksum of input stream. * @return Calculated checksum in bytes. * @throws IOException I/O errors while reading. */ public static byte[] computeChecksum(InputStream is, Algorithm algorithm) throws IOException { SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm); try (BufferedInputStream bis = new BufferedInputStream(is)) { byte[] buffer = new byte[CHECKSUM_BUFFER_SIZE]; int bytesRead; while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) { sdkChecksum.update(buffer, 0, bytesRead); } return sdkChecksum.getChecksumBytes(); } } /** * * @param executionAttributes Execution attributes defined for the request. * @return Optional ChecksumSpec if checksum Algorithm exist for the checksumSpec */ public static Optional<ChecksumSpecs> checksumSpecWithRequestAlgorithm(ExecutionAttributes executionAttributes) { ChecksumSpecs resolvedChecksumSpecs = getResolvedChecksumSpecs(executionAttributes); if (resolvedChecksumSpecs != null && resolvedChecksumSpecs.algorithm() != null) { return Optional.of(resolvedChecksumSpecs); } return Optional.empty(); } /** * Checks if the request header is already updated with Calculated checksum. * * @param sdkHttpRequest SdkHttpRequest * @return True if the flexible checksum header was already updated. */ public static boolean isHttpChecksumPresent(SdkHttpRequest sdkHttpRequest, ChecksumSpecs checksumSpec) { //check for the Direct header Or check if Trailer Header is present. return sdkHttpRequest.firstMatchingHeader(checksumSpec.headerName()).isPresent() || isTrailerChecksumPresent(sdkHttpRequest, checksumSpec); } public static boolean isMd5ChecksumRequired(ExecutionAttributes executionAttributes) { ChecksumSpecs resolvedChecksumSpecs = getResolvedChecksumSpecs(executionAttributes); if (resolvedChecksumSpecs == null) { return false; } return resolvedChecksumSpecs.algorithm() == null && resolvedChecksumSpecs.isRequestChecksumRequired(); } private static boolean isTrailerChecksumPresent(SdkHttpRequest sdkHttpRequest, ChecksumSpecs checksumSpec) { Optional<String> trailerBasedChecksum = sdkHttpRequest.firstMatchingHeader(X_AMZ_TRAILER); if (trailerBasedChecksum.isPresent()) { return trailerBasedChecksum.filter(checksum -> checksum.equalsIgnoreCase(checksumSpec.headerName())).isPresent(); } return false; } /** * The trailer based Checksum is computed only if following criteria is met * - Flexible checksum is not already computed. * - Streaming Unsigned Payload defined. * - Unsigned Payload request. */ public static boolean isTrailerBasedFlexibleChecksumComputed(SdkHttpRequest sdkHttpRequest, ExecutionAttributes executionAttributes, ChecksumSpecs checksumSpecs, boolean hasRequestBody, boolean isContentStreaming) { return hasRequestBody && !HttpChecksumUtils.isHttpChecksumPresent(sdkHttpRequest, checksumSpecs) && HttpChecksumUtils.isStreamingUnsignedPayload(sdkHttpRequest, executionAttributes, checksumSpecs, isContentStreaming); } /** * * @param executionAttributes Execution attributes for the request. * @param httpRequest Http Request. * @param clientType Client Type for which the Trailer checksum is appended. * @param checksumSpecs Checksum specs for the request. * @param hasRequestBody Request body. * @return True if Trailer checksum needs to be calculated and appended. */ public static boolean isTrailerBasedChecksumForClientType( ExecutionAttributes executionAttributes, SdkHttpRequest httpRequest, ClientType clientType, ChecksumSpecs checksumSpecs, boolean hasRequestBody, boolean isContentSteaming) { ClientType actualClientType = executionAttributes.getAttribute(SdkExecutionAttribute.CLIENT_TYPE); return actualClientType.equals(clientType) && checksumSpecs != null && HttpChecksumUtils.isTrailerBasedFlexibleChecksumComputed( httpRequest, executionAttributes, checksumSpecs, hasRequestBody, isContentSteaming); } /** * Loops through the Supported list of checksum for the operation, and gets the Header value for the checksum header. * @param sdkHttpResponse response from service. * @param resolvedChecksumSpecs Resolved checksum specification for the operation. * @return Algorithm and its corresponding checksum value as sent by the service. */ public static Pair<Algorithm, String> getAlgorithmChecksumValuePair(SdkHttpResponse sdkHttpResponse, ChecksumSpecs resolvedChecksumSpecs) { return resolvedChecksumSpecs.responseValidationAlgorithms().stream().map( algorithm -> { Optional<String> firstMatchingHeader = sdkHttpResponse.firstMatchingHeader(httpChecksumHeader(algorithm.name())); return firstMatchingHeader.map(s -> Pair.of(algorithm, s)).orElse(null); }).filter(Objects::nonNull).findFirst().orElse(null); } /** * * @param resolvedChecksumSpecs Resolved checksum specification for the operation. * @return True is Response is to be validated for checksum checks. */ public static boolean isHttpChecksumValidationEnabled(ChecksumSpecs resolvedChecksumSpecs) { return resolvedChecksumSpecs != null && resolvedChecksumSpecs.isValidationEnabled() && resolvedChecksumSpecs.responseValidationAlgorithms() != null; } public static byte[] longToByte(Long input) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.putLong(input); return buffer.array(); } }
2,175
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/Mimetype.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.StringTokenizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; /** * Utility class that maintains a listing of known Mimetypes, and determines the * mimetype of files based on file extensions. * <p> * This class is obtained with the {#link {@link #getInstance()} method that * recognizes loaded mime types from the file <code>mime.types</code> if this * file is available at the root of the classpath. The mime.types file format, * and most of the content, is taken from the Apache HTTP server's mime.types * file. * <p> * The format for mime type setting documents is: * <code>mimetype + extension (+ extension)*</code>. Any * blank lines in the file are ignored, as are lines starting with * <code>#</code> which are considered comments. * * @see <a href="https://github.com/apache/httpd/blob/trunk/docs/conf/mime.types">mime.types</a> */ @SdkInternalApi public final class Mimetype { /** The default XML mimetype: application/xml */ public static final String MIMETYPE_XML = "application/xml"; /** The default HTML mimetype: text/html */ public static final String MIMETYPE_HTML = "text/html"; /** The default binary mimetype: application/octet-stream */ public static final String MIMETYPE_OCTET_STREAM = "application/octet-stream"; /** The default gzip mimetype: application/x-gzip */ public static final String MIMETYPE_GZIP = "application/x-gzip"; public static final String MIMETYPE_TEXT_PLAIN = "text/plain"; public static final String MIMETYPE_EVENT_STREAM = "application/vnd.amazon.eventstream"; private static final Logger LOG = LoggerFactory.getLogger(Mimetype.class); private static final String MIME_TYPE_PATH = "software/amazon/awssdk/core/util/mime.types"; private static final ClassLoader CLASS_LOADER = ClassLoaderHelper.classLoader(Mimetype.class); private static volatile Mimetype mimetype; /** * Map that stores file extensions as keys, and the corresponding mimetype as values. */ private final Map<String, String> extensionToMimetype = new HashMap<>(); private Mimetype() { Optional.ofNullable(CLASS_LOADER).map(loader -> loader.getResourceAsStream(MIME_TYPE_PATH)).ifPresent( stream -> { try { loadAndReplaceMimetypes(stream); } catch (IOException e) { LOG.debug("Failed to load mime types from file in the classpath: mime.types", e); } finally { IoUtils.closeQuietly(stream, null); } } ); } /** * Loads MIME type info from the file 'mime.types' in the classpath, if it's available. */ public static Mimetype getInstance() { if (mimetype == null) { synchronized (Mimetype.class) { if (mimetype == null) { mimetype = new Mimetype(); } } } return mimetype; } /** * Determines the mimetype of a file by looking up the file's extension in an internal listing * to find the corresponding mime type. If the file has no extension, or the extension is not * available in the listing contained in this class, the default mimetype * <code>application/octet-stream</code> is returned. * * @param path the file whose extension may match a known mimetype. * @return the file's mimetype based on its extension, or a default value of * <code>application/octet-stream</code> if a mime type value cannot be found. */ public String getMimetype(Path path) { Validate.notNull(path, "path"); Path file = path.getFileName(); if (file != null) { return getMimetype(file.toString()); } return MIMETYPE_OCTET_STREAM; } /** * Determines the mimetype of a file by looking up the file's extension in an internal listing * to find the corresponding mime type. If the file has no extension, or the extension is not * available in the listing contained in this class, the default mimetype * <code>application/octet-stream</code> is returned. * * @param file the file whose extension may match a known mimetype. * @return the file's mimetype based on its extension, or a default value of * <code>application/octet-stream</code> if a mime type value cannot be found. */ public String getMimetype(File file) { return getMimetype(file.toPath()); } /** * Determines the mimetype of a file by looking up the file's extension in * an internal listing to find the corresponding mime type. If the file has * no extension, or the extension is not available in the listing contained * in this class, the default mimetype <code>application/octet-stream</code> * is returned. * * @param fileName The name of the file whose extension may match a known * mimetype. * @return The file's mimetype based on its extension, or a default value of * {@link #MIMETYPE_OCTET_STREAM} if a mime type value cannot * be found. */ String getMimetype(String fileName) { int lastPeriodIndex = fileName.lastIndexOf('.'); if (lastPeriodIndex > 0 && lastPeriodIndex + 1 < fileName.length()) { String ext = StringUtils.lowerCase(fileName.substring(lastPeriodIndex + 1)); if (extensionToMimetype.containsKey(ext)) { return extensionToMimetype.get(ext); } } return MIMETYPE_OCTET_STREAM; } /** * Reads and stores the mime type setting corresponding to a file extension, by reading * text from an InputStream. If a mime type setting already exists when this method is run, * the mime type value is replaced with the newer one. */ private void loadAndReplaceMimetypes(InputStream is) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); br.lines().filter(line -> !line.startsWith("#")).forEach(line -> { line = line.trim(); StringTokenizer st = new StringTokenizer(line, " \t"); if (st.countTokens() > 1) { String mimetype = st.nextToken(); while (st.hasMoreTokens()) { String extension = st.nextToken(); extensionToMimetype.put(StringUtils.lowerCase(extension), mimetype); } } }); } }
2,176
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/MetricUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 static software.amazon.awssdk.core.http.HttpResponseHandler.X_AMZN_REQUEST_ID_HEADERS; import static software.amazon.awssdk.core.http.HttpResponseHandler.X_AMZ_ID_2_HEADER; import java.net.URI; import java.net.URISyntaxException; import java.time.Duration; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.internal.http.RequestExecutionContext; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.metrics.NoOpMetricCollector; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.utils.Pair; /** * Utility methods for working with metrics. */ @SdkInternalApi public final class MetricUtils { private MetricUtils() { } /** * Measure the duration of the given callable. * * @param c The callable to measure. * @return A {@code Pair} containing the result of {@code c} and the duration. */ public static <T> Pair<T, Duration> measureDuration(Supplier<T> c) { long start = System.nanoTime(); T result = c.get(); Duration d = Duration.ofNanos(System.nanoTime() - start); return Pair.of(result, d); } /** * Report a duration metric of the given {@link CompletableFuture} supplier. * * @param c The callable to measure. * @param metricCollector The MetricCollector where the metric is to be reported. * @param metric The metric to be reported. * @return A {@code Pair} containing the result of {@code c} and the duration. */ public static <T> CompletableFuture<T> reportDuration(Supplier<CompletableFuture<T>> c, MetricCollector metricCollector, SdkMetric<Duration> metric) { long start = System.nanoTime(); CompletableFuture<T> result = c.get(); result.whenComplete((r, t) -> { Duration d = Duration.ofNanos(System.nanoTime() - start); metricCollector.reportMetric(metric, d); }); return result; } /** * Measure the duration of the given callable. * * @param c The callable to measure. * @return A {@code Pair} containing the result of {@code c} and the duration. */ public static <T> Pair<T, Duration> measureDurationUnsafe(Callable<T> c) throws Exception { long start = System.nanoTime(); T result = c.call(); Duration d = Duration.ofNanos(System.nanoTime() - start); return Pair.of(result, d); } /** * Collect the SERVICE_ENDPOINT metric for this request. */ public static void collectServiceEndpointMetrics(MetricCollector metricCollector, SdkHttpFullRequest httpRequest) { if (metricCollector != null && !(metricCollector instanceof NoOpMetricCollector) && httpRequest != null) { // Only interested in the service endpoint so don't include any path, query, or fragment component URI requestUri = httpRequest.getUri(); try { URI serviceEndpoint = new URI(requestUri.getScheme(), requestUri.getAuthority(), null, null, null); metricCollector.reportMetric(CoreMetric.SERVICE_ENDPOINT, serviceEndpoint); } catch (URISyntaxException e) { // This should not happen since getUri() should return a valid URI throw SdkClientException.create("Unable to collect SERVICE_ENDPOINT metric", e); } } } public static void collectHttpMetrics(MetricCollector metricCollector, SdkHttpFullResponse httpResponse) { if (metricCollector != null && !(metricCollector instanceof NoOpMetricCollector) && httpResponse != null) { metricCollector.reportMetric(HttpMetric.HTTP_STATUS_CODE, httpResponse.statusCode()); X_AMZN_REQUEST_ID_HEADERS.forEach(h -> { httpResponse.firstMatchingHeader(h).ifPresent(v -> metricCollector.reportMetric(CoreMetric.AWS_REQUEST_ID, v)); }); httpResponse.firstMatchingHeader(X_AMZ_ID_2_HEADER) .ifPresent(v -> metricCollector.reportMetric(CoreMetric.AWS_EXTENDED_REQUEST_ID, v)); } } public static MetricCollector createAttemptMetricsCollector(RequestExecutionContext context) { MetricCollector parentCollector = context.executionContext().metricCollector(); if (parentCollector != null) { return parentCollector.createChild("ApiCallAttempt"); } return NoOpMetricCollector.create(); } public static MetricCollector createHttpMetricsCollector(RequestExecutionContext context) { MetricCollector parentCollector = context.attemptMetricCollector(); if (parentCollector != null) { return parentCollector.createChild("HttpClient"); } return NoOpMetricCollector.create(); } }
2,177
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/async/InputStreamResponseTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.ResponseInputStream; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.utils.async.InputStreamSubscriber; /** * A {@link AsyncResponseTransformer} that allows performing blocking reads on the response data. * <p> * Created with {@link AsyncResponseTransformer#toBlockingInputStream()}. */ @SdkInternalApi public class InputStreamResponseTransformer<ResponseT extends SdkResponse> implements AsyncResponseTransformer<ResponseT, ResponseInputStream<ResponseT>> { private volatile CompletableFuture<ResponseInputStream<ResponseT>> future; private volatile ResponseT response; @Override public CompletableFuture<ResponseInputStream<ResponseT>> prepare() { CompletableFuture<ResponseInputStream<ResponseT>> result = new CompletableFuture<>(); this.future = result; return result; } @Override public void onResponse(ResponseT response) { this.response = response; } @Override public void onStream(SdkPublisher<ByteBuffer> publisher) { InputStreamSubscriber inputStreamSubscriber = new InputStreamSubscriber(); publisher.subscribe(inputStreamSubscriber); future.complete(new ResponseInputStream<>(response, inputStreamSubscriber)); } @Override public void exceptionOccurred(Throwable error) { future.completeExceptionally(error); } }
2,178
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/async/SdkPublishers.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.SdkPublisher; /** * Common implementations of {@link SdkPublisher} that are provided for convenience when building asynchronous * interceptors to be used with specific clients. */ @SdkInternalApi public final class SdkPublishers { private SdkPublishers() { } /** * Constructs an {@link SdkPublisher} that wraps a {@link ByteBuffer} publisher and inserts additional content * that wraps the published content like an envelope. This can be used when you want to transform the content of * an asynchronous SDK response by putting it in an envelope. This publisher implementation does not comply with * the complete flow spec (as it inserts data into the middle of a flow between a third-party publisher and * subscriber rather than acting as a fully featured independent publisher) and therefore should only be used in a * limited fashion when we have complete control over how data is being published to the publisher it wraps. * @param publisher The underlying publisher to wrap the content of. * @param envelopePrefix A string representing the content to be inserted as the head of the containing envelope. * @param envelopeSuffix A string representing the content to be inserted as the tail of containing envelope. * @return An {@link SdkPublisher} that wraps the provided publisher. */ public static SdkPublisher<ByteBuffer> envelopeWrappedPublisher(Publisher<ByteBuffer> publisher, String envelopePrefix, String envelopeSuffix) { return EnvelopeWrappedSdkPublisher.of(publisher, wrapUtf8(envelopePrefix), wrapUtf8(envelopeSuffix), SdkPublishers::concat); } private static ByteBuffer wrapUtf8(String s) { return ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8)); } private static ByteBuffer concat(ByteBuffer b1, ByteBuffer b2) { ByteBuffer result = ByteBuffer.allocate(b1.remaining() + b2.remaining()); result.put(b1); result.put(b2); result.rewind(); return result; } }
2,179
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/async/EnvelopeWrappedSdkPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import java.util.function.BiFunction; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.SdkPublisher; /** * Publisher implementation that wraps the content of another publisher in an envelope with an optional prefix (or * header) and suffix (or footer). The prefix content will be prepended to the first published object from the * wrapped publisher, and the suffix content will be published when the wrapped publisher signals completion. * <p> * The envelope prefix will not be published until the wrapped publisher publishes something or is completed. * The envelope suffix will not be published until the wrapped publisher is completed. * <p> * This class can be used in an asynchronous interceptor in the AWS SDK to wrap content around the incoming * bytestream from a response. * <p> * A function must be supplied that can be used to concatenate the envelope content with the content being published by * the wrapped publisher. Example usage: * {@code * Publisher<String> wrappedPublisher = ContentEnvelopeWrappingPublisher.of(publisher, "S", "E", (s1, s2) -> s1 + s2); * } * If publisher publishes a single string "1", wrappedPublisher will publish "S1" (prepending the envelop prefix). If * publisher then publishes a second string "2", wrappedPublisher will then publish "2" (no added content). If * publisher then completes, wrappedPublisher will then publish "E" and then complete. * <p> * WARNING: This publisher implementation does not comply with the complete flow spec (as it inserts data into the * middle of a flow between a third-party publisher and subscriber rather than acting as a fully featured * independent publisher) and therefore should only be used in a limited fashion when we have complete control over * how data is being published to the publisher it wraps. * * @param <T> The type of objects being published */ @SdkInternalApi public class EnvelopeWrappedSdkPublisher<T> implements SdkPublisher<T> { private final Publisher<T> wrappedPublisher; private final T contentPrefix; private final T contentSuffix; private final BiFunction<T, T, T> mergeContentFunction; private EnvelopeWrappedSdkPublisher(Publisher<T> wrappedPublisher, T contentPrefix, T contentSuffix, BiFunction<T, T, T> mergeContentFunction) { this.wrappedPublisher = wrappedPublisher; this.contentPrefix = contentPrefix; this.contentSuffix = contentSuffix; this.mergeContentFunction = mergeContentFunction; } /** * Create a new publisher that wraps the content of an existing publisher. * @param wrappedPublisher The publisher who's content will be wrapped. * @param contentPrefix The content to be inserted in front of the wrapped content. * @param contentSuffix The content to be inserted at the back of the wrapped content. * @param mergeContentFunction A function that will be used to merge the inserted content into the wrapped content. * @param <T> The content type. * @return A newly initialized instance of this class. */ public static <T> EnvelopeWrappedSdkPublisher<T> of(Publisher<T> wrappedPublisher, T contentPrefix, T contentSuffix, BiFunction<T, T, T> mergeContentFunction) { return new EnvelopeWrappedSdkPublisher<>(wrappedPublisher, contentPrefix, contentSuffix, mergeContentFunction); } /** * See {@link Publisher#subscribe(Subscriber)} */ @Override public void subscribe(Subscriber<? super T> subscriber) { if (subscriber == null) { throw new NullPointerException("subscriber must be non-null on call to subscribe()"); } wrappedPublisher.subscribe(new ContentWrappedSubscriber(subscriber)); } private class ContentWrappedSubscriber implements Subscriber<T> { private final Subscriber<? super T> wrappedSubscriber; private boolean prefixApplied = false; private boolean suffixApplied = false; private ContentWrappedSubscriber(Subscriber<? super T> wrappedSubscriber) { this.wrappedSubscriber = wrappedSubscriber; } @Override public void onSubscribe(Subscription subscription) { wrappedSubscriber.onSubscribe(subscription); } @Override public void onNext(T t) { T contentToSend = t; if (!prefixApplied) { prefixApplied = true; if (contentPrefix != null) { contentToSend = mergeContentFunction.apply(contentPrefix, t); } } wrappedSubscriber.onNext(contentToSend); } @Override public void onError(Throwable throwable) { wrappedSubscriber.onError(throwable); } @Override public void onComplete() { try { // Only transmit the close of the envelope once and only if the prefix has been previously sent. if (!suffixApplied && prefixApplied) { suffixApplied = true; if (contentSuffix != null) { // TODO: This should respect the demand from the subscriber as technically an onComplete // signal could be received even if there is no demand. We have minimized the impact of this // by only making it applicable in situations where there data has already been transmitted // over the stream. wrappedSubscriber.onNext(contentSuffix); } } } finally { wrappedSubscriber.onComplete(); } } } }
2,180
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/async/ChecksumValidatingPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.utils.BinaryUtils; /** * Publisher to update the checksum as it reads the data and * finally compares the computed checksum with expected Checksum. */ @SdkInternalApi public final class ChecksumValidatingPublisher implements SdkPublisher<ByteBuffer> { private final Publisher<ByteBuffer> publisher; private final SdkChecksum sdkChecksum; private final String expectedChecksum; public ChecksumValidatingPublisher(Publisher<ByteBuffer> publisher, SdkChecksum sdkChecksum, String expectedChecksum) { this.publisher = publisher; this.sdkChecksum = sdkChecksum; this.expectedChecksum = expectedChecksum; } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { publisher.subscribe(new ChecksumValidatingSubscriber(s, sdkChecksum, expectedChecksum)); } private static class ChecksumValidatingSubscriber implements Subscriber<ByteBuffer> { private final Subscriber<? super ByteBuffer> wrapped; private final SdkChecksum sdkChecksum; private final String expectedChecksum; private String calculatedChecksum = null; ChecksumValidatingSubscriber(Subscriber<? super ByteBuffer> wrapped, SdkChecksum sdkChecksum, String expectedChecksum) { this.wrapped = wrapped; this.sdkChecksum = sdkChecksum; this.expectedChecksum = expectedChecksum; } @Override public void onSubscribe(Subscription s) { wrapped.onSubscribe(s); } @Override public void onNext(ByteBuffer byteBuffer) { byteBuffer.mark(); try { sdkChecksum.update(byteBuffer); } finally { byteBuffer.reset(); } wrapped.onNext(byteBuffer); } @Override public void onError(Throwable t) { wrapped.onError(t); } @Override public void onComplete() { if (this.calculatedChecksum == null) { calculatedChecksum = BinaryUtils.toBase64(sdkChecksum.getChecksumBytes()); if (!expectedChecksum.equals(calculatedChecksum)) { onError(SdkClientException.create( String.format("Data read has a different checksum than expected. Was %s, but expected %s", calculatedChecksum, expectedChecksum))); return; // Return after onError and not call onComplete below } } wrapped.onComplete(); } } }
2,181
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/async/ByteBuffersAsyncRequestBody.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.internal.util.Mimetype; import software.amazon.awssdk.utils.Logger; /** * An implementation of {@link AsyncRequestBody} for providing data from the supplied {@link ByteBuffer} array. This is created * using static methods on {@link AsyncRequestBody} * * @see AsyncRequestBody#fromBytes(byte[]) * @see AsyncRequestBody#fromBytesUnsafe(byte[]) * @see AsyncRequestBody#fromByteBuffer(ByteBuffer) * @see AsyncRequestBody#fromByteBufferUnsafe(ByteBuffer) * @see AsyncRequestBody#fromByteBuffers(ByteBuffer...) * @see AsyncRequestBody#fromByteBuffersUnsafe(ByteBuffer...) * @see AsyncRequestBody#fromString(String) */ @SdkInternalApi public final class ByteBuffersAsyncRequestBody implements AsyncRequestBody { private static final Logger log = Logger.loggerFor(ByteBuffersAsyncRequestBody.class); private final String mimetype; private final Long length; private final ByteBuffer[] buffers; private ByteBuffersAsyncRequestBody(String mimetype, Long length, ByteBuffer... buffers) { this.mimetype = mimetype; this.length = length; this.buffers = buffers; } @Override public Optional<Long> contentLength() { return Optional.ofNullable(length); } @Override public String contentType() { return mimetype; } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { // As per rule 1.9 we must throw NullPointerException if the subscriber parameter is null if (s == null) { throw new NullPointerException("Subscription MUST NOT be null."); } // As per 2.13, this method must return normally (i.e. not throw). try { s.onSubscribe( new Subscription() { private final AtomicInteger index = new AtomicInteger(0); private final AtomicBoolean completed = new AtomicBoolean(false); @Override public void request(long n) { if (completed.get()) { return; } if (n > 0) { int i = index.getAndIncrement(); if (i >= buffers.length) { return; } long remaining = n; do { ByteBuffer buffer = buffers[i]; s.onNext(buffer.asReadOnlyBuffer()); remaining--; } while (remaining > 0 && (i = index.getAndIncrement()) < buffers.length); if (i >= buffers.length - 1 && completed.compareAndSet(false, true)) { s.onComplete(); } } else { s.onError(new IllegalArgumentException("§3.9: non-positive requests are not allowed!")); } } @Override public void cancel() { completed.set(true); } } ); } catch (Throwable ex) { log.error(() -> s + " violated the Reactive Streams rule 2.13 by throwing an exception from onSubscribe.", ex); } } public static ByteBuffersAsyncRequestBody of(ByteBuffer... buffers) { long length = Arrays.stream(buffers) .mapToLong(ByteBuffer::remaining) .sum(); return new ByteBuffersAsyncRequestBody(Mimetype.MIMETYPE_OCTET_STREAM, length, buffers); } public static ByteBuffersAsyncRequestBody of(Long length, ByteBuffer... buffers) { return new ByteBuffersAsyncRequestBody(Mimetype.MIMETYPE_OCTET_STREAM, length, buffers); } public static ByteBuffersAsyncRequestBody of(String mimetype, ByteBuffer... buffers) { long length = Arrays.stream(buffers) .mapToLong(ByteBuffer::remaining) .sum(); return new ByteBuffersAsyncRequestBody(mimetype, length, buffers); } public static ByteBuffersAsyncRequestBody of(String mimetype, Long length, ByteBuffer... buffers) { return new ByteBuffersAsyncRequestBody(mimetype, length, buffers); } public static ByteBuffersAsyncRequestBody from(byte[] bytes) { return new ByteBuffersAsyncRequestBody(Mimetype.MIMETYPE_OCTET_STREAM, (long) bytes.length, ByteBuffer.wrap(bytes)); } public static ByteBuffersAsyncRequestBody from(String mimetype, byte[] bytes) { return new ByteBuffersAsyncRequestBody(mimetype, (long) bytes.length, ByteBuffer.wrap(bytes)); } }
2,182
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/async/FileAsyncRequestBodySplitHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import java.nio.ByteBuffer; import java.nio.file.Path; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncRequestBodySplitConfiguration; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.async.SimplePublisher; /** * A helper class to split a {@link FileAsyncRequestBody} to multiple smaller async request bodies. It ensures the buffer used to * be under the configured size via {@link AsyncRequestBodySplitConfiguration#bufferSizeInBytes()} by tracking the number of * concurrent ongoing {@link AsyncRequestBody}s. */ @SdkInternalApi public final class FileAsyncRequestBodySplitHelper { private static final Logger log = Logger.loggerFor(FileAsyncRequestBodySplitHelper.class); private final AtomicBoolean isSendingRequestBody = new AtomicBoolean(false); private final AtomicLong remainingBytes; private final long totalContentLength; private final Path path; private final int bufferPerAsyncRequestBody; private final long totalBufferSize; private final long chunkSize; private volatile boolean isDone = false; private AtomicInteger numAsyncRequestBodiesInFlight = new AtomicInteger(0); private AtomicInteger chunkIndex = new AtomicInteger(0); public FileAsyncRequestBodySplitHelper(FileAsyncRequestBody asyncRequestBody, AsyncRequestBodySplitConfiguration splitConfiguration) { Validate.notNull(asyncRequestBody, "asyncRequestBody"); Validate.notNull(splitConfiguration, "splitConfiguration"); Validate.isTrue(asyncRequestBody.contentLength().isPresent(), "Content length must be present", asyncRequestBody); this.totalContentLength = asyncRequestBody.contentLength().get(); this.remainingBytes = new AtomicLong(totalContentLength); this.path = asyncRequestBody.path(); this.chunkSize = splitConfiguration.chunkSizeInBytes() == null ? AsyncRequestBodySplitConfiguration.defaultConfiguration().chunkSizeInBytes() : splitConfiguration.chunkSizeInBytes(); this.totalBufferSize = splitConfiguration.bufferSizeInBytes() == null ? AsyncRequestBodySplitConfiguration.defaultConfiguration().bufferSizeInBytes() : splitConfiguration.bufferSizeInBytes(); this.bufferPerAsyncRequestBody = asyncRequestBody.chunkSizeInBytes(); } public SdkPublisher<AsyncRequestBody> split() { SimplePublisher<AsyncRequestBody> simplePublisher = new SimplePublisher<>(); try { sendAsyncRequestBody(simplePublisher); } catch (Throwable throwable) { simplePublisher.error(throwable); } return SdkPublisher.adapt(simplePublisher); } private void sendAsyncRequestBody(SimplePublisher<AsyncRequestBody> simplePublisher) { do { if (!isSendingRequestBody.compareAndSet(false, true)) { return; } try { doSendAsyncRequestBody(simplePublisher); } finally { isSendingRequestBody.set(false); } } while (shouldSendMore()); } private void doSendAsyncRequestBody(SimplePublisher<AsyncRequestBody> simplePublisher) { while (shouldSendMore()) { AsyncRequestBody currentAsyncRequestBody = newFileAsyncRequestBody(simplePublisher); simplePublisher.send(currentAsyncRequestBody); numAsyncRequestBodiesInFlight.incrementAndGet(); checkCompletion(simplePublisher, currentAsyncRequestBody); } } private void checkCompletion(SimplePublisher<AsyncRequestBody> simplePublisher, AsyncRequestBody currentAsyncRequestBody) { long remaining = remainingBytes.addAndGet(-currentAsyncRequestBody.contentLength().get()); if (remaining == 0) { isDone = true; simplePublisher.complete(); } else if (remaining < 0) { isDone = true; simplePublisher.error(SdkClientException.create( "Unexpected error occurred. Remaining data is negative: " + remaining)); } } private void startNextRequestBody(SimplePublisher<AsyncRequestBody> simplePublisher) { numAsyncRequestBodiesInFlight.decrementAndGet(); sendAsyncRequestBody(simplePublisher); } private AsyncRequestBody newFileAsyncRequestBody(SimplePublisher<AsyncRequestBody> simplePublisher) { long position = chunkSize * chunkIndex.getAndIncrement(); long numBytesToReadForThisChunk = Math.min(totalContentLength - position, chunkSize); FileAsyncRequestBody fileAsyncRequestBody = FileAsyncRequestBody.builder() .path(path) .position(position) .numBytesToRead(numBytesToReadForThisChunk) .build(); return new FileAsyncRequestBodyWrapper(fileAsyncRequestBody, simplePublisher); } /** * Should not send more if it's done OR sending next request body would exceed the total buffer size */ private boolean shouldSendMore() { if (isDone) { return false; } long currentUsedBuffer = (long) numAsyncRequestBodiesInFlight.get() * bufferPerAsyncRequestBody; return currentUsedBuffer + bufferPerAsyncRequestBody <= totalBufferSize; } @SdkTestInternalApi AtomicInteger numAsyncRequestBodiesInFlight() { return numAsyncRequestBodiesInFlight; } private final class FileAsyncRequestBodyWrapper implements AsyncRequestBody { private final FileAsyncRequestBody fileAsyncRequestBody; private final SimplePublisher<AsyncRequestBody> simplePublisher; FileAsyncRequestBodyWrapper(FileAsyncRequestBody fileAsyncRequestBody, SimplePublisher<AsyncRequestBody> simplePublisher) { this.fileAsyncRequestBody = fileAsyncRequestBody; this.simplePublisher = simplePublisher; } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { fileAsyncRequestBody.doAfterOnComplete(() -> startNextRequestBody(simplePublisher)) // The reason we still need to call startNextRequestBody when the subscription is // cancelled is that upstream could cancel the subscription even though the stream has // finished successfully before onComplete. If this happens, doAfterOnComplete callback // will never be invoked, and if the current buffer is full, the publisher will stop // sending new FileAsyncRequestBody, leading to uncompleted future. .doAfterOnCancel(() -> startNextRequestBody(simplePublisher)) .subscribe(s); } @Override public Optional<Long> contentLength() { return fileAsyncRequestBody.contentLength(); } } }
2,183
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/async/ChecksumCalculatingAsyncRequestBody.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import static software.amazon.awssdk.core.HttpChecksumConstant.DEFAULT_ASYNC_CHUNK_SIZE; import static software.amazon.awssdk.core.internal.util.ChunkContentUtils.LAST_CHUNK_LEN; import static software.amazon.awssdk.core.internal.util.ChunkContentUtils.calculateChecksumTrailerLength; import static software.amazon.awssdk.core.internal.util.ChunkContentUtils.calculateChunkLength; import static software.amazon.awssdk.core.internal.util.ChunkContentUtils.createChecksumTrailer; import static software.amazon.awssdk.core.internal.util.ChunkContentUtils.createChunk; import java.nio.ByteBuffer; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.async.DelegatingSubscriber; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Wrapper class to wrap an AsyncRequestBody. * This will read the data in chunk format and append Checksum as trailer at the end. */ @SdkInternalApi public class ChecksumCalculatingAsyncRequestBody implements AsyncRequestBody { private static final byte[] FINAL_BYTE = new byte[0]; private final AsyncRequestBody wrapped; private final SdkChecksum sdkChecksum; private final Algorithm algorithm; private final String trailerHeader; private final long totalBytes; private ChecksumCalculatingAsyncRequestBody(DefaultBuilder builder) { Validate.notNull(builder.asyncRequestBody, "wrapped AsyncRequestBody cannot be null"); Validate.notNull(builder.algorithm, "algorithm cannot be null"); Validate.notNull(builder.trailerHeader, "trailerHeader cannot be null"); this.wrapped = builder.asyncRequestBody; this.algorithm = builder.algorithm; this.sdkChecksum = builder.algorithm != null ? SdkChecksum.forAlgorithm(algorithm) : null; this.trailerHeader = builder.trailerHeader; this.totalBytes = wrapped.contentLength() .orElseThrow(() -> new UnsupportedOperationException("Content length must be supplied.")); } /** * @return Builder instance to construct a {@link FileAsyncRequestBody}. */ public static ChecksumCalculatingAsyncRequestBody.Builder builder() { return new DefaultBuilder(); } public interface Builder extends SdkBuilder<ChecksumCalculatingAsyncRequestBody.Builder, ChecksumCalculatingAsyncRequestBody> { /** * Sets the AsyncRequestBody that will be wrapped. * @param asyncRequestBody AsyncRequestBody. * @return This builder for method chaining. */ ChecksumCalculatingAsyncRequestBody.Builder asyncRequestBody(AsyncRequestBody asyncRequestBody); /** * Sets the checksum algorithm. * @param algorithm algorithm that is used to compute the checksum. * @return This builder for method chaining. */ ChecksumCalculatingAsyncRequestBody.Builder algorithm(Algorithm algorithm); /** * Sets the Trailer header where computed SdkChecksum will be updated. * @param trailerHeader Trailer header name which will be appended at the end of the string. * @return This builder for method chaining. */ ChecksumCalculatingAsyncRequestBody.Builder trailerHeader(String trailerHeader); } private static final class DefaultBuilder implements ChecksumCalculatingAsyncRequestBody.Builder { private AsyncRequestBody asyncRequestBody; private Algorithm algorithm; private String trailerHeader; @Override public ChecksumCalculatingAsyncRequestBody build() { return new ChecksumCalculatingAsyncRequestBody(this); } @Override public Builder asyncRequestBody(AsyncRequestBody asyncRequestBody) { this.asyncRequestBody = asyncRequestBody; return this; } @Override public ChecksumCalculatingAsyncRequestBody.Builder algorithm(Algorithm algorithm) { this.algorithm = algorithm; return this; } @Override public ChecksumCalculatingAsyncRequestBody.Builder trailerHeader(String trailerHeader) { this.trailerHeader = trailerHeader; return this; } } @Override public Optional<Long> contentLength() { if (wrapped.contentLength().isPresent() && algorithm != null) { return Optional.of(calculateChunkLength(wrapped.contentLength().get()) + LAST_CHUNK_LEN + calculateChecksumTrailerLength(algorithm, trailerHeader)); } return wrapped.contentLength(); } @Override public String contentType() { return wrapped.contentType(); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { Validate.notNull(s, "Subscription MUST NOT be null."); if (sdkChecksum != null) { sdkChecksum.reset(); } SynchronousChunkBuffer synchronousChunkBuffer = new SynchronousChunkBuffer(totalBytes); alwaysInvokeOnNext(wrapped).flatMapIterable(synchronousChunkBuffer::buffer) .subscribe(new ChecksumCalculatingSubscriber(s, sdkChecksum, trailerHeader, totalBytes)); } private SdkPublisher<ByteBuffer> alwaysInvokeOnNext(SdkPublisher<ByteBuffer> source) { return subscriber -> source.subscribe(new OnNextGuaranteedSubscriber(subscriber)); } private static final class ChecksumCalculatingSubscriber implements Subscriber<ByteBuffer> { private final Subscriber<? super ByteBuffer> wrapped; private final SdkChecksum checksum; private final String trailerHeader; private byte[] checksumBytes; private final AtomicLong remainingBytes; private Subscription subscription; ChecksumCalculatingSubscriber(Subscriber<? super ByteBuffer> wrapped, SdkChecksum checksum, String trailerHeader, long totalBytes) { this.wrapped = wrapped; this.checksum = checksum; this.trailerHeader = trailerHeader; this.remainingBytes = new AtomicLong(totalBytes); } @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; wrapped.onSubscribe(subscription); } @Override public void onNext(ByteBuffer byteBuffer) { boolean lastByte = this.remainingBytes.addAndGet(-byteBuffer.remaining()) <= 0; try { if (checksum != null) { byteBuffer.mark(); checksum.update(byteBuffer); byteBuffer.reset(); } if (lastByte && checksumBytes == null && checksum != null) { checksumBytes = checksum.getChecksumBytes(); ByteBuffer allocatedBuffer = getFinalChecksumAppendedChunk(byteBuffer); wrapped.onNext(allocatedBuffer); } else { ByteBuffer allocatedBuffer = createChunk(byteBuffer, false); wrapped.onNext(allocatedBuffer); } } catch (SdkException sdkException) { this.subscription.cancel(); onError(sdkException); } } private ByteBuffer getFinalChecksumAppendedChunk(ByteBuffer byteBuffer) { ByteBuffer finalChunkedByteBuffer = createChunk(ByteBuffer.wrap(FINAL_BYTE), true); ByteBuffer checksumTrailerByteBuffer = createChecksumTrailer( BinaryUtils.toBase64(checksumBytes), trailerHeader); ByteBuffer contentChunk = byteBuffer.hasRemaining() ? createChunk(byteBuffer, false) : byteBuffer; ByteBuffer checksumAppendedBuffer = ByteBuffer.allocate( contentChunk.remaining() + finalChunkedByteBuffer.remaining() + checksumTrailerByteBuffer.remaining()); checksumAppendedBuffer .put(contentChunk) .put(finalChunkedByteBuffer) .put(checksumTrailerByteBuffer); checksumAppendedBuffer.flip(); return checksumAppendedBuffer; } @Override public void onError(Throwable t) { wrapped.onError(t); } @Override public void onComplete() { wrapped.onComplete(); } } private static final class SynchronousChunkBuffer { private final ChunkBuffer chunkBuffer; SynchronousChunkBuffer(long totalBytes) { this.chunkBuffer = ChunkBuffer.builder().bufferSize(DEFAULT_ASYNC_CHUNK_SIZE).totalBytes(totalBytes).build(); } private Iterable<ByteBuffer> buffer(ByteBuffer bytes) { return chunkBuffer.split(bytes); } } public static class OnNextGuaranteedSubscriber extends DelegatingSubscriber<ByteBuffer, ByteBuffer> { private volatile boolean onNextInvoked; public OnNextGuaranteedSubscriber(Subscriber<? super ByteBuffer> subscriber) { super(subscriber); } @Override public void onNext(ByteBuffer t) { if (!onNextInvoked) { onNextInvoked = true; } subscriber.onNext(t); } @Override public void onComplete() { if (!onNextInvoked) { subscriber.onNext(ByteBuffer.wrap(new byte[0])); } super.onComplete(); } } }
2,184
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/async/ChunkBuffer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import static software.amazon.awssdk.core.HttpChecksumConstant.DEFAULT_ASYNC_CHUNK_SIZE; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Class that will buffer incoming BufferBytes to chunks of bufferSize. * If totalBytes is not provided, i.e. content-length is unknown, {@link #getBufferedData()} should be used in the Subscriber's * {@code onComplete()} to check for a final chunk that is smaller than the chunk size, and send if present. */ @SdkInternalApi public final class ChunkBuffer { private static final Logger log = Logger.loggerFor(ChunkBuffer.class); private final AtomicLong transferredBytes; private final ByteBuffer currentBuffer; private final int chunkSize; private final Long totalBytes; private ChunkBuffer(Long totalBytes, Integer bufferSize) { int chunkSize = bufferSize != null ? bufferSize : DEFAULT_ASYNC_CHUNK_SIZE; this.chunkSize = chunkSize; this.currentBuffer = ByteBuffer.allocate(chunkSize); this.totalBytes = totalBytes; this.transferredBytes = new AtomicLong(0); } public static Builder builder() { return new DefaultBuilder(); } /** * Split the input {@link ByteBuffer} into multiple smaller {@link ByteBuffer}s, each of which contains {@link #chunkSize} * worth of bytes. If the last chunk of the input ByteBuffer contains less than {@link #chunkSize} data, the last chunk will * be buffered. */ public synchronized Iterable<ByteBuffer> split(ByteBuffer inputByteBuffer) { if (!inputByteBuffer.hasRemaining()) { return Collections.singletonList(inputByteBuffer); } List<ByteBuffer> byteBuffers = new ArrayList<>(); // If current buffer is not empty, fill the buffer first. if (currentBuffer.position() != 0) { fillCurrentBuffer(inputByteBuffer); if (isCurrentBufferFull()) { addCurrentBufferToIterable(byteBuffers); } } // If the input buffer is not empty, split the input buffer if (inputByteBuffer.hasRemaining()) { splitRemainingInputByteBuffer(inputByteBuffer, byteBuffers); } // If this is the last chunk, add data buffered to the iterable if (isLastChunk()) { addCurrentBufferToIterable(byteBuffers); } return byteBuffers; } private boolean isCurrentBufferFull() { return currentBuffer.position() == chunkSize; } /** * Splits the input ByteBuffer to multiple chunks and add them to the iterable. */ private void splitRemainingInputByteBuffer(ByteBuffer inputByteBuffer, List<ByteBuffer> byteBuffers) { while (inputByteBuffer.hasRemaining()) { ByteBuffer inputByteBufferCopy = inputByteBuffer.asReadOnlyBuffer(); if (inputByteBuffer.remaining() < chunkSize) { currentBuffer.put(inputByteBuffer); break; } int newLimit = inputByteBufferCopy.position() + chunkSize; inputByteBufferCopy.limit(newLimit); inputByteBuffer.position(newLimit); byteBuffers.add(inputByteBufferCopy); transferredBytes.addAndGet(chunkSize); } } /** * Retrieve the current buffered data. */ public Optional<ByteBuffer> getBufferedData() { int remainingBytesInBuffer = currentBuffer.position(); if (remainingBytesInBuffer == 0) { return Optional.empty(); } ByteBuffer bufferedChunk = ByteBuffer.allocate(remainingBytesInBuffer); currentBuffer.flip(); bufferedChunk.put(currentBuffer); bufferedChunk.flip(); return Optional.of(bufferedChunk); } private boolean isLastChunk() { if (totalBytes == null) { return false; } long remainingBytes = totalBytes - transferredBytes.get(); return remainingBytes != 0 && remainingBytes == currentBuffer.position(); } private void addCurrentBufferToIterable(List<ByteBuffer> byteBuffers) { Optional<ByteBuffer> bufferedChunk = getBufferedData(); if (bufferedChunk.isPresent()) { byteBuffers.add(bufferedChunk.get()); transferredBytes.addAndGet(bufferedChunk.get().remaining()); currentBuffer.clear(); } } private void fillCurrentBuffer(ByteBuffer inputByteBuffer) { while (currentBuffer.position() < chunkSize) { if (!inputByteBuffer.hasRemaining()) { break; } int remainingCapacity = chunkSize - currentBuffer.position(); if (inputByteBuffer.remaining() < remainingCapacity) { currentBuffer.put(inputByteBuffer); } else { ByteBuffer remainingChunk = inputByteBuffer.asReadOnlyBuffer(); int newLimit = inputByteBuffer.position() + remainingCapacity; remainingChunk.limit(newLimit); inputByteBuffer.position(newLimit); currentBuffer.put(remainingChunk); } } } public interface Builder extends SdkBuilder<Builder, ChunkBuffer> { Builder bufferSize(int bufferSize); Builder totalBytes(long totalBytes); } private static final class DefaultBuilder implements Builder { private Integer bufferSize; private Long totalBytes; @Override public ChunkBuffer build() { return new ChunkBuffer(totalBytes, bufferSize); } @Override public Builder bufferSize(int bufferSize) { this.bufferSize = bufferSize; return this; } @Override public Builder totalBytes(long totalBytes) { this.totalBytes = totalBytes; return this; } } }
2,185
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/async/CompressionAsyncRequestBody.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import static software.amazon.awssdk.core.internal.io.AwsChunkedInputStream.DEFAULT_CHUNK_SIZE; import java.nio.ByteBuffer; import java.util.Collections; import java.util.Optional; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.internal.compression.Compressor; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.async.DelegatingSubscriber; import software.amazon.awssdk.utils.async.FlatteningSubscriber; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Wrapper class to wrap an AsyncRequestBody. * This will chunk and compress the payload with the provided {@link Compressor}. */ @SdkInternalApi public class CompressionAsyncRequestBody implements AsyncRequestBody { private final AsyncRequestBody wrapped; private final Compressor compressor; private final ChunkBuffer chunkBuffer; private CompressionAsyncRequestBody(DefaultBuilder builder) { this.wrapped = Validate.paramNotNull(builder.asyncRequestBody, "asyncRequestBody"); this.compressor = Validate.paramNotNull(builder.compressor, "compressor"); int chunkSize = builder.chunkSize != null ? builder.chunkSize : DEFAULT_CHUNK_SIZE; this.chunkBuffer = ChunkBuffer.builder() .bufferSize(chunkSize) .build(); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { Validate.notNull(s, "Subscription MUST NOT be null."); SdkPublisher<Iterable<ByteBuffer>> split = split(wrapped).addTrailingData(() -> Collections.singleton(getBufferedDataIfPresent())); SdkPublisher<ByteBuffer> flattening = flattening(split); flattening.map(compressor::compress).subscribe(s); } @Override public Optional<Long> contentLength() { return wrapped.contentLength(); } @Override public String contentType() { return wrapped.contentType(); } private SdkPublisher<Iterable<ByteBuffer>> split(SdkPublisher<ByteBuffer> source) { return subscriber -> source.subscribe(new SplittingSubscriber(subscriber)); } private Iterable<ByteBuffer> getBufferedDataIfPresent() { return chunkBuffer.getBufferedData() .map(Collections::singletonList) .orElse(Collections.emptyList()); } private SdkPublisher<ByteBuffer> flattening(SdkPublisher<Iterable<ByteBuffer>> source) { return subscriber -> source.subscribe(new FlatteningSubscriber<>(subscriber)); } /** * @return Builder instance to construct a {@link CompressionAsyncRequestBody}. */ public static Builder builder() { return new DefaultBuilder(); } public interface Builder extends SdkBuilder<CompressionAsyncRequestBody.Builder, CompressionAsyncRequestBody> { /** * Sets the AsyncRequestBody that will be wrapped. * @param asyncRequestBody * @return This builder for method chaining. */ Builder asyncRequestBody(AsyncRequestBody asyncRequestBody); /** * Sets the compressor to compress the request. * @param compressor * @return This builder for method chaining. */ Builder compressor(Compressor compressor); /** * Sets the chunk size. Default size is 128 * 1024. * @param chunkSize * @return This builder for method chaining. */ Builder chunkSize(Integer chunkSize); } private static final class DefaultBuilder implements Builder { private AsyncRequestBody asyncRequestBody; private Compressor compressor; private Integer chunkSize; @Override public CompressionAsyncRequestBody build() { return new CompressionAsyncRequestBody(this); } @Override public Builder asyncRequestBody(AsyncRequestBody asyncRequestBody) { this.asyncRequestBody = asyncRequestBody; return this; } @Override public Builder compressor(Compressor compressor) { this.compressor = compressor; return this; } @Override public Builder chunkSize(Integer chunkSize) { this.chunkSize = chunkSize; return this; } } private final class SplittingSubscriber extends DelegatingSubscriber<ByteBuffer, Iterable<ByteBuffer>> { protected SplittingSubscriber(Subscriber<? super Iterable<ByteBuffer>> subscriber) { super(subscriber); } @Override public void onNext(ByteBuffer byteBuffer) { Iterable<ByteBuffer> buffers = chunkBuffer.split(byteBuffer); subscriber.onNext(buffers); } } }
2,186
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/async/AsyncStreamPrepender.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public class AsyncStreamPrepender<T> implements Publisher<T> { private final Publisher<T> delegate; private final T firstItem; public AsyncStreamPrepender(Publisher<T> delegate, T firstItem) { this.delegate = delegate; this.firstItem = firstItem; } @Override public void subscribe(Subscriber<? super T> s) { delegate.subscribe(new DelegateSubscriber(s)); } private class DelegateSubscriber implements Subscriber<T> { private final Subscriber<? super T> subscriber; private volatile boolean complete = false; private volatile boolean firstRequest = true; private DelegateSubscriber(Subscriber<? super T> subscriber) { this.subscriber = subscriber; } @Override public void onSubscribe(Subscription subscription) { subscriber.onSubscribe(new Subscription() { private final AtomicLong requests = new AtomicLong(0L); private volatile boolean cancelled = false; private volatile boolean isOutermostCall = true; @Override public void request(long n) { if (cancelled) { return; } if (n <= 0) { subscription.cancel(); subscriber.onError(new IllegalArgumentException("Requested " + n + " items")); } if (firstRequest) { firstRequest = false; if (n - 1 > 0) { requests.addAndGet(n - 1); } isOutermostCall = false; subscriber.onNext(firstItem); isOutermostCall = true; if (complete) { subscriber.onComplete(); return; } } else { requests.addAndGet(n); } if (isOutermostCall) { try { isOutermostCall = false; long l; while ((l = requests.getAndSet(0L)) > 0) { subscription.request(l); } } finally { isOutermostCall = true; } } } @Override public void cancel() { cancelled = true; subscription.cancel(); } }); } @Override public void onNext(T item) { subscriber.onNext(item); } @Override public void onError(Throwable t) { subscriber.onError(t); } @Override public void onComplete() { complete = true; if (!firstRequest) { subscriber.onComplete(); } } } }
2,187
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/async/FileAsyncRequestBody.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousFileChannel; import java.nio.channels.CompletionHandler; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.FileTime; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncRequestBodySplitConfiguration; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.internal.util.Mimetype; import software.amazon.awssdk.core.internal.util.NoopSubscription; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.NumericUtils; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Implementation of {@link AsyncRequestBody} that reads data from a file. * * @see AsyncRequestBody#fromFile(Path) * @see AsyncRequestBody#fromFile(java.io.File) */ @SdkInternalApi public final class FileAsyncRequestBody implements AsyncRequestBody { private static final Logger log = Logger.loggerFor(FileAsyncRequestBody.class); /** * Default size (in bytes) of ByteBuffer chunks read from the file and delivered to the subscriber. */ private static final int DEFAULT_CHUNK_SIZE = 16 * 1024; /** * File to read. */ private final Path path; private final long fileLength; /** * Size (in bytes) of ByteBuffer chunks read from the file and delivered to the subscriber. */ private final int chunkSizeInBytes; private final long position; private final long numBytesToRead; private FileAsyncRequestBody(DefaultBuilder builder) { this.path = builder.path; this.chunkSizeInBytes = builder.chunkSizeInBytes == null ? DEFAULT_CHUNK_SIZE : builder.chunkSizeInBytes; this.fileLength = invokeSafely(() -> Files.size(path)); this.position = builder.position == null ? 0 : Validate.isNotNegative(builder.position, "position"); this.numBytesToRead = builder.numBytesToRead == null ? fileLength - this.position : Validate.isNotNegative(builder.numBytesToRead, "numBytesToRead"); } @Override public SdkPublisher<AsyncRequestBody> split(AsyncRequestBodySplitConfiguration splitConfiguration) { Validate.notNull(splitConfiguration, "splitConfiguration"); return new FileAsyncRequestBodySplitHelper(this, splitConfiguration).split(); } public Path path() { return path; } public long fileLength() { return fileLength; } public int chunkSizeInBytes() { return chunkSizeInBytes; } public long position() { return position; } public long numBytesToRead() { return numBytesToRead; } @Override public Optional<Long> contentLength() { return Optional.of(numBytesToRead); } @Override public String contentType() { return Mimetype.getInstance().getMimetype(path); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { AsynchronousFileChannel channel = null; try { channel = openInputChannel(this.path); // We need to synchronize here because the subscriber could call // request() from within onSubscribe which would potentially // trigger onNext before onSubscribe is finished. Subscription subscription = new FileSubscription(channel, s); synchronized (subscription) { s.onSubscribe(subscription); } } catch (IOException | RuntimeException e) { if (channel != null) { runAndLogError(log.logger(), "Unable to close file channel", channel::close); } // subscribe() must return normally, so we need to signal the // failure to open via onError() once onSubscribe() is signaled. s.onSubscribe(new NoopSubscription(s)); s.onError(e); } } /** * @return Builder instance to construct a {@link FileAsyncRequestBody}. */ public static Builder builder() { return new DefaultBuilder(); } /** * A builder for {@link FileAsyncRequestBody}. */ public interface Builder extends SdkBuilder<Builder, FileAsyncRequestBody> { /** * Sets the file to send to the service. * * @param path Path to file to read. * @return This builder for method chaining. */ Builder path(Path path); /** * Sets the size of chunks to read from the file. Increasing this will cause more data to be buffered into memory but * may yield better latencies. Decreasing this will reduce memory usage but may cause reduced latency. Setting this value * is very dependent on upload speed and requires some performance testing to tune. * * <p>The default chunk size is {@value #DEFAULT_CHUNK_SIZE} bytes</p> * * @param chunkSize New chunk size in bytes. * @return This builder for method chaining. */ Builder chunkSizeInBytes(Integer chunkSize); /** * Sets the file position at which the request body begins. * * <p>By default, it's 0, i.e., reading from the beginning. * * @param position the position of the file * @return The builder for method chaining. */ Builder position(Long position); /** * Sets the number of bytes to read from this file. * * <p>By default, it's same as the file length. * * @param numBytesToRead number of bytes to read * @return The builder for method chaining. */ Builder numBytesToRead(Long numBytesToRead); } private static final class DefaultBuilder implements Builder { private Long position; private Path path; private Integer chunkSizeInBytes; private Long numBytesToRead; @Override public Builder path(Path path) { this.path = path; return this; } public void setPath(Path path) { path(path); } @Override public Builder chunkSizeInBytes(Integer chunkSizeInBytes) { this.chunkSizeInBytes = chunkSizeInBytes; return this; } @Override public Builder position(Long position) { this.position = position; return this; } @Override public Builder numBytesToRead(Long numBytesToRead) { this.numBytesToRead = numBytesToRead; return this; } public void setChunkSizeInBytes(Integer chunkSizeInBytes) { chunkSizeInBytes(chunkSizeInBytes); } @Override public FileAsyncRequestBody build() { return new FileAsyncRequestBody(this); } } /** * Reads the file for one subscriber. */ private final class FileSubscription implements Subscription { private final AsynchronousFileChannel inputChannel; private final Subscriber<? super ByteBuffer> subscriber; private final AtomicLong currentPosition; private final AtomicLong remainingBytes; private final long sizeAtStart; private final FileTime modifiedTimeAtStart; private long outstandingDemand = 0; private boolean readInProgress = false; private volatile boolean done = false; private final Object lock = new Object(); private FileSubscription(AsynchronousFileChannel inputChannel, Subscriber<? super ByteBuffer> subscriber) throws IOException { this.inputChannel = inputChannel; this.subscriber = subscriber; this.sizeAtStart = inputChannel.size(); this.modifiedTimeAtStart = Files.getLastModifiedTime(path); this.remainingBytes = new AtomicLong(numBytesToRead); this.currentPosition = new AtomicLong(position); } @Override public void request(long n) { if (done) { return; } if (n < 1) { IllegalArgumentException ex = new IllegalArgumentException(subscriber + " violated the Reactive Streams rule 3.9 by requesting a " + "non-positive number of elements."); signalOnError(ex); } else { try { // We need to synchronize here because of the race condition // where readData finishes reading at the same time request // demand comes in synchronized (lock) { // As governed by rule 3.17, when demand overflows `Long.MAX_VALUE` we treat the signalled demand as // "effectively unbounded" if (Long.MAX_VALUE - outstandingDemand < n) { outstandingDemand = Long.MAX_VALUE; } else { outstandingDemand += n; } if (!readInProgress) { readInProgress = true; readData(); } } } catch (Exception e) { signalOnError(e); } } } @Override public void cancel() { synchronized (this) { if (!done) { done = true; closeFile(); } } } private void readData() { // It's possible to have another request for data come in after we've closed the file. if (!inputChannel.isOpen() || done) { return; } ByteBuffer buffer = ByteBuffer.allocate(Math.min(chunkSizeInBytes, NumericUtils.saturatedCast(remainingBytes.get()))); inputChannel.read(buffer, currentPosition.get(), buffer, new CompletionHandler<Integer, ByteBuffer>() { @Override public void completed(Integer result, ByteBuffer attachment) { try { if (result > 0) { attachment.flip(); int readBytes = attachment.remaining(); currentPosition.addAndGet(readBytes); remainingBytes.addAndGet(-readBytes); signalOnNext(attachment); if (remainingBytes.get() == 0) { closeFile(); signalOnComplete(); } synchronized (lock) { // If we have more permits, queue up another read. if (--outstandingDemand > 0) { readData(); } else { readInProgress = false; } } } else { // Reached the end of the file, notify the subscriber and cleanup closeFile(); signalOnComplete(); } } catch (Throwable throwable) { closeFile(); signalOnError(throwable); } } @Override public void failed(Throwable exc, ByteBuffer attachment) { signalOnError(exc); closeFile(); } }); } private void closeFile() { try { inputChannel.close(); } catch (IOException e) { log.warn(() -> "Failed to close the file", e); } } private void signalOnNext(ByteBuffer attachment) { synchronized (this) { if (!done) { subscriber.onNext(attachment); } } } private void signalOnComplete() { try { long sizeAtEnd = Files.size(path); if (sizeAtStart != sizeAtEnd) { signalOnError(new IOException("File size changed after reading started. Initial size: " + sizeAtStart + ". " + "Current size: " + sizeAtEnd)); return; } if (remainingBytes.get() > 0) { signalOnError(new IOException("Fewer bytes were read than were expected, was the file modified after " + "reading started?")); return; } FileTime modifiedTimeAtEnd = Files.getLastModifiedTime(path); if (modifiedTimeAtStart.compareTo(modifiedTimeAtEnd) != 0) { signalOnError(new IOException("File last-modified time changed after reading started. Initial modification " + "time: " + modifiedTimeAtStart + ". Current modification time: " + modifiedTimeAtEnd)); return; } } catch (NoSuchFileException e) { signalOnError(new IOException("Unable to check file status after read. Was the file deleted or were its " + "permissions changed?", e)); return; } catch (IOException e) { signalOnError(new IOException("Unable to check file status after read.", e)); return; } synchronized (this) { if (!done) { done = true; subscriber.onComplete(); } } } private void signalOnError(Throwable t) { synchronized (this) { if (!done) { done = true; subscriber.onError(t); } } } } private static AsynchronousFileChannel openInputChannel(Path path) throws IOException { return AsynchronousFileChannel.open(path, StandardOpenOption.READ); } }
2,188
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/async/InputStreamWithExecutorAsyncRequestBody.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Optional; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncRequestBodyFromInputStreamConfiguration; import software.amazon.awssdk.core.async.BlockingInputStreamAsyncRequestBody; import software.amazon.awssdk.core.exception.NonRetryableException; import software.amazon.awssdk.core.internal.util.NoopSubscription; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Logger; /** * A {@link AsyncRequestBody} that allows reading data off of an {@link InputStream} using a background * {@link ExecutorService}. * <p> * Created via {@link AsyncRequestBody#fromInputStream(InputStream, Long, ExecutorService)}. */ @SdkInternalApi public class InputStreamWithExecutorAsyncRequestBody implements AsyncRequestBody { private static final Logger log = Logger.loggerFor(InputStreamWithExecutorAsyncRequestBody.class); private final Object subscribeLock = new Object(); private final InputStream inputStream; private final Long contentLength; private final ExecutorService executor; private Future<?> writeFuture; public InputStreamWithExecutorAsyncRequestBody(AsyncRequestBodyFromInputStreamConfiguration configuration) { this.inputStream = configuration.inputStream(); this.contentLength = configuration.contentLength(); this.executor = configuration.executor(); IoUtils.markStreamWithMaxReadLimit(inputStream, configuration.maxReadLimit()); } @Override public Optional<Long> contentLength() { return Optional.ofNullable(contentLength); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { // Each subscribe cancels the previous subscribe. synchronized (subscribeLock) { try { if (writeFuture != null) { writeFuture.cancel(true); waitForCancellation(writeFuture); // Wait for the cancellation tryReset(inputStream); } BlockingInputStreamAsyncRequestBody delegate = AsyncRequestBody.forBlockingInputStream(contentLength); writeFuture = executor.submit(() -> doBlockingWrite(delegate)); delegate.subscribe(s); } catch (Throwable t) { s.onSubscribe(new NoopSubscription(s)); s.onError(t); } } } private void tryReset(InputStream inputStream) { try { inputStream.reset(); } catch (IOException e) { String message = "Request cannot be retried, because the request stream could not be reset."; throw NonRetryableException.create(message, e); } } @SdkTestInternalApi public Future<?> activeWriteFuture() { synchronized (subscribeLock) { return writeFuture; } } private void doBlockingWrite(BlockingInputStreamAsyncRequestBody asyncRequestBody) { try { asyncRequestBody.writeInputStream(inputStream); } catch (Throwable t) { log.debug(() -> "Encountered error while writing input stream to service.", t); throw t; } } private void waitForCancellation(Future<?> writeFuture) { try { writeFuture.get(10, TimeUnit.SECONDS); } catch (ExecutionException | CancellationException e) { // Expected - we cancelled. } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (TimeoutException e) { throw new IllegalStateException("Timed out waiting to reset the input stream.", e); } } }
2,189
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/async/FileAsyncResponseTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import static software.amazon.awssdk.core.FileTransformerConfiguration.FileWriteOption.CREATE_OR_APPEND_TO_EXISTING; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousFileChannel; import java.nio.channels.CompletionHandler; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.FileTransformerConfiguration; import software.amazon.awssdk.core.FileTransformerConfiguration.FailureBehavior; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.exception.SdkClientException; /** * {@link AsyncResponseTransformer} that writes the data to the specified file. * * @param <ResponseT> Response POJO type. */ @SdkInternalApi public final class FileAsyncResponseTransformer<ResponseT> implements AsyncResponseTransformer<ResponseT, ResponseT> { private final Path path; private volatile AsynchronousFileChannel fileChannel; private volatile CompletableFuture<Void> cf; private volatile ResponseT response; private final long position; private final FileTransformerConfiguration configuration; public FileAsyncResponseTransformer(Path path) { this.path = path; this.configuration = FileTransformerConfiguration.defaultCreateNew(); this.position = 0L; } public FileAsyncResponseTransformer(Path path, FileTransformerConfiguration fileConfiguration) { this.path = path; this.configuration = fileConfiguration; this.position = determineFilePositionToWrite(path); } private long determineFilePositionToWrite(Path path) { if (configuration.fileWriteOption() == CREATE_OR_APPEND_TO_EXISTING) { try { return Files.size(path); } catch (NoSuchFileException e) { // Ignore } catch (IOException exception) { throw SdkClientException.create("Cannot determine the current file size " + path, exception); } } return 0L; } private AsynchronousFileChannel createChannel(Path path) throws IOException { Set<OpenOption> options = new HashSet<>(); switch (configuration.fileWriteOption()) { case CREATE_OR_APPEND_TO_EXISTING: Collections.addAll(options, StandardOpenOption.WRITE, StandardOpenOption.CREATE); break; case CREATE_OR_REPLACE_EXISTING: Collections.addAll(options, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); break; case CREATE_NEW: Collections.addAll(options, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW); break; default: throw new IllegalArgumentException("Unsupported file write option: " + configuration.fileWriteOption()); } ExecutorService executorService = configuration.executorService().orElse(null); return AsynchronousFileChannel.open(path, options, executorService); } @Override public CompletableFuture<ResponseT> prepare() { cf = new CompletableFuture<>(); cf.whenComplete((r, t) -> { if (t != null && fileChannel != null) { invokeSafely(fileChannel::close); } }); return cf.thenApply(ignored -> response); } @Override public void onResponse(ResponseT response) { this.response = response; } @Override public void onStream(SdkPublisher<ByteBuffer> publisher) { // onStream may be called multiple times so reset the file channel every time this.fileChannel = invokeSafely(() -> createChannel(path)); publisher.subscribe(new FileSubscriber(this.fileChannel, path, cf, this::exceptionOccurred, position)); } @Override public void exceptionOccurred(Throwable throwable) { try { if (fileChannel != null) { invokeSafely(fileChannel::close); } } finally { if (configuration.failureBehavior() == FailureBehavior.DELETE) { invokeSafely(() -> Files.deleteIfExists(path)); } } cf.completeExceptionally(throwable); } /** * {@link Subscriber} implementation that writes chunks to a file. */ static class FileSubscriber implements Subscriber<ByteBuffer> { private final AtomicLong position; private final AsynchronousFileChannel fileChannel; private final Path path; private final CompletableFuture<Void> future; private final Consumer<Throwable> onErrorMethod; private volatile boolean writeInProgress = false; private volatile boolean closeOnLastWrite = false; private Subscription subscription; FileSubscriber(AsynchronousFileChannel fileChannel, Path path, CompletableFuture<Void> future, Consumer<Throwable> onErrorMethod, long startingPosition) { this.fileChannel = fileChannel; this.path = path; this.future = future; this.onErrorMethod = onErrorMethod; this.position = new AtomicLong(startingPosition); } @Override public void onSubscribe(Subscription s) { if (this.subscription != null) { s.cancel(); return; } this.subscription = s; // Request the first chunk to start producing content s.request(1); } @Override public void onNext(ByteBuffer byteBuffer) { if (byteBuffer == null) { throw new NullPointerException("Element must not be null"); } performWrite(byteBuffer); } private void performWrite(ByteBuffer byteBuffer) { writeInProgress = true; fileChannel.write(byteBuffer, position.get(), byteBuffer, new CompletionHandler<Integer, ByteBuffer>() { @Override public void completed(Integer result, ByteBuffer attachment) { position.addAndGet(result); if (byteBuffer.hasRemaining()) { performWrite(byteBuffer); } else { synchronized (FileSubscriber.this) { writeInProgress = false; if (closeOnLastWrite) { close(); } else { subscription.request(1); } } } } @Override public void failed(Throwable exc, ByteBuffer attachment) { subscription.cancel(); future.completeExceptionally(exc); } }); } @Override public void onError(Throwable t) { onErrorMethod.accept(t); } @Override public void onComplete() { // if write in progress, tell write to close on finish. synchronized (this) { if (writeInProgress) { closeOnLastWrite = true; } else { close(); } } } private void close() { try { if (fileChannel != null) { invokeSafely(fileChannel::close); } future.complete(null); } catch (RuntimeException exception) { future.completeExceptionally(exception); } } @Override public String toString() { return getClass() + ":" + path.toString(); } } }
2,190
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/async/SplittingPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import java.nio.ByteBuffer; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncRequestBodySplitConfiguration; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.exception.NonRetryableException; import software.amazon.awssdk.core.internal.util.NoopSubscription; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.async.SimplePublisher; /** * Splits an {@link AsyncRequestBody} to multiple smaller {@link AsyncRequestBody}s, each of which publishes a specific portion of * the original data. * * <p>If content length is known, each {@link AsyncRequestBody} is sent to the subscriber right after it's initialized. * Otherwise, it is sent after the entire content for that chunk is buffered. This is required to get content length. */ @SdkInternalApi public class SplittingPublisher implements SdkPublisher<AsyncRequestBody> { private static final Logger log = Logger.loggerFor(SplittingPublisher.class); private final AsyncRequestBody upstreamPublisher; private final SplittingSubscriber splittingSubscriber; private final SimplePublisher<AsyncRequestBody> downstreamPublisher = new SimplePublisher<>(); private final long chunkSizeInBytes; private final long bufferSizeInBytes; public SplittingPublisher(AsyncRequestBody asyncRequestBody, AsyncRequestBodySplitConfiguration splitConfiguration) { this.upstreamPublisher = Validate.paramNotNull(asyncRequestBody, "asyncRequestBody"); Validate.notNull(splitConfiguration, "splitConfiguration"); this.chunkSizeInBytes = splitConfiguration.chunkSizeInBytes() == null ? AsyncRequestBodySplitConfiguration.defaultConfiguration().chunkSizeInBytes() : splitConfiguration.chunkSizeInBytes(); this.bufferSizeInBytes = splitConfiguration.bufferSizeInBytes() == null ? AsyncRequestBodySplitConfiguration.defaultConfiguration().bufferSizeInBytes() : splitConfiguration.bufferSizeInBytes(); this.splittingSubscriber = new SplittingSubscriber(upstreamPublisher.contentLength().orElse(null)); if (!upstreamPublisher.contentLength().isPresent()) { Validate.isTrue(bufferSizeInBytes >= chunkSizeInBytes, "bufferSizeInBytes must be larger than or equal to " + "chunkSizeInBytes if the content length is unknown"); } } @Override public void subscribe(Subscriber<? super AsyncRequestBody> downstreamSubscriber) { downstreamPublisher.subscribe(downstreamSubscriber); upstreamPublisher.subscribe(splittingSubscriber); } private class SplittingSubscriber implements Subscriber<ByteBuffer> { private Subscription upstreamSubscription; private final Long upstreamSize; private final AtomicInteger chunkNumber = new AtomicInteger(0); private volatile DownstreamBody currentBody; private final AtomicBoolean hasOpenUpstreamDemand = new AtomicBoolean(false); private final AtomicLong dataBuffered = new AtomicLong(0); /** * A hint to determine whether we will exceed maxMemoryUsage by the next OnNext call. */ private int byteBufferSizeHint; private volatile boolean upstreamComplete; SplittingSubscriber(Long upstreamSize) { this.upstreamSize = upstreamSize; } @Override public void onSubscribe(Subscription s) { this.upstreamSubscription = s; this.currentBody = initializeNextDownstreamBody(upstreamSize != null, calculateChunkSize(upstreamSize), chunkNumber.get()); // We need to request subscription *after* we set currentBody because onNext could be invoked right away. upstreamSubscription.request(1); } private DownstreamBody initializeNextDownstreamBody(boolean contentLengthKnown, long chunkSize, int chunkNumber) { DownstreamBody body = new DownstreamBody(contentLengthKnown, chunkSize, chunkNumber); if (contentLengthKnown) { sendCurrentBody(body); } return body; } @Override public void onNext(ByteBuffer byteBuffer) { hasOpenUpstreamDemand.set(false); byteBufferSizeHint = byteBuffer.remaining(); while (true) { if (!byteBuffer.hasRemaining()) { break; } int amountRemainingInChunk = amountRemainingInChunk(); // If we have fulfilled this chunk, // complete the current body if (amountRemainingInChunk == 0) { completeCurrentBodyAndCreateNewIfNeeded(byteBuffer); amountRemainingInChunk = amountRemainingInChunk(); } // If the current ByteBuffer < this chunk, send it as-is if (amountRemainingInChunk > byteBuffer.remaining()) { currentBody.send(byteBuffer.duplicate()); break; } // If the current ByteBuffer == this chunk, send it as-is and // complete the current body if (amountRemainingInChunk == byteBuffer.remaining()) { currentBody.send(byteBuffer.duplicate()); completeCurrentBodyAndCreateNewIfNeeded(byteBuffer); break; } // If the current ByteBuffer > this chunk, split this ByteBuffer ByteBuffer firstHalf = byteBuffer.duplicate(); int newLimit = firstHalf.position() + amountRemainingInChunk; firstHalf.limit(newLimit); byteBuffer.position(newLimit); currentBody.send(firstHalf); } maybeRequestMoreUpstreamData(); } private void completeCurrentBodyAndCreateNewIfNeeded(ByteBuffer byteBuffer) { completeCurrentBody(); int currentChunk = chunkNumber.incrementAndGet(); boolean shouldCreateNewDownstreamRequestBody; Long dataRemaining = totalDataRemaining(); if (upstreamSize == null) { shouldCreateNewDownstreamRequestBody = !upstreamComplete || byteBuffer.hasRemaining(); } else { shouldCreateNewDownstreamRequestBody = dataRemaining != null && dataRemaining > 0; } if (shouldCreateNewDownstreamRequestBody) { long chunkSize = calculateChunkSize(dataRemaining); currentBody = initializeNextDownstreamBody(upstreamSize != null, chunkSize, currentChunk); } } private int amountRemainingInChunk() { return Math.toIntExact(currentBody.maxLength - currentBody.transferredLength); } private void completeCurrentBody() { log.debug(() -> "completeCurrentBody for chunk " + chunkNumber.get()); currentBody.complete(); if (upstreamSize == null) { sendCurrentBody(currentBody); } } @Override public void onComplete() { upstreamComplete = true; log.trace(() -> "Received onComplete()"); completeCurrentBody(); downstreamPublisher.complete(); } @Override public void onError(Throwable t) { log.trace(() -> "Received onError()", t); downstreamPublisher.error(t); } private void sendCurrentBody(AsyncRequestBody body) { downstreamPublisher.send(body).exceptionally(t -> { downstreamPublisher.error(t); return null; }); } private long calculateChunkSize(Long dataRemaining) { // Use default chunk size if the content length is unknown if (dataRemaining == null) { return chunkSizeInBytes; } return Math.min(chunkSizeInBytes, dataRemaining); } private void maybeRequestMoreUpstreamData() { long buffered = dataBuffered.get(); if (shouldRequestMoreData(buffered) && hasOpenUpstreamDemand.compareAndSet(false, true)) { log.trace(() -> "Requesting more data, current data buffered: " + buffered); upstreamSubscription.request(1); } } private boolean shouldRequestMoreData(long buffered) { return buffered == 0 || buffered + byteBufferSizeHint <= bufferSizeInBytes; } private Long totalDataRemaining() { if (upstreamSize == null) { return null; } return upstreamSize - (chunkNumber.get() * chunkSizeInBytes); } private final class DownstreamBody implements AsyncRequestBody { /** * The maximum length of the content this AsyncRequestBody can hold. If the upstream content length is known, this is * the same as totalLength */ private final long maxLength; private final Long totalLength; private final SimplePublisher<ByteBuffer> delegate = new SimplePublisher<>(); private final int chunkNumber; private final AtomicBoolean subscribeCalled = new AtomicBoolean(false); private volatile long transferredLength = 0; private DownstreamBody(boolean contentLengthKnown, long maxLength, int chunkNumber) { this.totalLength = contentLengthKnown ? maxLength : null; this.maxLength = maxLength; this.chunkNumber = chunkNumber; } @Override public Optional<Long> contentLength() { return totalLength != null ? Optional.of(totalLength) : Optional.of(transferredLength); } public void send(ByteBuffer data) { log.trace(() -> String.format("Sending bytebuffer %s to chunk %d", data, chunkNumber)); int length = data.remaining(); transferredLength += length; addDataBuffered(length); delegate.send(data).whenComplete((r, t) -> { addDataBuffered(-length); if (t != null) { error(t); } }); } public void complete() { log.debug(() -> "Received complete() for chunk number: " + chunkNumber + " length " + transferredLength); delegate.complete().whenComplete((r, t) -> { if (t != null) { error(t); } }); } public void error(Throwable error) { delegate.error(error); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { if (subscribeCalled.compareAndSet(false, true)) { delegate.subscribe(s); } else { s.onSubscribe(new NoopSubscription(s)); s.onError(NonRetryableException.create( "A retry was attempted, but AsyncRequestBody.split does not " + "support retries.")); } } private void addDataBuffered(int length) { dataBuffered.addAndGet(length); if (length < 0) { maybeRequestMoreUpstreamData(); } } } } }
2,191
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/async/ByteArrayAsyncResponseTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.utils.BinaryUtils; /** * Implementation of {@link AsyncResponseTransformer} that dumps content into a byte array and supports further * conversions into types, like strings. * * This can be created with static methods on {@link AsyncResponseTransformer}. * * @param <ResponseT> Pojo response type. * @see AsyncResponseTransformer#toBytes() */ @SdkInternalApi public final class ByteArrayAsyncResponseTransformer<ResponseT> implements AsyncResponseTransformer<ResponseT, ResponseBytes<ResponseT>> { private volatile CompletableFuture<byte[]> cf; private volatile ResponseT response; @Override public CompletableFuture<ResponseBytes<ResponseT>> prepare() { cf = new CompletableFuture<>(); return cf.thenApply(arr -> ResponseBytes.fromByteArray(response, arr)); } @Override public void onResponse(ResponseT response) { this.response = response; } @Override public void onStream(SdkPublisher<ByteBuffer> publisher) { publisher.subscribe(new BaosSubscriber(cf)); } @Override public void exceptionOccurred(Throwable throwable) { cf.completeExceptionally(throwable); } static class BaosSubscriber implements Subscriber<ByteBuffer> { private final CompletableFuture<byte[]> resultFuture; private ByteArrayOutputStream baos = new ByteArrayOutputStream(); private Subscription subscription; BaosSubscriber(CompletableFuture<byte[]> resultFuture) { this.resultFuture = resultFuture; } @Override public void onSubscribe(Subscription s) { if (this.subscription != null) { s.cancel(); return; } this.subscription = s; subscription.request(Long.MAX_VALUE); } @Override public void onNext(ByteBuffer byteBuffer) { invokeSafely(() -> baos.write(BinaryUtils.copyBytesFrom(byteBuffer))); subscription.request(1); } @Override public void onError(Throwable throwable) { baos = null; resultFuture.completeExceptionally(throwable); } @Override public void onComplete() { resultFuture.complete(baos.toByteArray()); } } }
2,192
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/async/PublisherAsyncResponseTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.async; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.ResponsePublisher; import software.amazon.awssdk.core.async.SdkPublisher; /** * Transforms a {@link ResponseT} and {@link ByteBuffer} {@link SdkPublisher} into a {@link ResponsePublisher}. * * @param <ResponseT> Pojo response type. * @see AsyncResponseTransformer#toPublisher() */ @SdkInternalApi public final class PublisherAsyncResponseTransformer<ResponseT extends SdkResponse> implements AsyncResponseTransformer<ResponseT, ResponsePublisher<ResponseT>> { private volatile CompletableFuture<ResponsePublisher<ResponseT>> future; private volatile ResponseT response; @Override public CompletableFuture<ResponsePublisher<ResponseT>> prepare() { CompletableFuture<ResponsePublisher<ResponseT>> f = new CompletableFuture<>(); this.future = f; return f; } @Override public void onResponse(ResponseT response) { this.response = response; } @Override public void onStream(SdkPublisher<ByteBuffer> publisher) { future.complete(new ResponsePublisher<>(response, publisher)); } @Override public void exceptionOccurred(Throwable error) { future.completeExceptionally(error); } }
2,193
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/io/AwsCompressionInputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.io; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.internal.compression.Compressor; import software.amazon.awssdk.utils.Validate; /** * A wrapper class of InputStream that implements compression in chunks. */ @SdkInternalApi public final class AwsCompressionInputStream extends AwsChunkedInputStream { private final Compressor compressor; private AwsCompressionInputStream(InputStream in, Compressor compressor) { this.compressor = compressor; if (in instanceof AwsCompressionInputStream) { // This could happen when the request is retried. AwsCompressionInputStream originalCompressionStream = (AwsCompressionInputStream) in; this.is = originalCompressionStream.is; this.underlyingStreamBuffer = originalCompressionStream.underlyingStreamBuffer; } else { this.is = in; this.underlyingStreamBuffer = null; } } public static Builder builder() { return new Builder(); } @Override public int read(byte[] b, int off, int len) throws IOException { abortIfNeeded(); Validate.notNull(b, "buff"); if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } if (currentChunkIterator == null || !currentChunkIterator.hasNext()) { if (isTerminating) { return -1; } isTerminating = setUpNextChunk(); } int count = currentChunkIterator.read(b, off, len); if (count > 0) { isAtStart = false; log.trace(() -> count + " byte read from the stream."); } return count; } private boolean setUpNextChunk() throws IOException { byte[] chunkData = new byte[DEFAULT_CHUNK_SIZE]; int chunkSizeInBytes = 0; while (chunkSizeInBytes < DEFAULT_CHUNK_SIZE) { /** Read from the buffer of the uncompressed stream */ if (underlyingStreamBuffer != null && underlyingStreamBuffer.hasNext()) { chunkData[chunkSizeInBytes++] = underlyingStreamBuffer.next(); } else { /** Read from the wrapped stream */ int bytesToRead = DEFAULT_CHUNK_SIZE - chunkSizeInBytes; int count = is.read(chunkData, chunkSizeInBytes, bytesToRead); if (count != -1) { if (underlyingStreamBuffer != null) { underlyingStreamBuffer.buffer(chunkData, chunkSizeInBytes, count); } chunkSizeInBytes += count; } else { break; } } } if (chunkSizeInBytes == 0) { return true; } if (chunkSizeInBytes < chunkData.length) { chunkData = Arrays.copyOf(chunkData, chunkSizeInBytes); } // Compress the chunk byte[] compressedChunkData = compressor.compress(chunkData); currentChunkIterator = new ChunkContentIterator(compressedChunkData); return false; } /** * The readlimit parameter is ignored. */ @Override public void mark(int readlimit) { abortIfNeeded(); if (!isAtStart) { throw new UnsupportedOperationException("Compression stream only supports mark() at the start of the stream."); } if (is.markSupported()) { log.debug(() -> "AwsCompressionInputStream marked at the start of the stream " + "(will directly mark the wrapped stream since it's mark-supported)."); is.mark(readlimit); } else { log.debug(() -> "AwsCompressionInputStream marked at the start of the stream " + "(initializing the buffer since the wrapped stream is not mark-supported)."); underlyingStreamBuffer = new UnderlyingStreamBuffer(SKIP_BUFFER_SIZE); } } /** * Reset the stream, either by resetting the wrapped stream or using the * buffer created by this class. */ @Override public void reset() throws IOException { abortIfNeeded(); // Clear up any encoded data currentChunkIterator = null; // Reset the wrapped stream if it is mark-supported, // otherwise use our buffered data. if (is.markSupported()) { log.debug(() -> "AwsCompressionInputStream reset " + "(will reset the wrapped stream because it is mark-supported)."); is.reset(); } else { log.debug(() -> "AwsCompressionInputStream reset (will use the buffer of the decoded stream)."); Validate.notNull(underlyingStreamBuffer, "Cannot reset the stream because the mark is not set."); underlyingStreamBuffer.startReadBuffer(); } isAtStart = true; isTerminating = false; } public static final class Builder { InputStream inputStream; Compressor compressor; public AwsCompressionInputStream build() { return new AwsCompressionInputStream( this.inputStream, this.compressor); } public Builder inputStream(InputStream inputStream) { this.inputStream = inputStream; return this; } public Builder compressor(Compressor compressor) { this.compressor = compressor; return this; } } }
2,194
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/io/AwsChunkedEncodingInputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.io; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.internal.chunked.AwsChunkedEncodingConfig; import software.amazon.awssdk.utils.Validate; /** * A wrapper of InputStream that implements pseudo-chunked-encoding. * Each chunk will be buffered for the calculation of the chunk signature * which is added at the head of each chunk.<br> * The default chunk size cannot be customized, since we need to calculate * the expected encoded stream length before reading the wrapped stream.<br> * This class will use the mark() &amp; reset() of the wrapped InputStream if they * are supported, otherwise it will create a buffer for bytes read from * the wrapped stream. */ @SdkInternalApi public abstract class AwsChunkedEncodingInputStream extends AwsChunkedInputStream { protected static final String CRLF = "\r\n"; protected static final byte[] FINAL_CHUNK = new byte[0]; protected static final String HEADER_COLON_SEPARATOR = ":"; protected byte[] calculatedChecksum = null; protected final String checksumHeaderForTrailer; protected boolean isTrailingTerminated = true; private final int chunkSize; private final int maxBufferSize; private final SdkChecksum sdkChecksum; private boolean isLastTrailingCrlf; /** * Creates a chunked encoding input stream initialized with the originating stream. The configuration allows * specification of the size of each chunk, as well as the buffer size. Use the same values as when * calculating total length of the stream. * * @param in The original InputStream. * @param config The configuration allows the user to customize chunk size and buffer size. * See {@link AwsChunkedEncodingConfig} for default values. */ protected AwsChunkedEncodingInputStream(InputStream in, SdkChecksum sdkChecksum, String checksumHeaderForTrailer, AwsChunkedEncodingConfig config) { AwsChunkedEncodingConfig awsChunkedEncodingConfig = config == null ? AwsChunkedEncodingConfig.create() : config; int providedMaxBufferSize = awsChunkedEncodingConfig.bufferSize(); if (in instanceof AwsChunkedEncodingInputStream) { // This could happen when the request is retried. AwsChunkedEncodingInputStream originalChunkedStream = (AwsChunkedEncodingInputStream) in; providedMaxBufferSize = Math.max(originalChunkedStream.maxBufferSize, providedMaxBufferSize); is = originalChunkedStream.is; underlyingStreamBuffer = originalChunkedStream.underlyingStreamBuffer; } else { is = in; underlyingStreamBuffer = null; } this.chunkSize = awsChunkedEncodingConfig.chunkSize(); this.maxBufferSize = providedMaxBufferSize; if (maxBufferSize < chunkSize) { throw new IllegalArgumentException("Max buffer size should not be less than chunk size"); } this.sdkChecksum = sdkChecksum; this.checksumHeaderForTrailer = checksumHeaderForTrailer; } protected abstract static class Builder<T extends Builder> { protected InputStream inputStream; protected SdkChecksum sdkChecksum; protected String checksumHeaderForTrailer; protected AwsChunkedEncodingConfig awsChunkedEncodingConfig; protected Builder() { } /** * @param inputStream The original InputStream. * @return */ public T inputStream(InputStream inputStream) { this.inputStream = inputStream; return (T) this; } /** * @param awsChunkedEncodingConfig Maximum number of bytes buffered by this class. * @return */ public T awsChunkedEncodingConfig(AwsChunkedEncodingConfig awsChunkedEncodingConfig) { this.awsChunkedEncodingConfig = awsChunkedEncodingConfig; return (T) this; } /** * * @param sdkChecksum Instance of SdkChecksum, this can be null if we do not want to calculate Checksum * @return */ public T sdkChecksum(SdkChecksum sdkChecksum) { this.sdkChecksum = sdkChecksum; return (T) this; } /** * * @param checksumHeaderForTrailer String value of Trailer header where checksum will be updated. * @return */ public T checksumHeaderForTrailer(String checksumHeaderForTrailer) { this.checksumHeaderForTrailer = checksumHeaderForTrailer; return (T) this; } } @Override public int read(byte[] b, int off, int len) throws IOException { abortIfNeeded(); Validate.notNull(b, "buff"); if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } if (null == currentChunkIterator || !currentChunkIterator.hasNext()) { if (isTerminating && isTrailingTerminated) { return -1; } else if (!isTerminating) { isTerminating = setUpNextChunk(); } else { isTrailingTerminated = setUpTrailingChunks(); } } int count = currentChunkIterator.read(b, off, len); if (count > 0) { isAtStart = false; log.trace(() -> count + " byte read from the stream."); } return count; } private boolean setUpTrailingChunks() { if (sdkChecksum == null) { return true; } if (calculatedChecksum == null) { calculatedChecksum = sdkChecksum.getChecksumBytes(); currentChunkIterator = new ChunkContentIterator(createChecksumChunkHeader()); return false; } else if (!isLastTrailingCrlf) { // Signed Payload needs Checksums to be signed at the end. currentChunkIterator = new ChunkContentIterator(CRLF.getBytes(StandardCharsets.UTF_8)); isLastTrailingCrlf = true; } return true; } /** * The readlimit parameter is ignored. */ @Override public void mark(int readlimit) { abortIfNeeded(); if (!isAtStart) { throw new UnsupportedOperationException("Chunk-encoded stream only supports mark() at the start of the stream."); } if (sdkChecksum != null) { sdkChecksum.mark(readlimit); } if (is.markSupported()) { log.debug(() -> "AwsChunkedEncodingInputStream marked at the start of the stream " + "(will directly mark the wrapped stream since it's mark-supported)."); is.mark(readlimit); } else { log.debug(() -> "AwsChunkedEncodingInputStream marked at the start of the stream " + "(initializing the buffer since the wrapped stream is not mark-supported)."); underlyingStreamBuffer = new UnderlyingStreamBuffer(maxBufferSize); } } /** * Reset the stream, either by resetting the wrapped stream or using the * buffer created by this class. */ @Override public void reset() throws IOException { abortIfNeeded(); // Clear up any encoded data currentChunkIterator = null; if (sdkChecksum != null) { sdkChecksum.reset(); } // Reset the wrapped stream if it is mark-supported, // otherwise use our buffered data. if (is.markSupported()) { log.debug(() -> "AwsChunkedEncodingInputStream reset " + "(will reset the wrapped stream because it is mark-supported)."); is.reset(); } else { log.debug(() -> "AwsChunkedEncodingInputStream reset (will use the buffer of the decoded stream)."); Validate.notNull(underlyingStreamBuffer, "Cannot reset the stream because the mark is not set."); underlyingStreamBuffer.startReadBuffer(); } isAtStart = true; isTerminating = false; } /** * Read in the next chunk of data, and create the necessary chunk extensions. * * @return Returns true if next chunk is the last empty chunk. */ private boolean setUpNextChunk() throws IOException { byte[] chunkData = new byte[chunkSize]; int chunkSizeInBytes = 0; while (chunkSizeInBytes < chunkSize) { /** Read from the buffer of the decoded stream */ if (null != underlyingStreamBuffer && underlyingStreamBuffer.hasNext()) { chunkData[chunkSizeInBytes++] = underlyingStreamBuffer.next(); } else { /** Read from the wrapped stream */ int bytesToRead = chunkSize - chunkSizeInBytes; int count = is.read(chunkData, chunkSizeInBytes, bytesToRead); if (count != -1) { if (null != underlyingStreamBuffer) { underlyingStreamBuffer.buffer(chunkData, chunkSizeInBytes, count); } chunkSizeInBytes += count; } else { break; } } } if (chunkSizeInBytes == 0) { if (sdkChecksum != null) { isTrailingTerminated = false; } byte[] finalChunk = createFinalChunk(FINAL_CHUNK); currentChunkIterator = new ChunkContentIterator(finalChunk); return true; } else { if (chunkSizeInBytes < chunkData.length) { chunkData = Arrays.copyOf(chunkData, chunkSizeInBytes); } byte[] chunkContent = createChunk(chunkData); currentChunkIterator = new ChunkContentIterator(chunkContent); if (sdkChecksum != null) { sdkChecksum.update(chunkData); } return false; } } /** * The final chunk. * * @param finalChunk The last byte which will be often 0 byte. * @return Final chunk that will be appended with CRLF or any required signatures. */ protected abstract byte[] createFinalChunk(byte[] finalChunk); /** * Creates chunk for the given buffer. * The chucks could be appended with Signatures or any additional bytes by Concrete classes. * * @param chunkData The chunk of original data. * @return Chunked data which will have signature if signed or just data if unsigned. */ protected abstract byte[] createChunk(byte[] chunkData); /** * @return ChecksumChunkHeader in bytes based on the Header name field. */ protected abstract byte[] createChecksumChunkHeader(); }
2,195
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/io/SdkLengthAwareInputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.io; import static software.amazon.awssdk.utils.NumericUtils.saturatedCast; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * An {@code InputStream} that is aware of its length. The main purpose of this class is to support truncating streams to a * length that is shorter than the total length of the stream. */ @SdkInternalApi public class SdkLengthAwareInputStream extends FilterInputStream { private static final Logger LOG = Logger.loggerFor(SdkLengthAwareInputStream.class); private long length; private long remaining; public SdkLengthAwareInputStream(InputStream in, long length) { super(in); this.length = Validate.isNotNegative(length, "length"); this.remaining = this.length; } @Override public int read() throws IOException { if (!hasMoreBytes()) { LOG.debug(() -> String.format("Specified InputStream length of %d has been reached. Returning EOF.", length)); return -1; } int read = super.read(); if (read != -1) { remaining--; } return read; } @Override public int read(byte[] b, int off, int len) throws IOException { if (!hasMoreBytes()) { LOG.debug(() -> String.format("Specified InputStream length of %d has been reached. Returning EOF.", length)); return -1; } len = Math.min(len, saturatedCast(remaining)); int read = super.read(b, off, len); if (read > 0) { remaining -= read; } return read; } @Override public long skip(long requestedBytesToSkip) throws IOException { requestedBytesToSkip = Math.min(requestedBytesToSkip, remaining); long skippedActual = super.skip(requestedBytesToSkip); remaining -= skippedActual; return skippedActual; } @Override public int available() throws IOException { int streamAvailable = super.available(); return Math.min(streamAvailable, saturatedCast(remaining)); } @Override public void mark(int readlimit) { super.mark(readlimit); // mark() causes reset() to change the stream's position back to the current position. Therefore, when reset() is called, // the new length of the stream will be equal to the current value of 'remaining'. length = remaining; } @Override public void reset() throws IOException { super.reset(); remaining = length; } public long remaining() { return remaining; } private boolean hasMoreBytes() { return remaining > 0; } }
2,196
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/io/ChunkContentIterator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.io; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi class ChunkContentIterator { private final byte[] bytes; private int pos; ChunkContentIterator(byte[] bytes) { this.bytes = bytes; } public boolean hasNext() { return pos < bytes.length; } public int read(byte[] output, int offset, int length) { if (length == 0) { return 0; } if (!hasNext()) { return -1; } int remaingBytesNum = bytes.length - pos; int bytesToRead = Math.min(remaingBytesNum, length); System.arraycopy(bytes, pos, output, offset, bytesToRead); pos += bytesToRead; return bytesToRead; } }
2,197
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/io/Releasable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.io; import static software.amazon.awssdk.utils.IoUtils.closeQuietly; import java.io.Closeable; import org.slf4j.Logger; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Used for releasing a resource. * <p> * For example, the creation of a <code>ResettableInputStream</code> 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 * <code>ResettableInputStream#disableClose()</code>, so that the release method * becomes the only way to truly close the opened file. */ @SdkInternalApi public interface Releasable { /** * Releases the allocated resource. This method should not be called except * by the caller who allocated the resource at the very top of the call * stack. This allows, typically, a {@link Closeable} resource to be not * unintentionally released owing to the calling of the * {@link Closeable#close()} methods by implementation deep down in the call * stack. * <p> * For example, the creation of a <code>ResettableInputStream</code> 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 * <code>ResettableInputStream#disableClose()</code>, so that the release method * becomes the only way to truly close the opened file. */ void release(); /** * Releases the given {@link Closeable} especially if it was an instance of * {@link Releasable}. * <p> * For example, the creation of a <code>ResettableInputStream</code> 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 * <code>ResettableInputStream#disableClose()</code>, so that the release method * becomes the only way to truly close the opened file. */ static void release(Closeable is, Logger log) { closeQuietly(is, log); if (is instanceof Releasable) { Releasable r = (Releasable) is; r.release(); } } }
2,198
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/io/ChecksumValidatingInputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.io; import java.io.IOException; import java.io.InputStream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.Abortable; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.Validate; /** * Stream that will update the Checksum as the data is read. * When end of the stream is reached the computed Checksum is validated with Expected checksum. */ @SdkInternalApi public class ChecksumValidatingInputStream extends InputStream implements Abortable { private final SdkChecksum checkSum; private final InputStream inputStream; private final String expectedChecksum; private String computedChecksum = null; private boolean endOfStream = false; /** * Creates an input stream using the specified Checksum, input stream, and length. * * @param inputStream the input stream * @param sdkChecksum the Checksum implementation * @param expectedChecksum the checksum value as seen un . */ public ChecksumValidatingInputStream(InputStream inputStream, SdkChecksum sdkChecksum, String expectedChecksum) { this.inputStream = inputStream; checkSum = sdkChecksum; this.expectedChecksum = expectedChecksum; } /** * Reads from the underlying stream. If the end of the stream is reached, the * running checksum will be appended a byte at a time (1 per read call). * * @return byte read, if eos has been reached, -1 will be returned. */ @Override public int read() throws IOException { int read = -1; if (!endOfStream) { read = inputStream.read(); if (read != -1) { checkSum.update(read); } if (read == -1) { endOfStream = true; validateAndThrow(); } } return read; } /** * Reads up to len bytes at a time from the input stream, updates the checksum. If the end of the stream has been reached * the checksum will be appended to the last 4 bytes. * * @param buf buffer to write into * @param off offset in the buffer to write to * @param len maximum number of bytes to attempt to read. * @return number of bytes written into buf, otherwise -1 will be returned to indicate eos. */ @Override public int read(byte[] buf, int off, int len) throws IOException { Validate.notNull(buf, "buff"); int read = -1; if (!endOfStream) { read = inputStream.read(buf, off, len); if (read != -1) { checkSum.update(buf, off, read); } if (read == -1) { endOfStream = true; validateAndThrow(); } } return read; } /** * Resets stream state, including the running checksum. */ @Override public synchronized void reset() throws IOException { inputStream.reset(); checkSum.reset(); } @Override public void abort() { if (inputStream instanceof Abortable) { ((Abortable) inputStream).abort(); } } @Override public void close() throws IOException { inputStream.close(); } private void validateAndThrow() { if (computedChecksum == null) { computedChecksum = BinaryUtils.toBase64(checkSum.getChecksumBytes()); } if (!expectedChecksum.equals(computedChecksum)) { throw SdkClientException.builder().message( String.format("Data read has a different checksum than expected. Was %s, but expected %s", computedChecksum, expectedChecksum)).build(); } } }
2,199