index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ComparableUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public final class ComparableUtils { private ComparableUtils() { } /** * Does a safe comparison of two {@link Comparable} objects accounting for nulls * * @param d1 * First object * @param d2 * Second object * @return A positive number if the object double is larger, a negative number if the second * object is larger, or 0 if they are equal. Null is considered less than any non-null * value */ public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } /** * Get the minimum value from a list of comparable vales. * * @param values The values from which the minimum should be extracted. * @return The minimum value in the list. */ @SafeVarargs public static <T extends Comparable<T>> T minimum(T... values) { return values == null ? null : Stream.of(values).min(Comparable::compareTo).orElse(null); } /** * Get the maximum value from a list of comparable vales. * * @param values The values from which the maximum should be extracted. * @return The maximum value in the list. */ @SafeVarargs public static <T extends Comparable<T>> T maximum(T... values) { return values == null ? null : Stream.of(values).max(Comparable::compareTo).orElse(null); } }
3,000
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/OptionalUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Functions that make working with optionals easier. */ @SdkProtectedApi public final class OptionalUtils { /** * This class should be used statically. */ private OptionalUtils() { } /** * Attempt to find a present-valued optional in a list of optionals. * * @param firstValue The first value that should be checked. * @param fallbackValues The suppliers we should check in order for a present value. * @return The first present value (or Optional.empty() if none are present) */ @SafeVarargs public static <T> Optional<T> firstPresent(Optional<T> firstValue, Supplier<Optional<T>>... fallbackValues) { if (firstValue.isPresent()) { return firstValue; } for (Supplier<Optional<T>> fallbackValueSupplier : fallbackValues) { Optional<T> fallbackValue = fallbackValueSupplier.get(); if (fallbackValue.isPresent()) { return fallbackValue; } } return Optional.empty(); } public static <T> Optional<T> firstPresent(Optional<T> firstValue, Supplier<T> fallbackValue) { if (firstValue.isPresent()) { return firstValue; } return Optional.ofNullable(fallbackValue.get()); } }
3,001
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Either.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Represents a value that can be one of two types. * * @param <L> Left type * @param <R> Right type */ @SdkProtectedApi public final class Either<L, R> { private final Optional<L> left; private final Optional<R> right; private Either(Optional<L> l, Optional<R> r) { left = l; right = r; } /** * Maps the Either to a type and returns the resolved value (which may be from the left or the right value). * * @param lFunc Function that maps the left value if present. * @param rFunc Function that maps the right value if present. * @param <T> Type that both the left and right should be mapped to. * @return Mapped value from either lFunc or rFunc depending on which value is present. */ public <T> T map( Function<? super L, ? extends T> lFunc, Function<? super R, ? extends T> rFunc) { return left.<T>map(lFunc).orElseGet(() -> right.map(rFunc).get()); } /** * Map the left most value and return a new Either reflecting the new types. * * @param lFunc Function that maps the left value if present. * @param <T> New type of left value. * @return New Either bound to the new left type and the same right type. */ public <T> Either<T, R> mapLeft(Function<? super L, ? extends T> lFunc) { return new Either<>(left.map(lFunc), right); } /** * Map the right most value and return a new Either reflecting the new types. * * @param rFunc Function that maps the right value if present. * @param <T> New type of right value. * @return New Either bound to the same left type and the new right type. */ public <T> Either<L, T> mapRight(Function<? super R, ? extends T> rFunc) { return new Either<>(left, right.map(rFunc)); } /** * Apply the consumers to the left or the right value depending on which is present. * * @param lFunc Consumer of left value, invoked if left value is present. * @param rFunc Consumer of right value, invoked if right value is present. */ public void apply(Consumer<? super L> lFunc, Consumer<? super R> rFunc) { left.ifPresent(lFunc); right.ifPresent(rFunc); } /** * Create a new Either with the left type. * * @param value Left value * @param <L> Left type * @param <R> Right type */ public static <L, R> Either<L, R> left(L value) { return new Either<>(Optional.of(value), Optional.empty()); } /** * Create a new Either with the right type. * * @param value Right value * @param <L> Left type * @param <R> Right type */ public static <L, R> Either<L, R> right(R value) { return new Either<>(Optional.empty(), Optional.of(value)); } /** * @return the left value */ public Optional<L> left() { return left; } /** * @return the right value */ public Optional<R> right() { return right; } /** * Create a new {@code Optional<Either>} from two possibly null values. * * If both values are null, {@link Optional#empty()} is returned. Only one of the left or right values * is allowed to be non-null, otherwise an {@link IllegalArgumentException} is thrown. * @param left The left value (possibly null) * @param right The right value (possibly null) * @param <L> Left type * @param <R> Right type * @return an Optional Either representing one of the two values or empty if both are null */ public static <L, R> Optional<Either<L, R>> fromNullable(L left, R right) { if (left != null && right == null) { return Optional.of(left(left)); } if (left == null && right != null) { return Optional.of(right(right)); } if (left == null && right == null) { return Optional.empty(); } throw new IllegalArgumentException(String.format("Only one of either left or right should be non-null. " + "Got (left: %s, right: %s)", left, right)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Either)) { return false; } Either<?, ?> either = (Either<?, ?>) o; return left.equals(either.left) && right.equals(either.right); } @Override public int hashCode() { return 31 * left.hashCode() + right.hashCode(); } }
3,002
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/UserHomeDirectoryUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Load the home directory that should be used for the stored file. This will check the same environment variables as the CLI * to identify the location of home, before falling back to java-specific resolution. */ @SdkProtectedApi public final class UserHomeDirectoryUtils { private UserHomeDirectoryUtils() { } public static String userHomeDirectory() { // CHECKSTYLE:OFF - To match the logic of the CLI we have to consult environment variables directly. Optional<String> home = SystemSetting.getStringValueFromEnvironmentVariable("HOME"); if (home.isPresent()) { return home.get(); } boolean isWindows = JavaSystemSetting.OS_NAME.getStringValue() .map(s -> StringUtils.lowerCase(s).startsWith("windows")) .orElse(false); if (isWindows) { Optional<String> userProfile = SystemSetting.getStringValueFromEnvironmentVariable("USERPROFILE"); if (userProfile.isPresent()) { return userProfile.get(); } Optional<String> homeDrive = SystemSetting.getStringValueFromEnvironmentVariable("HOMEDRIVE"); Optional<String> homePath = SystemSetting.getStringValueFromEnvironmentVariable("HOMEPATH"); if (homeDrive.isPresent() && homePath.isPresent()) { return homeDrive.get() + homePath.get(); } } return JavaSystemSetting.USER_HOME.getStringValueOrThrow(); // CHECKSTYLE:ON } }
3,003
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ConditionalDecorator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.List; import java.util.function.Predicate; import java.util.function.UnaryOperator; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.internal.DefaultConditionalDecorator; /** * An interface that defines a class that contains a transform for another type as well as a condition for whether * that transform should be applied. * * @param <T> A type that can be decorated, or transformed, through applying a function. */ @FunctionalInterface @SdkProtectedApi public interface ConditionalDecorator<T> { default Predicate<T> predicate() { return t -> true; } UnaryOperator<T> transform(); static <T> ConditionalDecorator<T> create(Predicate<T> predicate, UnaryOperator<T> transform) { DefaultConditionalDecorator.Builder<T> builder = new DefaultConditionalDecorator.Builder<>(); return builder.predicate(predicate).transform(transform).build(); } /** * This function will transform an initially supplied value with provided transforming, or decorating, functions that are * conditionally and sequentially applied. For each pair of condition and transform: if the condition evaluates to true, the * transform will be applied to the incoming value and the output from the transform is the input to the next transform. * <p> * If the supplied collection is ordered, the function is guaranteed to apply the transforms in the order in which they appear * in the collection. * * @param initialValue The untransformed start value * @param decorators A list of condition to transform * @param <T> The type of the value * @return A single transformed value that is the result of applying all transforms evaluated to true */ static <T> T decorate(T initialValue, List<ConditionalDecorator<T>> decorators) { return decorators.stream() .filter(d -> d.predicate().test(initialValue)) .reduce(initialValue, (element, decorator) -> decorator.transform().apply(element), (el1, el2) -> { throw new IllegalStateException("Should not reach here, combine function not " + "needed unless executed in parallel."); }); } }
3,004
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/SystemSetting.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.internal.SystemSettingUtils; /** * An interface implemented by enums in other packages in order to define the system settings the want loaded. An enum * is expected to implement this interface, and then have values loaded from the {@link System} using methods like * {@link #getStringValue()}. */ @SdkProtectedApi public interface SystemSetting { /** * The system property of the setting (or null if there is no property for this setting). */ String property(); /** * The environment variable of the setting (or null if there is no environment variable for this setting). */ String environmentVariable(); /** * The default value of the setting (or empty if there is no default). This value will be applied if the customer did not * specify a setting. */ String defaultValue(); /** * Attempt to load a system setting from {@link System#getProperty(String)} and {@link System#getenv(String)}. This should be * used in favor of those methods because the SDK should support both methods of configuration. * * {@link System#getProperty(String)} takes precedent over {@link System#getenv(String)} if both are specified. * * @return The requested setting, or {@link Optional#empty()} if the values were not set, or the security manager did not * allow reading the setting. */ default Optional<String> getStringValue() { return SystemSettingUtils.resolveSetting(this); } /** * Attempt to load a system setting from {@link System#getenv(String)}. This should NOT BE USED, so checkstyle will * complain about using it. The only reason this is made available is for when we ABSOLUTELY CANNOT support a system * property for a specific setting. That should be the exception, NOT the rule. We should almost always provide a system * property alternative for all environment variables. * * @return The requested setting, or {@link Optional#empty()} if the values were not set, or the security manager did not * allow reading the setting. */ static Optional<String> getStringValueFromEnvironmentVariable(String key) { return SystemSettingUtils.resolveEnvironmentVariable(key); } /** * Attempt to load a system setting from {@link System#getProperty(String)} and {@link System#getenv(String)}. This should be * used in favor of those methods because the SDK should support both methods of configuration. * * {@link System#getProperty(String)} takes precedent over {@link System#getenv(String)} if both are specified. * <p> * Similar to {@link #getStringValue()}, but does not fall back to the default value. * * @return The requested setting, or {@link Optional#empty()} if the values were not set, or the security manager did not * allow reading the setting. */ default Optional<String> getNonDefaultStringValue() { return SystemSettingUtils.resolveNonDefaultSetting(this); } /** * Load the requested system setting as per the documentation in {@link #getStringValue()}, throwing an exception if the value * was not set and had no default. * * @return The requested setting. */ default String getStringValueOrThrow() { return getStringValue().orElseThrow(() -> new IllegalStateException("Either the environment variable " + environmentVariable() + " or the java" + "property " + property() + " must be set.")); } /** * Attempt to load a system setting from {@link System#getProperty(String)} and {@link System#getenv(String)}. This should be * used in favor of those methods because the SDK should support both methods of configuration. * * The result will be converted to an integer. * * {@link System#getProperty(String)} takes precedent over {@link System#getenv(String)} if both are specified. * * @return The requested setting, or {@link Optional#empty()} if the values were not set, or the security manager did not * allow reading the setting. */ default Optional<Integer> getIntegerValue() { return getStringValue().map(Integer::parseInt); } /** * Load the requested system setting as per the documentation in {@link #getIntegerValue()}, throwing an exception if the * value was not set and had no default. * * @return The requested setting. */ default Integer getIntegerValueOrThrow() { return Integer.parseInt(getStringValueOrThrow()); } /** * Attempt to load a system setting from {@link System#getProperty(String)} and {@link System#getenv(String)}. This should be * used in favor of those methods because the SDK should support both methods of configuration. * * The result will be converted to a boolean. * * {@link System#getProperty(String)} takes precedent over {@link System#getenv(String)} if both are specified. * * @return The requested setting, or {@link Optional#empty()} if the values were not set, or the security manager did not * allow reading the setting. */ default Optional<Boolean> getBooleanValue() { return getStringValue().map(value -> SystemSettingUtils.safeStringToBoolean(this, value)); } /** * Load the requested system setting as per the documentation in {@link #getBooleanValue()}, throwing an * exception if the value was not set and had no default. * * @return The requested setting. */ default Boolean getBooleanValueOrThrow() { return getBooleanValue().orElseThrow(() -> new IllegalStateException("Either the environment variable " + environmentVariable() + " or the java" + "property " + property() + " must be set.")); } }
3,005
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ThreadFactoryBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; /** * A builder for creating a thread factory. This allows changing the behavior of the created thread factory. */ @SdkProtectedApi public class ThreadFactoryBuilder { /** * To prevent thread names from becoming too long we limit to 4 digits for the pool number before wrapping back * around. */ private static final int POOL_NUMBER_MAX = 10_000; private static final AtomicLong POOL_NUMBER = new AtomicLong(0); private String threadNamePrefix = "aws-java-sdk"; private Boolean daemonThreads = true; /** * The name prefix for threads created by this thread factory. The prefix will be appended with a number unique to the thread * factory and a number unique to the thread. * * For example, "aws-java-sdk-thread" could become "aws-java-sdk-thread-3-4". * * By default, this is "aws-java-sdk-thread". */ public ThreadFactoryBuilder threadNamePrefix(String threadNamePrefix) { this.threadNamePrefix = threadNamePrefix; return this; } /** * Whether the threads created by the factory should be daemon threads. By default this is true - we shouldn't be holding up * the customer's JVM shutdown unless we're absolutely sure we want to. */ public ThreadFactoryBuilder daemonThreads(Boolean daemonThreads) { this.daemonThreads = daemonThreads; return this; } /** * Test API to reset pool count for reliable assertions. */ @SdkTestInternalApi static void resetPoolNumber() { POOL_NUMBER.set(0); } /** * Create the {@link ThreadFactory} with the configuration currently applied to this builder. */ public ThreadFactory build() { String threadNamePrefixWithPoolNumber = threadNamePrefix + "-" + POOL_NUMBER.getAndIncrement() % POOL_NUMBER_MAX; ThreadFactory result = new NamedThreadFactory(Executors.defaultThreadFactory(), threadNamePrefixWithPoolNumber); if (daemonThreads) { result = new DaemonThreadFactory(result); } return result; } }
3,006
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/JavaSystemSetting.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * The system properties usually provided by the Java runtime. */ @SdkProtectedApi public enum JavaSystemSetting implements SystemSetting { JAVA_VERSION("java.version"), JAVA_VENDOR("java.vendor"), TEMP_DIRECTORY("java.io.tmpdir"), JAVA_VM_NAME("java.vm.name"), JAVA_VM_VERSION("java.vm.version"), OS_NAME("os.name"), OS_VERSION("os.version"), USER_HOME("user.home"), USER_LANGUAGE("user.language"), USER_REGION("user.region"), USER_NAME("user.name"), SSL_KEY_STORE("javax.net.ssl.keyStore"), SSL_KEY_STORE_PASSWORD("javax.net.ssl.keyStorePassword"), SSL_KEY_STORE_TYPE("javax.net.ssl.keyStoreType") ; private final String systemProperty; JavaSystemSetting(String systemProperty) { this.systemProperty = systemProperty; } @Override public String property() { return systemProperty; } @Override public String environmentVariable() { return null; } @Override public String defaultValue() { return null; } }
3,007
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Platform.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public class Platform { private Platform() { } /** * Determine whether the current operation system seems to be Windows. */ public static boolean isWindows() { return JavaSystemSetting.OS_NAME.getStringValue() .map(s -> StringUtils.lowerCase(s).startsWith("windows")) .orElse(false); } }
3,008
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Lazy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkPublicApi; /** * A class that lazily constructs a value the first time {@link #getValue()} is invoked. * * This should be {@link #close()}d if the initializer returns value that needs to be {@link AutoCloseable#close()}d. */ @SdkPublicApi public class Lazy<T> implements SdkAutoCloseable { private final Supplier<T> initializer; private volatile T value; public Lazy(Supplier<T> initializer) { this.initializer = initializer; } public static <T> Lazy<T> withValue(T initialValue) { return new ResolvedLazy<>(initialValue); } public boolean hasValue() { return value != null; } public T getValue() { T result = value; if (result == null) { synchronized (this) { result = value; if (result == null) { result = initializer.get(); value = result; } } } return result; } @Override public String toString() { T value = this.value; return ToString.builder("Lazy") .add("value", value == null ? "Uninitialized" : value) .build(); } @Override public void close() { try { // Make sure the value has been initialized before we attempt to close it getValue(); } catch (RuntimeException e) { // Failed to initialize the value. } IoUtils.closeIfCloseable(initializer, null); IoUtils.closeIfCloseable(value, null); } private static class ResolvedLazy<T> extends Lazy<T> { private final T initialValue; private ResolvedLazy(T initialValue) { super(null); this.initialValue = initialValue; } @Override public boolean hasValue() { return true; } @Override public T getValue() { return initialValue; } @Override public String toString() { return ToString.builder("Lazy") .add("value", initialValue) .build(); } @Override public void close() { IoUtils.closeIfCloseable(initialValue, null); } } }
3,009
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ProxyConfigProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Optional; import java.util.Set; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.internal.proxy.ProxyEnvironmentVariableConfigProvider; import software.amazon.awssdk.utils.internal.proxy.ProxySystemPropertyConfigProvider; /** * Interface for providing proxy configuration settings. Implementations of this interface can retrieve proxy configuration * from various sources such as system properties and environment variables. **/ @SdkProtectedApi public interface ProxyConfigProvider { /** * Constant representing the HTTPS scheme. */ String HTTPS = "https"; /** * Returns a new {@code ProxyConfigProvider} that retrieves proxy configuration from system properties. * * @param scheme The URI scheme for which the proxy configuration is needed (e.g., "http" or "https"). * @return A {@code ProxyConfigProvider} for system property-based proxy configuration. */ static ProxyConfigProvider fromSystemPropertySettings(String scheme) { return new ProxySystemPropertyConfigProvider(scheme); } /** * Returns a new {@code ProxyConfigProvider} that retrieves proxy configuration from environment variables. * * @param scheme The URI scheme for which the proxy configuration is needed (e.g., "http" or "https"). * @return A {@code ProxyConfigProvider} for environment variable-based proxy configuration. */ static ProxyConfigProvider fromEnvironmentSettings(String scheme) { return new ProxyEnvironmentVariableConfigProvider(scheme); } /** * Returns a {@code ProxyConfigProvider} based on the specified settings for using system properties, environment * variables, and the scheme. * * @param useSystemPropertyValues A {@code Boolean} indicating whether to use system property values. * @param useEnvironmentVariableValues A {@code Boolean} indicating whether to use environment variable values. * @param scheme The URI scheme for which the proxy configuration is needed (e.g., "http" or "https"). * @return A {@code ProxyConfigProvider} based on the specified settings. */ static ProxyConfigProvider fromSystemEnvironmentSettings(Boolean useSystemPropertyValues, Boolean useEnvironmentVariableValues, String scheme) { ProxyConfigProvider resultProxyConfig = null; if (Boolean.TRUE.equals(useSystemPropertyValues)) { resultProxyConfig = fromSystemPropertySettings(scheme); } else if (Boolean.TRUE.equals(useEnvironmentVariableValues)) { return fromEnvironmentSettings(scheme); } boolean isProxyConfigurationNotSet = resultProxyConfig != null && resultProxyConfig.host() == null && resultProxyConfig.port() == 0 && !resultProxyConfig.password().isPresent() && !resultProxyConfig.userName().isPresent() && CollectionUtils.isNullOrEmpty(resultProxyConfig.nonProxyHosts()); if (isProxyConfigurationNotSet && Boolean.TRUE.equals(useEnvironmentVariableValues)) { return fromEnvironmentSettings(scheme); } return resultProxyConfig; } /** * Gets the proxy port. * * @return The proxy port. */ int port(); /** * Gets the proxy username if available. * * @return An optional containing the proxy username, if available. */ Optional<String> userName(); /** * Gets the proxy password if available. * * @return An optional containing the proxy password, if available. */ Optional<String> password(); /** * Gets the proxy host. * * @return The proxy host. */ String host(); /** * Gets the set of non-proxy hosts. * * @return A set containing the non-proxy host names. */ Set<String> nonProxyHosts(); }
3,010
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ProxySystemSetting.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * The system properties related to http and https proxies */ @SdkProtectedApi public enum ProxySystemSetting implements SystemSetting { PROXY_HOST("http.proxyHost"), PROXY_PORT("http.proxyPort"), NON_PROXY_HOSTS("http.nonProxyHosts"), PROXY_USERNAME("http.proxyUser"), PROXY_PASSWORD("http.proxyPassword"), HTTPS_PROXY_HOST("https.proxyHost"), HTTPS_PROXY_PORT("https.proxyPort"), HTTPS_PROXY_USERNAME("https.proxyUser"), HTTPS_PROXY_PASSWORD("https.proxyPassword") ; private final String systemProperty; ProxySystemSetting(String systemProperty) { this.systemProperty = systemProperty; } @Override public String property() { return systemProperty; } @Override public String environmentVariable() { return null; } @Override public String defaultValue() { return null; } }
3,011
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/SdkAutoCloseable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import software.amazon.awssdk.annotations.SdkPublicApi; /** * An implementation of {@link AutoCloseable} that does not throw any checked exceptions. The SDK does not throw checked * exceptions in its close() methods, so users of the SDK should not need to handle them. */ @SdkPublicApi // CHECKSTYLE:OFF - This is the only place we're allowed to use AutoCloseable public interface SdkAutoCloseable extends AutoCloseable { // CHECKSTYLE:ON /** * {@inheritDoc} */ @Override void close(); }
3,012
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Validate.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.time.Duration; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.function.Predicate; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * <p>This class assists in validating arguments. The validation methods are * based along the following principles: * <ul> * <li>An invalid {@code null} argument causes a {@link NullPointerException}.</li> * <li>A non-{@code null} argument causes an {@link IllegalArgumentException}.</li> * <li>An invalid index into an array/collection/map/string causes an {@link IndexOutOfBoundsException}.</li> * </ul> * * <p>All exceptions messages are * <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax">format strings</a> * as defined by the Java platform. For example:</p> * * <pre> * Validate.isTrue(i &gt; 0, "The value must be greater than zero: %d", i); * Validate.notNull(surname, "The surname must not be %s", null); * </pre> * * <p>This class's source was modified from the Apache commons-lang library: https://github.com/apache/commons-lang/</p> * * <p>#ThreadSafe#</p> * @see java.lang.String#format(String, Object...) */ @SdkProtectedApi public final class Validate { private static final String DEFAULT_IS_NULL_EX_MESSAGE = "The validated object is null"; private Validate() { } // isTrue //--------------------------------------------------------------------------------- /** * <p>Validate that the argument condition is {@code true}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.</p> * * <pre> * Validate.isTrue(i &gt;= min &amp;&amp; i &lt;= max, "The value must be between &#37;d and &#37;d", min, max); * Validate.isTrue(myObject.isOk(), "The object is not okay");</pre> * * @param expression the boolean expression to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if expression is {@code false} */ public static void isTrue(final boolean expression, final String message, final Object... values) { if (!expression) { throw new IllegalArgumentException(String.format(message, values)); } } // isFalse //--------------------------------------------------------------------------------- /** * <p>Validate that the argument condition is {@code false}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.</p> * * <pre> * Validate.isFalse(myObject.permitsSomething(), "The object is not allowed to permit something");</pre> * * @param expression the boolean expression to check * @param message the {@link String#format(String, Object...)} exception message if not false, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if expression is {@code true} */ public static void isFalse(final boolean expression, final String message, final Object... values) { isTrue(!expression, message, values); } // notNull //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument is not {@code null}; * otherwise throwing an exception with the specified message. * * <pre>Validate.notNull(myObject, "The object must not be null");</pre> * * @param <T> the object type * @param object the object to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message * @return the validated object (never {@code null} for method chaining) * @throws NullPointerException if the object is {@code null} */ public static <T> T notNull(final T object, final String message, final Object... values) { if (object == null) { throw new NullPointerException(String.format(message, values)); } return object; } /** * <p>Validate that the specified argument is {@code null}; * otherwise throwing an exception with the specified message. * * <pre>Validate.isNull(myObject, "The object must be null");</pre> * * @param <T> the object type * @param object the object to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message * @throws IllegalArgumentException if the object is not {@code null} */ public static <T> void isNull(final T object, final String message, final Object... values) { if (object != null) { throw new IllegalArgumentException(String.format(message, values)); } } /** * <p>Validate that the specified field/param is not {@code null}; * otherwise throwing an exception with a precanned message that includes the parameter name. * * <pre>Validate.paramNotNull(myObject, "myObject");</pre> * * @param <T> the object type * @param object the object to check * @param paramName The name of the param or field being checked. * @return the validated object (never {@code null} for method chaining) * @throws NullPointerException if the object is {@code null} */ public static <T> T paramNotNull(final T object, final String paramName) { if (object == null) { throw new NullPointerException(String.format("%s must not be null.", paramName)); } return object; } /** * <p>Validate that the specified char sequence is neither * {@code null}, a length of zero (no characters), empty nor * whitespace; otherwise throwing an exception with the specified * message. * * <pre>Validate.paramNotBlank(myCharSequence, "myCharSequence");</pre> * * @param <T> the char sequence type * @param chars the character sequence to check * @param paramName The name of the param or field being checked. * @return the validated char sequence (never {@code null} for method chaining) * @throws NullPointerException if the char sequence is {@code null} */ public static <T extends CharSequence> T paramNotBlank(final T chars, final String paramName) { if (chars == null) { throw new NullPointerException(String.format("%s must not be null.", paramName)); } if (StringUtils.isBlank(chars)) { throw new IllegalArgumentException(String.format("%s must not be blank or empty.", paramName)); } return chars; } /** * <p>Validate the stateful predicate is true for the given object and return the object; * otherwise throw an exception with the specified message.</p> * * {@code String value = Validate.validState(someString, s -> s.length() == 0, "must be blank got: %s", someString);} * * * @param <T> the object type * @param object the object to check * @param test the predicate to apply, will return true if the object is valid * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message * @return the validated object * @throws NullPointerException if the object is {@code null} */ public static <T> T validState(final T object, final Predicate<T> test, final String message, final Object... values) { if (!test.test(object)) { throw new IllegalStateException(String.format(message, values)); } return object; } // notEmpty array //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument array is neither {@code null} * nor a length of zero (no elements); otherwise throwing an exception * with the specified message. * * <pre>Validate.notEmpty(myArray, "The array must not be empty");</pre> * * @param <T> the array type * @param array the array to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @return the validated array (never {@code null} method for chaining) * @throws NullPointerException if the array is {@code null} * @throws IllegalArgumentException if the array is empty */ public static <T> T[] notEmpty(final T[] array, final String message, final Object... values) { if (array == null) { throw new NullPointerException(String.format(message, values)); } if (array.length == 0) { throw new IllegalArgumentException(String.format(message, values)); } return array; } // notEmpty collection //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument collection is neither {@code null} * nor a size of zero (no elements); otherwise throwing an exception * with the specified message. * * <pre>Validate.notEmpty(myCollection, "The collection must not be empty");</pre> * * @param <T> the collection type * @param collection the collection to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @return the validated collection (never {@code null} method for chaining) * @throws NullPointerException if the collection is {@code null} * @throws IllegalArgumentException if the collection is empty */ public static <T extends Collection<?>> T notEmpty(final T collection, final String message, final Object... values) { if (collection == null) { throw new NullPointerException(String.format(message, values)); } if (collection.isEmpty()) { throw new IllegalArgumentException(String.format(message, values)); } return collection; } // notEmpty map //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument map is neither {@code null} * nor a size of zero (no elements); otherwise throwing an exception * with the specified message. * * <pre>Validate.notEmpty(myMap, "The map must not be empty");</pre> * * @param <T> the map type * @param map the map to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @return the validated map (never {@code null} method for chaining) * @throws NullPointerException if the map is {@code null} * @throws IllegalArgumentException if the map is empty */ public static <T extends Map<?, ?>> T notEmpty(final T map, final String message, final Object... values) { if (map == null) { throw new NullPointerException(String.format(message, values)); } if (map.isEmpty()) { throw new IllegalArgumentException(String.format(message, values)); } return map; } // notEmpty string //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument character sequence is * neither {@code null} nor a length of zero (no characters); * otherwise throwing an exception with the specified message. * * <pre>Validate.notEmpty(myString, "The string must not be empty");</pre> * * @param <T> the character sequence type * @param chars the character sequence to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @return the validated character sequence (never {@code null} method for chaining) * @throws NullPointerException if the character sequence is {@code null} * @throws IllegalArgumentException if the character sequence is empty */ public static <T extends CharSequence> T notEmpty(final T chars, final String message, final Object... values) { if (chars == null) { throw new NullPointerException(String.format(message, values)); } if (chars.length() == 0) { throw new IllegalArgumentException(String.format(message, values)); } return chars; } // notBlank string //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument character sequence is * neither {@code null}, a length of zero (no characters), empty * nor whitespace; otherwise throwing an exception with the specified * message. * * <pre>Validate.notBlank(myString, "The string must not be blank");</pre> * * @param <T> the character sequence type * @param chars the character sequence to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @return the validated character sequence (never {@code null} method for chaining) * @throws NullPointerException if the character sequence is {@code null} * @throws IllegalArgumentException if the character sequence is blank */ public static <T extends CharSequence> T notBlank(final T chars, final String message, final Object... values) { if (chars == null) { throw new NullPointerException(String.format(message, values)); } if (StringUtils.isBlank(chars)) { throw new IllegalArgumentException(String.format(message, values)); } return chars; } // noNullElements array //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument array is neither * {@code null} nor contains any elements that are {@code null}; * otherwise throwing an exception with the specified message. * * <pre>Validate.noNullElements(myArray, "The array is null or contains null.");</pre> * * @param <T> the array type * @param array the array to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message * @return the validated array (never {@code null} method for chaining) * @throws NullPointerException if the array is {@code null} * @throws IllegalArgumentException if an element is {@code null} */ public static <T> T[] noNullElements(final T[] array, final String message, final Object... values) { Validate.notNull(array, message); for (T anArray : array) { if (anArray == null) { throw new IllegalArgumentException(String.format(message, values)); } } return array; } // noNullElements iterable //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument iterable is neither * {@code null} nor contains any elements that are {@code null}; * otherwise throwing an exception with the specified message. * * <pre>Validate.noNullElements(myCollection, "The collection is null or contains null.");</pre> * * @param <T> the iterable type * @param iterable the iterable to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message. * @return the validated iterable (never {@code null} method for chaining) * @throws NullPointerException if the array is {@code null} * @throws IllegalArgumentException if an element is {@code null} */ public static <T extends Iterable<?>> T noNullElements(final T iterable, final String message, final Object... values) { Validate.notNull(iterable, DEFAULT_IS_NULL_EX_MESSAGE); int i = 0; for (Iterator<?> it = iterable.iterator(); it.hasNext(); i++) { if (it.next() == null) { throw new IllegalArgumentException(String.format(message, values)); } } return iterable; } // validState //--------------------------------------------------------------------------------- /** * <p>Validate that the stateful condition is {@code true}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.</p> * * <pre>Validate.validState(this.isOk(), "The state is not OK: %s", myObject);</pre> * * @param expression the boolean expression to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalStateException if expression is {@code false} */ public static void validState(final boolean expression, final String message, final Object... values) { if (!expression) { throw new IllegalStateException(String.format(message, values)); } } // inclusiveBetween //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument object fall between the two * inclusive values specified; otherwise, throws an exception with the * specified message.</p> * * <pre>Validate.inclusiveBetween(0, 2, 1, "Not in boundaries");</pre> * * @param <T> the type of the argument object * @param start the inclusive start value, not null * @param end the inclusive end value, not null * @param value the object to validate, not null * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if the value falls outside the boundaries */ public static <T extends Comparable<U>, U> T inclusiveBetween(final U start, final U end, final T value, final String message, final Object... values) { if (value.compareTo(start) < 0 || value.compareTo(end) > 0) { throw new IllegalArgumentException(String.format(message, values)); } return value; } /** * Validate that the specified primitive value falls between the two * inclusive values specified; otherwise, throws an exception with the * specified message. * * <pre>Validate.inclusiveBetween(0, 2, 1, "Not in range");</pre> * * @param start the inclusive start value * @param end the inclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * * @throws IllegalArgumentException if the value falls outside the boundaries */ public static long inclusiveBetween(final long start, final long end, final long value, final String message) { if (value < start || value > end) { throw new IllegalArgumentException(message); } return value; } /** * Validate that the specified primitive value falls between the two * inclusive values specified; otherwise, throws an exception with the * specified message. * * <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre> * * @param start the inclusive start value * @param end the inclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * * @throws IllegalArgumentException if the value falls outside the boundaries */ public static double inclusiveBetween(final double start, final double end, final double value, final String message) { if (value < start || value > end) { throw new IllegalArgumentException(message); } return value; } // exclusiveBetween //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument object fall between the two * exclusive values specified; otherwise, throws an exception with the * specified message.</p> * * <pre>Validate.exclusiveBetween(0, 2, 1, "Not in boundaries");</pre> * * @param <T> the type of the argument object * @param start the exclusive start value, not null * @param end the exclusive end value, not null * @param value the object to validate, not null * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if the value falls outside the boundaries */ public static <T extends Comparable<U>, U> T exclusiveBetween(final U start, final U end, final T value, final String message, final Object... values) { if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) { throw new IllegalArgumentException(String.format(message, values)); } return value; } /** * Validate that the specified primitive value falls between the two * exclusive values specified; otherwise, throws an exception with the * specified message. * * <pre>Validate.exclusiveBetween(0, 2, 1, "Not in range");</pre> * * @param start the exclusive start value * @param end the exclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * * @throws IllegalArgumentException if the value falls outside the boundaries */ public static long exclusiveBetween(final long start, final long end, final long value, final String message) { if (value <= start || value >= end) { throw new IllegalArgumentException(message); } return value; } /** * Validate that the specified primitive value falls between the two * exclusive values specified; otherwise, throws an exception with the * specified message. * * <pre>Validate.exclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre> * * @param start the exclusive start value * @param end the exclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * * @throws IllegalArgumentException if the value falls outside the boundaries */ public static double exclusiveBetween(final double start, final double end, final double value, final String message) { if (value <= start || value >= end) { throw new IllegalArgumentException(message); } return value; } // isInstanceOf //--------------------------------------------------------------------------------- /** * <p>Validate that the argument is an instance of the specified class; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary class</p> * * <pre>Validate.isInstanceOf(OkClass.class, object, "Wrong class, object is of class %s", * object.getClass().getName());</pre> * * @param type the class the object must be validated against, not null * @param obj the object to check, null throws an exception * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if argument is not of specified class */ public static <T, U> U isInstanceOf(final Class<U> type, final T obj, final String message, final Object... values) { if (!type.isInstance(obj)) { throw new IllegalArgumentException(String.format(message, values)); } return type.cast(obj); } // isAssignableFrom //--------------------------------------------------------------------------------- /** * Validates that the argument can be converted to the specified class, if not throws an exception. * * <p>This method is useful when validating if there will be no casting errors.</p> * * <pre>Validate.isAssignableFrom(SuperClass.class, object.getClass());</pre> * * <p>The message of the exception is &quot;The validated object can not be converted to the&quot; * followed by the name of the class and &quot;class&quot;</p> * * @param superType the class the class must be validated against, not null * @param type the class to check, not null * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if argument can not be converted to the specified class */ public static <T> Class<? extends T> isAssignableFrom(final Class<T> superType, final Class<?> type, final String message, final Object... values) { if (!superType.isAssignableFrom(type)) { throw new IllegalArgumentException(String.format(message, values)); } return (Class<? extends T>) type; } /** * Asserts that the given number is positive (non-negative and non-zero). * * @param num Number to validate * @param fieldName Field name to display in exception message if not positive. * @return Number if positive. */ public static int isPositive(int num, String fieldName) { if (num <= 0) { throw new IllegalArgumentException(String.format("%s must be positive", fieldName)); } return num; } /** * Asserts that the given number is positive (non-negative and non-zero). * * @param num Number to validate * @param fieldName Field name to display in exception message if not positive. * @return Number if positive. */ public static long isPositive(long num, String fieldName) { if (num <= 0) { throw new IllegalArgumentException(String.format("%s must be positive", fieldName)); } return num; } public static double isPositive(double num, String fieldName) { if (num <= 0) { throw new IllegalArgumentException(String.format("%s must be positive", fieldName)); } return num; } public static int isNotNegative(int num, String fieldName) { if (num < 0) { throw new IllegalArgumentException(String.format("%s must not be negative", fieldName)); } return num; } public static Long isNotNegativeOrNull(Long num, String fieldName) { if (num == null) { return null; } if (num < 0) { throw new IllegalArgumentException(String.format("%s must not be negative", fieldName)); } return num; } public static long isNotNegative(long num, String fieldName) { if (num < 0) { throw new IllegalArgumentException(String.format("%s must not be negative", fieldName)); } return num; } /** * Asserts that the given duration is positive (non-negative and non-zero). * * @param duration Number to validate * @param fieldName Field name to display in exception message if not positive. * @return Duration if positive. */ public static Duration isPositive(Duration duration, String fieldName) { if (duration == null) { throw new IllegalArgumentException(String.format("%s cannot be null", fieldName)); } if (duration.isNegative() || duration.isZero()) { throw new IllegalArgumentException(String.format("%s must be positive", fieldName)); } return duration; } /** * Asserts that the given duration is positive (non-negative and non-zero) or null. * * @param duration Number to validate * @param fieldName Field name to display in exception message if not positive. * @return Duration if positive or null. */ public static Duration isPositiveOrNull(Duration duration, String fieldName) { if (duration == null) { return null; } return isPositive(duration, fieldName); } /** * Asserts that the given boxed integer is positive (non-negative and non-zero) or null. * * @param num Boxed integer to validate * @param fieldName Field name to display in exception message if not positive. * @return Duration if positive or null. */ public static Integer isPositiveOrNull(Integer num, String fieldName) { if (num == null) { return null; } return isPositive(num, fieldName); } /** * Asserts that the given boxed double is positive (non-negative and non-zero) or null. * * @param num Boxed double to validate * @param fieldName Field name to display in exception message if not positive. * @return Duration if double or null. */ public static Double isPositiveOrNull(Double num, String fieldName) { if (num == null) { return null; } return isPositive(num, fieldName); } /** * Asserts that the given boxed long is positive (non-negative and non-zero) or null. * * @param num Boxed long to validate * @param fieldName Field name to display in exception message if not positive. * @return Duration if positive or null. */ public static Long isPositiveOrNull(Long num, String fieldName) { if (num == null) { return null; } return isPositive(num, fieldName); } /** * Asserts that the given duration is positive (non-negative and non-zero). * * @param duration Number to validate * @param fieldName Field name to display in exception message if not positive. * @return Duration if positive. */ public static Duration isNotNegative(Duration duration, String fieldName) { if (duration == null) { throw new IllegalArgumentException(String.format("%s cannot be null", fieldName)); } if (duration.isNegative()) { throw new IllegalArgumentException(String.format("%s must not be negative", fieldName)); } return duration; } /** * Returns the param if non null, otherwise gets a default value from the provided {@link Supplier}. * * @param param Param to return if non null. * @param defaultValue Supplier of default value. * @param <T> Type of value. * @return Value of param or default value if param was null. */ public static <T> T getOrDefault(T param, Supplier<T> defaultValue) { paramNotNull(defaultValue, "defaultValue"); return param != null ? param : defaultValue.get(); } /** * Verify that only one of the objects is non null. If all objects are null this method * does not throw. * * @param message Error message if more than one object is non-null. * @param objs Objects to validate. * @throws IllegalArgumentException if more than one of the objects was non-null. */ public static void mutuallyExclusive(String message, Object... objs) { boolean oneProvided = false; for (Object o : objs) { if (o != null) { if (oneProvided) { throw new IllegalArgumentException(message); } else { oneProvided = true; } } } } }
3,013
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/HostnameValidator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public final class HostnameValidator { private static final Pattern DEFAULT_HOSTNAME_COMPLIANT_PATTERN = Pattern.compile("[A-Za-z0-9\\-]+"); private static final int HOSTNAME_MAX_LENGTH = 63; private HostnameValidator() { } public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object) { validateHostnameCompliant(hostnameComponent, paramName, object, DEFAULT_HOSTNAME_COMPLIANT_PATTERN); } public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object, Pattern pattern) { if (hostnameComponent == null) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the required '%s' " + "component is missing.", object, paramName)); } if (StringUtils.isEmpty(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component is empty.", object, paramName)); } if (StringUtils.isBlank(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component is blank.", object, paramName)); } if (hostnameComponent.length() > HOSTNAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component exceeds the maximum length of %d characters.", object, paramName, HOSTNAME_MAX_LENGTH)); } Matcher m = pattern.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component must match the pattern \"%s\".", object, paramName, pattern)); } } }
3,014
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ProxyEnvironmentSetting.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static software.amazon.awssdk.utils.internal.SystemSettingUtils.resolveEnvironmentVariable; import java.util.Locale; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * An enumeration representing environment settings related to proxy configuration. Instances of this enum are used to * define and access proxy configuration settings obtained from environment variables. */ @SdkProtectedApi public enum ProxyEnvironmentSetting implements SystemSetting { HTTP_PROXY("http_proxy"), HTTPS_PROXY("https_proxy"), NO_PROXY("no_proxy") ; private final String environmentVariable; ProxyEnvironmentSetting(String environmentVariable) { this.environmentVariable = environmentVariable; } @Override public Optional<String> getStringValue() { Optional<String> envVarLowercase = resolveEnvironmentVariable(environmentVariable); if (envVarLowercase.isPresent()) { return getValueIfValid(envVarLowercase.get()); } Optional<String> envVarUppercase = resolveEnvironmentVariable(environmentVariable.toUpperCase(Locale.getDefault())); if (envVarUppercase.isPresent()) { return getValueIfValid(envVarUppercase.get()); } return Optional.empty(); } @Override public String property() { return null; } @Override public String environmentVariable() { return environmentVariable; } @Override public String defaultValue() { return null; } private Optional<String> getValueIfValid(String value) { String trimmedValue = value.trim(); if (!trimmedValue.isEmpty()) { return Optional.of(trimmedValue); } return Optional.empty(); } }
3,015
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/DateUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static java.time.ZoneOffset.UTC; import static java.time.format.DateTimeFormatter.ISO_INSTANT; import static java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME; import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME; import java.math.BigDecimal; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.chrono.IsoChronology; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.time.format.ResolverStyle; import java.util.Arrays; import java.util.List; import java.util.Locale; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * Utilities for parsing and formatting dates. */ @ThreadSafe @SdkProtectedApi public final class DateUtils { /** * Alternate ISO 8601 format without fractional seconds. */ static final DateTimeFormatter ALTERNATE_ISO_8601_DATE_FORMAT = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd'T'HH:mm:ss'Z'") .toFormatter() .withZone(UTC); /** * RFC 822 date/time formatter. */ static final DateTimeFormatter RFC_822_DATE_TIME = new DateTimeFormatterBuilder() .parseCaseInsensitive() .parseLenient() .appendPattern("EEE, dd MMM yyyy HH:mm:ss") .appendLiteral(' ') .appendOffset("+HHMM", "GMT") .toFormatter() .withLocale(Locale.US) .withResolverStyle(ResolverStyle.SMART) .withChronology(IsoChronology.INSTANCE); // ISO_INSTANT does not handle offsets in Java 12-. See https://bugs.openjdk.java.net/browse/JDK-8166138 private static final List<DateTimeFormatter> ALTERNATE_ISO_8601_FORMATTERS = Arrays.asList(ISO_INSTANT, ALTERNATE_ISO_8601_DATE_FORMAT, ISO_OFFSET_DATE_TIME); private static final int MILLI_SECOND_PRECISION = 3; private DateUtils() { } /** * Parses the specified date string as an ISO 8601 date (yyyy-MM-dd'T'HH:mm:ss.SSSZZ) * and returns the {@link Instant} object. * * @param dateString * The date string to parse. * * @return The parsed Instant object. */ public static Instant parseIso8601Date(String dateString) { // For EC2 Spot Fleet. if (dateString.endsWith("+0000")) { dateString = dateString .substring(0, dateString.length() - 5) .concat("Z"); } DateTimeParseException exception = null; for (DateTimeFormatter formatter : ALTERNATE_ISO_8601_FORMATTERS) { try { return parseInstant(dateString, formatter); } catch (DateTimeParseException e) { exception = e; } } if (exception != null) { throw exception; } // should never execute this throw new RuntimeException("Failed to parse date " + dateString); } /** * Formats the specified date as an ISO 8601 string. * * @param date the date to format * @return the ISO-8601 string representing the specified date */ public static String formatIso8601Date(Instant date) { return ISO_INSTANT.format(date); } /** * Parses the specified date string as an RFC 822 date and returns the Date object. * * @param dateString * The date string to parse. * * @return The parsed Date object. */ public static Instant parseRfc822Date(String dateString) { if (dateString == null) { return null; } return parseInstant(dateString, RFC_822_DATE_TIME); } /** * Formats the specified date as an RFC 822 string. * * @param instant * The instant to format. * * @return The RFC 822 string representing the specified date. */ public static String formatRfc822Date(Instant instant) { return RFC_822_DATE_TIME.format(ZonedDateTime.ofInstant(instant, UTC)); } /** * Parses the specified date string as an RFC 1123 date and returns the Date * object. * * @param dateString * The date string to parse. * * @return The parsed Date object. */ public static Instant parseRfc1123Date(String dateString) { if (dateString == null) { return null; } return parseInstant(dateString, RFC_1123_DATE_TIME); } /** * Formats the specified date as an RFC 1123 string. * * @param instant * The instant to format. * * @return The RFC 1123 string representing the specified date. */ public static String formatRfc1123Date(Instant instant) { return RFC_1123_DATE_TIME.format(ZonedDateTime.ofInstant(instant, UTC)); } /** * Returns the number of days since epoch with respect to the given number * of milliseconds since epoch. */ public static long numberOfDaysSinceEpoch(long milliSinceEpoch) { return Duration.ofMillis(milliSinceEpoch).toDays(); } private static Instant parseInstant(String dateString, DateTimeFormatter formatter) { // Should not call formatter.withZone(ZoneOffset.UTC) because it will override the zone // for timestamps with an offset. See https://bugs.openjdk.java.net/browse/JDK-8177021 if (formatter.equals(ISO_OFFSET_DATE_TIME)) { return formatter.parse(dateString, Instant::from); } return formatter.withZone(ZoneOffset.UTC).parse(dateString, Instant::from); } /** * Parses the given string containing a Unix timestamp with millisecond decimal precision into an {@link Instant} object. */ public static Instant parseUnixTimestampInstant(String dateString) throws NumberFormatException { if (dateString == null) { return null; } validateTimestampLength(dateString); BigDecimal dateValue = new BigDecimal(dateString); return Instant.ofEpochMilli(dateValue.scaleByPowerOfTen(MILLI_SECOND_PRECISION).longValue()); } /** * Parses the given string containing a Unix timestamp in epoch millis into a {@link Instant} object. */ public static Instant parseUnixTimestampMillisInstant(String dateString) throws NumberFormatException { if (dateString == null) { return null; } return Instant.ofEpochMilli(Long.parseLong(dateString)); } /** * Formats the give {@link Instant} object into an Unix timestamp with millisecond decimal precision. */ public static String formatUnixTimestampInstant(Instant instant) { if (instant == null) { return null; } BigDecimal dateValue = BigDecimal.valueOf(instant.toEpochMilli()); return dateValue.scaleByPowerOfTen(0 - MILLI_SECOND_PRECISION) .toPlainString(); } private static void validateTimestampLength(String timestamp) { // Helps avoid BigDecimal parsing unnecessarily large numbers, since it's unbounded // Long has a max value of 9,223,372,036,854,775,807, which is 19 digits. Assume that a valid timestamp is no // no longer than 20 characters long (+1 for decimal) if (timestamp.length() > 20) { throw new RuntimeException("Input timestamp string must be no longer than 20 characters"); } } }
3,016
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ToString.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Arrays; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * A class to standardize implementations of {@link Object#toString()} across the SDK. * * <pre>{@code * ToString.builder("Person") * .add("name", name) * .add("age", age) * .build(); * }</pre> */ @NotThreadSafe @SdkProtectedApi public final class ToString { private final StringBuilder result; private final int startingLength; /** * @see #builder(String) */ private ToString(String className) { this.result = new StringBuilder(className).append("("); this.startingLength = result.length(); } /** * Create a to-string result for the given class name. */ public static String create(String className) { return className + "()"; } /** * Create a to-string result builder for the given class name. * @param className The name of the class being toString'd */ public static ToString builder(String className) { return new ToString(className); } /** * Add a field to the to-string result. * @param fieldName The name of the field. Must not be null. * @param field The value of the field. Value is ignored if null. */ public ToString add(String fieldName, Object field) { if (field != null) { String value; if (field.getClass().isArray()) { if (field instanceof byte[]) { value = "0x" + BinaryUtils.toHex((byte[]) field); } else { value = Arrays.toString((Object[]) field); } } else { value = String.valueOf(field); } result.append(fieldName).append("=").append(value).append(", "); } return this; } /** * Convert this result to a string. The behavior of calling other methods after this one is undefined. */ public String build() { if (result.length() > startingLength) { result.setLength(result.length() - 2); } return result.append(")").toString(); } }
3,017
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/CancellableOutputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.io.OutputStream; import software.amazon.awssdk.annotations.SdkPublicApi; /** * An implementation of {@link OutputStream} to which writing can be {@link #cancel()}ed. * <p> * Cancelling tells the downstream receiver of the output that the stream will not be written to anymore, and that the * data sent was incomplete. The stream must still be {@link #close()}d by the caller. */ @SdkPublicApi public abstract class CancellableOutputStream extends OutputStream { /** * Cancel writing to the stream. This is different than {@link #close()} in that it indicates the data written so * far is truncated and incomplete. Callers must still invoke {@link #close()} even if the stream is * cancelled. */ public abstract void cancel(); }
3,018
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ImmutableMap.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * An immutable map that could be built by convenient constructors. * <p> * Example of using map Builder: * * <pre> * { * &#064;code * Map&lt;String, AttibuteValue&gt; item = new ImmutableMap.Builder&lt;String, AttibuteValue&gt;() * .put(&quot;one&quot;, new AttibuteValue(&quot;1&quot;)) * .put(&quot;two&quot;, new AttibuteValue(&quot;2&quot;)) * .put(&quot;three&quot;, new AttibuteValue(&quot;3&quot;)).build(); * } * </pre> * * For <i>small</i> immutable maps (up to five entries), the * {@code ImmutableMapParamter.of()} methods are preferred: * * <pre> * {@code * Map<String, AttibuteValue> item = * ImmutableMap * .of("one", new AttributeValue("1"), * "two", new AttributeValue("2"), * "three", new AttributeValue("3"), * } * </pre> * * @param <K> * Class of the key for the map. * @param <V> * Class of the value for the map. */ @SdkProtectedApi public final class ImmutableMap<K, V> implements Map<K, V> { private static final String UNMODIFIABLE_MESSAGE = "This is an immutable map."; private static final String DUPLICATED_KEY_MESSAGE = "Duplicate keys are provided."; private final Map<K, V> map; private ImmutableMap(Map<K, V> map) { this.map = map; } /** * Returns a new MapParameterBuilder instance. */ public static <K, V> Builder<K, V> builder() { return new Builder<>(); } /** * Returns an ImmutableMap instance containing a single entry. * * @param k0 * Key of the single entry. * @param v0 * Value of the single entry. */ public static <K, V> ImmutableMap<K, V> of(K k0, V v0) { Map<K, V> map = Collections.singletonMap(k0, v0); return new ImmutableMap<>(map); } /** * Returns an ImmutableMap instance containing two entries. * * @param k0 * Key of the first entry. * @param v0 * Value of the first entry. * @param k1 * Key of the second entry. * @param v1 * Value of the second entry. */ public static <K, V> ImmutableMap<K, V> of(K k0, V v0, K k1, V v1) { Map<K, V> map = new HashMap<>(); putAndWarnDuplicateKeys(map, k0, v0); putAndWarnDuplicateKeys(map, k1, v1); return new ImmutableMap<>(map); } /** * Returns an ImmutableMap instance containing three entries. * * @param k0 * Key of the first entry. * @param v0 * Value of the first entry. * @param k1 * Key of the second entry. * @param v1 * Value of the second entry. * @param k2 * Key of the third entry. * @param v2 * Value of the third entry. */ public static <K, V> ImmutableMap<K, V> of(K k0, V v0, K k1, V v1, K k2, V v2) { Map<K, V> map = new HashMap<>(); putAndWarnDuplicateKeys(map, k0, v0); putAndWarnDuplicateKeys(map, k1, v1); putAndWarnDuplicateKeys(map, k2, v2); return new ImmutableMap<>(map); } /** * Returns an ImmutableMap instance containing four entries. * * @param k0 * Key of the first entry. * @param v0 * Value of the first entry. * @param k1 * Key of the second entry. * @param v1 * Value of the second entry. * @param k2 * Key of the third entry. * @param v2 * Value of the third entry. * @param k3 * Key of the fourth entry. * @param v3 * Value of the fourth entry. */ public static <K, V> ImmutableMap<K, V> of(K k0, V v0, K k1, V v1, K k2, V v2, K k3, V v3) { Map<K, V> map = new HashMap<>(); putAndWarnDuplicateKeys(map, k0, v0); putAndWarnDuplicateKeys(map, k1, v1); putAndWarnDuplicateKeys(map, k2, v2); putAndWarnDuplicateKeys(map, k3, v3); return new ImmutableMap<>(map); } /** * Returns an ImmutableMap instance containing five entries. * * @param k0 * Key of the first entry. * @param v0 * Value of the first entry. * @param k1 * Key of the second entry. * @param v1 * Value of the second entry. * @param k2 * Key of the third entry. * @param v2 * Value of the third entry. * @param k3 * Key of the fourth entry. * @param v3 * Value of the fourth entry. * @param k4 * Key of the fifth entry. * @param v4 * Value of the fifth entry. */ public static <K, V> ImmutableMap<K, V> of(K k0, V v0, K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { Map<K, V> map = new HashMap<>(); putAndWarnDuplicateKeys(map, k0, v0); putAndWarnDuplicateKeys(map, k1, v1); putAndWarnDuplicateKeys(map, k2, v2); putAndWarnDuplicateKeys(map, k3, v3); putAndWarnDuplicateKeys(map, k4, v4); return new ImmutableMap<>(map); } private static <K, V> void putAndWarnDuplicateKeys(Map<K, V> map, K key, V value) { if (map.containsKey(key)) { throw new IllegalArgumentException(DUPLICATED_KEY_MESSAGE); } map.put(key, value); } /** Inherited methods **/ @Override public boolean containsKey(Object key) { return map.containsKey(key); } @Override public boolean containsValue(Object value) { return map.containsValue(value); } @Override public Set<Entry<K, V>> entrySet() { return map.entrySet(); } @Override public V get(Object key) { return map.get(key); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public Set<K> keySet() { return map.keySet(); } @Override public int size() { return map.size(); } @Override public Collection<V> values() { return map.values(); } /** Unsupported methods **/ @Override public void clear() { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } @Override public V put(K key, V value) { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } @Override public void putAll(Map<? extends K, ? extends V> map) { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } @Override public V remove(Object key) { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } @Override public boolean equals(Object o) { return map.equals(o); } @Override public int hashCode() { return map.hashCode(); } @Override public String toString() { return map.toString(); } /** * A convenient builder for creating ImmutableMap instances. */ public static class Builder<K, V> { private final Map<K, V> entries; public Builder() { this.entries = new HashMap<>(); } /** * Add a key-value pair into the built map. The method will throw * IllegalArgumentException immediately when duplicate keys are * provided. * * @return Returns a reference to this object so that method calls can * be chained together. */ public Builder<K, V> put(K key, V value) { putAndWarnDuplicateKeys(entries, key, value); return this; } /** * Generates and returns a new ImmutableMap instance which * contains all the entries added into the Builder by {@code put()} * method. */ public ImmutableMap<K, V> build() { HashMap<K, V> builtMap = new HashMap<>(entries); return new ImmutableMap<>(builtMap); } } }
3,019
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/cache/CachedSupplier.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.cache; import static java.time.temporal.ChronoUnit.MINUTES; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.utils.ComparableUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.Validate; /** * A wrapper for a {@link Supplier} that applies certain caching rules to the retrieval of its value, including customizable * pre-fetching behaviors for updating values as they get close to expiring so that not all threads have to block to update the * value. * * For example, the {@link OneCallerBlocks} strategy will have a single caller block to update the value, and the * {@link NonBlocking} strategy maintains a thread pool for updating the value asynchronously in the background. * * This should be created using {@link #builder(Supplier)}. */ @SdkProtectedApi public class CachedSupplier<T> implements Supplier<T>, SdkAutoCloseable { private static final Logger log = Logger.loggerFor(CachedSupplier.class); /** * Maximum time to wait for a blocking refresh lock before calling refresh again. This is to rate limit how many times we call * refresh. In the ideal case, refresh always occurs in a timely fashion and only one thread actually does the refresh. */ private static final Duration BLOCKING_REFRESH_MAX_WAIT = Duration.ofSeconds(5); /** * Used as a primitive form of rate limiting for the speed of our refreshes. This will make sure that the backing supplier has * a period of time to update the value when the {@link RefreshResult#staleTime()} arrives without getting called by every * thread that initiates a {@link #get()}. */ private final Lock refreshLock = new ReentrantLock(); /** * The strategy we should use for pre-fetching the cached data when the {@link RefreshResult#prefetchTime()} arrives. This is * configured when the cache is created via {@link Builder#prefetchStrategy(PrefetchStrategy)}. */ private final PrefetchStrategy prefetchStrategy; /** * Whether the {@link #prefetchStrategy} has been initialized via {@link PrefetchStrategy#initializeCachedSupplier}. */ private final AtomicBoolean prefetchStrategyInitialized = new AtomicBoolean(false); /** * How the supplier should behave when the cached value is stale on retrieval or fails to be retrieved. */ private final StaleValueBehavior staleValueBehavior; /** * The clock used by this supplier. Adjustable for testing. */ private final Clock clock; /** * The number of consecutive failures encountered when updating a stale value. */ private final AtomicInteger consecutiveStaleRetrievalFailures = new AtomicInteger(0); /** * The name to include with each log message, to differentiate caches. */ private final String cachedValueName; /** * The value currently stored in this cache. */ private volatile RefreshResult<T> cachedValue; /** * The "expensive" to call supplier that is used to refresh the {@link #cachedValue}. */ private final Supplier<RefreshResult<T>> valueSupplier; /** * Random instance used for jittering refresh results. */ private final Random jitterRandom = new Random(); private CachedSupplier(Builder<T> builder) { Validate.notNull(builder.supplier, "builder.supplier"); Validate.notNull(builder.jitterEnabled, "builder.jitterEnabled"); this.valueSupplier = jitteredPrefetchValueSupplier(builder.supplier, builder.jitterEnabled); this.prefetchStrategy = Validate.notNull(builder.prefetchStrategy, "builder.prefetchStrategy"); this.staleValueBehavior = Validate.notNull(builder.staleValueBehavior, "builder.staleValueBehavior"); this.clock = Validate.notNull(builder.clock, "builder.clock"); this.cachedValueName = Validate.notNull(builder.cachedValueName, "builder.cachedValueName"); } /** * Retrieve a builder that can be used for creating a {@link CachedSupplier}. * * @param valueSupplier The value supplier that should have its value cached. */ public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } @Override public T get() { if (cacheIsStale()) { log.debug(() -> "(" + cachedValueName + ") Cached value is stale and will be refreshed."); refreshCache(); } else if (shouldInitiateCachePrefetch()) { log.debug(() -> "(" + cachedValueName + ") Cached value has reached prefetch time and will be refreshed."); prefetchCache(); } return this.cachedValue.value(); } /** * Determines whether the value in this cache is stale, and all threads should block and wait for an updated value. */ private boolean cacheIsStale() { RefreshResult<T> currentCachedValue = cachedValue; if (currentCachedValue == null) { return true; } if (currentCachedValue.staleTime() == null) { return false; } Instant now = clock.instant(); return !now.isBefore(currentCachedValue.staleTime()); } /** * Determines whether the cached value's prefetch time has passed and we should initiate a pre-fetch on the value using the * configured {@link #prefetchStrategy}. */ private boolean shouldInitiateCachePrefetch() { RefreshResult<T> currentCachedValue = cachedValue; if (currentCachedValue == null) { return false; } if (currentCachedValue.prefetchTime() == null) { return false; } return !clock.instant().isBefore(currentCachedValue.prefetchTime()); } /** * Initiate a pre-fetch of the data using the configured {@link #prefetchStrategy}. */ private void prefetchCache() { prefetchStrategy.prefetch(this::refreshCache); } /** * Perform a blocking refresh of the cached value. This will rate limit synchronous refresh calls based on the * {@link #BLOCKING_REFRESH_MAX_WAIT} time. This ensures that when the data needs to be updated, we won't immediately hammer * the underlying value refresher if it can get back to us in a reasonable time. */ private void refreshCache() { try { boolean lockAcquired = refreshLock.tryLock(BLOCKING_REFRESH_MAX_WAIT.getSeconds(), TimeUnit.SECONDS); try { // Make sure the value was not refreshed while we waited for the lock. if (cacheIsStale() || shouldInitiateCachePrefetch()) { log.debug(() -> "(" + cachedValueName + ") Refreshing cached value."); // It wasn't, call the supplier to update it. if (prefetchStrategyInitialized.compareAndSet(false, true)) { prefetchStrategy.initializeCachedSupplier(this); } try { RefreshResult<T> cachedValue = handleFetchedSuccess(prefetchStrategy.fetch(valueSupplier)); this.cachedValue = cachedValue; log.debug(() -> "(" + cachedValueName + ") Successfully refreshed cached value. " + "Next Prefetch Time: " + cachedValue.prefetchTime() + ". " + "Next Stale Time: " + cachedValue.staleTime()); } catch (RuntimeException t) { cachedValue = handleFetchFailure(t); } } } finally { if (lockAcquired) { refreshLock.unlock(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted waiting to refresh a cached value.", e); } } /** * Perform necessary transformations of the successfully-fetched value based on the stale value behavior of this supplier. */ private RefreshResult<T> handleFetchedSuccess(RefreshResult<T> fetch) { consecutiveStaleRetrievalFailures.set(0); Instant now = clock.instant(); if (now.isBefore(fetch.staleTime())) { return fetch; } switch (staleValueBehavior) { case STRICT: Instant newStale = now.plusSeconds(1); log.warn(() -> "(" + cachedValueName + ") Retrieved value expiration is in the past (" + fetch.staleTime() + "). Using expiration of " + newStale); return fetch.toBuilder().staleTime(newStale).build(); // Refresh again in 1 second case ALLOW: Instant newStaleTime = jitterTime(now, Duration.ofMinutes(1), Duration.ofMinutes(10)); log.warn(() -> "(" + cachedValueName + ") Cached value expiration has been extended to " + newStaleTime + " because the downstream service returned a time in the past: " + fetch.staleTime()); return fetch.toBuilder() .staleTime(newStaleTime) .build(); default: throw new IllegalStateException("Unknown stale-value-behavior: " + staleValueBehavior); } } /** * Perform necessary transformations of the currently-cached value based on the stale value behavior of this supplier. */ private RefreshResult<T> handleFetchFailure(RuntimeException e) { log.debug(() -> "(" + cachedValueName + ") Failed to refresh cached value.", e); RefreshResult<T> currentCachedValue = cachedValue; if (currentCachedValue == null) { throw e; } Instant now = clock.instant(); if (!now.isBefore(currentCachedValue.staleTime())) { int numFailures = consecutiveStaleRetrievalFailures.incrementAndGet(); switch (staleValueBehavior) { case STRICT: throw e; case ALLOW: Instant newStaleTime = jitterTime(now, Duration.ofMillis(1), maxStaleFailureJitter(numFailures)); log.warn(() -> "(" + cachedValueName + ") Cached value expiration has been extended to " + newStaleTime + " because calling the downstream service failed (consecutive failures: " + numFailures + ").", e); return currentCachedValue.toBuilder() .staleTime(newStaleTime) .build(); default: throw new IllegalStateException("Unknown stale-value-behavior: " + staleValueBehavior); } } return currentCachedValue; } /** * Wrap a value supplier with one that jitters its prefetch time. */ private Supplier<RefreshResult<T>> jitteredPrefetchValueSupplier(Supplier<RefreshResult<T>> supplier, boolean prefetchJitterEnabled) { return () -> { RefreshResult<T> result = supplier.get(); if (!prefetchJitterEnabled || result.prefetchTime() == null) { return result; } Duration maxJitter = maxPrefetchJitter(result); if (maxJitter.isZero()) { return result; } Instant newPrefetchTime = jitterTime(result.prefetchTime(), Duration.ZERO, maxJitter); return result.toBuilder() .prefetchTime(newPrefetchTime) .build(); }; } private Duration maxPrefetchJitter(RefreshResult<T> result) { Instant staleTime = result.staleTime() != null ? result.staleTime() : Instant.MAX; Instant oneMinuteBeforeStale = staleTime.minus(1, MINUTES); if (!result.prefetchTime().isBefore(oneMinuteBeforeStale)) { return Duration.ZERO; } Duration timeBetweenPrefetchAndStale = Duration.between(result.prefetchTime(), oneMinuteBeforeStale); if (timeBetweenPrefetchAndStale.toDays() > 365) { // The value will essentially never become stale. The user is likely using this for a value that should be // periodically refreshed on a best-effort basis. Use a 5-minute jitter range to respect their requested // prefetch time. return Duration.ofMinutes(5); } return timeBetweenPrefetchAndStale; } private Duration maxStaleFailureJitter(int numFailures) { long exponentialBackoffMillis = (1L << numFailures - 1) * 100; return ComparableUtils.minimum(Duration.ofMillis(exponentialBackoffMillis), Duration.ofSeconds(10)); } private Instant jitterTime(Instant time, Duration jitterStart, Duration jitterEnd) { long jitterRange = jitterEnd.minus(jitterStart).toMillis(); long jitterAmount = Math.abs(jitterRandom.nextLong() % jitterRange); return time.plus(jitterStart).plusMillis(jitterAmount); } /** * Free any resources consumed by the prefetch strategy this supplier is using. */ @Override public void close() { prefetchStrategy.close(); } /** * A Builder for {@link CachedSupplier}, created by {@link #builder(Supplier)}. */ public static final class Builder<T> { private final Supplier<RefreshResult<T>> supplier; private PrefetchStrategy prefetchStrategy = new OneCallerBlocks(); private Boolean jitterEnabled = true; private StaleValueBehavior staleValueBehavior = StaleValueBehavior.STRICT; private Clock clock = Clock.systemUTC(); private String cachedValueName = "unknown"; private Builder(Supplier<RefreshResult<T>> supplier) { this.supplier = supplier; } /** * Configure the way in which data in the cache should be pre-fetched when the data's {@link RefreshResult#prefetchTime()} * arrives. * * By default, this uses the {@link OneCallerBlocks} strategy, which will block a single {@link #get()} caller to update * the value. */ public Builder<T> prefetchStrategy(PrefetchStrategy prefetchStrategy) { this.prefetchStrategy = prefetchStrategy; return this; } /** * Configure the way the cache should behave when a stale value is retrieved or when retrieving a value fails while the * cache is stale. * * By default, this uses {@link StaleValueBehavior#STRICT}. */ public Builder<T> staleValueBehavior(StaleValueBehavior staleValueBehavior) { this.staleValueBehavior = staleValueBehavior; return this; } /** * Configures a name for the cached value. This name will be included with logs emitted by this supplier, to aid * in debugging. * * By default, this uses "unknown". */ public Builder<T> cachedValueName(String cachedValueName) { this.cachedValueName = cachedValueName; return this; } /** * Configure the clock used for this cached supplier. Configurable for testing. */ @SdkTestInternalApi public Builder<T> clock(Clock clock) { this.clock = clock; return this; } /** * Whether jitter is enabled on the prefetch time. Can be disabled for testing. */ @SdkTestInternalApi Builder<T> jitterEnabled(Boolean jitterEnabled) { this.jitterEnabled = jitterEnabled; return this; } /** * Create a {@link CachedSupplier} using the current configuration of this builder. */ public CachedSupplier<T> build() { return new CachedSupplier<>(this); } } /** * The way in which the cache should be pre-fetched when the data's {@link RefreshResult#prefetchTime()} arrives. * * @see OneCallerBlocks * @see NonBlocking */ @FunctionalInterface public interface PrefetchStrategy extends SdkAutoCloseable { /** * Execute the provided value updater to update the cache. The specific implementation defines how this is invoked. */ void prefetch(Runnable valueUpdater); /** * Invoke the provided supplier to retrieve the refresh result. This is useful for prefetch strategies to override when * they care about the refresh result. */ default <T> RefreshResult<T> fetch(Supplier<RefreshResult<T>> supplier) { return supplier.get(); } /** * Invoked when the prefetch strategy is registered with a {@link CachedSupplier}. */ default void initializeCachedSupplier(CachedSupplier<?> cachedSupplier) { } /** * Free any resources associated with the strategy. This is invoked when the {@link CachedSupplier#close()} method is * invoked. */ @Override default void close() { } } /** * How the cached supplier should behave when a stale value is retrieved from the underlying supplier or the underlying * supplier fails while the cached value is stale. */ public enum StaleValueBehavior { /** * Strictly treat the stale time. Never return a stale cached value (except when the supplier returns an expired * value, in which case the supplier will return the value but only for a very short period of time to prevent * overloading the underlying supplier). */ STRICT, /** * Allow stale values to be returned from the cache. Value retrieval will never fail, as long as the cache has * succeeded when calling the underlying supplier at least once. */ ALLOW } }
3,020
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/cache/OneCallerBlocks.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.cache; import java.util.concurrent.atomic.AtomicBoolean; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * A {@link CachedSupplier.PrefetchStrategy} that will have one caller at a time block to update the value. * * Multiple calls to {@link #prefetch(Runnable)} will result in only one caller actually performing the update, with the others * immediately returning. */ @SdkProtectedApi public class OneCallerBlocks implements CachedSupplier.PrefetchStrategy { /** * Whether we are currently refreshing the supplier. This is used to make sure only one caller is blocking at a time. */ private final AtomicBoolean currentlyRefreshing = new AtomicBoolean(false); @Override public void prefetch(Runnable valueUpdater) { if (currentlyRefreshing.compareAndSet(false, true)) { try { valueUpdater.run(); } finally { currentlyRefreshing.set(false); } } } }
3,021
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/cache/RefreshResult.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.cache; import java.time.Instant; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A wrapper for the value returned by the {@link Supplier} underlying a {@link CachedSupplier}. The underlying {@link Supplier} * returns this to specify when the underlying value should be refreshed. */ @SdkProtectedApi public final class RefreshResult<T> implements ToCopyableBuilder<RefreshResult.Builder<T>, RefreshResult<T>> { private final T value; private final Instant staleTime; private final Instant prefetchTime; private RefreshResult(Builder<T> builder) { this.value = builder.value; this.staleTime = builder.staleTime; this.prefetchTime = builder.prefetchTime; } /** * Get a builder for creating a {@link RefreshResult}. * * @param value The value that should be cached by the supplier. */ public static <T> Builder<T> builder(T value) { return new Builder<>(value); } /** * The value resulting from the refresh. */ public T value() { return value; } /** * When the configured value is stale and should no longer be used. All threads will block until the value is updated. */ public Instant staleTime() { return staleTime; } /** * When the configured value is getting close to stale and should be updated using the supplier's * {@link CachedSupplier#prefetchStrategy}. */ public Instant prefetchTime() { return prefetchTime; } @Override public RefreshResult.Builder<T> toBuilder() { return new RefreshResult.Builder<>(this); } /** * A builder for a {@link RefreshResult}. */ public static final class Builder<T> implements CopyableBuilder<Builder<T>, RefreshResult<T>> { private final T value; private Instant staleTime = Instant.MAX; private Instant prefetchTime = Instant.MAX; private Builder(T value) { this.value = value; } private Builder(RefreshResult<T> value) { this.value = value.value; this.staleTime = value.staleTime; this.prefetchTime = value.prefetchTime; } /** * Specify the time at which the value in this cache is stale, and all calls to {@link CachedSupplier#get()} should block * to try to update the value. * * If this isn't specified, all threads will never block to update the value. */ public Builder<T> staleTime(Instant staleTime) { this.staleTime = staleTime; return this; } /** * Specify the time at which a thread that calls {@link CachedSupplier#get()} should trigger a cache prefetch. The * exact behavior of a "prefetch" is defined when the cache is created with * {@link CachedSupplier.Builder#prefetchStrategy(CachedSupplier.PrefetchStrategy)}, and may either have one thread block * to refresh the cache or have an asynchronous task reload the value in the background. * * If this isn't specified, the prefetch strategy will never be used and all threads will block to update the value when * the {@link #staleTime(Instant)} arrives. */ public Builder<T> prefetchTime(Instant prefetchTime) { this.prefetchTime = prefetchTime; return this; } /** * Build a {@link RefreshResult} using the values currently configured in this builder. */ public RefreshResult<T> build() { return new RefreshResult<>(this); } } }
3,022
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/cache/NonBlocking.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.cache; import java.time.Duration; import java.time.Instant; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.ThreadFactoryBuilder; /** * A {@link CachedSupplier.PrefetchStrategy} that will run a single thread in the background to update the value. A call to * prefetch on this strategy will never return. * * Multiple calls to {@link #prefetch(Runnable)} will still only result in one background task performing the update. */ @SdkProtectedApi public class NonBlocking implements CachedSupplier.PrefetchStrategy { private static final Logger log = Logger.loggerFor(NonBlocking.class); /** * The maximum number of concurrent refreshes before we start logging warnings and skipping refreshes. */ private static final int MAX_CONCURRENT_REFRESHES = 100; /** * The semaphore around concurrent background refreshes, enforcing the {@link #MAX_CONCURRENT_REFRESHES}. */ private static final Semaphore CONCURRENT_REFRESH_LEASES = new Semaphore(MAX_CONCURRENT_REFRESHES); /** * Thread used to kick off refreshes during the prefetch window. This does not do the actual refreshing. That's left for * the {@link #EXECUTOR}. */ private static final ScheduledThreadPoolExecutor SCHEDULER = new ScheduledThreadPoolExecutor(1, new ThreadFactoryBuilder().threadNamePrefix("sdk-cache-scheduler") .daemonThreads(true) .build()); /** * Threads used to do the actual work of refreshing the values (because the cached supplier might block, so we don't * want the work to be done by a small thread pool). This executor is created as unbounded, but we start complaining and * skipping refreshes when there are more than {@link #MAX_CONCURRENT_REFRESHES} running. */ private static final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(1, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), new ThreadFactoryBuilder().threadNamePrefix("sdk-cache") .daemonThreads(true) .build()); /** * An incrementing number, used to uniquely identify an instance of NonBlocking in the {@link #asyncThreadName}. */ private static final AtomicLong INSTANCE_NUMBER = new AtomicLong(0); /** * Whether we are currently refreshing the supplier. This is used to make sure only one caller is blocking at a time. */ private final AtomicBoolean currentlyPrefetching = new AtomicBoolean(false); /** * Name of the thread refreshing the cache for this strategy. */ private final String asyncThreadName; /** * The refresh task currently scheduled for this non-blocking instance. We ensure that no more than one task is scheduled * per instance. */ private final AtomicReference<ScheduledFuture<?>> refreshTask = new AtomicReference<>(); /** * Whether this strategy has been shutdown (and should stop doing background refreshes) */ private volatile boolean shutdown = false; /** * The cached supplier using this non-blocking instance. */ private volatile CachedSupplier<?> cachedSupplier; static { // Ensure that cancelling a task actually removes it from the queue. SCHEDULER.setRemoveOnCancelPolicy(true); } /** * Create a non-blocking prefetch strategy that uses the provided value for the name of the background thread that will be * performing the update. */ public NonBlocking(String asyncThreadName) { this.asyncThreadName = asyncThreadName + "-" + INSTANCE_NUMBER.getAndIncrement(); } @SdkTestInternalApi static ThreadPoolExecutor executor() { return EXECUTOR; } @Override public void initializeCachedSupplier(CachedSupplier<?> cachedSupplier) { this.cachedSupplier = cachedSupplier; } @Override public void prefetch(Runnable valueUpdater) { // Only run one async prefetch at a time. if (currentlyPrefetching.compareAndSet(false, true)) { tryRunBackgroundTask(valueUpdater, () -> currentlyPrefetching.set(false)); } } @Override public <T> RefreshResult<T> fetch(Supplier<RefreshResult<T>> supplier) { RefreshResult<T> result = supplier.get(); schedulePrefetch(result); return result; } private void schedulePrefetch(RefreshResult<?> result) { if (shutdown || result.staleTime() == null || result.prefetchTime() == null) { return; } Duration timeUntilPrefetch = Duration.between(Instant.now(), result.prefetchTime()); if (timeUntilPrefetch.isNegative() || timeUntilPrefetch.toDays() > 7) { log.debug(() -> "Skipping background refresh because the prefetch time is in the past or too far in the future: " + result.prefetchTime()); return; } Instant backgroundRefreshTime = result.prefetchTime().plusSeconds(1); Duration timeUntilBackgroundRefresh = timeUntilPrefetch.plusSeconds(1); log.debug(() -> "Scheduling refresh attempt for " + backgroundRefreshTime + " (in " + timeUntilBackgroundRefresh.toMillis() + " ms)"); ScheduledFuture<?> scheduledTask = SCHEDULER.schedule(() -> { runWithInstanceThreadName(() -> { log.debug(() -> "Executing refresh attempt scheduled for " + backgroundRefreshTime); // If the supplier has already been prefetched, this will just be a cache hit. tryRunBackgroundTask(cachedSupplier::get); }); }, timeUntilBackgroundRefresh.toMillis(), TimeUnit.MILLISECONDS); updateTask(scheduledTask); if (shutdown) { updateTask(null); } } @Override public void close() { shutdown = true; updateTask(null); } public void updateTask(ScheduledFuture<?> newTask) { ScheduledFuture<?> currentTask; do { currentTask = refreshTask.get(); if (currentTask != null && !currentTask.isDone()) { currentTask.cancel(false); } } while (!refreshTask.compareAndSet(currentTask, newTask)); } public void tryRunBackgroundTask(Runnable runnable) { tryRunBackgroundTask(runnable, () -> { }); } public void tryRunBackgroundTask(Runnable runnable, Runnable runOnCompletion) { if (!CONCURRENT_REFRESH_LEASES.tryAcquire()) { log.warn(() -> "Skipping a background refresh task because there are too many other tasks running."); runOnCompletion.run(); return; } try { EXECUTOR.submit(() -> { runWithInstanceThreadName(() -> { try { runnable.run(); } catch (Throwable t) { log.warn(() -> "Exception occurred in AWS SDK background task.", t); } finally { CONCURRENT_REFRESH_LEASES.release(); runOnCompletion.run(); } }); }); } catch (Throwable t) { log.warn(() -> "Exception occurred when submitting AWS SDK background task.", t); CONCURRENT_REFRESH_LEASES.release(); runOnCompletion.run(); } } public void runWithInstanceThreadName(Runnable runnable) { String baseThreadName = Thread.currentThread().getName(); try { Thread.currentThread().setName(baseThreadName + "-" + asyncThreadName); runnable.run(); } finally { Thread.currentThread().setName(baseThreadName); } } }
3,023
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/cache
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/cache/lru/LruCache.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.cache.lru; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * A thread-safe LRU (Least Recently Used) cache implementation that returns the value for a specified key, * retrieving it by either getting the stored value from the cache or using a supplied function to calculate that value * and add it to the cache. * <p> * When the cache is full, a new value will push out the least recently used value. * When the cache is queried for an already stored value (cache hit), this value is moved to the back of the queue * before it's returned so that the order of most recently used to least recently used can be maintained. * <p> * The user can configure the maximum size of the cache, which is set to a default of 100. * <p> * Null values are accepted. */ @SdkProtectedApi @ThreadSafe public final class LruCache<K, V> { private static final Logger log = Logger.loggerFor(LruCache.class); private static final int DEFAULT_SIZE = 100; private final Map<K, CacheEntry<K, V>> cache; private final Function<K, V> valueSupplier; private final Object listLock = new Object(); private final int maxCacheSize; private CacheEntry<K, V> leastRecentlyUsed = null; private CacheEntry<K, V> mostRecentlyUsed = null; private LruCache(Builder<K, V> b) { this.valueSupplier = b.supplier; Integer customSize = Validate.isPositiveOrNull(b.maxSize, "size"); this.maxCacheSize = customSize != null ? customSize : DEFAULT_SIZE; this.cache = new ConcurrentHashMap<>(); } /** * Get a value based on the key. If the value exists in the cache, it's returned, and it's position in the cache is updated. * Otherwise, the value is calculated based on the supplied function {@link Builder#builder(Function)}. */ public V get(K key) { while (true) { CacheEntry<K, V> cachedEntry = cache.computeIfAbsent(key, this::newEntry); synchronized (listLock) { if (cachedEntry.evicted()) { continue; } moveToBackOfQueue(cachedEntry); return cachedEntry.value(); } } } private CacheEntry<K, V> newEntry(K key) { V value = valueSupplier.apply(key); return new CacheEntry<>(key, value); } /** * Moves an entry to the back of the queue and sets it as the most recently used. If the entry is already the * most recently used, do nothing. * <p> * Summary of cache update: * <ol> * <li>Detach the entry from its current place in the double linked list.</li> * <li>Add it to the back of the queue (most recently used)</li> *</ol> */ private void moveToBackOfQueue(CacheEntry<K, V> entry) { if (entry.equals(mostRecentlyUsed)) { return; } removeFromQueue(entry); addToQueue(entry); } /** * Detaches an entry from its neighbors in the cache. Remove the entry from its current place in the double linked list * by letting its previous neighbor point to its next neighbor, and vice versa, if those exist. * <p> * The least-recently-used and most-recently-used pointers are reset if needed. * <p> * <b>Note:</b> Detaching an entry does not delete it from the cache hash map. */ private void removeFromQueue(CacheEntry<K, V> entry) { CacheEntry<K, V> previousEntry = entry.previous(); if (previousEntry != null) { previousEntry.setNext(entry.next()); } CacheEntry<K, V> nextEntry = entry.next(); if (nextEntry != null) { nextEntry.setPrevious(entry.previous()); } if (entry.equals(leastRecentlyUsed)) { leastRecentlyUsed = entry.previous(); } if (entry.equals(mostRecentlyUsed)) { mostRecentlyUsed = entry.next(); } } /** * Adds an entry to the queue as the most recently used, adjusts all pointers and triggers an evict * event if the cache is now full. */ private void addToQueue(CacheEntry<K, V> entry) { if (mostRecentlyUsed != null) { mostRecentlyUsed.setPrevious(entry); entry.setNext(mostRecentlyUsed); } entry.setPrevious(null); mostRecentlyUsed = entry; if (leastRecentlyUsed == null) { leastRecentlyUsed = entry; } if (size() > maxCacheSize) { evict(); } } /** * Removes the least recently used entry from the cache, marks it as evicted and removes it from the queue. */ private void evict() { leastRecentlyUsed.isEvicted(true); closeEvictedResourcesIfPossible(leastRecentlyUsed.value); cache.remove(leastRecentlyUsed.key()); removeFromQueue(leastRecentlyUsed); } private void closeEvictedResourcesIfPossible(V value) { if (value instanceof AutoCloseable) { try { ((AutoCloseable) value).close(); } catch (Exception e) { log.warn(() -> "Attempted to close instance that was evicted by cache, but got exception: " + e.getMessage()); } } } public int size() { return cache.size(); } public static <K, V> LruCache.Builder<K, V> builder(Function<K, V> supplier) { return new Builder<>(supplier); } public static final class Builder<K, V> { private final Function<K, V> supplier; private Integer maxSize; private Builder(Function<K, V> supplier) { this.supplier = supplier; } public Builder<K, V> maxSize(Integer maxSize) { this.maxSize = maxSize; return this; } public LruCache<K, V> build() { return new LruCache<>(this); } } private static final class CacheEntry<K, V> { private final K key; private final V value; private boolean evicted = false; private CacheEntry<K, V> previous; private CacheEntry<K, V> next; private CacheEntry(K key, V value) { this.key = key; this.value = value; } K key() { return key; } V value() { return value; } boolean evicted() { return evicted; } void isEvicted(boolean evicted) { this.evicted = evicted; } CacheEntry<K, V> next() { return next; } void setNext(CacheEntry<K, V> next) { this.next = next; } CacheEntry<K, V> previous() { return previous; } void setPrevious(CacheEntry<K, V> previous) { this.previous = previous; } @Override @SuppressWarnings("unchecked") public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || getClass() != o.getClass()) { return false; } CacheEntry<?, ?> that = (CacheEntry<?, ?>) o; return Objects.equals(key, that.key) && Objects.equals(value, that.value); } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); return result; } } }
3,024
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/FlatteningSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; @SdkProtectedApi public class FlatteningSubscriber<U> extends DelegatingSubscriber<Iterable<U>, U> { private static final Logger log = Logger.loggerFor(FlatteningSubscriber.class); /** * The amount of unfulfilled demand open against the upstream subscriber. */ private final AtomicLong upstreamDemand = new AtomicLong(0); /** * The amount of unfulfilled demand the downstream subscriber has opened against us. */ private final AtomicLong downstreamDemand = new AtomicLong(0); /** * A flag that is used to ensure that only one thread is handling updates to the state of this subscriber at a time. This * allows us to ensure that the downstream onNext, onComplete and onError are only ever invoked serially. */ private final AtomicBoolean handlingStateUpdate = new AtomicBoolean(false); /** * Items given to us by the upstream subscriber that we will use to fulfill demand of the downstream subscriber. */ private final LinkedBlockingQueue<U> allItems = new LinkedBlockingQueue<>(); /** * Whether the upstream subscriber has called onError on us. If this is null, we haven't gotten an onError. If it's non-null * this will be the exception that the upstream passed to our onError. After we get an onError, we'll call onError on the * downstream subscriber as soon as possible. */ private final AtomicReference<Throwable> onErrorFromUpstream = new AtomicReference<>(null); /** * Whether we have called onComplete or onNext on the downstream subscriber. */ private volatile boolean terminalCallMadeDownstream = false; /** * Whether the upstream subscriber has called onComplete on us. After this happens, we'll drain any outstanding items in the * allItems queue and then call onComplete on the downstream subscriber. */ private volatile boolean onCompleteCalledByUpstream = false; /** * The subscription to the upstream subscriber. */ private Subscription upstreamSubscription; public FlatteningSubscriber(Subscriber<? super U> subscriber) { super(subscriber); } @Override public void onSubscribe(Subscription subscription) { if (upstreamSubscription != null) { log.warn(() -> "Received duplicate subscription, cancelling the duplicate.", new IllegalStateException()); subscription.cancel(); return; } upstreamSubscription = subscription; subscriber.onSubscribe(new Subscription() { @Override public void request(long l) { addDownstreamDemand(l); handleStateUpdate(); } @Override public void cancel() { subscription.cancel(); } }); } @Override public void onNext(Iterable<U> nextItems) { try { nextItems.forEach(item -> { Validate.notNull(nextItems, "Collections flattened by the flattening subscriber must not contain null."); allItems.add(item); }); } catch (RuntimeException e) { upstreamSubscription.cancel(); onError(e); throw e; } upstreamDemand.decrementAndGet(); handleStateUpdate(); } @Override public void onError(Throwable throwable) { onErrorFromUpstream.compareAndSet(null, throwable); handleStateUpdate(); } @Override public void onComplete() { onCompleteCalledByUpstream = true; handleStateUpdate(); } /** * Increment the downstream demand by the provided value, accounting for overflow. */ private void addDownstreamDemand(long l) { if (l > 0) { downstreamDemand.getAndUpdate(current -> { long newValue = current + l; return newValue >= 0 ? newValue : Long.MAX_VALUE; }); } else { log.error(() -> "Demand " + l + " must not be negative."); upstreamSubscription.cancel(); onError(new IllegalArgumentException("Demand must not be negative")); } } /** * This is invoked after each downstream request or upstream onNext, onError or onComplete. */ private void handleStateUpdate() { do { // Anything that happens after this if statement and before we set handlingStateUpdate to false is guaranteed to only // happen on one thread. For that reason, we should only invoke onNext, onComplete or onError within that block. if (!handlingStateUpdate.compareAndSet(false, true)) { return; } try { // If we've already called onComplete or onError, don't do anything. if (terminalCallMadeDownstream) { return; } // Call onNext, onComplete and onError as needed based on the current subscriber state. handleOnNextState(); handleUpstreamDemandState(); handleOnCompleteState(); handleOnErrorState(); } catch (Error e) { throw e; } catch (Throwable e) { log.error(() -> "Unexpected exception encountered that violates the reactive streams specification. Attempting " + "to terminate gracefully.", e); upstreamSubscription.cancel(); onError(e); } finally { handlingStateUpdate.set(false); } // It's possible we had an important state change between when we decided to release the state update flag, and we // actually released it. If that seems to have happened, try to handle that state change on this thread, because // another thread is not guaranteed to come around and do so. } while (onNextNeeded() || upstreamDemandNeeded() || onCompleteNeeded() || onErrorNeeded()); } /** * Fulfill downstream demand by pulling items out of the item queue and sending them downstream. */ private void handleOnNextState() { while (onNextNeeded() && !onErrorNeeded()) { downstreamDemand.decrementAndGet(); subscriber.onNext(allItems.poll()); } } /** * Returns true if we need to call onNext downstream. If this is executed outside the handling-state-update condition, the * result is subject to change. */ private boolean onNextNeeded() { return !allItems.isEmpty() && downstreamDemand.get() > 0; } /** * Request more upstream demand if it's needed. */ private void handleUpstreamDemandState() { if (upstreamDemandNeeded()) { ensureUpstreamDemandExists(); } } /** * Returns true if we need to increase our upstream demand. */ private boolean upstreamDemandNeeded() { return upstreamDemand.get() <= 0 && downstreamDemand.get() > 0 && allItems.isEmpty(); } /** * If there are zero pending items in the queue and the upstream has called onComplete, then tell the downstream * we're done. */ private void handleOnCompleteState() { if (onCompleteNeeded()) { terminalCallMadeDownstream = true; subscriber.onComplete(); } } /** * Returns true if we need to call onNext downstream. If this is executed outside the handling-state-update condition, the * result is subject to change. */ private boolean onCompleteNeeded() { return onCompleteCalledByUpstream && allItems.isEmpty() && !terminalCallMadeDownstream; } /** * If the upstream has called onError, then tell the downstream we're done, no matter what state the queue is in. */ private void handleOnErrorState() { if (onErrorNeeded()) { terminalCallMadeDownstream = true; subscriber.onError(onErrorFromUpstream.get()); } } /** * Returns true if we need to call onError downstream. If this is executed outside the handling-state-update condition, the * result is subject to change. */ private boolean onErrorNeeded() { return onErrorFromUpstream.get() != null && !terminalCallMadeDownstream; } /** * Ensure that we have at least 1 demand upstream, so that we can get more items. */ private void ensureUpstreamDemandExists() { if (this.upstreamDemand.get() < 0) { log.error(() -> "Upstream delivered more data than requested. Resetting state to prevent a frozen stream.", new IllegalStateException()); upstreamDemand.set(1); upstreamSubscription.request(1); } else if (this.upstreamDemand.compareAndSet(0, 1)) { upstreamSubscription.request(1); } } }
3,025
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/EventListeningSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.util.function.Consumer; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.Logger; /** * A {@link Subscriber} that can invoke callbacks during various parts of the subscriber and subscription lifecycle. */ @SdkProtectedApi public final class EventListeningSubscriber<T> extends DelegatingSubscriber<T, T> { private static final Logger log = Logger.loggerFor(EventListeningSubscriber.class); private final Runnable afterCompleteListener; private final Consumer<Throwable> afterErrorListener; private final Runnable afterCancelListener; public EventListeningSubscriber(Subscriber<T> subscriber, Runnable afterCompleteListener, Consumer<Throwable> afterErrorListener, Runnable afterCancelListener) { super(subscriber); this.afterCompleteListener = afterCompleteListener; this.afterErrorListener = afterErrorListener; this.afterCancelListener = afterCancelListener; } @Override public void onNext(T t) { super.subscriber.onNext(t); } @Override public void onSubscribe(Subscription subscription) { super.onSubscribe(new CancelListeningSubscriber(subscription)); } @Override public void onError(Throwable throwable) { super.onError(throwable); if (afterErrorListener != null) { callListener(() -> afterErrorListener.accept(throwable), "Post-onError callback failed. This exception will be dropped."); } } @Override public void onComplete() { super.onComplete(); callListener(afterCompleteListener, "Post-onComplete callback failed. This exception will be dropped."); } private class CancelListeningSubscriber extends DelegatingSubscription { protected CancelListeningSubscriber(Subscription s) { super(s); } @Override public void cancel() { super.cancel(); callListener(afterCancelListener, "Post-cancel callback failed. This exception will be dropped."); } } private void callListener(Runnable listener, String listenerFailureMessage) { if (listener != null) { try { listener.run(); } catch (RuntimeException e) { log.error(() -> listenerFailureMessage, e); } } } }
3,026
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/DelegatingSubscription.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public class DelegatingSubscription implements Subscription { private final Subscription s; protected DelegatingSubscription(Subscription s) { this.s = s; } @Override public void request(long l) { s.request(l); } @Override public void cancel() { s.cancel(); } }
3,027
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/InputStreamSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Queue; import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult; /** * Adapts a {@link Subscriber} to a {@link InputStream}. * <p> * Reads from the stream will block until data is published to this subscriber. The amount of data stored in memory by this * subscriber when the input stream is not being read is bounded. */ @SdkProtectedApi public final class InputStreamSubscriber extends InputStream implements Subscriber<ByteBuffer>, SdkAutoCloseable { private static final int BUFFER_SIZE = 4 * 1024 * 1024; // 4 MB private final ByteBufferStoringSubscriber delegate; private final ByteBuffer singleByte = ByteBuffer.allocate(1); private final AtomicReference<State> inputStreamState = new AtomicReference<>(State.UNINITIALIZED); private final AtomicBoolean drainingCallQueue = new AtomicBoolean(false); private final Queue<QueueEntry> callQueue = new ConcurrentLinkedQueue<>(); private final Object subscribeLock = new Object(); private Subscription subscription; private boolean done = false; public InputStreamSubscriber() { this.delegate = new ByteBufferStoringSubscriber(BUFFER_SIZE); } @Override public void onSubscribe(Subscription s) { synchronized (subscribeLock) { if (!inputStreamState.compareAndSet(State.UNINITIALIZED, State.READABLE)) { close(); return; } this.subscription = new CancelWatcher(s); delegate.onSubscribe(subscription); } } @Override public void onNext(ByteBuffer byteBuffer) { callQueue.add(new QueueEntry(false, () -> delegate.onNext(byteBuffer))); drainQueue(); } @Override public void onError(Throwable t) { callQueue.add(new QueueEntry(true, () -> delegate.onError(t))); drainQueue(); } @Override public void onComplete() { callQueue.add(new QueueEntry(true, delegate::onComplete)); drainQueue(); } @Override public int read() { singleByte.clear(); TransferResult transferResult = delegate.blockingTransferTo(singleByte); if (singleByte.hasRemaining()) { assert transferResult == TransferResult.END_OF_STREAM; return -1; } return singleByte.get(0) & 0xFF; } @Override public int read(byte[] b) { return read(b, 0, b.length); } @Override public int read(byte[] bytes, int off, int len) { if (len == 0) { return 0; } ByteBuffer byteBuffer = ByteBuffer.wrap(bytes, off, len); TransferResult transferResult = delegate.blockingTransferTo(byteBuffer); int dataTransferred = byteBuffer.position() - off; if (dataTransferred == 0) { assert transferResult == TransferResult.END_OF_STREAM; return -1; } return dataTransferred; } @Override public void close() { synchronized (subscribeLock) { if (inputStreamState.compareAndSet(State.UNINITIALIZED, State.CLOSED)) { delegate.onSubscribe(new NoOpSubscription()); delegate.onError(new CancellationException()); } else if (inputStreamState.compareAndSet(State.READABLE, State.CLOSED)) { subscription.cancel(); onError(new CancellationException()); } } } private void drainQueue() { do { if (!drainingCallQueue.compareAndSet(false, true)) { break; } try { doDrainQueue(); } finally { drainingCallQueue.set(false); } } while (!callQueue.isEmpty()); } private void doDrainQueue() { while (true) { QueueEntry entry = callQueue.poll(); if (done || entry == null) { return; } done = entry.terminal; entry.call.run(); } } private static final class QueueEntry { private final boolean terminal; private final Runnable call; private QueueEntry(boolean terminal, Runnable call) { this.terminal = terminal; this.call = call; } } private enum State { UNINITIALIZED, READABLE, CLOSED } private final class CancelWatcher implements Subscription { private final Subscription s; private CancelWatcher(Subscription s) { this.s = s; } @Override public void request(long n) { s.request(n); } @Override public void cancel() { s.cancel(); close(); } } private static final class NoOpSubscription implements Subscription { @Override public void request(long n) { } @Override public void cancel() { } } }
3,028
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/StoringSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Optional; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.Validate; /** * An implementation of {@link Subscriber} that stores the events it receives for retrieval. * * <p>Events can be observed via {@link #peek()} and {@link #poll()}. The number of events stored is limited by the * {@code maxElements} configured at construction. */ @SdkProtectedApi public class StoringSubscriber<T> implements Subscriber<T> { /** * The maximum number of events that can be stored in this subscriber. The number of events in {@link #events} may be * slightly higher once {@link #onComplete()} and {@link #onError(Throwable)} events are added. */ private final int maxEvents; /** * The events stored in this subscriber. The maximum size of this queue is approximately {@link #maxEvents}. */ private final Queue<Event<T>> events; /** * The active subscription. Set when {@link #onSubscribe(Subscription)} is invoked. */ private Subscription subscription; /** * Create a subscriber that stores up to {@code maxElements} events for retrieval. */ public StoringSubscriber(int maxEvents) { Validate.isPositive(maxEvents, "Max elements must be positive."); this.maxEvents = maxEvents; this.events = new ConcurrentLinkedQueue<>(); } /** * Check the first event stored in this subscriber. * * <p>This will return empty if no events are currently available (outstanding demand has not yet * been filled). */ public Optional<Event<T>> peek() { return Optional.ofNullable(events.peek()); } /** * Remove and return the first event stored in this subscriber. * * <p>This will return empty if no events are currently available (outstanding demand has not yet * been filled). */ public Optional<Event<T>> poll() { Event<T> result = events.poll(); if (result != null) { subscription.request(1); return Optional.of(result); } return Optional.empty(); } @Override public void onSubscribe(Subscription subscription) { if (this.subscription != null) { subscription.cancel(); } this.subscription = subscription; subscription.request(maxEvents); } @Override public void onNext(T t) { Validate.notNull(t, "onNext(null) is not allowed."); try { events.add(Event.value(t)); } catch (RuntimeException e) { subscription.cancel(); onError(new IllegalStateException("Failed to store element.", e)); } } @Override public void onComplete() { events.add(Event.complete()); } @Override public void onError(Throwable throwable) { events.add(Event.error(throwable)); } /** * An event stored for later retrieval by this subscriber. * * <p>Stored events are one of the follow {@link #type()}s: * <ul> * <li>{@code VALUE} - A value received by {@link #onNext(Object)}, available via {@link #value()}.</li> * <li>{@code COMPLETE} - Indicating {@link #onComplete()} was called.</li> * <li>{@code ERROR} - Indicating {@link #onError(Throwable)} was called. The exception is available via * {@link #runtimeError()}</li> * <li>{@code EMPTY} - Indicating that no events remain in the queue (but more from upstream may be given later).</li> * </ul> */ public static final class Event<T> { private final EventType type; private final T value; private final Throwable error; private Event(EventType type, T value, Throwable error) { this.type = type; this.value = value; this.error = error; } private static <T> Event<T> complete() { return new Event<>(EventType.ON_COMPLETE, null, null); } private static <T> Event<T> error(Throwable error) { return new Event<>(EventType.ON_ERROR, null, error); } private static <T> Event<T> value(T value) { return new Event<>(EventType.ON_NEXT, value, null); } /** * Retrieve the {@link EventType} of this event. */ public EventType type() { return type; } /** * The value stored in this {@code VALUE} type. Null for all other event types. */ public T value() { return value; } /** * The error stored in this {@code ERROR} type. Null for all other event types. If a checked exception was received via * {@link #onError(Throwable)}, this will return a {@code RuntimeException} with the checked exception as its cause. */ public RuntimeException runtimeError() { if (type != EventType.ON_ERROR) { return null; } if (error instanceof RuntimeException) { return (RuntimeException) error; } if (error instanceof IOException) { return new UncheckedIOException((IOException) error); } return new RuntimeException(error); } } public enum EventType { ON_NEXT, ON_COMPLETE, ON_ERROR } }
3,029
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/SimplePublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import static software.amazon.awssdk.utils.async.SimplePublisher.QueueEntry.Type.CANCEL; import static software.amazon.awssdk.utils.async.SimplePublisher.QueueEntry.Type.ON_COMPLETE; import static software.amazon.awssdk.utils.async.SimplePublisher.QueueEntry.Type.ON_ERROR; import static software.amazon.awssdk.utils.async.SimplePublisher.QueueEntry.Type.ON_NEXT; import java.util.Queue; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Supplier; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * A {@link Publisher} to which callers can {@link #send(Object)} messages, simplifying the process of implementing a publisher. * * <p><b>Operations</b> * * <p>The {@code SimplePublisher} supports three simplified operations: * <ol> * <li>{@link #send(Object)} for sending messages</li> * <li>{@link #complete()} for indicating the successful end of messages</li> * <li>{@link #error(Throwable)} for indicating the unsuccessful end of messages</li> * </ol> * * Each of these operations returns a {@link CompletableFuture} for indicating when the message has been successfully sent. * * <p>Callers are expected to invoke a series of {@link #send(Object)}s followed by a single {@link #complete()} or * {@link #error(Throwable)}. See the documentation on each operation for more details. * * <p>This publisher will store an unbounded number of messages. It is recommended that callers limit the number of in-flight * {@link #send(Object)} operations in order to bound the amount of memory used by this publisher. */ @SdkProtectedApi public final class SimplePublisher<T> implements Publisher<T> { private static final Logger log = Logger.loggerFor(SimplePublisher.class); /** * Track the amount of outstanding demand requested by the active subscriber. */ private final AtomicLong outstandingDemand = new AtomicLong(); /** * The queue of events to be processed, in the order they should be processed. These events are lower priority than those * in {@link #highPriorityQueue} and will be processed after that queue is empty. * * <p>All logic within this publisher is represented using events in this queue. This ensures proper ordering of events * processing and simplified reasoning about thread safety. */ private final Queue<QueueEntry<T>> standardPriorityQueue = new ConcurrentLinkedQueue<>(); /** * The queue of events to be processed, in the order they should be processed. These events are higher priority than those * in {@link #standardPriorityQueue} and will be processed first. * * <p>Events are written to this queue to "skip the line" in processing, so it's typically reserved for terminal events, * like subscription cancellation. * * <p>All logic within this publisher is represented using events in this queue. This ensures proper ordering of events * processing and simplified reasoning about thread safety. */ private final Queue<QueueEntry<T>> highPriorityQueue = new ConcurrentLinkedQueue<>(); /** * Whether the {@link #standardPriorityQueue} and {@link #highPriorityQueue}s are currently being processed. Only one thread * may read events from the queues at a time. */ private final AtomicBoolean processingQueue = new AtomicBoolean(false); /** * The failure message that should be sent to future events. */ private final FailureMessage failureMessage = new FailureMessage(); /** * The subscriber provided via {@link #subscribe(Subscriber)}. This publisher only supports a single subscriber. */ private Subscriber<? super T> subscriber; /** * Send a message using this publisher. * * <p>Messages sent using this publisher will eventually be sent to a downstream subscriber, in the order they were * written. When the message is sent to the subscriber, the returned future will be completed successfully. * * <p>This method may be invoked concurrently when the order of messages is not important. * * <p>In the time between when this method is invoked and the returned future is not completed, this publisher stores the * request message in memory. Callers are recommended to limit the number of sends in progress at a time to bound the * amount of memory used by this publisher. * * <p>The returned future will be completed exceptionally if the downstream subscriber cancels the subscription, or * if the {@code send} call was performed after a {@link #complete()} or {@link #error(Throwable)} call. * * @param value The message to send. Must not be null. * @return A future that is completed when the message is sent to the subscriber. */ public CompletableFuture<Void> send(T value) { log.trace(() -> "Received send() with " + value); OnNextQueueEntry<T> entry = new OnNextQueueEntry<>(value); try { Validate.notNull(value, "Null cannot be written."); standardPriorityQueue.add(entry); processEventQueue(); } catch (RuntimeException t) { entry.resultFuture.completeExceptionally(t); } return entry.resultFuture; } /** * Indicate that no more {@link #send(Object)} calls will be made, and that stream of messages is completed successfully. * * <p>This can be called before any in-flight {@code send} calls are complete. Such messages will be processed before the * stream is treated as complete. The returned future will be completed successfully when the {@code complete} is sent to * the downstream subscriber. * * <p>After this method is invoked, any future {@link #send(Object)}, {@code complete()} or {@link #error(Throwable)} * calls will be completed exceptionally and not be processed. * * <p>The returned future will be completed exceptionally if the downstream subscriber cancels the subscription, or * if the {@code complete} call was performed after a {@code complete} or {@link #error(Throwable)} call. * * @return A future that is completed when the complete has been sent to the downstream subscriber. */ public CompletableFuture<Void> complete() { log.trace(() -> "Received complete()"); OnCompleteQueueEntry<T> entry = new OnCompleteQueueEntry<>(); try { standardPriorityQueue.add(entry); processEventQueue(); } catch (RuntimeException t) { entry.resultFuture.completeExceptionally(t); } return entry.resultFuture; } /** * Indicate that no more {@link #send(Object)} calls will be made, and that streaming of messages has failed. * * <p>This can be called before any in-flight {@code send} calls are complete. Such messages will be processed before the * stream is treated as being in-error. The returned future will be completed successfully when the {@code error} is * sent to the downstream subscriber. * * <p>After this method is invoked, any future {@link #send(Object)}, {@link #complete()} or {@code #error(Throwable)} * calls will be completed exceptionally and not be processed. * * <p>The returned future will be completed exceptionally if the downstream subscriber cancels the subscription, or * if the {@code complete} call was performed after a {@link #complete()} or {@code error} call. * * @param error The error to send. * @return A future that is completed when the exception has been sent to the downstream subscriber. */ public CompletableFuture<Void> error(Throwable error) { log.trace(() -> "Received error() with " + error, error); OnErrorQueueEntry<T> entry = new OnErrorQueueEntry<>(error); try { standardPriorityQueue.add(entry); processEventQueue(); } catch (RuntimeException t) { entry.resultFuture.completeExceptionally(t); } return entry.resultFuture; } /** * A method called by the downstream subscriber in order to subscribe to the publisher. */ @Override public void subscribe(Subscriber<? super T> s) { if (subscriber != null) { s.onSubscribe(new NoOpSubscription()); s.onError(new IllegalStateException("Only one subscription may be active at a time.")); } this.subscriber = s; s.onSubscribe(new SubscriptionImpl()); processEventQueue(); } /** * Process the messages in the event queue. This is invoked after every operation on the publisher that changes the state * of the event queue. * * <p>Internally, this method will only be executed by one thread at a time. Any calls to this method will another thread * is processing the queue will return immediately. This ensures: (1) thread safety in queue processing, (2) mutual recursion * between onSubscribe/onNext with {@link Subscription#request(long)} are impossible. */ private void processEventQueue() { do { if (!processingQueue.compareAndSet(false, true)) { // Some other thread is processing the queue, so we don't need to. return; } try { doProcessQueue(); } catch (Throwable e) { panicAndDie(e); break; } finally { processingQueue.set(false); } // Once releasing the processing-queue flag, we need to double-check that the queue still doesn't need to be // processed, because new messages might have come in since we decided to release the flag. } while (shouldProcessQueueEntry(standardPriorityQueue.peek()) || shouldProcessQueueEntry(highPriorityQueue.peek())); } /** * Pop events off of the queue and process them in the order they are given, returning when we can no longer process the * event at the head of the queue. * * <p>Invoked only from within the {@link #processEventQueue()} method with the {@link #processingQueue} flag held. */ private void doProcessQueue() { while (true) { QueueEntry<T> entry = highPriorityQueue.peek(); Queue<?> sourceQueue = highPriorityQueue; if (entry == null) { entry = standardPriorityQueue.peek(); sourceQueue = standardPriorityQueue; } if (!shouldProcessQueueEntry(entry)) { // We're done processing entries. return; } if (failureMessage.isSet()) { entry.resultFuture.completeExceptionally(failureMessage.get()); } else { switch (entry.type()) { case ON_NEXT: OnNextQueueEntry<T> onNextEntry = (OnNextQueueEntry<T>) entry; log.trace(() -> "Calling onNext() with " + onNextEntry.value); subscriber.onNext(onNextEntry.value); long newDemand = outstandingDemand.decrementAndGet(); log.trace(() -> "Decreased demand to " + newDemand); break; case ON_COMPLETE: failureMessage.trySet(() -> new IllegalStateException("onComplete() was already invoked.")); log.trace(() -> "Calling onComplete()"); subscriber.onComplete(); break; case ON_ERROR: OnErrorQueueEntry<T> onErrorEntry = (OnErrorQueueEntry<T>) entry; failureMessage.trySet(() -> new IllegalStateException("onError() was already invoked.", onErrorEntry.failure)); log.trace(() -> "Calling onError() with " + onErrorEntry.failure, onErrorEntry.failure); subscriber.onError(onErrorEntry.failure); break; case CANCEL: failureMessage.trySet(() -> new CancellationException("subscription has been cancelled.")); subscriber = null; // Allow subscriber to be garbage collected after cancellation. break; default: // Should never happen. Famous last words? throw new IllegalStateException("Unknown entry type: " + entry.type()); } entry.resultFuture.complete(null); } sourceQueue.remove(); } } /** * Return true if we should process the provided queue entry. */ private boolean shouldProcessQueueEntry(QueueEntry<T> entry) { if (entry == null) { // The queue is empty. return false; } if (failureMessage.isSet()) { return true; } if (subscriber == null) { // We don't have a subscriber yet. return false; } if (entry.type() != ON_NEXT) { // This event isn't an on-next event, so we don't need subscriber demand in order to process it. return true; } // This is an on-next event and we're not failing on-next events, so make sure we have demand available before // processing it. return outstandingDemand.get() > 0; } /** * Invoked from within {@link #processEventQueue()} when we can't process the queue for some reason. This is likely * caused by a downstream subscriber throwing an exception from {@code onNext}, which it should never do. * * <p>Here we try our best to fail all of the entries in the queue, so that no callers have "stuck" futures. */ private void panicAndDie(Throwable cause) { try { // Create exception here instead of in supplier to preserve a more-useful stack trace. RuntimeException failure = new IllegalStateException("Encountered fatal error in publisher", cause); failureMessage.trySet(() -> failure); subscriber.onError(cause instanceof Error ? cause : failure); while (true) { QueueEntry<T> entry = standardPriorityQueue.poll(); if (entry == null) { break; } entry.resultFuture.completeExceptionally(failure); } } catch (Throwable t) { t.addSuppressed(cause); log.error(() -> "Failed while processing a failure. This could result in stuck futures.", t); } } /** * The subscription passed to the first {@link #subscriber} that subscribes to this publisher. This allows the downstream * subscriber to request for more {@code onNext} calls or to {@code cancel} the stream of messages. */ private class SubscriptionImpl implements Subscription { @Override public void request(long n) { log.trace(() -> "Received request() with " + n); if (n <= 0) { // Create exception here instead of in supplier to preserve a more-useful stack trace. IllegalArgumentException failure = new IllegalArgumentException("A downstream publisher requested an invalid " + "amount of data: " + n); highPriorityQueue.add(new OnErrorQueueEntry<>(failure)); processEventQueue(); } else { long newDemand = outstandingDemand.updateAndGet(current -> { if (Long.MAX_VALUE - current < n) { return Long.MAX_VALUE; } return current + n; }); log.trace(() -> "Increased demand to " + newDemand); processEventQueue(); } } @Override public void cancel() { log.trace(() -> "Received cancel() from " + subscriber); // Create exception here instead of in supplier to preserve a more-useful stack trace. highPriorityQueue.add(new CancelQueueEntry<>()); processEventQueue(); } } /** * A lazily-initialized failure message for future events sent to this publisher after a terminal event has * occurred. */ private static final class FailureMessage { private Supplier<Throwable> failureMessageSupplier; private Throwable failureMessage; private void trySet(Supplier<Throwable> supplier) { if (failureMessageSupplier == null) { failureMessageSupplier = supplier; } } private boolean isSet() { return failureMessageSupplier != null; } private Throwable get() { if (failureMessage == null) { failureMessage = failureMessageSupplier.get(); } return failureMessage; } } /** * An entry in the {@link #standardPriorityQueue}. */ abstract static class QueueEntry<T> { /** * The future that was returned to a {@link #send(Object)}, {@link #complete()} or {@link #error(Throwable)} message. */ protected final CompletableFuture<Void> resultFuture = new CompletableFuture<>(); /** * Retrieve the type of this queue entry. */ protected abstract Type type(); protected enum Type { ON_NEXT, ON_COMPLETE, ON_ERROR, CANCEL } } /** * An entry added when we get a {@link #send(Object)} call. */ private static final class OnNextQueueEntry<T> extends QueueEntry<T> { private final T value; private OnNextQueueEntry(T value) { this.value = value; } @Override protected Type type() { return ON_NEXT; } } /** * An entry added when we get a {@link #complete()} call. */ private static final class OnCompleteQueueEntry<T> extends QueueEntry<T> { @Override protected Type type() { return ON_COMPLETE; } } /** * An entry added when we get an {@link #error(Throwable)} call. */ private static final class OnErrorQueueEntry<T> extends QueueEntry<T> { private final Throwable failure; private OnErrorQueueEntry(Throwable failure) { this.failure = failure; } @Override protected Type type() { return ON_ERROR; } } /** * An entry added when we get a {@link SubscriptionImpl#cancel()} call. */ private static final class CancelQueueEntry<T> extends QueueEntry<T> { @Override protected Type type() { return CANCEL; } } /** * A subscription that does nothing. This is used for signaling {@code onError} to subscribers that subscribe to this * publisher for the second time. Only one subscriber is supported. */ private static final class NoOpSubscription implements Subscription { @Override public void request(long n) { } @Override public void cancel() { } } }
3,030
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/InputStreamConsumingPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import static software.amazon.awssdk.utils.CompletableFutureUtils.joinInterruptibly; import static software.amazon.awssdk.utils.CompletableFutureUtils.joinInterruptiblyIgnoringFailures; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * A publisher to which an {@link InputStream} can be written. * <p> * See {@link #doBlockingWrite(InputStream)}. */ @SdkProtectedApi public class InputStreamConsumingPublisher implements Publisher<ByteBuffer> { private static final int BUFFER_SIZE = 16 * 1024; // 16 KB private final SimplePublisher<ByteBuffer> delegate = new SimplePublisher<>(); /** * Write the provided input stream to the stream subscribed to this publisher. * <p> * This method will block the calling thread to write until: (1) the provided input stream is fully consumed, * (2) the subscription is cancelled, (3) reading from the input stream fails, or (4) {@link #cancel()} is called. * * @return The amount of data written to the downstream subscriber. */ public long doBlockingWrite(InputStream inputStream) { try { long dataWritten = 0; while (true) { byte[] data = new byte[BUFFER_SIZE]; int dataLength = inputStream.read(data); if (dataLength > 0) { dataWritten += dataLength; joinInterruptibly(delegate.send(ByteBuffer.wrap(data, 0, dataLength))); } else if (dataLength < 0) { // We ignore cancel failure on completion, because as long as our onNext calls have succeeded, the // subscriber got everything we wanted to send. joinInterruptiblyIgnoringCancellation(delegate.complete()); break; } } return dataWritten; } catch (IOException e) { joinInterruptiblyIgnoringFailures(delegate.error(e)); throw new UncheckedIOException(e); } catch (RuntimeException | Error e) { joinInterruptiblyIgnoringFailures(delegate.error(e)); throw e; } } /** * Cancel an ongoing {@link #doBlockingWrite(InputStream)} call. */ public void cancel() { delegate.error(new CancellationException("Input stream has been cancelled.")); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { delegate.subscribe(s); } private void joinInterruptiblyIgnoringCancellation(CompletableFuture<Void> complete) { try { joinInterruptibly(complete); } catch (CancellationException e) { // Ignore } } }
3,031
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/BufferingSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.util.ArrayList; import java.util.List; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public class BufferingSubscriber<T> extends DelegatingSubscriber<T, List<T>> { private final int bufferSize; private List<T> currentBuffer; private Subscription subscription; public BufferingSubscriber(Subscriber<? super List<T>> subscriber, int bufferSize) { super(subscriber); this.bufferSize = bufferSize; currentBuffer = new ArrayList<>(bufferSize); } @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; super.onSubscribe(subscription); } @Override public void onNext(T t) { currentBuffer.add(t); if (currentBuffer.size() == bufferSize) { subscriber.onNext(currentBuffer); currentBuffer.clear(); } else { subscription.request(1); } } @Override public void onComplete() { // Deliver any remaining items before calling on complete if (currentBuffer.size() > 0) { subscriber.onNext(currentBuffer); } super.onComplete(); } }
3,032
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/LimitingSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.util.concurrent.atomic.AtomicInteger; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.internal.async.EmptySubscription; @SdkProtectedApi public class LimitingSubscriber<T> extends DelegatingSubscriber<T, T> { private final int limit; private final AtomicInteger delivered = new AtomicInteger(0); private Subscription subscription; public LimitingSubscriber(Subscriber<? super T> subscriber, int limit) { super(subscriber); this.limit = limit; } @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; if (limit == 0) { subscription.cancel(); super.onSubscribe(new EmptySubscription(super.subscriber)); } else { super.onSubscribe(subscription); } } @Override public void onNext(T t) { int deliveredItems = delivered.incrementAndGet(); // We may get more events even after cancelling so we ignore them. if (deliveredItems <= limit) { subscriber.onNext(t); if (deliveredItems == limit) { subscription.cancel(); subscriber.onComplete(); } } } }
3,033
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/OutputStreamPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import static software.amazon.awssdk.utils.CompletableFutureUtils.joinInterruptibly; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.CancellableOutputStream; import software.amazon.awssdk.utils.Validate; /** * Adapts a {@link Publisher} to an {@link OutputStream}. * <p> * Writes to the stream will block until demand is available in the downstream subscriber. */ @SdkProtectedApi public final class OutputStreamPublisher extends CancellableOutputStream implements Publisher<ByteBuffer> { private final SimplePublisher<ByteBuffer> delegate = new SimplePublisher<>(); private final AtomicBoolean done = new AtomicBoolean(false); /** * An in-memory buffer used to store "small" (single-byte) writes so that we're not fulfilling downstream demand using tiny * one-byte buffers. */ private ByteBuffer smallWriteBuffer; @Override public void write(int b) { Validate.validState(!done.get(), "Output stream is cancelled or closed."); if (smallWriteBuffer != null && !smallWriteBuffer.hasRemaining()) { flush(); } if (smallWriteBuffer == null) { smallWriteBuffer = ByteBuffer.allocate(4 * 1024); // 4 KB } smallWriteBuffer.put((byte) b); } @Override public void write(byte[] b) { flush(); send(ByteBuffer.wrap(b)); } @Override public void write(byte[] b, int off, int len) { flush(); send(ByteBuffer.wrap(b, off, len)); } @Override public void flush() { if (smallWriteBuffer != null && smallWriteBuffer.position() > 0) { smallWriteBuffer.flip(); send(smallWriteBuffer); smallWriteBuffer = null; } } @Override public void cancel() { if (done.compareAndSet(false, true)) { delegate.error(new CancellationException("Output stream has been cancelled.")); } } @Override public void close() { if (done.compareAndSet(false, true)) { flush(); // We ignore cancel failure on completion, because as long as our onNext calls have succeeded, the // subscriber got everything we wanted to send. joinInterruptiblyIgnoringCancellation(delegate.complete()); } } private void send(ByteBuffer bytes) { joinInterruptibly(delegate.send(bytes)); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { delegate.subscribe(s); } private void joinInterruptiblyIgnoringCancellation(CompletableFuture<Void> complete) { try { joinInterruptibly(complete); } catch (CancellationException e) { // Ignore } } }
3,034
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/ByteBufferStoringSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import static software.amazon.awssdk.utils.async.StoringSubscriber.EventType.ON_NEXT; import java.nio.ByteBuffer; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Phaser; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.async.StoringSubscriber.Event; /** * An implementation of {@link Subscriber} that stores {@link ByteBuffer} events it receives for retrieval. * * <p>Stored bytes can be read via {@link #transferTo(ByteBuffer)}. */ @SdkProtectedApi public class ByteBufferStoringSubscriber implements Subscriber<ByteBuffer> { /** * The minimum amount of data (in bytes) that should be buffered in memory at a time. The subscriber will request new byte * buffers from upstream until the bytes received equals or exceeds this value. */ private final long minimumBytesBuffered; /** * The amount of data (in bytes) currently stored in this subscriber. The subscriber will request more data when this value * is below the {@link #minimumBytesBuffered}. */ private final AtomicLong bytesBuffered = new AtomicLong(0L); /** * A delegate subscriber that we use to store the buffered bytes in the order they are received. */ private final StoringSubscriber<ByteBuffer> storingSubscriber; private final CountDownLatch subscriptionLatch = new CountDownLatch(1); private final Phaser phaser = new Phaser(1); /** * The active subscription. Set when {@link #onSubscribe(Subscription)} is invoked. */ private Subscription subscription; /** * Create a subscriber that stores at least {@code minimumBytesBuffered} in memory for retrieval. */ public ByteBufferStoringSubscriber(long minimumBytesBuffered) { this.minimumBytesBuffered = Validate.isPositive(minimumBytesBuffered, "Data buffer minimum must be positive"); this.storingSubscriber = new StoringSubscriber<>(Integer.MAX_VALUE); } /** * Transfer the data stored by this subscriber into the provided byte buffer. * * <p>If the data stored by this subscriber exceeds {@code out}'s {@code limit}, then {@code out} will be filled. If the data * stored by this subscriber is less than {@code out}'s {@code limit}, then all stored data will be written to {@code out}. * * <p>If {@link #onError(Throwable)} was called on this subscriber, as much data as is available will be transferred into * {@code out} before the provided exception is thrown (as a {@link RuntimeException}). * * <p>If {@link #onComplete()} was called on this subscriber, as much data as is available will be transferred into * {@code out}, and this will return {@link TransferResult#END_OF_STREAM}. * * <p>Note: This method MUST NOT be called concurrently with itself or {@link #blockingTransferTo(ByteBuffer)}. Other methods * on this class may be called concurrently with this one. This MUST NOT be called before * {@link #onSubscribe(Subscription)} has returned. */ public TransferResult transferTo(ByteBuffer out) { int transferred = 0; Optional<Event<ByteBuffer>> next = storingSubscriber.peek(); while (out.hasRemaining()) { if (!next.isPresent() || next.get().type() != ON_NEXT) { break; } transferred += transfer(next.get().value(), out); next = storingSubscriber.peek(); } addBufferedDataAmount(-transferred); if (!next.isPresent()) { return TransferResult.SUCCESS; } switch (next.get().type()) { case ON_COMPLETE: return TransferResult.END_OF_STREAM; case ON_ERROR: throw next.get().runtimeError(); case ON_NEXT: return TransferResult.SUCCESS; default: throw new IllegalStateException("Unknown stored type: " + next.get().type()); } } /** * Like {@link #transferTo(ByteBuffer)}, but blocks until some data has been written. * * <p>Note: This method MUST NOT be called concurrently with itself or {@link #transferTo(ByteBuffer)}. Other methods * on this class may be called concurrently with this one. */ public TransferResult blockingTransferTo(ByteBuffer out) { try { subscriptionLatch.await(); while (true) { int currentPhase = phaser.getPhase(); int positionBeforeTransfer = out.position(); TransferResult result = transferTo(out); if (result == TransferResult.END_OF_STREAM) { return TransferResult.END_OF_STREAM; } if (!out.hasRemaining()) { return TransferResult.SUCCESS; } if (positionBeforeTransfer == out.position()) { // We didn't read any data, and we still have space for more data. Wait for the state to be updated. phaser.awaitAdvanceInterruptibly(currentPhase); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } private int transfer(ByteBuffer in, ByteBuffer out) { int amountToTransfer = Math.min(in.remaining(), out.remaining()); ByteBuffer truncatedIn = in.duplicate(); truncatedIn.limit(truncatedIn.position() + amountToTransfer); out.put(truncatedIn); in.position(truncatedIn.position()); if (!in.hasRemaining()) { storingSubscriber.poll(); } return amountToTransfer; } @Override public void onSubscribe(Subscription s) { storingSubscriber.onSubscribe(new DemandIgnoringSubscription(s)); subscription = s; subscription.request(1); subscriptionLatch.countDown(); } @Override public void onNext(ByteBuffer byteBuffer) { storingSubscriber.onNext(byteBuffer.duplicate()); addBufferedDataAmount(byteBuffer.remaining()); phaser.arrive(); } @Override public void onError(Throwable t) { storingSubscriber.onError(t); phaser.arrive(); } @Override public void onComplete() { storingSubscriber.onComplete(); phaser.arrive(); } private void addBufferedDataAmount(long amountToAdd) { long currentDataBuffered = bytesBuffered.addAndGet(amountToAdd); maybeRequestMore(currentDataBuffered); } private void maybeRequestMore(long currentDataBuffered) { if (currentDataBuffered < minimumBytesBuffered) { subscription.request(1); } } /** * The result of {@link #transferTo(ByteBuffer)}. */ public enum TransferResult { /** * Data was successfully transferred to {@code out}, and the end of stream has been reached. No future calls to * {@link #transferTo(ByteBuffer)} will yield additional data. */ END_OF_STREAM, /** * Data was successfully transferred to {@code out}, but the end of stream has not been reached. Future calls to * {@link #transferTo(ByteBuffer)} may yield additional data. */ SUCCESS } }
3,035
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/FilteringSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.util.function.Predicate; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public class FilteringSubscriber<T> extends DelegatingSubscriber<T, T> { private final Predicate<T> predicate; private Subscription subscription; public FilteringSubscriber(Subscriber<? super T> sourceSubscriber, Predicate<T> predicate) { super(sourceSubscriber); this.predicate = predicate; } @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; super.onSubscribe(subscription); } @Override public void onNext(T t) { try { if (predicate.test(t)) { subscriber.onNext(t); } else { // Consumed a demand but didn't deliver. Request other to make up for it subscription.request(1); } } catch (RuntimeException e) { // Handle the predicate throwing an exception subscription.cancel(); onError(e); } } }
3,036
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/DelegatingSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.util.concurrent.atomic.AtomicBoolean; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public abstract class DelegatingSubscriber<T, U> implements Subscriber<T> { protected final Subscriber<? super U> subscriber; private final AtomicBoolean complete = new AtomicBoolean(false); protected DelegatingSubscriber(Subscriber<? super U> subscriber) { this.subscriber = subscriber; } @Override public void onSubscribe(Subscription subscription) { subscriber.onSubscribe(subscription); } @Override public void onError(Throwable throwable) { if (complete.compareAndSet(false, true)) { subscriber.onError(throwable); } } @Override public void onComplete() { if (complete.compareAndSet(false, true)) { subscriber.onComplete(); } } }
3,037
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/DemandIgnoringSubscription.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public final class DemandIgnoringSubscription implements Subscription { private final Subscription delegate; public DemandIgnoringSubscription(Subscription delegate) { this.delegate = delegate; } @Override public void request(long n) { // Ignore demand requests from downstream, they want too much. // We feed them the amount that we want. } @Override public void cancel() { delegate.cancel(); } }
3,038
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/AddingTrailingDataSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.util.Iterator; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Supplier; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * Allows to send trailing data before invoking onComplete on the downstream subscriber. * trailingDataIterable will be created when the upstream subscriber has called onComplete. */ @SdkProtectedApi public class AddingTrailingDataSubscriber<T> extends DelegatingSubscriber<T, T> { private static final Logger log = Logger.loggerFor(AddingTrailingDataSubscriber.class); /** * The subscription to the upstream subscriber. */ private Subscription upstreamSubscription; /** * The amount of unfulfilled demand the downstream subscriber has opened against us. */ private final AtomicLong downstreamDemand = new AtomicLong(0); /** * Whether the upstream subscriber has called onComplete on us. */ private volatile boolean onCompleteCalledByUpstream = false; /** * Whether the upstream subscriber has called onError on us. */ private volatile boolean onErrorCalledByUpstream = false; /** * Whether we have called onComplete on the downstream subscriber. */ private volatile boolean onCompleteCalledOnDownstream = false; private final Supplier<Iterable<T>> trailingDataIterableSupplier; private Iterator<T> trailingDataIterator; public AddingTrailingDataSubscriber(Subscriber<? super T> subscriber, Supplier<Iterable<T>> trailingDataIterableSupplier) { super(Validate.paramNotNull(subscriber, "subscriber")); this.trailingDataIterableSupplier = Validate.paramNotNull(trailingDataIterableSupplier, "trailingDataIterableSupplier"); } @Override public void onSubscribe(Subscription subscription) { if (upstreamSubscription != null) { log.warn(() -> "Received duplicate subscription, cancelling the duplicate.", new IllegalStateException()); subscription.cancel(); return; } upstreamSubscription = subscription; subscriber.onSubscribe(new Subscription() { @Override public void request(long l) { if (onErrorCalledByUpstream || onCompleteCalledOnDownstream) { return; } addDownstreamDemand(l); if (onCompleteCalledByUpstream) { sendTrailingDataAndCompleteIfNeeded(); return; } upstreamSubscription.request(l); } @Override public void cancel() { upstreamSubscription.cancel(); } }); } @Override public void onError(Throwable throwable) { onErrorCalledByUpstream = true; subscriber.onError(throwable); } @Override public void onNext(T t) { Validate.paramNotNull(t, "item"); downstreamDemand.decrementAndGet(); subscriber.onNext(t); } @Override public void onComplete() { onCompleteCalledByUpstream = true; sendTrailingDataAndCompleteIfNeeded(); } private void addDownstreamDemand(long l) { if (l > 0) { downstreamDemand.getAndUpdate(current -> { long newValue = current + l; return newValue >= 0 ? newValue : Long.MAX_VALUE; }); } else { upstreamSubscription.cancel(); onError(new IllegalArgumentException("Demand must not be negative")); } } private synchronized void sendTrailingDataAndCompleteIfNeeded() { if (onCompleteCalledOnDownstream) { return; } if (trailingDataIterator == null) { Iterable<T> supplier = trailingDataIterableSupplier.get(); if (supplier == null) { completeDownstreamSubscriber(); return; } trailingDataIterator = supplier.iterator(); } sendTrailingDataIfNeeded(); if (!trailingDataIterator.hasNext()) { completeDownstreamSubscriber(); } } private void sendTrailingDataIfNeeded() { long demand = downstreamDemand.get(); while (trailingDataIterator.hasNext() && demand > 0) { subscriber.onNext(trailingDataIterator.next()); demand = downstreamDemand.decrementAndGet(); } } private void completeDownstreamSubscriber() { subscriber.onComplete(); onCompleteCalledOnDownstream = true; } }
3,039
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/SequentialSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * A simple implementation of {@link Subscriber} that requests data one at a time. * * @param <T> Type of data requested */ @SdkProtectedApi public class SequentialSubscriber<T> implements Subscriber<T> { private final Consumer<T> consumer; private final CompletableFuture<?> future; private Subscription subscription; public SequentialSubscriber(Consumer<T> consumer, CompletableFuture<Void> future) { this.consumer = consumer; this.future = future; } @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(1); } @Override public void onNext(T t) { try { consumer.accept(t); subscription.request(1); } catch (RuntimeException e) { // Handle the consumer throwing an exception subscription.cancel(); future.completeExceptionally(e); } } @Override public void onError(Throwable t) { future.completeExceptionally(t); } @Override public void onComplete() { future.complete(null); } }
3,040
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/Base16Lower.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import software.amazon.awssdk.annotations.SdkInternalApi; /** * A Base 16 codec API, which encodes into hex string in lower case. * * See http://www.ietf.org/rfc/rfc4648.txt * * @author Hanson Char */ @SdkInternalApi public final class Base16Lower { private static final Base16Codec CODEC = new Base16Codec(false); private Base16Lower() { } /** * Returns a base 16 encoded string (in lower case) of the given bytes. */ public static String encodeAsString(byte... bytes) { if (bytes == null) { return null; } return bytes.length == 0 ? "" : CodecUtils.toStringDirect(CODEC.encode(bytes)); } /** * Returns a base 16 encoded byte array of the given bytes. */ public static byte[] encode(byte[] bytes) { return bytes == null || bytes.length == 0 ? bytes : CODEC.encode(bytes); } /** * Decodes the given base 16 encoded string, * skipping carriage returns, line feeds and spaces as needed. */ public static byte[] decode(String b16) { if (b16 == null) { return null; } if (b16.length() == 0) { return new byte[0]; } byte[] buf = new byte[b16.length()]; int len = CodecUtils.sanitize(b16, buf); return CODEC.decode(buf, len); } /** * Decodes the given base 16 encoded bytes. */ public static byte[] decode(byte[] b16) { return b16 == null || b16.length == 0 ? b16 : CODEC.decode(b16, b16.length); } }
3,041
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/CodegenNamingUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import static java.util.stream.Collectors.joining; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.StringUtils; /** * Internal class used by the code generator and release scripts to produce sanitized names. * * In the future, we should consider adding a build-utils module for tools used at build time * by multiple modules so that we don't have these at runtime when they aren't needed. */ @SdkInternalApi public final class CodegenNamingUtils { private CodegenNamingUtils() { } public static String[] splitOnWordBoundaries(String toSplit) { String result = toSplit; // All non-alphanumeric characters are spaces result = result.replaceAll("[^A-Za-z0-9]+", " "); // acm-success -> "acm success" // If a number has a standalone v in front of it, separate it out (version). result = result.replaceAll("([^a-z]{2,})v([0-9]+)", "$1 v$2 ") // TESTv4 -> "TEST v4 " .replaceAll("([^A-Z]{2,})V([0-9]+)", "$1 V$2 "); // TestV4 -> "Test V4 " // Add a space between camelCased words result = String.join(" ", result.split("(?<=[a-z])(?=[A-Z]([a-zA-Z]|[0-9]))")); // AcmSuccess -> // "Acm Success" // Add a space after acronyms result = result.replaceAll("([A-Z]+)([A-Z][a-z])", "$1 $2"); // ACMSuccess -> "ACM Success" // Add space after a number in the middle of a word result = result.replaceAll("([0-9])([a-zA-Z])", "$1 $2"); // s3ec2 -> "s3 ec2" // Remove extra spaces - multiple consecutive ones or those and the beginning/end of words result = result.replaceAll(" +", " ") // "Foo Bar" -> "Foo Bar" .trim(); // " Foo " -> Foo return result.split(" "); } public static String pascalCase(String word) { return Stream.of(splitOnWordBoundaries(word)).map(StringUtils::lowerCase).map(StringUtils::capitalize).collect(joining()); } public static String pascalCase(String... words) { return Stream.of(words).map(StringUtils::lowerCase).map(StringUtils::capitalize).collect(joining()); } public static String lowercaseFirstChar(String word) { char[] chars = word.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return String.valueOf(chars); } }
3,042
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/MappingSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import java.util.function.Function; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Maps a subscriber of one type to another type. If an exception is thrown by the mapping function itself, the error * will be propagated to the downstream subscriber as if it had come from the publisher and then the subscription will * be implicitly cancelled and no further events from the publisher will be passed along. */ @SdkInternalApi public class MappingSubscriber<T, U> implements Subscriber<T> { private final Subscriber<? super U> delegateSubscriber; private final Function<T, U> mapFunction; private boolean isCancelled = false; private Subscription subscription = null; private MappingSubscriber(Subscriber<? super U> delegateSubscriber, Function<T, U> mapFunction) { this.delegateSubscriber = delegateSubscriber; this.mapFunction = mapFunction; } public static <T, U> MappingSubscriber<T, U> create(Subscriber<? super U> subscriber, Function<T, U> mapFunction) { return new MappingSubscriber<>(subscriber, mapFunction); } @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; delegateSubscriber.onSubscribe(subscription); } @Override public void onError(Throwable throwable) { if (!isCancelled) { delegateSubscriber.onError(throwable); } } @Override public void onComplete() { if (!isCancelled) { delegateSubscriber.onComplete(); } } @Override public void onNext(T t) { if (!isCancelled) { try { delegateSubscriber.onNext(mapFunction.apply(t)); } catch (RuntimeException e) { // If the map function throws an exception, the subscription should be cancelled as the publisher will // otherwise not be aware it has happened and should have the opportunity to clean up resources. cancelSubscriptions(); delegateSubscriber.onError(e); } } } private void cancelSubscriptions() { this.isCancelled = true; if (this.subscription != null) { try { this.subscription.cancel(); } catch (RuntimeException ignored) { // ignore exceptions } } } }
3,043
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/CodecUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Codec internal utilities * * @author Hanson Char */ @SdkInternalApi public final class CodecUtils { private CodecUtils() { } /** * Transforms the given string into the given destination byte array * truncating each character into a byte and skipping carriage returns and * line feeds if any. * <p> * dmurray: "It so happens that we're currently only calling this method * with src.length == dest.length, in which case it works, but we could * theoretically get away with passing a smaller dest if we knew ahead of * time that src contained some number of spaces. In that case it looks like * this implementation would truncate the result." * <p> * hchar: * "Yes, but the truncation is the intentional behavior of this internal * routine in that case." * * @param singleOctets * non-null string containing only single octet characters * @param dest * destination byte array * * @return the actual length of the destination byte array holding data * @throws IllegalArgumentException * if the input string contains any multi-octet character */ static int sanitize(final String singleOctets, byte[] dest) { int capacity = dest.length; char[] src = singleOctets.toCharArray(); int limit = 0; for (int i = 0; i < capacity; i++) { char c = src[i]; if (c == '\r' || c == '\n' || c == ' ') { continue; } if (c > Byte.MAX_VALUE) { throw new IllegalArgumentException("Invalid character found at position " + i + " for " + singleOctets); } dest[limit++] = (byte) c; } return limit; } /** * Returns a byte array representing the given string, * truncating each character into a byte directly. * * @throws IllegalArgumentException if the input string contains any multi-octet character */ public static byte[] toBytesDirect(final String singleOctets) { char[] src = singleOctets.toCharArray(); byte[] dest = new byte[src.length]; for (int i = 0; i < dest.length; i++) { char c = src[i]; if (c > Byte.MAX_VALUE) { throw new IllegalArgumentException("Invalid character found at position " + i + " for " + singleOctets); } dest[i] = (byte) c; } return dest; } /** * Returns a string representing the given byte array, * treating each byte as a single octet character. */ public static String toStringDirect(final byte[] bytes) { char[] dest = new char[bytes.length]; int i = 0; for (byte b : bytes) { dest[i++] = (char) b; } return new String(dest); } }
3,044
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/DefaultConditionalDecorator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import java.util.Objects; import java.util.function.Predicate; import java.util.function.UnaryOperator; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.ConditionalDecorator; @SdkInternalApi public final class DefaultConditionalDecorator<T> implements ConditionalDecorator<T> { private final Predicate<T> predicate; private final UnaryOperator<T> transform; DefaultConditionalDecorator(Builder<T> builder) { this.predicate = builder.predicate; this.transform = builder.transform; } public static <T> Builder<T> builder() { return new Builder<>(); } @Override public Predicate<T> predicate() { return predicate; } @Override public UnaryOperator<T> transform() { return transform; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof DefaultConditionalDecorator)) { return false; } DefaultConditionalDecorator<?> that = (DefaultConditionalDecorator<?>) o; if (!Objects.equals(predicate, that.predicate)) { return false; } return Objects.equals(transform, that.transform); } @Override public int hashCode() { int result = predicate != null ? predicate.hashCode() : 0; result = 31 * result + (transform != null ? transform.hashCode() : 0); return result; } public static final class Builder<T> { private Predicate<T> predicate; private UnaryOperator<T> transform; public Builder<T> predicate(Predicate<T> predicate) { this.predicate = predicate; return this; } public Builder<T> transform(UnaryOperator<T> transform) { this.transform = transform; return this; } public ConditionalDecorator<T> build() { return new DefaultConditionalDecorator<>(this); } } }
3,045
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/Base16.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import software.amazon.awssdk.annotations.SdkInternalApi; /** * A Base 16 codec API, which encodes into hex string in upper case. * * See http://www.ietf.org/rfc/rfc4648.txt * * @author Hanson Char */ @SdkInternalApi public final class Base16 { private static final Base16Codec CODEC = new Base16Codec(); private Base16() { } /** * Returns a base 16 encoded string (in upper case) of the given bytes. */ public static String encodeAsString(byte... bytes) { if (bytes == null) { return null; } return bytes.length == 0 ? "" : CodecUtils.toStringDirect(CODEC.encode(bytes)); } /** * Returns a base 16 encoded byte array of the given bytes. */ public static byte[] encode(byte[] bytes) { return bytes == null || bytes.length == 0 ? bytes : CODEC.encode(bytes); } /** * Decodes the given base 16 encoded string, * skipping carriage returns, line feeds and spaces as needed. */ public static byte[] decode(String b16) { if (b16 == null) { return null; } if (b16.length() == 0) { return new byte[0]; } byte[] buf = new byte[b16.length()]; int len = CodecUtils.sanitize(b16, buf); return CODEC.decode(buf, len); } /** * Decodes the given base 16 encoded bytes. */ public static byte[] decode(byte[] b16) { return b16 == null || b16.length == 0 ? b16 : CODEC.decode(b16, b16.length); } }
3,046
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/Base16Codec.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import software.amazon.awssdk.annotations.SdkInternalApi; /** * A Base 16 codec implementation. * * @author Hanson Char */ @SdkInternalApi public final class Base16Codec { private static final int OFFSET_OF_LITTLE_A = 'a' - 10; private static final int OFFSET_OF_A = 'A' - 10; private static final int MASK_4BITS = (1 << 4) - 1; private final byte[] alphabets; Base16Codec() { this(true); } Base16Codec(boolean upperCase) { this.alphabets = upperCase ? CodecUtils.toBytesDirect("0123456789ABCDEF") : CodecUtils.toBytesDirect("0123456789abcdef"); } public byte[] encode(byte[] src) { byte[] dest = new byte[src.length * 2]; byte p; for (int i = 0, j = 0; i < src.length; i++) { p = src[i]; dest[j++] = alphabets[p >>> 4 & MASK_4BITS]; dest[j++] = alphabets[p & MASK_4BITS]; } return dest; } public byte[] decode(byte[] src, final int length) { if (length % 2 != 0) { throw new IllegalArgumentException( "Input is expected to be encoded in multiple of 2 bytes but found: " + length ); } byte[] dest = new byte[length / 2]; for (int i = 0, j = 0; j < dest.length; j++) { dest[j] = (byte) ( pos(src[i++]) << 4 | pos(src[i++]) ) ; } return dest; } protected int pos(byte in) { int pos = LazyHolder.DECODED[in]; if (pos > -1) { return pos; } throw new IllegalArgumentException("Invalid base 16 character: '" + (char) in + "'"); } private static class LazyHolder { private static final byte[] DECODED = decodeTable(); private static byte[] decodeTable() { byte[] dest = new byte['f' + 1]; for (int i = 0; i <= 'f'; i++) { if (i >= '0' && i <= '9') { dest[i] = (byte) (i - '0'); } else if (i >= 'A' && i <= 'F') { dest[i] = (byte) (i - OFFSET_OF_A); } else if (i >= 'a') { dest[i] = (byte) (i - OFFSET_OF_LITTLE_A); } else { dest[i] = -1; } } return dest; } } }
3,047
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/SystemSettingUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import static software.amazon.awssdk.utils.OptionalUtils.firstPresent; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.SystemSetting; /** * A set of static utility methods for shared code in {@link SystemSetting}. */ @SdkInternalApi public final class SystemSettingUtils { private static final Logger LOG = LoggerFactory.getLogger(SystemSettingUtils.class); private SystemSettingUtils() { } /** * Resolve the value of this system setting, loading it from the System by checking: * <ol> * <li>The system properties.</li> * <li>The environment variables.</li> * <li>The default value.</li> * </ol> */ public static Optional<String> resolveSetting(SystemSetting setting) { return firstPresent(resolveProperty(setting), () -> resolveEnvironmentVariable(setting), () -> resolveDefault(setting)) .map(String::trim); } /** * Resolve the value of this system setting, loading it from the System by checking: * <ol> * <li>The system properties.</li> * <li>The environment variables.</li> * </ol> * <p> * This is similar to {@link #resolveSetting(SystemSetting)} but does not fall back to the default value if neither * the environment variable or system property value are present. */ public static Optional<String> resolveNonDefaultSetting(SystemSetting setting) { return firstPresent(resolveProperty(setting), () -> resolveEnvironmentVariable(setting)) .map(String::trim); } /** * Attempt to load this setting from the system properties. */ private static Optional<String> resolveProperty(SystemSetting setting) { // CHECKSTYLE:OFF - This is the only place we're allowed to use System.getProperty return Optional.ofNullable(setting.property()).map(System::getProperty); // CHECKSTYLE:ON } /** * Attempt to load this setting from the environment variables. */ public static Optional<String> resolveEnvironmentVariable(SystemSetting setting) { return resolveEnvironmentVariable(setting.environmentVariable()); } /** * Attempt to load a key from the environment variables. */ public static Optional<String> resolveEnvironmentVariable(String key) { try { return Optional.ofNullable(key).map(SystemSettingUtilsTestBackdoor::getEnvironmentVariable); } catch (SecurityException e) { LOG.debug("Unable to load the environment variable '{}' because the security manager did not allow the SDK" + " to read this system property. This setting will be assumed to be null", key, e); return Optional.empty(); } } /** * Load the default value from the setting. */ private static Optional<String> resolveDefault(SystemSetting setting) { return Optional.ofNullable(setting.defaultValue()); } /** * Convert a string to boolean safely (as opposed to the less strict {@link Boolean#parseBoolean(String)}). If a customer * specifies a boolean value it should be "true" or "false" (case insensitive) or an exception will be thrown. */ public static Boolean safeStringToBoolean(SystemSetting setting, String value) { if (value.equalsIgnoreCase("true")) { return true; } else if (value.equalsIgnoreCase("false")) { return false; } throw new IllegalStateException("Environment variable '" + setting.environmentVariable() + "' or system property '" + setting.property() + "' was defined as '" + value + "', but should be 'false' or 'true'"); } }
3,048
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/SystemSettingUtilsTestBackdoor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.utils.SystemSetting; /** * This is a backdoor to add overrides to the results of querying {@link SystemSetting}s. This is used for testing environment * variables within the SDK */ @SdkTestInternalApi @SdkInternalApi public final class SystemSettingUtilsTestBackdoor { private static final Map<String, String> ENVIRONMENT_OVERRIDES = new HashMap<>(); private SystemSettingUtilsTestBackdoor() { } public static void addEnvironmentVariableOverride(String key, String value) { ENVIRONMENT_OVERRIDES.put(key, value); } public static void clearEnvironmentVariableOverrides() { ENVIRONMENT_OVERRIDES.clear(); } static String getEnvironmentVariable(String key) { if (!ENVIRONMENT_OVERRIDES.isEmpty() && ENVIRONMENT_OVERRIDES.containsKey(key)) { return ENVIRONMENT_OVERRIDES.get(key); } // CHECKSTYLE:OFF - This is the only place we should access environment variables return System.getenv(key); // CHECKSTYLE:ON } }
3,049
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/ReflectionUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.ImmutableMap; /** * Utilities that assist with Java language reflection. */ @SdkInternalApi public final class ReflectionUtils { private static final Map<Class<?>, Class<?>> PRIMITIVES_TO_WRAPPERS = new ImmutableMap.Builder<Class<?>, Class<?>>() .put(boolean.class, Boolean.class) .put(byte.class, Byte.class) .put(char.class, Character.class) .put(double.class, Double.class) .put(float.class, Float.class) .put(int.class, Integer.class) .put(long.class, Long.class) .put(short.class, Short.class) .put(void.class, Void.class) .build(); private ReflectionUtils() { } /** * Returns the wrapped class type associated with a primitive if one is known. * @param clazz The class to get the wrapped class for. * @return If the input class is a primitive class, an associated non-primitive wrapped class type will be returned, * otherwise the same class will be returned indicating that no wrapping class is known. */ public static Class<?> getWrappedClass(Class<?> clazz) { if (!clazz.isPrimitive()) { return clazz; } return PRIMITIVES_TO_WRAPPERS.getOrDefault(clazz, clazz); } }
3,050
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/EnumUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import java.util.EnumSet; import java.util.Map; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.CollectionUtils; /** * Utility class for working with {@link Enum}s. */ @SdkInternalApi public final class EnumUtils { private EnumUtils() { } /** * Create a map that indexes all enum values by a given index function. This can offer a faster runtime complexity * compared to iterating an enum's {@code values()}. * * @see CollectionUtils#uniqueIndex(Iterable, Function) */ public static <K, V extends Enum<V>> Map<K, V> uniqueIndex(Class<V> enumType, Function<? super V, K> indexFunction) { return CollectionUtils.uniqueIndex(EnumSet.allOf(enumType), indexFunction); } }
3,051
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/proxy/ProxyEnvironmentVariableConfigProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal.proxy; import static software.amazon.awssdk.utils.http.SdkHttpUtils.parseNonProxyHostsEnvironmentVariable; import java.net.MalformedURLException; import java.net.URL; import java.util.Objects; import java.util.Optional; import java.util.Set; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.ProxyConfigProvider; import software.amazon.awssdk.utils.ProxyEnvironmentSetting; import software.amazon.awssdk.utils.StringUtils; /** * An implementation of the {@link ProxyConfigProvider} interface that retrieves proxy configuration settings from environment * variables. This class is responsible for extracting proxy host, port, username, and password settings from environment * variables based on the specified proxy scheme (HTTP or HTTPS). * * @see ProxyConfigProvider */ @SdkInternalApi public class ProxyEnvironmentVariableConfigProvider implements ProxyConfigProvider { private static final Logger log = Logger.loggerFor(ProxyEnvironmentVariableConfigProvider.class); private final String scheme; private final URL proxyUrl; public ProxyEnvironmentVariableConfigProvider(String scheme) { this.scheme = scheme == null ? "http" : scheme; this.proxyUrl = silentlyGetUrl().orElse(null); } private Optional<URL> silentlyGetUrl() { String stringUrl = Objects.equals(this.scheme, HTTPS) ? ProxyEnvironmentSetting.HTTPS_PROXY.getStringValue().orElse(null) : ProxyEnvironmentSetting.HTTP_PROXY.getStringValue().orElse(null); if (StringUtils.isNotBlank(stringUrl)) { try { return Optional.of(new URL(stringUrl)); } catch (MalformedURLException e) { log.error(() -> "Malformed proxy config environment variable " + stringUrl, e); } } return Optional.empty(); } @Override public int port() { return Optional.ofNullable(this.proxyUrl) .map(URL::getPort) .orElse(0); } @Override public Optional<String> userName() { return Optional.ofNullable(this.proxyUrl) .map(URL::getUserInfo) .flatMap(userInfo -> Optional.ofNullable(userInfo.split(":", 2)[0])); } @Override public Optional<String> password() { return Optional.ofNullable(this.proxyUrl) .map(URL::getUserInfo) .filter(userInfo -> userInfo.contains(":")) .map(userInfo -> userInfo.split(":", 2)) .filter(parts -> parts.length > 1) .map(parts -> parts[1]); } @Override public String host() { return Optional.ofNullable(this.proxyUrl).map(URL::getHost).orElse(null); } @Override public Set<String> nonProxyHosts() { return parseNonProxyHostsEnvironmentVariable(); } }
3,052
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/proxy/ProxySystemPropertyConfigProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal.proxy; import static software.amazon.awssdk.utils.http.SdkHttpUtils.parseNonProxyHostsProperty; import java.util.Objects; import java.util.Optional; import java.util.Set; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.ProxyConfigProvider; import software.amazon.awssdk.utils.ProxySystemSetting; /** * An implementation of the {@link ProxyConfigProvider} interface that retrieves proxy configuration settings from system * properties. This class is responsible for extracting proxy host, port, username, and password settings from system properties * based on the specified proxy scheme (HTTP or HTTPS). * * @see ProxyConfigProvider */ @SdkInternalApi public class ProxySystemPropertyConfigProvider implements ProxyConfigProvider { private static final Logger log = Logger.loggerFor(ProxySystemPropertyConfigProvider.class); private final String scheme; public ProxySystemPropertyConfigProvider(String scheme) { this.scheme = scheme == null ? "http" : scheme; } private static Integer safelyParseInt(String string) { try { return Integer.parseInt(string); } catch (Exception e) { log.error(() -> "Failed to parse string" + string, e); } return null; } @Override public int port() { return Objects.equals(this.scheme, HTTPS) ? ProxySystemSetting.HTTPS_PROXY_PORT.getStringValue() .map(ProxySystemPropertyConfigProvider::safelyParseInt) .orElse(0) : ProxySystemSetting.PROXY_PORT.getStringValue() .map(ProxySystemPropertyConfigProvider::safelyParseInt) .orElse(0); } @Override public Optional<String> userName() { return Objects.equals(this.scheme, HTTPS) ? ProxySystemSetting.HTTPS_PROXY_USERNAME.getStringValue() : ProxySystemSetting.PROXY_USERNAME.getStringValue(); } @Override public Optional<String> password() { return Objects.equals(scheme, HTTPS) ? ProxySystemSetting.HTTPS_PROXY_PASSWORD.getStringValue() : ProxySystemSetting.PROXY_PASSWORD.getStringValue(); } @Override public String host() { return Objects.equals(scheme, HTTPS) ? ProxySystemSetting.HTTPS_PROXY_HOST.getStringValue().orElse(null) : ProxySystemSetting.PROXY_HOST.getStringValue().orElse(null); } @Override public Set<String> nonProxyHosts() { return parseNonProxyHostsProperty(); } }
3,053
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/internal/async/EmptySubscription.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal.async; import java.util.concurrent.atomic.AtomicBoolean; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; /** * A NoOp implementation of {@link Subscription} interface. * * This subscription calls {@link Subscriber#onComplete()} on first request for data and then terminates the subscription. */ @SdkInternalApi public final class EmptySubscription implements Subscription { private final AtomicBoolean isTerminated = new AtomicBoolean(false); private final Subscriber<?> subscriber; public EmptySubscription(Subscriber<?> subscriber) { this.subscriber = subscriber; } @Override public void request(long n) { if (isTerminated()) { return; } if (n <= 0) { throw new IllegalArgumentException("Non-positive request signals are illegal"); } if (terminate()) { subscriber.onComplete(); } } @Override public void cancel() { terminate(); } private boolean terminate() { return isTerminated.compareAndSet(false, true); } private boolean isTerminated() { return isTerminated.get(); } }
3,054
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/http/SdkHttpUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.http; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.mapping; import static java.util.stream.Collectors.toList; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import static software.amazon.awssdk.utils.StringUtils.isEmpty; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.ProxyEnvironmentSetting; import software.amazon.awssdk.utils.ProxySystemSetting; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; /** * A set of utilities that assist with HTTP message-related interactions. */ @SdkProtectedApi public final class SdkHttpUtils { private static final String DEFAULT_ENCODING = "UTF-8"; /** * Characters that we need to fix up after URLEncoder.encode(). */ private static final String[] ENCODED_CHARACTERS_WITH_SLASHES = new String[] {"+", "*", "%7E", "%2F"}; private static final String[] ENCODED_CHARACTERS_WITH_SLASHES_REPLACEMENTS = new String[] {"%20", "%2A", "~", "/"}; private static final String[] ENCODED_CHARACTERS_WITHOUT_SLASHES = new String[] {"+", "*", "%7E"}; private static final String[] ENCODED_CHARACTERS_WITHOUT_SLASHES_REPLACEMENTS = new String[] {"%20", "%2A", "~"}; // List of headers that may appear only once in a request; i.e. is not a list of values. // Taken from https://github.com/apache/httpcomponents-client/blob/81c1bc4dc3ca5a3134c5c60e8beff08be2fd8792/httpclient5-cache/src/test/java/org/apache/hc/client5/http/impl/cache/HttpTestUtils.java#L69-L85 with modifications: // removed: accept-ranges, if-match, if-none-match, vary since it looks like they're defined as lists private static final Set<String> SINGLE_HEADERS = Stream.of("age", "authorization", "content-length", "content-location", "content-md5", "content-range", "content-type", "date", "etag", "expires", "from", "host", "if-modified-since", "if-range", "if-unmodified-since", "last-modified", "location", "max-forwards", "proxy-authorization", "range", "referer", "retry-after", "server", "user-agent") .collect(Collectors.toSet()); private SdkHttpUtils() { } /** * Encode a string according to RFC 3986: encoding for URI paths, query strings, etc. */ public static String urlEncode(String value) { return urlEncode(value, false); } /** * Encode a string according to RFC 3986, but ignore "/" characters. This is useful for encoding the components of a path, * without encoding the path separators. */ public static String urlEncodeIgnoreSlashes(String value) { return urlEncode(value, true); } /** * Encode a string according to RFC 1630: encoding for form data. */ public static String formDataEncode(String value) { return value == null ? null : invokeSafely(() -> URLEncoder.encode(value, DEFAULT_ENCODING)); } /** * Decode the string according to RFC 3986: encoding for URI paths, query strings, etc. * <p> * Assumes the decoded string is UTF-8 encoded. * * @param value The string to decode. * @return The decoded string. */ public static String urlDecode(String value) { if (value == null) { return null; } try { return URLDecoder.decode(value, DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unable to decode value", e); } } /** * Encode each of the keys and values in the provided query parameters using {@link #urlEncode(String)}. */ public static Map<String, List<String>> encodeQueryParameters(Map<String, List<String>> rawQueryParameters) { return encodeMapOfLists(rawQueryParameters, SdkHttpUtils::urlEncode); } /** * Encode each of the keys and values in the provided form data using {@link #formDataEncode(String)}. */ public static Map<String, List<String>> encodeFormData(Map<String, List<String>> rawFormData) { return encodeMapOfLists(rawFormData, SdkHttpUtils::formDataEncode); } private static Map<String, List<String>> encodeMapOfLists(Map<String, List<String>> map, UnaryOperator<String> encoder) { Validate.notNull(map, "Map must not be null."); Map<String, List<String>> result = new LinkedHashMap<>(); for (Entry<String, List<String>> queryParameter : map.entrySet()) { String key = queryParameter.getKey(); String encodedKey = encoder.apply(key); List<String> value = queryParameter.getValue(); List<String> encodedValue = value == null ? null : queryParameter.getValue().stream().map(encoder).collect(Collectors.toList()); result.put(encodedKey, encodedValue); } return result; } /** * Encode a string for use in the path of a URL; uses URLEncoder.encode, * (which encodes a string for use in the query portion of a URL), then * applies some postfilters to fix things up per the RFC. Can optionally * handle strings which are meant to encode a path (ie include '/'es * which should NOT be escaped). * * @param value the value to encode * @param ignoreSlashes true if the value is intended to represent a path * @return the encoded value */ private static String urlEncode(String value, boolean ignoreSlashes) { if (value == null) { return null; } String encoded = invokeSafely(() -> URLEncoder.encode(value, DEFAULT_ENCODING)); if (!ignoreSlashes) { return StringUtils.replaceEach(encoded, ENCODED_CHARACTERS_WITHOUT_SLASHES, ENCODED_CHARACTERS_WITHOUT_SLASHES_REPLACEMENTS); } return StringUtils.replaceEach(encoded, ENCODED_CHARACTERS_WITH_SLASHES, ENCODED_CHARACTERS_WITH_SLASHES_REPLACEMENTS); } /** * Encode the provided query parameters using {@link #encodeQueryParameters(Map)} and then flatten them into a string that * can be used as the query string in a URL. The result is not prepended with "?". */ public static Optional<String> encodeAndFlattenQueryParameters(Map<String, List<String>> rawQueryParameters) { return encodeAndFlatten(rawQueryParameters, SdkHttpUtils::urlEncode); } /** * Encode the provided form data using {@link #encodeFormData(Map)} and then flatten them into a string that * can be used as the body of a form data request. */ public static Optional<String> encodeAndFlattenFormData(Map<String, List<String>> rawFormData) { return encodeAndFlatten(rawFormData, SdkHttpUtils::formDataEncode); } private static Optional<String> encodeAndFlatten(Map<String, List<String>> data, UnaryOperator<String> encoder) { Validate.notNull(data, "Map must not be null."); if (data.isEmpty()) { return Optional.empty(); } StringBuilder queryString = new StringBuilder(); data.forEach((key, values) -> { String encodedKey = encoder.apply(key); if (values != null) { values.forEach(value -> { if (queryString.length() > 0) { queryString.append('&'); } queryString.append(encodedKey); if (value != null) { queryString.append('=').append(encoder.apply(value)); } }); } }); return Optional.of(queryString.toString()); } /** * Flatten the provided query parameters into a string that can be used as the query string in a URL. The result is not * prepended with "?". This is useful when you have already-encoded query parameters you wish to flatten. */ public static Optional<String> flattenQueryParameters(Map<String, List<String>> toFlatten) { if (toFlatten.isEmpty()) { return Optional.empty(); } StringBuilder result = new StringBuilder(); flattenQueryParameters(result, toFlatten); return Optional.of(result.toString()); } /** * Flatten the provided query parameters into a string that can be used as the query string in a URL. The result is not * prepended with "?". This is useful when you have already-encoded query parameters you wish to flatten. */ public static void flattenQueryParameters(StringBuilder result, Map<String, List<String>> toFlatten) { if (toFlatten.isEmpty()) { return; } boolean first = true; for (Entry<String, List<String>> encodedQueryParameter : toFlatten.entrySet()) { String key = encodedQueryParameter.getKey(); List<String> values = Optional.ofNullable(encodedQueryParameter.getValue()).orElseGet(Collections::emptyList); for (String value : values) { if (!first) { result.append('&'); } else { first = false; } result.append(key); if (value != null) { result.append('='); result.append(value); } } } } /** * Returns true if the specified port is the standard port for the given protocol. (i.e. 80 for HTTP or 443 for HTTPS). * * Null or -1 ports (to simplify interaction with {@link URI}'s default value) are treated as standard ports. * * @return True if the specified port is standard for the specified protocol, otherwise false. */ public static boolean isUsingStandardPort(String protocol, Integer port) { Validate.paramNotNull(protocol, "protocol"); Validate.isTrue(protocol.equals("http") || protocol.equals("https"), "Protocol must be 'http' or 'https', but was '%s'.", protocol); String scheme = StringUtils.lowerCase(protocol); return port == null || port == -1 || (scheme.equals("http") && port == 80) || (scheme.equals("https") && port == 443); } /** * Retrieve the standard port for the provided protocol. */ public static int standardPort(String protocol) { if (protocol.equalsIgnoreCase("http")) { return 80; } else if (protocol.equalsIgnoreCase("https")) { return 443; } else { throw new IllegalArgumentException("Unknown protocol: " + protocol); } } /** * Append the given path to the given baseUri, separating them with a slash, if required. The result will preserve the * trailing slash of the provided path. */ public static String appendUri(String baseUri, String path) { Validate.paramNotNull(baseUri, "baseUri"); StringBuilder resultUri = new StringBuilder(baseUri); if (!StringUtils.isEmpty(path)) { if (!baseUri.endsWith("/")) { resultUri.append("/"); } resultUri.append(path.startsWith("/") ? path.substring(1) : path); } return resultUri.toString(); } /** * Perform a case-insensitive search for a particular header in the provided map of headers. * * @param headers The headers to search. * @param header The header to search for (case insensitively). * @return A stream providing the values for the headers that matched the requested header. * @deprecated Use {@code SdkHttpHeaders#matchingHeaders} */ @Deprecated public static Stream<String> allMatchingHeaders(Map<String, List<String>> headers, String header) { return headers.entrySet().stream() .filter(e -> e.getKey().equalsIgnoreCase(header)) .flatMap(e -> e.getValue() != null ? e.getValue().stream() : Stream.empty()); } /** * Perform a case-insensitive search for a particular header in the provided map of headers. * * @param headersToSearch The headers to search. * @param headersToFind The headers to search for (case insensitively). * @return A stream providing the values for the headers that matched the requested header. * @deprecated Use {@code SdkHttpHeaders#matchingHeaders} */ @Deprecated public static Stream<String> allMatchingHeadersFromCollection(Map<String, List<String>> headersToSearch, Collection<String> headersToFind) { return headersToSearch.entrySet().stream() .filter(e -> headersToFind.stream() .anyMatch(headerToFind -> e.getKey().equalsIgnoreCase(headerToFind))) .flatMap(e -> e.getValue() != null ? e.getValue().stream() : Stream.empty()); } /** * Perform a case-insensitive search for a particular header in the provided map of headers, returning the first matching * header, if one is found. * <br> * This is useful for headers like 'Content-Type' or 'Content-Length' of which there is expected to be only one value present. * * @param headers The headers to search. * @param header The header to search for (case insensitively). * @return The first header that matched the requested one, or empty if one was not found. * @deprecated Use {@code SdkHttpHeaders#firstMatchingHeader} */ @Deprecated public static Optional<String> firstMatchingHeader(Map<String, List<String>> headers, String header) { for (Entry<String, List<String>> headerEntry : headers.entrySet()) { if (headerEntry.getKey().equalsIgnoreCase(header) && headerEntry.getValue() != null && !headerEntry.getValue().isEmpty()) { return Optional.of(headerEntry.getValue().get(0)); } } return Optional.empty(); } /** * Perform a case-insensitive search for a set of headers in the provided map of headers, returning the first matching * header, if one is found. * * @param headersToSearch The headers to search. * @param headersToFind The header to search for (case insensitively). * @return The first header that matched a requested one, or empty if one was not found. * @deprecated Use {@code SdkHttpHeaders#firstMatchingHeader} */ @Deprecated public static Optional<String> firstMatchingHeaderFromCollection(Map<String, List<String>> headersToSearch, Collection<String> headersToFind) { for (Entry<String, List<String>> headerEntry : headersToSearch.entrySet()) { for (String headerToFind : headersToFind) { if (headerEntry.getKey().equalsIgnoreCase(headerToFind) && headerEntry.getValue() != null && !headerEntry.getValue().isEmpty()) { return Optional.of(headerEntry.getValue().get(0)); } } } return Optional.empty(); } public static boolean isSingleHeader(String h) { return SINGLE_HEADERS.contains(StringUtils.lowerCase(h)); } /** * Extracts query parameters from the given URI */ public static Map<String, List<String>> uriParams(URI uri) { return splitQueryString(uri.getRawQuery()) .stream() .map(s -> s.split("=")) .map(s -> s.length == 1 ? new String[] { s[0], null } : s) .collect(groupingBy(a -> urlDecode(a[0]), mapping(a -> urlDecode(a[1]), toList()))); } public static List<String> splitQueryString(String queryString) { List<String> results = new ArrayList<>(); StringBuilder result = new StringBuilder(); for (int i = 0; i < queryString.length(); i++) { char character = queryString.charAt(i); if (character != '&') { result.append(character); } else { results.add(StringUtils.trimToEmpty(result.toString())); result.setLength(0); } } results.add(StringUtils.trimToEmpty(result.toString())); return results; } /** * Returns the Java system property for nonProxyHosts as set of Strings. * See http://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html */ public static Set<String> parseNonProxyHostsProperty() { String systemNonProxyHosts = ProxySystemSetting.NON_PROXY_HOSTS.getStringValue().orElse(null); return extractNonProxyHosts(systemNonProxyHosts); } private static Set<String> extractNonProxyHosts(String systemNonProxyHosts) { if (systemNonProxyHosts != null && !isEmpty(systemNonProxyHosts)) { return Arrays.stream(systemNonProxyHosts.split("\\|")) .map(String::toLowerCase) .map(s -> StringUtils.replace(s, "*", ".*?")) .collect(Collectors.toSet()); } return Collections.emptySet(); } public static Set<String> parseNonProxyHostsEnvironmentVariable() { String systemNonProxyHosts = ProxyEnvironmentSetting.NO_PROXY.getStringValue().orElse(null); return extractNonProxyHosts(systemNonProxyHosts); } }
3,055
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/builder/SdkBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.builder; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; /** * A mutable object that can be used to create an immutable object of type T. * * @param <B> the builder type (this) * @param <T> the type that the builder will build */ @SdkPublicApi public interface SdkBuilder<B extends SdkBuilder<B, T>, T> extends Buildable { /** * An immutable object that is created from the * properties that have been set on the builder. * * @return an instance of T */ @Override T build(); /** * A convenience operator that takes something that will * mutate the builder in some way and allows inclusion of it * in chaining operations. For example instead of: * * <pre><code> * Builder builder = ClassBeingBuilt.builder(); * builder = Util.addSomeDetailToTheBuilder(builder); * ClassBeingBuilt clz = builder.build(); * </code></pre> * <p> * This can be done in a statement: * * <pre><code> * ClassBeingBuilt = ClassBeingBuilt.builder().applyMutation(Util::addSomeDetailToTheBuilder).build(); * </code></pre> * * @param mutator the function that mutates the builder * @return B the mutated builder instance */ @SuppressWarnings("unchecked") default B applyMutation(Consumer<B> mutator) { mutator.accept((B) this); return (B) this; } }
3,056
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/builder/ToCopyableBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.builder; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Implementors of this interface provide a way to get from an instance of T to a {@link CopyableBuilder}. This allows * modification of an otherwise immutable object using the source object as a base. * * @param <T> the type that the builder will build (this) * @param <B> the builder type */ @SdkPublicApi public interface ToCopyableBuilder<B extends CopyableBuilder<B, T>, T extends ToCopyableBuilder<B, T>> { /** * Take this object and create a builder that contains all of the current property values of this object. * * @return a builder for type T */ B toBuilder(); /** * A convenience method for calling {@link #toBuilder()}, updating the returned builder and then calling * {@link CopyableBuilder#build()}. This is useful for making small modifications to the existing object. * * @param modifier A function that mutates this immutable object using the provided builder. * @return A new copy of this object with the requested modifications. */ default T copy(Consumer<? super B> modifier) { return toBuilder().applyMutation(modifier::accept).build(); } }
3,057
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/builder/Buildable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.builder; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public interface Buildable { Object build(); }
3,058
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/builder/CopyableBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.builder; import software.amazon.awssdk.annotations.SdkPublicApi; /** * A special type of {@link SdkBuilder} that can be used when the built type implements {@link ToCopyableBuilder}. */ @SdkPublicApi public interface CopyableBuilder<B extends CopyableBuilder<B, T>, T extends ToCopyableBuilder<B, T>> extends SdkBuilder<B, T> { /** * A shallow copy of this object created by building an immutable T and then transforming it back to a builder. * * @return a copy of this object */ default B copy() { return build().toBuilder(); } }
3,059
0
Create_ds/aws-sdk-java-v2/docs/design/core/metrics
Create_ds/aws-sdk-java-v2/docs/design/core/metrics/prototype/MetricConfigurationProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.provider; import java.util.Set; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.metrics.MetricCategory; /** * Interface to configure the options in metrics feature. * * This interface acts as a feature flag for metrics. The methods in the interface are called for each request. * This gives flexibility for metrics feature to be enabled/disabled at runtime and configuration changes * can be picked up at runtime without need for deploying the application (depending on the implementation). * * @see SystemSettingsMetricConfigurationProvider */ @SdkPublicApi public interface MetricConfigurationProvider { /** * @return true if the metrics feature is enabled. * false if the feature is disabled. */ boolean enabled(); /** * Return the set of {@link MetricCategory} that are enabled for metrics collection. * Only metrics belonging to these categories will be collected. */ Set<MetricCategory> metricCategories(); }
3,060
0
Create_ds/aws-sdk-java-v2/docs/design/core/metrics
Create_ds/aws-sdk-java-v2/docs/design/core/metrics/prototype/MetricPublisherConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.metrics.publisher; import java.util.Collections; import java.util.List; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Configure the options to publish the metrics. * <p> * By default, SDK creates and uses only CloudWatch publisher with default options (Default credential chain * and region chain). * To use CloudWatch publisher with custom options or any other publishers, create a * #PublisherConfiguration object and set it in the ClientOverrideConfiguration on the client. * </p> * * <p> * SDK exposes the CloudWatch and CSM publisher implementation, so instances of these classes with * different configuration can be set in this class. * </p> */ public final class MetricPublisherConfiguration implements ToCopyableBuilder<MetricPublisherConfiguration.Builder, MetricPublisherConfiguration> { private final List<MetricPublisher> publishers = Collections.emptyList(); public MetricPublisherConfiguration(Builder builder) { this.publishers.addAll(builder.publishers); } /** * @return the list of #MetricPublisher to be used for publishing the metrics */ public List<MetricPublisher> publishers() { return publishers; } /** * @return a {@link Builder} object to construct a PublisherConfiguration instance. */ public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return new Builder(); } public static final class Builder implements CopyableBuilder<Builder, MetricPublisherConfiguration> { private final List<MetricPublisher> publishers = Collections.emptyList(); private Builder() { } /** * Sets the list of publishers used for publishing the metrics. */ public Builder publishers(List<MetricPublisher> publishers) { this.publishers.addAll(publishers); return this; } /** * Add a publisher to the list of publishers used for publishing the metrics. */ public Builder addPublisher(MetricPublisher publisher) { this.publishers.add(publisher); return this; } public MetricPublisherConfiguration build() { return new MetricPublisherConfiguration(this); } } }
3,061
0
Create_ds/aws-sdk-java-v2/docs/design/core/metrics
Create_ds/aws-sdk-java-v2/docs/design/core/metrics/prototype/MetricCollection.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * An immutable collection of metrics. */ public interface MetricCollection extends SdkIterable<MetricRecord<?>> { /** * @return The name of this metric collection. */ String name(); /** * Return all the values of the given metric. An empty list is returned if * there are no reported values for the given metric. * * @param metric The metric. * @param <T> The type of the value. * @return All of the values of this metric. */ <T> List<T> metricValues(SdkMetric<T> metric); /** * Returns the child metric collections. An empty list is returned if there * are no children. * @return The child metric collections. */ List<MetricCollection> children(); /** * Return all of the {@link #children()} with a specific name. * * @param name The name by which we will filter {@link #children()}. * @return The child metric collections that have the provided name. */ Stream<MetricCollection> childrenWithName(String name); /** * @return The time at which this collection was created. */ Instant creationTime(); }
3,062
0
Create_ds/aws-sdk-java-v2/docs/design/core/metrics
Create_ds/aws-sdk-java-v2/docs/design/core/metrics/prototype/MetricCollector.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * Used to collect metrics collected by the SDK. * <p> * Collectors are allowed to nest, allowing metrics to be collected within the * context of other metrics. */ @NotThreadSafe @SdkPublicApi public interface MetricCollector { /** * @return The name of this collector. */ String name(); /** * Report a metric. */ <T> void reportMetric(SdkMetric<T> metric, T value); /** * * @param name The name of the child collector. * @return The child collector. */ MetricCollector createChild(String name); /** * Return the collected metrics. The returned {@code MetricCollection} must * preserve the children of this collector; in other words the tree formed * by this collector and its children should be identical to the tree formed * by the returned {@code MetricCollection} and its child collections. * <p> * Calling {@code collect()} prevents further invocations of {@link * #reportMetric(SdkMetric, Object)}. * * @return The collected metrics. */ MetricCollection collect(); static MetricCollector create(String name) { return DefaultMetricCollector.create(name); } }
3,063
0
Create_ds/aws-sdk-java-v2/docs/design/core/metrics
Create_ds/aws-sdk-java-v2/docs/design/core/metrics/prototype/SdkMetric.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * A specific SDK metric. * * @param <T> The type for values of this metric. */ @SdkPublicApi public interface SdkMetric<T> { /** * @return The name of this metric. */ public String name(); /** * @return The categories of this metric. */ public Set<MetricCategory> categories(); /** * @return The level of this metric. */ MetricLevel level(); /** * @return The class of the value associated with this metric. */ public Class<T> valueClass(); /** * Cast the given object to the value class associated with this event. * * @param o The object. * @return The cast object. * @throws ClassCastException If {@code o} is not an instance of type {@code * T}. */ public T convertValue(Object o); }
3,064
0
Create_ds/aws-sdk-java-v2/docs/design/core/metrics
Create_ds/aws-sdk-java-v2/docs/design/core/metrics/prototype/MetricPublisher.java
/** * Interface to report and publish the collected SDK metric events to external * sources. * <p> * Conceptually, a publisher receives a stream of {@link MetricCollection} * objects overs its lifetime through its {@link #publish(MetricCollection)} )} * method. Implementations are then free further aggregate these events into * sets of metrics that are then published to some external system for further * use. As long as a publisher is not closed, then it can receive {@code * MetricCollection} objects at any time. In addition, as the SDK makes use of * multithreading, it's possible that the publisher is shared concurrently by * multiple threads, and necessitates that all implementations are threadsafe. */ @ThreadSafe @SdkPublicApi public interface MetricPublisher extends SdkAutoCloseable { /** * Notify the publisher of new metric data. After this call returns, the * caller can safely discard the given {@code metricCollection} instance if * it no longer needs it. Implementations are strongly encouraged to * complete any further aggregation and publishing of metrics in an * asynchronous manner to avoid blocking the calling thread. * <p> * With the exception of a {@code null} {@code metricCollection}, all * invocations of this method must return normally. This is to ensure that * callers of the publisher can safely assume that even in situations where * an error happens during publishing that it will not interrupt the calling * thread. * * @param metricCollection The collection of metrics. * @throws IllegalArgumentException If {@code metricCollection} is {@code * null}. */ void publish(MetricCollection metricCollection); /** * {@inheritDoc} * <p> * <b>Important:</b> Implementations must block the calling thread until all * pending metrics are published and any resources acquired have been freed. */ @Override void close(); }
3,065
0
Create_ds/aws-sdk-java-v2/docs/design/core/event-streaming
Create_ds/aws-sdk-java-v2/docs/design/core/event-streaming/reconnect/CurrentState.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.transcribestreaming; import com.github.davidmoten.rx2.Bytes; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import org.junit.Test; import org.reactivestreams.Publisher; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.transcribestreaming.model.AudioEvent; import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; import software.amazon.awssdk.services.transcribestreaming.model.LanguageCode; import software.amazon.awssdk.services.transcribestreaming.model.MediaEncoding; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler; import software.amazon.awssdk.services.transcribestreaming.model.TranscriptEvent; import software.amazon.awssdk.services.transcribestreaming.model.TranscriptResultStream; public class CurrentState { private File audioFile = new File(getClass().getClassLoader().getResource("silence_16kHz_s16le.wav").getFile()); @Test public void demoCurrentState() throws FileNotFoundException { try (TranscribeStreamingAsyncClient client = TranscribeStreamingAsyncClient.create()) { // Create the audio stream for transcription - we have to create a publisher that resumes where it left off. // If we don't, we'll replay the whole thing again on a reconnect. Publisher<AudioStream> audioStream = Bytes.from(new FileInputStream(audioFile)) .map(SdkBytes::fromByteArray) .map(bytes -> AudioEvent.builder().audioChunk(bytes).build()) .cast(AudioStream.class); CompletableFuture<Void> result = printAudio(client, audioStream, null, 3); result.join(); } } private CompletableFuture<Void> printAudio(TranscribeStreamingAsyncClient client, Publisher<AudioStream> audioStream, String sessionId, int resumesRemaining) { if (resumesRemaining == 0) { CompletableFuture<Void> result = new CompletableFuture<>(); result.completeExceptionally(new IllegalStateException("Failed to resume audio, because the maximum resumes " + "have been exceeded.")); return result; } // Create the request for transcribe that includes the audio metadata StartStreamTranscriptionRequest audioMetadata = StartStreamTranscriptionRequest.builder() .languageCode(LanguageCode.EN_US) .mediaEncoding(MediaEncoding.PCM) .mediaSampleRateHertz(16_000) .sessionId(sessionId) .build(); // Create the transcription handler AtomicReference<String> atomicSessionId = new AtomicReference<>(sessionId); Consumer<TranscriptResultStream> reader = event -> { if (event instanceof TranscriptEvent) { TranscriptEvent transcriptEvent = (TranscriptEvent) event; System.out.println(transcriptEvent.transcript().results()); } }; StartStreamTranscriptionResponseHandler responseHandler = StartStreamTranscriptionResponseHandler.builder() .onResponse(r -> atomicSessionId.set(r.sessionId())) .subscriber(reader) .build(); // Start talking with transcribe return client.startStreamTranscription(audioMetadata, audioStream, responseHandler) .handle((x, error) -> resumePrintAudio(client, audioStream, atomicSessionId.get(), resumesRemaining, error)) .thenCompose(flatten -> flatten); } private CompletableFuture<Void> resumePrintAudio(TranscribeStreamingAsyncClient client, Publisher<AudioStream> audioStream, String sessionId, int resumesRemaining, Throwable error) { if (error == null) { return CompletableFuture.completedFuture(null); } System.out.print("Error happened. Reconnecting and trying again..."); error.printStackTrace(); if (sessionId == null) { CompletableFuture<Void> result = new CompletableFuture<>(); result.completeExceptionally(error); return result; } // If we failed, recursively call printAudio return printAudio(client, audioStream, sessionId, resumesRemaining - 1); } }
3,066
0
Create_ds/aws-sdk-java-v2/docs/design/core/event-streaming/reconnect
Create_ds/aws-sdk-java-v2/docs/design/core/event-streaming/reconnect/prototype/Option2.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.transcribestreaming; import com.github.davidmoten.rx2.Bytes; import io.reactivex.Flowable; import java.io.File; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import org.junit.Test; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.transcribestreaming.model.AudioEvent; import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; import software.amazon.awssdk.services.transcribestreaming.model.LanguageCode; import software.amazon.awssdk.services.transcribestreaming.model.MediaEncoding; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler; import software.amazon.awssdk.services.transcribestreaming.model.TranscriptEvent; import software.amazon.awssdk.services.transcribestreaming.model.TranscriptResultStream; /** * Option 2: Update current method to automatically reconnect and hide: (1) the need for non-replayable publishers, * (2) the reconnect boilerplate. * * This behavior can be configured (e.g. disabled) via the "reconnect policy" on the client constructor. */ public class Option2Test { private File audioFile = new File(getClass().getClassLoader().getResource("silence_16kHz_s16le.wav").getFile()); @Test public void option2() { try (TranscribeStreamingAsyncClient client = TranscribeStreamingAsyncClient.create()) { // Create the request for transcribe that includes the audio metadata StartStreamTranscriptionRequest audioMetadata = StartStreamTranscriptionRequest.builder() .languageCode(LanguageCode.EN_US) .mediaEncoding(MediaEncoding.PCM) .mediaSampleRateHertz(16_000) .build(); // Create the audio stream for transcription Flowable<AudioStream> audioStream = Bytes.from(audioFile) .map(SdkBytes::fromByteArray) .map(bytes -> AudioEvent.builder().audioChunk(bytes).build()) .cast(AudioStream.class); // Create the visitor that handles the transcriptions from transcribe Consumer<TranscriptResultStream> reader = event -> { if (event instanceof TranscriptEvent) { TranscriptEvent transcriptEvent = (TranscriptEvent) event; System.out.println(transcriptEvent.transcript().results()); } }; StartStreamTranscriptionResponseHandler responseHandler = StartStreamTranscriptionResponseHandler.builder() .subscriber(reader) .build(); // Start talking with transcribe using the existing method CompletableFuture<Void> result = client.startStreamTranscription(audioMetadata, audioStream, responseHandler); result.join(); } } @Test public void disableReconnectsDemo() { // Turn off reconnects try (TranscribeStreamingAsyncClient client = TranscribeStreamingAsyncClient.builder() .overrideConfiguration(c -> c.reconnectPolicy(ReconnectPolicy.none())) .build()) { // .... } } }
3,067
0
Create_ds/aws-sdk-java-v2/docs/design/core/event-streaming/reconnect
Create_ds/aws-sdk-java-v2/docs/design/core/event-streaming/reconnect/prototype/Option1.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.transcribestreaming; import com.github.davidmoten.rx2.Bytes; import io.reactivex.Flowable; import java.io.File; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import org.junit.Test; import org.reactivestreams.Publisher; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.transcribestreaming.model.AudioEvent; import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; import software.amazon.awssdk.services.transcribestreaming.model.LanguageCode; import software.amazon.awssdk.services.transcribestreaming.model.MediaEncoding; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler; import software.amazon.awssdk.services.transcribestreaming.model.TranscriptEvent; import software.amazon.awssdk.services.transcribestreaming.model.TranscriptResultStream; /** * Option 1: Add a new method to hide: (1) the need for non-replayable publishers, (2) the reconnect boilerplate. */ public class Option1 { private File audioFile = new File(getClass().getClassLoader().getResource("silence_16kHz_s16le.wav").getFile()); @Test public void option1() { try (TranscribeStreamingAsyncClient client = TranscribeStreamingAsyncClient.create()) { // Create the request for transcribe that includes the audio metadata StartStreamTranscriptionRequest audioMetadata = StartStreamTranscriptionRequest.builder() .languageCode(LanguageCode.EN_US) .mediaEncoding(MediaEncoding.PCM) .mediaSampleRateHertz(16_000) .build(); // Create the audio stream for transcription Publisher<AudioStream> audioStream = Bytes.from(audioFile) .map(SdkBytes::fromByteArray) .map(bytes -> AudioEvent.builder().audioChunk(bytes).build()) .cast(AudioStream.class); // Create the visitor that handles the transcriptions from transcribe Consumer<TranscriptResultStream> reader = event -> { if (event instanceof TranscriptEvent) { TranscriptEvent transcriptEvent = (TranscriptEvent) event; System.out.println(transcriptEvent.transcript().results()); } }; StartStreamTranscriptionResponseHandler responseHandler = StartStreamTranscriptionResponseHandler.builder() .subscriber(reader) .build(); // Start talking with transcribe using a new auto-reconnect method (method name to be bikeshed) CompletableFuture<Void> result = client.startStreamTranscriptionWithAutoReconnect(audioMetadata, audioStream, responseHandler); result.join(); } } }
3,068
0
Create_ds/aws-sdk-java-v2/docs/design/services/s3
Create_ds/aws-sdk-java-v2/docs/design/services/s3/transfermanager/prototype.java
package software.amazon.awssdk.services.s3.transfer; /** * The S3 Transfer Manager is a library that allows users to easily and * optimally upload and downloads to and from S3. * <p> * The list of features includes: * <ul> * <li>Parallel uploads and downloads</li> * <li>Bandwidth limiting</li> * <li>Pause and resume of transfers</li> * </ul> * <p> * <b>Usage Example:</b> * <pre> * {@code * // Create using all default configuration values * S3TransferManager tm = S3TranferManager.create(); * * // Using custom configuration values to set max upload speed to avoid * // saturating the network interface. * S3TransferManager tm = S3TransferManager.builder() * .maxUploadBytesSecond(32 * 1024 * 1024) // 32 MiB * .build() * .build(); * } * </pre> */ public interface S3TransferManager { /** * Download an object identified by the bucket and key from S3 to the given * file. * <p> * <b>Usage Example:</b> * <pre> * {@code * // Initiate transfer * Download myFileDownload = tm.download(BUCKET, KEY, Paths.get("/tmp/myFile.txt"); * // Wait for transfer to complete * myFileDownload().completionFuture().join(); * } * </pre> * */ default Download download(String bucket, String key, Path file) { return download(DownloadObjectRequest.builder() .downloadSpecification(DownloadObjectSpecification.fromApiRequest(GetObjectRequest.builder() .bucket(bucket) .key(key) .build())) .build(), file); } /** * Download an object using an S3 presigned URL to the given file. * <p> * <b>Usage Example:</b> * <pre> * {@code * // Initiate transfer * Download myFileDownload = tm.download(myPresignedUrl, Paths.get("/tmp/myFile.txt"); * // Wait for transfer to complete * myFileDownload()completionFuture().join(); * } * </pre> */ default Download download(URL presignedUrl, Path file) { return download(DownloadObjectRequest.builder() .downloadSpecification(DownloadObjectSpecification.fromPresignedUrl(presignedUrl)) .build(), file); } /** * Download an object in S3 to the given file. * * <p> * <b>Usage Example:</b> * <pre> * {@code * // Initiate the transfer * Download myDownload = tm.download(DownloadObjectRequest.builder() * .downloadObjectSpecification(DownloadObjectSpecification.fromApiRequest( * GetObjectRequest.builder() * .bucket(BUCKET) * .key(KEY) * .build())) * // Set the known length of the object to avoid a HeadObject call * .size(1024 * 1024 * 5) * .build(), * Paths.get("/tmp/myFile.txt")); * // Wait for the transfer to complete * myDownload.completionFuture().join(); * } * </pre> */ Download download(DownloadObjectRequest request, Path file); /** * Resume a previously paused object download. */ Download resumeDownloadObject(DownloadObjectState downloadObjectState); /** * Download the set of objects from the bucket with the given prefix to a directory. * <p> * The transfer manager will use '/' as the path delimiter. * <p> * <b>Usage Example:</b> * <pre> * {@code * DownloadDirectory myDownload = tm.downloadDirectory(myBucket, myPrefix, Paths.get("/tmp"); * myDowload.completionFuture().join(); * } * </pre> * * @param bucket The bucket. * @param prefix The prefix. * @param destinationDirectory The directory where the objects will be * downloaded to. */ DownloadDirectory downloadDirectory(String bucket, String prefix, Path destinationDirectory); /** * Upload a directory of files to the given S3 bucket and under the given * prefix. * <p> * <b>Usage Example:</b> * <pre> * {@code * UploadDirectory myUpload = tm.uploadDirectory(myBucket, myPrefix, Paths.get("/path/to/my/directory)); * myUpload.completionFuture().join(); * } * </pre> */ UploadDirectory uploadDirectory(String bucket, String prefix, Path direcrtory); /** * Upload a file to S3. * <p> * <b>Usage Example:</b> * <pre> * {@code * UploadObject myUpload = tm.uploadObject(myBucket, myKey, Paths.get("myFile.txt")); * myUpload.completionFuture().join(); * } * </pre> */ default Upload upload(String bucket, String key, Path file) { return upload(UploadObjectRequest.builder() .uploadSpecification(UploadObjectSpecification.fromApiRequest(PutObjectRequest.builder() .bucket(bucket) .key(key) .build())) .build(), file); } /** * Upload a file to S3 using the given presigned URL. * <p> * <b>Usage Example:</b> * <pre> * {@code * Upload myUpload = tm.upload(myPresignedUrl, Paths.get("myFile.txt")); * myUpload.completionFuture().join(); * } * </pre> */ default Upload upload(URL presignedUrl, Path file) { return upload(UploadObjectRequest.builder() .uploadSpecification(UploadObjectSpecification.fromPresignedUrl(presignedUrl)) .build(), file); } /** * Upload a file to S3. */ Upload upload(UploadObjectRequest request, Path file); /** * Resume a previously paused object upload. */ Upload resumeUploadObject(UploadObjectState uploadObjectState); /** * Create an {@code S3TransferManager} using the default values. */ static S3TransferManager create() { return builder().build(); } static S3TransferManager.Builder builder() { return ...; } interface Builder { /** * The custom S3AsyncClient this transfer manager will use to make calls * to S3. */ Builder s3client(S3AsyncClient s3Client); /** * The max number of requests the Transfer Manager will have at any * point in time. This must be less than or equal to the max concurrent * setting on the S3 client. */ Builder maxConcurrency(Integer maxConcurrency); /** * The aggregate max upload rate in bytes per second over all active * upload transfers. The default is unlimited. */ Builder maxUploadBytesPerSecond(Long maxUploadBytesPerSecond); /** * The aggregate max download rate in bytes per second over all active * download transfers. The default value is unlimited. */ Builder maxDownloadBytesPerSecond(Long maxDownloadBytesPerSecond); /** * Add a progress listener to the currently configured list of * listeners. */ Builder addProgressListener(TransferProgressListener progressListener); /** * Set the list of progress listeners, overwriting any currently * configured list. */ Builder progressListeners(Collection<? extends TransferProgressListener> progressListeners); S3TransferManager build(); } } /** * Configuration object for multipart downloads. */ public interface MultipartDownloadConfiguration { /** * Whether multipart downloads are enabled. */ public Boolean enableMultipartDownloads(); /** * The minimum size for an object to be downloaded in multiple parts. */ public Long multipartDownloadThreshold(); /** * The maximum number of parts objects are to be downloaded in. */ public Integer maxDownloadPartCount(); /** * The minimum size for each part. */ public Long minDownloadPartSize(); } /** * Configuration object for multipart uploads. */ public final class MultipartUploadConfiguration { /** * Whether multipart uploads should be enabled. */ public Boolean enableMultipartUploads(); /** * The minimum size for an object to be uploaded in multipe parts. */ public Long multipartUploadThreshold(); /** * The maximum number of perts to upload an object in. */ public Integer maxUploadPartCount(); /** * The minimum size for each uploaded part. */ public Long minUploadPartSize(); } /** * Override configuration for a single transfer. */ public interface TransferOverrideConfiguration { /** * The maximum rate for this transfer in bytes per second. */ Long maxTransferBytesPerSecond(); /** * Override configuration for multipart downloads. */ MultipartDownloadConfiguration multipartDownloadConfiguration(); /** * Override configuration for multipart uploads. */ MultipartUploadConfiguration multipartUploadConfiguration(); } /** * A factory capable of creating the streams for individual parts of a given * object to be uploaded to S3. * <p> * There is no ordering guaranatee for when {@link * #streamForPart(PartUploadContext)} is called. */ public interface TransferRequestBody { /** * Return the stream for the object part described by given {@link * PartUploadContext}. * * @param context The context describing the part to be uploaded. * @return The part stream. */ Publisher<ByteBuffer> requestBodyForPart(PartUploadContext context); /** * Return the stream for a entire object to be uploaded as a single part. */ Publisher<ByteBuffer> requestBodyForObject(SinglePartUploadContext context); /** * Create a factory that creates streams for individual parts of the given * file. * * @param file The file whose parts the factory will create streams for. * @return The stream factory. */ static ObjectPartStreamCreator forFile(Path file) { return ...; } } /** * A factory capable of creating the {@link AsyncResponseTransformer} to handle * each downloaded object part. * <p> * There is no ordering guarantee for when {@link * #transformerForPart(PartDownloadContext)} invocations. It is invoked when the * response from S3 is received for the given part. */ public interface TransferResponseTransformer { /** * Return a transformer for downloading a single part of an object. */ AsyncResponseTransformer<GetObjectResponse, ?> transformerForPart(MultipartDownloadContext context); /** * Return a transformer for downloading an entire object as a single part. */ AsyncResponseTransformer<GetObjectResponse, ?> transformerForObject(SinglePartDownloadContext context) /** * Return a factory capable of creating transformers that will recombine the * object parts to a single file on disk. */ static TransferResponseTransformer forFile(Path file) { return ...; } } /** * The context object for the upload of an object part to S3. */ public interface MultipartUploadContext { /** * The original upload request given to the transfer manager. */ UploadObjectRequest uploadRequest(); /** * The request sent to S3 to initiate the multipart upload. */ CreateMultipartUploadRequest createMultipartRequest(); /** * The upload request to be sent to S3 for this part. */ UploadPartRequest uploadPartRequest(); /** * The offset from the beginning of the object where this part begins. */ long partOffset(); } public interface SinglePartUploadContext { /** * The original upload request given to the transfer manager. */ UploadObjectRequest uploadRequest(); /** * The request to be sent to S3 to upload the object as a single part. */ PutObjectRequest objectRequest(); } /** * Context object for an individual object part for a multipart download. */ public interface MultipartDownloadContext { /** * The original download request given to the Transfer Manager. */ DownloadObjectRequest downloadRequest(); /** * The part number. */ int partNumber(); /** * The offset from the beginning of the object where this part begins. */ long partOffset(); /** * The size of the part requested in bytes. */ long size(); /** * Whether this is the last part of the object. */ boolean isLastPart(); } /** * Context object for a single part download of an object. */ public interface SinglePartDownloadContext { /** * The original download request given to the Transfer Manager. */ DownloadObjectRequest downloadRequest(); /** * The request sent to S3 for this object. This is empty if downloading a presigned URL. */ GetObjectRequest objectRequest(); } /** * Progress listener for a Transfer. * <p> * The SDK guarantees that calls to {@link #transferProgressEvent(EventContext)} * are externally synchronized. */ public interface TransferProgressListener { /** * Called when a new progress event is available for a Transfer. * * @param ctx The context object for the given transfer event. */ void transferProgressEvent(EventContext ctx); interface EventContext { /** * The transfer this listener associated with. */ Transfer transfer(); } interface Initiated extends EventContext { /** * The amount of time that has elapsed since the transfer was * initiated. */ Duration elapsedTime(); } interface BytesTransferred extends Initiated { /** * The transfer request for the object whose bytes were transferred. */ TransferObjectRequest objectRequest(); /** * The number of bytes transferred for this event. */ long bytes(); /** * The total size of the object. */ long size(); /** * If the transfer of the given object is complete. */ boolean complete(); } interface Completed extends Initiated { } interface Cancelled extends Initiated { } interface Failed extends Initiated { /** * The error. */ Throwable error(); } } /** * A download transfer of a single object from S3. */ public interface Download extends Transfer { @Override DownloadObjectState pause(); } /** * An upload transfer of a single object to S3. */ public interface Upload extends Transfer { @Override UploadObjectState pause(); } /** * The state of an object download. */ public interface DownloadState extends TransferState { /** * Persist this state so it can later be resumed. */ void persistTo(OutputStream os); /** * Load a persisted transfer which can then be resumed. */ static DownloadState loadFrom(Inputstream is) { ... } } /** * The state of an object upload. */ public interface UploadState extends TransferState { /** * Persist this state so it can later be resumed. */ void persistTo(OutputStream os); /** * Load a persisted transfer which can then be resumed. */ static UploadState loadFrom(Inputstream is) { ... } } /** * Represents the transfer of one or more objects to or from S3. */ public interface Transfer { CompletableFuture<? extends CompletedTransfer> completionFuture(); /** * Pause this transfer, cancelling any requests in progress. * <p> * The returned state object can be used to resume this transfer at a later * time. * * @throws IllegalStateException If this transfer is completed or cancelled. * @throws UnsupportedOperationException If the transfer does not support * pause and resume. */ TransferState pause(); } public interface CompletedTransfer { /** * The metrics for this transfer. */ TransferMetrics metrics(); } /** * Metrics for a completed transfer. */ public interface TransferMetrics { /** * The number of milliseconds that elapsed before this transfer completed. */ long elapsedMillis(); /** * The total number of bytes transferred. */ long bytesTransferred(); } /** * A request to download an object. The object to download is specified using * the {@link DownloadObjectSpecification} union type. */ public class DownloadObjectRequest extends AbstractTransferRequest { /** * The specification for how to download the object. */ DownloadObjectSpecification downloadSpecification(); /** * The size of the object to be downloaded. */ public Long size(); public static DownloadObjectRequest forPresignedUrl(URL presignedUrl) { ... } public static DownloadObjectRequest forBucketAndKey(String bucket, String key) { ... } public interface Builder extends AbstractTransferRequest.Builder { /** * The specification for how to download the object. */ Builder downloadSpecification(DownloadObjectSpecification downloadSpecification); /** * Set the override configuration for this request. */ @Override Builder overrideConfiguration(TransferOverrideConfiguration config); /** * Set the progress listeners for this request. */ @Override Builder progressListeners(Collection<TransferProgressListener> progressListeners); /** * Add an additional progress listener for this request, appending it to * the list of currently configured listeners on this request. */ @Override Builder addProgressListener(TransferProgressListener progressListener); /** * Set the optional size of the object to be downloaded. */ Builder size(Long size); DownloadObjectRequest build(); } } /** * Union type to contain the different ways to express an object download from * S3. */ public class DownloadObjectSpecification { /** * Return this specification as a presigned URL. * * @throws IllegalStateException If this specifier is not a presigned URL. */ URL asPresignedUrl(); /** * Return this specification as a {@link GetObjectRequest API request}. * * @throws IllegalStateException If this specifier is not an API request. */ GetObjectRequest asApiRequest(); /** * Returns {@code true} if this is a presigned URL, {@code false} otherwise. */ boolean isPresignedUrl(); /** * Returns {@code true} if this is an API request, {@code false} otherwise. */ boolean isApiRequest(); /** * Create an instance from a presigned URL. */ static DownloadObjectSpecification fromPresignedUrl(URL presignedUrl) { ... } /** * Create an instance from an API request. */ static DownloadObjectSpecification fromApiRequest(GetObjectRequest apiRequest) { ... } } /** * A request to upload an object. The object to upload is specified using the * {@link UploadObjectSpecification} union type. */ public class UploadObjectRequest extends AbstractTransferRequest { /** * The specification for how to upload the object. */ UploadbjectSpecification uploadSpecification(); /** * The size of the object to be uploaded. */ long size(); public static UploadObjectRequest forPresignedUrl(URL presignedUrl) { ... } public static UploadObjectRequest forBucketAndKey(String bucket, String key) { ... } public interface Builder extends AbstractTransferRequest.Builder { /** * The specification for how to upload the object. */ Builder uploadSpecification(UploadObjectSpecification uploadSpecification); /** * Set the override configuration for this request. */ @Override Builder overrideConfiguration(TransferOverrideConfiguration config); /** * Set the progress listeners for this request. */ @Override Builder progressListeners(Collection<TransferProgressListener> progressListeners); /** * Add an additional progress listener for this request, appending it to * the list of currently configured listeners on this request. */ @Override Builder addProgressListener(TransferProgressListener progressListener); UploadObjectRequest build(); } } /** * Union type to contain the different ways to express an object upload from * S3. */ public class UploadObjectSpecification { /** * Return this specification as a presigned URL. * * @throws IllegalStateException If this specifier is not a presigned URL. */ URL asPresignedUrl(); /** * Return this specification as a {@link PutObjectRequest API request}. * * @throws IllegalStateException If this specifier is not an API request. */ PutObjectRequest asApiRequest(); /** * Returns {@code true} if this is a presigned URL, {@code false} otherwise. */ boolean isPresignedUrl(); /** * Returns {@code true} if this is an API request, {@code false} otherwise. */ boolean isApiRequest(); /** * Create an instance from a presigned URL. */ static UploadObjectSpecification fromPresignedUrl(URL presignedUrl) { ... } /** * Create an instance from an API request. */ static UploadObjectSpecification fromApiRequest(PutObjectRequest apiRequest) { ... } }
3,069
0
Create_ds/aws-sdk-java-v2/docs/design/services/dynamodb/high-level-library/archive/20200103/prototype/option-2
Create_ds/aws-sdk-java-v2/docs/design/services/dynamodb/high-level-library/archive/20200103/prototype/option-2/sync/Prototype.java
/** * A synchronous client for interacting (generically) with document databases. * * Features: * <ol> * <li>Support for Java-specific types, like {@link Instant} and {@link BigDecimal}.</li> * <li>Support for reading and writing custom objects (eg. Java Beans, POJOs).</li> * </ol> * * All {@link DocumentClient}s should be closed via {@link #close()}. */ @ThreadSafe public interface DocumentClient extends SdkAutoCloseable { /** * Create a {@link DocumentClient} for interating with document databases. * * The provided runtime will be used for handling object persistence. * * Usage Example: * <code> * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * client.listRepositories().repositories().forEach(System.out::println); * } * </code> */ static DocumentClient create(Class<? extends DocumentClientRuntime> runtimeClass); /** * Create a {@link DocumentClient.Builder} for configuring and creating {@link DocumentClient}s. * * The provided runtime will be used for handling object persistence. * * Usage Example: * <code> * try (DocumentClient client = DocumentClient.builder(DynamoDbRuntime.class) * .putOption(DynamoDbOption.CLIENT, DynamoDbClient.create()) * .build()) { * client.listRepositories().repositories().forEach(System.out::println); * } * </code> */ static DocumentClient.Builder builder(Class<? extends DocumentClientRuntime> runtimeClass); /** * Get all {@link DocumentRepository}s that are currently available from this client. * * This should return every repository that will not result in {@code client.repository(...)} throwing a * {@link NoSuchRepositoryException}. * * Usage Example: * <code> * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * client.listRepositories().repositories().forEach(System.out::println); * } * </code> */ ListRepositoriesResponse listRepositories(); /** * Retrieve a {@link DocumentRepository} based on the provided repository name/id. * * The {@link DocumentRepository} is used to directly interact with entities in the remote repository. * See {@link #mappedRepository(Class)} for a way of interacting with the repository using Java objects. * * If the repository does not exist, an exception is thrown. * * Usage Example: * <code> * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * DocumentRepository repository = client.repository("my-table"); * assert repository.name().equals("my-table"); * } catch (NoSuchRepositoryException e) { * System.out.println("The requested repository does not exist: " + e.getMessage()); * throw e; * } * </code> */ DocumentRepository repository(String repositoryId) throws NoSuchRepositoryException; /** * Retrieve a {@link DocumentRepository} based on the provided repository name/id. * * The {@link DocumentRepository} is used to create, read, update and delete entities in the remote repository. * See {@link #mappedRepository(Class)} for a way of interacting with the repository using Java objects. * * If the repository does not exist, the provided {@link MissingRepositoryBehavior} determines the behavior. * * Usage Example: * <code> * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * DocumentRepository repository = client.repository("my-table", MissingRepositoryBehavior.CREATE); * assert repository.name().equals("my-table"); * } * </code> */ DocumentRepository repository(String repositoryId, MissingRepositoryBehavior behavior) throws NoSuchRepositoryException; /** * Retrieve an implementation of a specific {@link MappedRepository} based on the provided Java object class. * * This {@link MappedRepository} implementation is used to create, read, update and delete entities in the remote repository * using Java objects. See {@link #repository(String)} for a way of interacting directly with the entities. * * If the repository does not exist, an exception is thrown. * * Usage Example: * <code> * @MappedRepository("my-table") * public interface MyItemRepository extends MappedRepository<MyItem, String> { * } * * public class MyItem { * @Id * @Column("partition-key") * private UUID partitionKey; * * @Column("creation-time") * private Instant creationTime; * * public String getPartitionKey() { return this.partitionKey; } * public Instant getCreationTime() { return this.creationTime; } * public void setPartitionKey(UUID partitionKey) { this.partitionKey = partitionKey; } * public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } * } * * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * MyItemRepository repository = client.mappedRepository(MyItemRepository.class); * assert repository.name().equals("my-table"); * } catch (NoSuchRepositoryException e) { * System.out.println("The requested repository does not exist: " + e.getMessage()); * throw e; * } * </code> */ <T extends MappedRepository<?, ?>> T mappedRepository(Class<T> repositoryClass); /** * Retrieve an implementation of a specific {@link MappedRepository} based on the provided Java object class. * * This {@link MappedRepository} implementation is used to create, read, update and delete entities in the remote repository * using Java objects. See {@link #repository(String)} for a way of interacting directly with the entities. * * If the repository does not exist, the provided {@link MissingRepositoryBehavior} determines the behavior. * * Usage Example: * <code> * @MappedRepository("my-table") * public interface MyItemRepository extends MappedRepository<MyItem, String> { * } * * public class MyItem { * @Id * @Column("partition-key") * private UUID partitionKey; * * @Column("creation-time") * private Instant creationTime; * * public String getPartitionKey() { return this.partitionKey; } * public Instant getCreationTime() { return this.creationTime; } * public void setPartitionKey(UUID partitionKey) { this.partitionKey = partitionKey; } * public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } * } * * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * MyItemRepository repository = client.mappedRepository(MyItemRepository.class, MissingRepositoryBehavior.CREATE); * assert repository.name().equals("my-table"); * } * </code> */ <T extends MappedRepository<?, ?>> T mappedRepository(Class<T> repositoryClass, MissingRepositoryBehavior behavior); /** * A builder for configuring and creating {@link DocumentClient} instances. * * @see #builder(Class) */ @NotThreadSafe interface Builder { /** * Configure the type converters that should be applied globally across all {@link DocumentRepository}s and * {@link MappedRepository}s from the client. This can also be overridden at the entity level. * * The following type conversions are supported by default: * <ul> * <li>{@link Long} / {@link long} -> {@link EntityValueType#LONG}</li> * <li>{@link Integer} / {@link int} -> {@link EntityValueType#INT}</li> * <li>{@link Short} / {@link short} -> {@link EntityValueType#SHORT}</li> * <li>{@link Float} / {@link float} -> {@link EntityValueType#FLOAT}</li> * <li>{@link Double} / {@link double} -> {@link EntityValueType#DOUBLE}</li> * <li>{@link Number} -> {@link EntityValueType#NUMBER}</li> * <li>{@link Temporal} -> {@link EntityValueType#NUMBER}</li> * <li>{@link Char} / {@link char} -> {@link EntityValueType#STRING}</li> * <li>{@link char[]} -> {@link EntityValueType#STRING}</li> * <li>{@link CharSequence} -> {@link EntityValueType#STRING}</li> * <li>{@link UUID} -> {@link EntityValueType#STRING}</li> * <li>{@link byte[]} -> {@link EntityValueType#BYTES}</li> * <li>{@link ByteBuffer} -> {@link EntityValueType#BYTES}</li> * <li>{@link BytesWrapper} -> {@link EntityValueType#BYTES}</li> * <li>{@link InputStream} -> {@link EntityValueType#BYTES}</li> * <li>{@link File} -> {@link EntityValueType#BYTES}</li> * <li>{@link Path} -> {@link EntityValueType#BYTES}</li> * <li>{@link Boolean} -> {@link EntityValueType#BOOLEAN}</li> * <li>{@link Collection} -> {@link EntityValueType#LIST}</li> * <li>{@link Stream} -> {@link EntityValueType#LIST}</li> * <li>{@link Iterable} -> {@link EntityValueType#LIST}</li> * <li>{@link Iterator} -> {@link EntityValueType#LIST}</li> * <li>{@link Enumeration} -> {@link EntityValueType#LIST}</li> * <li>{@link Optional} -> {@link EntityValueType#*}</li> * <li>{@link Map} -> {@link EntityValueType#ENTITY}</li> * <li>{@link Object} -> {@link EntityValueType#ENTITY}</li> * <li>{@link null} -> {@link EntityValueType#NULL}</li> * </ul> * * Usage Example: * <code> * try (DocumentClient client = DocumentClient.builder(DynamoDbRuntime.class) * .addConverter(InstantsAsStringsConverter.create()) * .build()) { * DocumentRepository repository = client.repository("my-table"); * * UUID id = UUID.randomUUID(); * repository.putEntity(Entity.builder() * .putChild("partition-key", id) * .putChild("creation-time", Instant.now()) * .build()); * * Thread.sleep(5_000); // GetEntity is eventually consistent with the Dynamo DB runtime. * * Entity item = repository.getEntity(Entity.builder() * .putChild("partition-key", id) * .build()); * * // Instants are usually converted to a number-type, but it was stored as an ISO-8601 string now because of the * // InstantsAsStringsConverter. * assert item.getChild("creation-time").isString(); * assert item.getChild("creation-time").as(Instant.class).isBetween(Instant.now().minus(1, MINUTE), * Instant.now()); * } * </code> */ DocumentClient.Builder converters(Iterable<? extends EntityValueConverter<?>> converters); DocumentClient.Builder addConverter(EntityValueConverter<?> converter); DocumentClient.Builder clearConverters(); /** * Usage Example: * <code> * try (DocumentClient client = DocumentClient.builder(DynamoDbRuntime.class) * .putOption(DynamoDbOption.CLIENT, DynamoDbClient.create()) * .build()) { * client.listRepositories().repositories().forEach(System.out::println); * } * </code> */ DocumentClient.Builder options(Map<? extends OptionKey<?>, ?> options); <T> DocumentClient.Builder putOption(OptionKey<T> optionKey, T optionValue); DocumentClient.Builder removeOption(OptionKey<?> optionKey); DocumentClient.Builder clearOptions(); } } /** * When calling {@link DocumentClient#repository} or {@link DocumentClient#mappedRepository} and a repository does not exist on * the service side, this is the behavior that the client should take. */ @ThreadSafe public enum MissingRepositoryBehavior { /** * Create the repository, if it's missing. */ CREATE, /** * Throw a {@link NoSuchRepositoryException}, if the repository is missing. */ FAIL, /** * Do not check whether the repository exists, for performance reasons. Methods that require the repository to exist will * fail. */ DO_NOT_CHECK } /** * An interface that repository-specific runtimes can implement to be supported by the document client. */ @ThreadSafe public interface DocumentClientRuntime { } /** * The DynamoDB implementation of the {@link DocumentClientRuntime}. */ @ThreadSafe public interface DynamoDbRuntime extends DocumentClientRuntime { } /** * The DynamoDB-specific options available for configuring the {@link DynamoDbRuntime} via * {@link DocumentClient.Builder#putOption}. */ @ThreadSafe public class DynamoDbOption { /** * Configure the DynamoDB client that should be used for communicating with DynamoDB. * * This only applies to the {@link DynamoDbRuntime}. * * Usage Example: * <code> * try (DocumentClient client = DocumentClient.builder(DynamoDbRuntime.class) * .putOption(DynamoDbOption.CLIENT, DynamoDbClient.create()) * .build()) { * client.listRepositories().repositories().forEach(System.out::println); * } * </code> */ public static final Option<DynamoDbClient> CLIENT = new Option<>(DynamoDbClient.class); } /** * A converter between Java types and repository types. These can be attached to {@link DocumentClient}s and * {@link Entity}s, so that types are automatically converted when writing to and reading from the repository. * * @see DocumentClient.Builder#converters(Iterable) * @see Entity.Builder#addConverter(EntityValueConverter) * * @param T The Java type that is generated by this converter. */ @ThreadSafe public interface EntityValueConverter<T> { /** * The default condition in which this converter is invoked. * * Even if this condition is not satisfied, it can still be invoked directly via * {@link EntityValue#from(Object, EntityValueConverter)}. */ ConversionCondition defaultConversionCondition(); /** * Convert the provided Java type into an {@link EntityValue}. */ EntityValue toEntityValue(T input, ConversionContext context); /** * Convert the provided {@link EntityValue} into a Java type. */ T fromEntityValue(EntityValue input, ConversionContext context); } /** * The condition in which a {@link EntityValueConverter} will be invoked. * * @see EntityValueConverter#defaultConversionCondition() */ @ThreadSafe public interface ConversionCondition { /** * Create a conversion condition that causes an {@link EntityValueConverter} to be invoked if an entity value's * {@link ConversionContext} matches a specific condition. * * This condition has a larger overhead than the {@link #isInstanceOf(Class)} and {@link #never()}, because it must be * invoked for every entity value being converted and its result cannot be cached. For this reason, lower-overhead * conditions like {@link #isInstanceOf(Class)} and {@link #never()} should be favored where performance is important. */ static ConversionCondition contextSatisfies(Predicate<ConversionContext> contextPredicate); /** * Create a conversion condition that causes an {@link EntityValueConverter} to be invoked if the entity value's * Java type matches the provided class. * * The result of this condition can be cached, and will likely not be invoked for previously-converted types. */ static ConversionCondition isInstanceOf(Class<?> clazz); /** * Create a conversion condition that causes an {@link EntityValueConverter} to never be invoked by default, except * when directly invoked via {@link EntityValue#from(Object, EntityValueConverter)}. * * The result of this condition can be cached, and will likely not be invoked for previously-converted types. */ static ConversionCondition never(); } /** * Additional context that can be used when converting between Java types and {@link EntityValue}s. * * @see EntityValueConverter#fromEntityValue(EntityValue, ConversionContext) * @see EntityValueConverter#toEntityValue(java.lang.Object, ConversionContext) */ @ThreadSafe public interface ConversionContext { /** * The name of the entity value being converted. */ String entityValueName(); /** * The schema of the entity value being converted. */ EntityValueSchema entityValueSchema(); /** * The entity that contains the entity value being converted. */ Entity parent(); /** * The schema of the {@link #parent()}. */ EntitySchema parentSchema(); } /** * The result of invoking {@link DocumentClient#listRepositories()}. */ @ThreadSafe public interface ListRepositoriesResponse { /** * A lazily-populated iterator over all accessible repositories. This may make multiple service calls in the * background when iterating over the full result set. */ SdkIterable<DocumentRepository> repositories(); } /** * A client that can be used for creating, reading, updating and deleting entities in a remote repository. * * Created via {@link DocumentClient#repository(String)}. * * Usage Example: * <code> * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * DocumentRepository repository = client.repository("my-table"); * * UUID id = UUID.randomUUID(); * repository.putEntity(Entity.builder() * .putChild("partition-key", id) * .putChild("creation-time", Instant.now()) * .build()); * * Thread.sleep(5_000); // GetEntity is eventually consistent with the Dynamo DB runtime. * * Entity item = repository.getEntity(Entity.builder() * .putChild("partition-key", id) * .build()); * * assert item.getChild("creation-time").as(Instant.class).isBetween(Instant.now().minus(1, MINUTE), * Instant.now()); * } catch (NoSuchEntityException e) { * System.out.println("Item could not be found. Maybe we didn't wait long enough for consistency?"); * throw e; * } * </code> */ public interface DocumentRepository { /** * Retrieve the name of this repository. * * Usage Example: * <code> * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * DocumentRepository repository = client.repository("my-table"); * assert repository.name().equals("my-table"); * } * </code> */ String name(); /** * Convert this repository to a mapped-repository, so that Java objects can be persisted and retrieved. * * Usage Example: * <code> * @MappedRepository("my-table") * public interface MyItemRepository extends MappedRepository<MyItem, String> { * } * * public class MyItem { * @Id * @Column("partition-key") * private UUID partitionKey; * * @Column("creation-time") * private Instant creationTime; * * public String getPartitionKey() { return this.partitionKey; } * public Instant getCreationTime() { return this.creationTime; } * public void setPartitionKey(UUID partitionKey) { this.partitionKey = partitionKey; } * public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } * } * * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * DocumentRepository unmappedRepository = client.repository("my-table"); * MyItemRepository mappedRepository = unmappedRepository.toMappedRepository(MyItemRepository.class); * assert mappedRepository.name().equals("my-table"); * } * </code> */ <T extends MappedRepository<?, ?>> T toMappedRepository(Class<T> repositoryClass); /** * Create or update an existing entity in the repository. * * Usage Example: * <code> * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * DocumentRepository repository = client.repository("my-table"); * * repository.putEntity(Entity.builder() * .putChild("partition-key", UUID.randomUUID()) * .putChild("creation-time", Instant.now()) * .build()); * } * </code> */ void putEntity(Entity entity); /** * Create or update an existing entity in the repository. * * This API allows specifying additional runtime-specific options via {@link PutRequest#putOption}, and retrieving runtime- * specific options via {@link PutResponse#option}. * * Usage Example: * <code> * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * DocumentRepository repository = client.repository("my-table"); * * PutResponse response = * repository.putEntity(Entity.builder() * .putChild("partition-key", UUID.randomUUID()) * .putChild("creation-time", Instant.now()) * .build(), * PutRequest.builder() * .putOption(DynamoDbPutRequestOption.REQUEST, * putItemRequest -> putItemRequest.returnConsumedCapacity(TOTAL)) * .build()); * System.out.println(response.option(DynamoDbPutResponseOption.RESPONSE).consumedCapacity()); * } * </code> */ PutResponse putEntity(Entity entity, PutRequest options) /** * Retrieve an entity from the repository. The index will be chosen automatically based on the fields provided in the * input entity. * * Usage Example: * <code> * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * DocumentRepository repository = client.repository("my-table"); * * UUID id = UUID.randomUUID(); * repository.putEntity(Entity.builder() * .putChild("partition-key", id) * .putChild("creation-time", Instant.now()) * .build()); * * Thread.sleep(5_000); // GetEntity is eventually consistent with the Dynamo DB runtime. * * Entity item = repository.getEntity(Entity.builder() * .putChild("partition-key", id) * .build()); * * assert item.getChild("creation-time").as(Instant.class).isBetween(Instant.now().minus(1, MINUTE), * Instant.now()); * } catch (NoSuchEntityException e) { * System.out.println("Item could not be found. Maybe we didn't wait long enough for consistency?"); * throw e; * } * </code> */ Entity getEntity(Entity keyEntity); /** * Retrieve an entity from the repository. The index will be chosen automatically based on the fields provided in the * input entity. * * This API allows specifying additional runtime-specific options via {@link GetRequest#putOption}, and retrieving runtime- * specific options via {@link GetResponse#option}. * * Usage Example: * <code> * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * DocumentRepository repository = client.repository("my-table"); * * UUID id = UUID.randomUUID(); * repository.putEntity(Entity.builder() * .putChild("partition-key", id) * .putChild("creation-time", Instant.now()) * .build()); * * GetResponse response = * repository.getEntity(Entity.builder() * .putChild("partition-key", id) * .build(), * GetRequest.builder() * .putOption(DynamoDbGetRequestOption.CONSISTENT, true) * .build()); * * assert response.entity().getChild("creation-time").as(Instant.class).isBetween(Instant.now().minus(1, MINUTE), * Instant.now()); * } * </code> */ GetResponse getEntity(Entity keyEntity, GetRequest options); } /** * A base class for type-specific repositories for creating, reading, updating and deleting entities in the remote repository * using Java objects. * * Created via {@link DocumentClient#mappedRepository(Class)}. */ public interface MappedRepository<T, ID> extends DocumentRepository { /** * Create or update an existing entity in the repository. * * Usage Example: * <code> * @MappedRepository * public interface MyItemRepository extends MappedRepository<MyItem, String> { * } * * @Repository("my-table") * public class MyItem { * @Id * @Column("partition-key") * private UUID partitionKey; * * @Column("creation-time") * private Instant creationTime; * * public String getPartitionKey() { return this.partitionKey; } * public Instant getCreationTime() { return this.creationTime; } * public void setPartitionKey(UUID partitionKey) { this.partitionKey = partitionKey; } * public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } * } * * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * MyItemRepository repository = client.repository(MyItemRepository.class); * * UUID id = UUID.randomUUID(); * * MyItem itemToCreate = new MyItem(); * itemToCreate.setPartitionKey(id); * itemToCreate.setCreationTime(Instant.now()); * * repository.putObject(itemToCreate); * } * </code> */ void putObject(T entity); /** * Create or update an existing entity in the repository. * * This API allows specifying additional runtime-specific options via {@link PutRequest#putOption}, and retrieving runtime- * specific options via {@link PutObjectResponse#option}. * * Usage Example: * <code> * @MappedRepository * public interface MyItemRepository extends MappedRepository<MyItem, String> { * } * * @Repository("my-table") * public class MyItem { * @Id * @Column("partition-key") * private UUID partitionKey; * * @Column("creation-time") * private Instant creationTime; * * public String getPartitionKey() { return this.partitionKey; } * public Instant getCreationTime() { return this.creationTime; } * public void setPartitionKey(UUID partitionKey) { this.partitionKey = partitionKey; } * public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } * } * * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * MyItemRepository repository = client.repository(MyItemRepository.class); * * UUID id = UUID.randomUUID(); * * MyItem itemToCreate = new MyItem(); * itemToCreate.setPartitionKey(id); * itemToCreate.setCreationTime(Instant.now()); * * PutObjectResponse<MyItem> response = * repository.putObject(itemToCreate, * PutRequest.builder() * .putOption(DynamoDbPutRequestOption.REQUEST, * putItemRequest -> putItemRequest.returnConsumedCapacity(TOTAL)) * .build()); * System.out.println(response.option(DynamoDbPutResponseOption.RESPONSE).consumedCapacity()); * } * </code> */ PutObjectResponse<T> putObject(T entity, PutRequest options) /** * Retrieve an object from the repository. The index will be chosen automatically based on the fields provided in the * input object. * * Usage Example: * <code> * @MappedRepository * public interface MyItemRepository extends MappedRepository<MyItem, String> { * } * * @Repository("my-table") * public class MyItem { * @Id * @Column("partition-key") * private UUID partitionKey; * * @Column("creation-time") * private Instant creationTime; * * public String getPartitionKey() { return this.partitionKey; } * public Instant getCreationTime() { return this.creationTime; } * public void setPartitionKey(UUID partitionKey) { this.partitionKey = partitionKey; } * public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } * } * * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * MyItemRepository repository = client.repository(MyItemRepository.class); * * UUID id = UUID.randomUUID(); * * MyItem itemToCreate = new MyItem(); * itemToCreate.setPartitionKey(id); * itemToCreate.setCreationTime(Instant.now()); * * repository.putObject(itemToCreate); * * // Wait a little bit, because getObject is eventually consistent by default. * Thread.sleep(5_000); * * MyItem itemToRetrieve = new MyItem(); * itemToRetrieve.setPartitionKey(id); * * MyItem retrievedItem = repository.getObject(itemToRetrieve); * assert retrievedItem.getCreationTime().isBetween(Instant.now().minus(1, MINUTE), * Instant.now()); * } catch (NoSuchEntityException e) { * System.out.println("Item could not be found. Maybe we didn't wait long enough for consistency?"); * throw e; * } * </code> */ T getObject(ID id); /** * Retrieve an entity from the repository. The index will be chosen automatically based on the fields provided in the * input entity. * * This API allows specifying additional runtime-specific options via {@link GetRequest#putOption}, and retrieving runtime- * specific options via {@link GetObjectResponse#option}. * * Usage Example: * <code> * @MappedRepository * public interface MyItemRepository extends MappedRepository<MyItem, String> { * } * * @Repository("my-table") * public class MyItem { * @Id * @Column("partition-key") * private UUID partitionKey; * * @Column("creation-time") * private Instant creationTime; * * public String getPartitionKey() { return this.partitionKey; } * public Instant getCreationTime() { return this.creationTime; } * public void setPartitionKey(UUID partitionKey) { this.partitionKey = partitionKey; } * public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } * } * * try (DocumentClient client = DocumentClient.create(DynamoDbRuntime.class)) { * MyItemRepository repository = client.repository(MyItemRepository.class); * * UUID id = UUID.randomUUID(); * * MyItem itemToCreate = new MyItem(); * itemToCreate.setPartitionKey(id); * itemToCreate.setCreationTime(Instant.now()); * * repository.putObject(itemToCreate); * * MyItem itemToRetrieve = new MyItem(); * itemToRetrieve.setPartitionKey(id); * * GetObjectResponse<MyItem> response = * repository.getObject(itemToRetrieve, * GetRequest.builder() * .putOption(DynamoDbGetRequestOption.CONSISTENT, true) * .build()); * * assert response.entity().getCreationTime().isBetween(Instant.now().minus(1, MINUTE), * Instant.now()); * } * </code> */ GetObjectResponse<T> getObject(ID id, GetRequest options); } /** * An entity in a {@link DocumentRepository}. This is similar to a "row" in a traditional relational database. * * In the following repository, { "User ID": 1, "Username": "joe" } is an entity: * * <pre> * Repository: Users * | ------------------ | * | User ID | Username | * | ------------------ | * | 1 | joe | * | 2 | jane | * | ------------------ | * </pre> */ @ThreadSafe public interface Entity { /** * Create a builder for configuring and creating an {@link Entity}. */ static Entity.Builder builder(); /** * Retrieve all {@link EntityValue}s in this entity. */ Map<String, EntityValue> children(); /** * Retrieve a specific {@link EntityValue} from this entity. */ EntityValue child(String entityName); interface Builder { /** * Add a child to this entity. The methods accepting "Object", will be converted using the default * {@link EntityValueConverter}s. */ Entity.Builder putChild(String entityName, Object value); Entity.Builder putChild(String entityName, Object value, EntityValueSchema schema); Entity.Builder putChild(String entityName, EntityValue value); Entity.Builder putChild(String entityName, EntityValue value, EntityValueSchema schema); Entity.Builder removeChild(String entityName); Entity.Builder clearChildren(); /** * Add converters that should be used for this entity and its children. These converters are used with a higher * precedence than those configured in the {@link DocumentClient.Builder}. * * See {@link DocumentClient.Builder#addConverter} for example usage. */ Entity.Builder converters(Iterable<? extends EntityValueConverter<?>> converters); Entity.Builder addConverter(EntityValueConverter<?> converter); Entity.Builder clearConverters(); /** * Create an {@link Entity} using the current configuration on the builder. */ Entity build(); } } /** * The value within an {@link Entity}. In a traditional relational database, this would be analogous to a cell * in the table. * * In the following table, "joe" and "jane" are both entity values: * <pre> * Table: Users * | ------------------ | * | User ID | Username | * | ------------------ | * | 1 | joe | * | 2 | jane | * | ------------------ | * </pre> */ @ThreadSafe public interface EntityValue { /** * Create an {@link EntityValue} from the provided object. */ static EntityValue from(Object object); /** * Create an {@link EntityValue} from the provided object, and associate this value with the provided * {@link EntityValueConverter}. This allows it to be immediately converted with {@link #as(Class)}. * * This is equivalent to {@code EntityValue.from(object).convertFromJavaType(converter)}. */ static EntityValue from(Object object, EntityValueConverter<?> converter); /** * Create an {@link EntityValue} that represents the null type. */ static EntityValue nullValue(); /** * Retrieve the {@link EntityValueType} of this value. */ EntityValueType type(); /** * The {@code is*} methods can be used to check the underlying repository type of the entity value. * * If the type isn't known (eg. because it was created via {@link EntityValue#from(Object)}), {@link #isJavaType()} * will return true. Such types will be converted into repository-specific types by the document client before they are * persisted. */ boolean isString(); default boolean isNumber() { return isFloat() || isDouble() || isShort() || isInt() || isLong(); } boolean isFloat(); boolean isDouble(); boolean isShort(); boolean isInt(); boolean isLong(); boolean isBytes(); boolean isBoolean(); boolean isNull(); boolean isJavaType(); boolean isList(); boolean isEntity(); /** * Convert this entity value into the requested Java type. * * This uses the {@link EntityValueConverter} configured on this type via * {@link #from(Object, EntityValueConverter)} or {@link #convertFromJavaType(EntityValueConverter)}. */ <T> T as(Class<T> type); /** * The {@code as*} methods can be used to retrieve this value without the type-conversion overhead of {@link #as(Class)}. * * An exception will be thrown from these methods if the requested type does not match the actual underlying type. When * the type isn't know, the {@code is*} or {@link #type()} methods can be used to query the underlying type before * invoking these {@code as*} methods. */ String asString(); BigDecimal asNumber(); float asFloat(); double asDouble(); short asShort(); int asInt(); long asLong(); SdkBytes asBytes(); Boolean asBoolean(); Object asJavaType(); List<EntityValue> asList(); Entity asEntity(); /** * Convert this entity value from a {@link EntityValueType#JAVA_TYPE} to a type that can be persisted in DynamoDB. * * This will throw an exception if {@link #isJavaType()} is false. */ EntityValue convertFromJavaType(EntityValueConverter<?> converter); } /** * The underlying repository type of an {@link EntityValue}. */ @ThreadSafe public enum EntityValueType { ENTITY, LIST, STRING, FLOAT, DOUBLE, SHORT, INT, LONG, BYTES, BOOLEAN, NULL, JAVA_TYPE } /** * The schema for a specific entity. This describes the entity's structure and which values it contains. * * This is mostly an implementation detail, and can be ignored except by developers interested in creating * {@link EntityValueConverter}s. */ @ThreadSafe public interface EntitySchema { /** * Create a builder for configuring and creating an {@link EntitySchema}. */ static EntitySchema.Builder builder(); interface Builder { /** * The Java type of the entity that this schema represents. */ EntitySchema.Builder javaType(Class<?> javaType); /** * The repository type of the entity that this schema represents. */ EntitySchema.Builder entityValueType(EntityValueType entityValueType); /** * The converter that should be used for converting an entity conforming to this schema to/from the * repository-specific type. */ EntitySchema.Builder converter(EntityValueConverter<?> converter); /** * Specify the child schemas that describe each child of this entity. */ EntitySchema.Builder childSchemas(Map<String, EntityValueSchema> childSchemas); EntitySchema.Builder putChildSchema(String childName, EntityValueSchema childSchema); EntitySchema.Builder removeChildSchema(String childName); EntitySchema.Builder clearChildSchemas(); /** * Create an {@link EntitySchema} using the current configuration on the builder. */ EntitySchema build(); } } /** * The schema for a specific entity value. This describes the entity child's structure, including what the Java-specific type * representation is for this value, etc. * * This is mostly an implementation detail, and can be ignored except by developers interested in creating * {@link EntityValueConverter}. */ @ThreadSafe public interface EntityValueSchema { /** * Create a builder for configuring and creating an {@link EntityValueSchema}s. */ static EntityValueSchema.Builder builder(); interface Builder { /** * Specify the Java-specific type representation for this type. */ EntityValueSchema.Builder javaType(Class<?> javaType); /** * The repository type of the value that this schema represents. */ EntityValueSchema.Builder entityValueType(EntityValueType entityValueType); /** * The converter that should be used for converting a value conforming to this schema to/from the * repository-specific type. */ EntityValueSchema.Builder converter(EntityValueConverter<?> converter); /** * Create an {@link EntityValueSchema} using the current configuration on the builder. */ EntityValueSchema build(); } }
3,070
0
Create_ds/aws-sdk-java-v2/docs/design/services/dynamodb/high-level-library/archive/20200103/prototype/option-1
Create_ds/aws-sdk-java-v2/docs/design/services/dynamodb/high-level-library/archive/20200103/prototype/option-1/sync/Prototype.java
/** * The entry-point for all DynamoDB client creation. All Java Dynamo features will be accessible through this single class. This * enables easy access to the different abstractions that the AWS SDK for Java provides (in exchange for a bigger JAR size). * * <p> * <b>Maven Module Location</b> * This would be in a separate maven module (software.amazon.awssdk:dynamodb-all) that depends on all other DynamoDB modules * (software.amazon.awssdk:dynamodb, software.amazon.awssdk:dynamodb-document). Customers that only want one specific client * could instead depend directly on the module that contains it. * </p> */ @ThreadSafe public interface DynamoDb { /** * Create a low-level DynamoDB client with default configuration. Equivalent to DynamoDbClient.create(). * Already GA in module software.amazon.awssdk:dynamodb. */ DynamoDbClient client(); /** * Create a low-level DynamoDB client builder. Equivalent to DynamoDbClient.builder(). * Already GA in module software.amazon.awssdk:dynamodb. */ DynamoDbClientBuilder clientBuilder(); /** * Create a high-level "document" DynamoDB client with default configuration. * * Usage Example: * <code> * try (DynamoDbDocumentClient client = DynamoDb.documentClient()) { * client.listTables().tables().forEach(System.out::println); * } * </code> * * @see DynamoDbDocumentClient */ DynamoDbDocumentClient documentClient(); /** * Create a high-level "document" DynamoDB client builder that can configure and create high-level "document" DynamoDB * clients. * * Usage Example: * <code> * try (DynamoDbClient lowLevelClient = DynamoDb.client(); * DynamoDbDocumentClient client = DynamoDb.documentClientBuilder() * .dynamoDbClient(lowLevelClient) * .build()) { * client.listTables().tables().forEach(System.out::println); * } * </code> * * @see DynamoDbDocumentClient.Builder */ DynamoDbDocumentClient.Builder documentClientBuilder(); } /** * A synchronous client for interacting with DynamoDB. While the low-level {@link DynamoDbClient} is generated from a service * model, this client is hand-written and provides a richer client experience for DynamoDB. * * Features: * <ol> * <li>Representations of DynamoDB resources, like {@link Table}s and {@link Item}s.</li> * <li>Support for Java-specific types, like {@link Instant} and {@link BigDecimal}.</li> * <li>Support for reading and writing custom objects (eg. Java Beans, POJOs).</li> * </ol> * * All {@link DynamoDbDocumentClient}s should be closed via {@link #close()}. */ @ThreadSafe public interface DynamoDbDocumentClient extends SdkAutoCloseable { /** * Create a {@link DynamoDbDocumentClient} with default configuration. * * Equivalent statements: * <ol> * <li>{@code DynamoDb.documentClient()}</li> * <li>{@code DynamoDb.documentClientBuilder().build()}</li> * <li>{@code DynamoDbDocumentClient.builder().build()}</li> * </ol> * * Usage Example: * <code> * try (DynamoDbDocumentClient client = DynamoDbDocumentClient.create()) { * client.listTables().table().forEach(System.out::println); * } * </code> */ static DynamoDbDocumentClient create(); /** * Create a {@link DynamoDbDocumentClient.Builder} that can be used to create a {@link DynamoDbDocumentClient} with custom * configuration. * * Equivalent to {@code DynamoDb.documentClientBuilder()}. * * Usage Example: * <code> * try (DynamoDbClient lowLevelClient = DynamoDbClient.create(); * DynamoDbDocumentClient client = DynamoDbDocumentClient.builder() * .dynamoDbClient(lowLevelClient) * .build()) { * client.listTables().tables().forEach(System.out::println); * } * </code> */ static DynamoDbDocumentClient.Builder builder(); /** * Create a Dynamo DB table that does not already exist. If the table exists already, use {@link #getTable(String)}. * * Usage Example: * <code> * try (DynamoDbDocumentClient client = DynamoDb.documentClient()) { * ProvisionedCapacity tableCapacity = ProvisionedCapacity.builder() * .readCapacity(5) * .writeCapacity(5) * .build(); * * KeySchema tableKeys = KeySchema.builder() * .putKey("partition-key", ItemAttributeIndexType.PARTITION_KEY) * .build(); * * client.createTable(CreateTableRequest.builder() * .tableName("my-table") * .provisionedCapacity(tableCapacity) * .keySchema(tableKeys) * .build()); * * System.out.println("Table created successfully."); * } catch (TableAlreadyExistsException e) { * System.out.println("Table creation failed."); * } * </code> */ CreateTableResponse createTable(CreateTableRequest createTableRequest) throws TableAlreadyExistsException; /** * Get a specific DynamoDB table, based on its table name. If the table does not exist, use {@link #createTable}. * * Usage Example: * <code> * try (DynamoDbDocumentClient client = DynamoDb.documentClient()) { * Table table = client.getTable("my-table"); * System.out.println(table); * } catch (NoSuchTableException e) { * System.out.println("Table does not exist."); * } * </code> */ Table getTable(String tableName) throws NoSuchTableException; /** * Get a lazily-populated iterable over all DynamoDB tables on the current account and region. * * Usage Example: * <code> * try (DynamoDbDocumentClient client = DynamoDb.documentClient()) { * String tables = client.listTables().tables().stream() * .map(Table::name) * .collect(Collectors.joining(",")); * System.out.println("Current Tables: " + tables); * } * </code> */ ListTablesResponse listTables(); /** * The builder for the high-level DynamoDB client. This is used by customers to configure the high-level client with default * values to be applied across all client operations. * * This can be created via {@link DynamoDb#documentClientBuilder()} or {@link DynamoDbDocumentClient#builder()}. */ interface Builder { /** * Configure the DynamoDB document client with a low-level DynamoDB client. * * Default: {@code DynamoDbClient.create()} */ DynamoDbDocumentClient.Builder dynamoDbClient(DynamoDbClient client); /** * Configure the DynamoDB document client with a specific set of configuration values that override the defaults. * * Default: {@code DocumentClientConfiguration.create()} */ DynamoDbDocumentClient.Builder documentClientConfiguration(DocumentClientConfiguration configuration); /** * Create a DynamoDB document client with all of the configured values. */ DynamoDbDocumentClient build(); } } /** * Configuration for a {@link DynamoDbDocumentClient}. This specific configuration is applied globally across all tables created * by a client builder. * * @see DynamoDbDocumentClient.Builder#documentClientConfiguration(DocumentClientConfiguration) */ @ThreadSafe public interface DocumentClientConfiguration { /** * Create document client configuration with default values. */ static DocumentClientConfiguration create(); /** * Create a builder instance, with an intent to override default values. */ static DocumentClientConfiguration.Builder builder(); interface Builder { /** * Configure the type converters that should be applied globally across all {@link Table}s from the client. This can * also be overridden at the Item level. * * The following type conversions are supported by default: * <ul> * <li>{@link Number} -> {@link ItemAttributeValueType#NUMBER}</li> * <li>{@link Temporal} -> {@link ItemAttributeValueType#NUMBER}</li> * <li>{@link CharSequence} -> {@link ItemAttributeValueType#STRING}</li> * <li>{@link UUID} -> {@link ItemAttributeValueType#STRING}</li> * <li>{@link byte[]} -> {@link ItemAttributeValueType#BYTES}</li> * <li>{@link ByteBuffer} -> {@link ItemAttributeValueType#BYTES}</li> * <li>{@link BytesWrapper} -> {@link ItemAttributeValueType#BYTES}</li> * <li>{@link InputStream} -> {@link ItemAttributeValueType#BYTES}</li> * <li>{@link File} -> {@link ItemAttributeValueType#BYTES}</li> * <li>{@link Boolean} -> {@link ItemAttributeValueType#BOOLEAN}</li> * <li>{@link Collection} -> {@link ItemAttributeValueType#LIST_OF_*}</li> * <li>{@link Stream} -> {@link ItemAttributeValueType#LIST_OF_*}</li> * <li>{@link Iterable} -> {@link ItemAttributeValueType#LIST_OF_*}</li> * <li>{@link Iterator} -> {@link ItemAttributeValueType#LIST_OF_*}</li> * <li>{@link Enumeration} -> {@link ItemAttributeValueType#LIST_OF_*}</li> * <li>{@link Optional} -> {@link ItemAttributeValue#*}</li> * <li>{@link Map} -> {@link ItemAttributeValueType#ITEM}</li> * <li>{@link Object} -> {@link ItemAttributeValueType#ITEM}</li> * <li>{@link null} -> {@link ItemAttributeValueType#NULL}</li> * </ul> * * Usage Example: * <code> * DocumentClientConfiguration clientConfiguration = * DocumentClientConfiguration.builder() * .addConverter(InstantsAsStringsConverter.create()) * .build(); * * try (DynamoDbDocumentClient client = DynamoDb.documentClientBuilder() * .documentClientConfiguration(clientConfiguration) * .build()) { * * Table table = client.getTable("my-table"); * UUID id = UUID.randomUUID(); * table.putItem(Item.builder() * .putAttribute("partition-key", id) * .putAttribute("creation-time", Instant.now()) * .build()); * * Item item = table.getItem(Item.builder() * .putAttribute("partition-key", id) * .build()); * * // Items are usually stored as a number, but it was stored as an ISO-8601 string now because of the * // InstantsAsStringsConverter. * assert item.attribute("creation-time").isString(); * assert item.attribute("creation-time").as(Instant.class).isBetween(Instant.now().minus(1, MINUTE), * Instant.now()); * } * </code> */ DocumentClientConfiguration.Builder converters(List<ItemAttributeValueConverter<?>> converters); DocumentClientConfiguration.Builder addConverter(ItemAttributeValueConverter<?> converter); DocumentClientConfiguration.Builder clearConverters(); /** * Create the configuration object client with all of the configured values. */ DocumentClientConfiguration build(); } } /** * A converter between Java types and DynamoDB types. These can be attached to {@link DynamoDbDocumentClient}s and * {@link Item}s, so that types are automatically converted when writing to and reading from DynamoDB. * * @see DocumentClientConfiguration.Builder#converters(List) * @see Item.Builder#converter(ItemAttributeValueConverter) * * @param T The Java type that is generated by this converter. */ @ThreadSafe public interface ItemAttributeValueConverter<T> { /** * The default condition in which this converter is invoked. * * Even if this condition is not satisfied, it can still be invoked directly via * {@link ItemAttributeValue#convert(ItemAttributeValueConverter)}. */ ConversionCondition defaultConversionCondition(); /** * Convert the provided Java type into an {@link ItemAttributeValue}. */ ItemAttributeValue toAttributeValue(T input, ConversionContext context); /** * Convert the provided {@link ItemAttributeValue} into a Java type. */ T fromAttributeValue(ItemAttributeValue input, ConversionContext context); } /** * The condition in which a {@link ItemAttributeValueConverter} will be invoked. * * @see ItemAttributeValueConverter#defaultConversionCondition(). */ @ThreadSafe public interface ConversionCondition { /** * Create a conversion condition that causes an {@link ItemAttributeValueConverter} to be invoked if an attribute value's * {@link ConversionContext} matches a specific condition. * * This condition has a larger overhead than the {@link #isInstanceOf(Class)} and {@link #never()}, because it must be * invoked for every attribute value being converted and its result cannot be cached. For this reason, lower-overhead * conditions like {@link #isInstanceOf(Class)} and {@link #never()} should be favored where performance is important. */ static ConversionCondition contextSatisfies(Predicate<ConversionContext> contextPredicate); /** * Create a conversion condition that causes an {@link ItemAttributeValueConverter} to be invoked if the attribute value's * Java type matches the provided class. * * The result of this condition can be cached, and will likely not be invoked for previously-converted types. */ static ConversionCondition isInstanceOf(Class<?> clazz); /** * Create a conversion condition that causes an {@link ItemAttributeValueConverter} to never be invoked by default, except * when directly invoked via {@link ItemAttributeValue#convert(ItemAttributeValueConverter)}. * * The result of this condition can be cached, and will likely not be invoked for previously-converted types. */ static ConversionCondition never(); } /** * Additional context that can be used in the context of converting between Java types and {@link ItemAttributeValue}s. * * @see ItemAttributeValueConverter#toAttributeValue(Object, ConversionContext) * @see ItemAttributeValueConverter#fromAttributeValue(ItemAttributeValue, ConversionContext) */ @ThreadSafe public interface ConversionContext { /** * The name of the attribute being converted. */ String attributeName(); /** * The schema of the attribute being converted. */ ItemAttributeSchema attributeSchema(); /** * The item that contains the attribute being converted. */ Item parent(); /** * The schema of the {@link #parent()}. */ ItemSchema parentSchema(); } /** * The result of invoking {@link DynamoDbDocumentClient#listTables()}. */ @ThreadSafe public interface ListTablesResponse { /** * A lazily-populated iterator over all tables in the current region. This may make multiple service calls in the * background when iterating over the full result set. */ SdkIterable<Table> tables(); } /** * A DynamoDB table, containing a collection of {@link Item}s. * * Currently supported operations: * <ul> * <li>Writing objects with {@link #putItem(Item)} and {@link #putObject(Object)}</li> * <li>Reading objects with {@link #getItem(Item)}} and {@link #getObject(Object)}</li> * <li>Accessing the current table configuration with {@link #metadata()}.</li> * <li>Creating new indexes with {@link #createGlobalSecondaryIndex(CreateGlobalSecondaryIndexRequest)}.</li> * </ul> * * The full version will all table operations, including Query, Delete, Update, Scan, etc. */ @ThreadSafe public interface Table { /** * Retrieve the name of this table. */ String name(); /** * Invoke DynamoDB to retrieve the metadata for this table. */ TableMetadata metadata(); /** * Invoke DynamoDB to create a new global secondary index for this table. * * Usage Example: * <code> * try (DynamoDbDocumentClient client = DynamoDb.documentClient()) { * ProvisionedCapacity indexCapacity = ProvisionedCapacity.builder() * .readCapacity(5) * .writeCapacity(5) * .build(); * * KeySchema indexKeys = KeySchema.builder() * .putKey("extra-partition-key", ItemAttributeIndexType.PARTITION_KEY) * .build(); * * Table table = client.getTable("my-table"); * * table.createGlobalSecondaryIndex(CreateGlobalSecondaryIndexRequest.builder() * .indexName("my-new-index") * .provisionedCapacity(tableCapacity) * .keySchema(tableKeys) * .build()); * } * </code> */ CreateGlobalSecondaryIndexResponse createGlobalSecondaryIndex(CreateGlobalSecondaryIndexRequest createRequest); /** * Invoke DynamoDB to create or override an {@link Item} in this table. * * This method is optimized for performance, and provides no additional response data. For additional options * like conditions or consumed capacity, see {@link #putItem(PutItemRequest)}. * * Usage Example: * <code> * try (DynamoDbDocumentClient client = DynamoDb.documentClient()) { * Table table = client.getTable("my-table"); * table.putItem(Item.builder() * .putAttribute("partition-key", UUID.randomUUID()) * .putAttribute("creation-time", Instant.now()) * .build()); * } * </code> */ void putItem(Item item); /** * Invoke DynamoDB to create or override an {@link Item} in this table. * * This method provides more options than {@link #putItem(Item)}, like conditions or consumed capacity. * * Usage Example: * <code> * try (DynamoDbDocumentClient client = DynamoDb.documentClient()) { * Table table = client.getTable("my-table"); * table.putItem(PutItemRequest.builder() * .item(Item.builder() * .putAttribute("partition-key", "key") * .putAttribute("version", 2) * .build()) * .condition("version = :expected_version") * .putConditionAttribute(":expected_version", 1) * .build()); * } catch (ConditionFailedException e) { * System.out.println("Precondition failed."); * throw e; * } * </code> */ PutItemResponse putItem(PutItemRequest putRequest) throws ConditionFailedException; /** * Invoke DynamoDB to create or override an Item in this table. * * This will convert the provided object into an {@link Item} automatically using the default Object-to-Item * {@link ItemAttributeValueConverter}, unless an alternate converter has been overridden for the provided type. * * This method is optimized for performance, and provides no additional response data. For additional options * like conditions or consumed capacity, see {@link #putObject(PutObjectRequest)}. * * Usage Example: * <code> * public class MyItem { * @Attribute("partition-key") * @Index(AttributeIndexType.PARTITION_KEY) * private String partitionKey; * * @Attribute("creation-time") * private Instant creationTime; * * public String getPartitionKey() { return this.partitionKey; } * public Instant getCreationTime() { return this.creationTime; } * public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } * public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } * } * * try (DynamoDbDocumentClient client = DynamoDb.documentClient()) { * Table table = client.getTable("my-table"); * * MyItem myItem = new MyItem(); * myItem.setPartitionKey(UUID.randomUUID()); * myItem.setCreationTime(Instant.now()); * * table.putObject(myItem); * } * </code> */ void putObject(Object item); /** * Invoke DynamoDB to create or override an Item in this table. * * This will convert the provided object into an {@link Item} automatically using the default Object-to-Item * {@link ItemAttributeValueConverter}, unless an alternate converter has been overridden for the provided type. * * This method provides more options than {@link #putObject(Object)} like conditions or consumed capacity. * * Usage Example: * <code> * public class MyItem { * @Attribute("partition-key") * @Index(AttributeIndexType.PARTITION_KEY) * private String partitionKey; * * @Attribute * private int version; * * public String getPartitionKey() { return this.partitionKey; } * public int getVersion() { return this.version; } * public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } * public void setVersion(int version) { this.version = version; } * } * * try (DynamoDbDocumentClient client = DynamoDb.documentClient()) { * Table table = client.getTable("my-table"); * * MyItem myItem = new MyItem(); * myItem.setPartitionKey(UUID.randomUUID()); * myItem.setVersion(2); * * table.putObject(PutObjectRequest.builder(myItem) * .condition("version = :expected_version") * .putConditionAttribute(":expected_version", 1) * .build()); * } catch (ConditionFailedException e) { * System.out.println("Precondition failed."); * throw e; * } * </code> */ <T> PutObjectResponse<T> putObject(PutObjectRequest<T> putRequest) throws ConditionFailedException; /** * Invoke DynamoDB to retrieve an Item in this table, based on its partition key (and sort key, if the table has one). * * This method is optimized for performance, and provides no additional response data. For additional options * like consistent reads, see {@link #getItem(GetItemRequest)}. * * Usage Example: * <code> * try (DynamoDbDocumentClient client = DynamoDb.documentClient()) { * Table table = client.getTable("my-table"); * UUID id = UUID.randomUUID(); * table.putItem(Item.builder() * .putAttribute("partition-key", id) * .putAttribute("creation-time", Instant.now()) * .build()); * * // Wait a little bit, because getItem is eventually consistent by default. * Thread.sleep(5_000); * * Item item = table.getItem(Item.builder() * .putAttribute("partition-key", id) * .build()); * * // Times are stored as numbers, by default, so they can also be used as sort keys. * assert item.attribute("creation-time").isNumber(); * assert item.attribute("creation-time").as(Instant.class).isBetween(Instant.now().minus(1, MINUTE), * Instant.now()); * } catch (NoSuchItemException e) { * System.out.println("Item could not be found. Maybe we didn't wait long enough for consistency?"); * throw e; * } * </code> */ Item getItem(Item item) throws NoSuchItemException; /** * Invoke DynamoDB to retrieve an Item in this table, based on its partition key (and sort key, if table has one). * * This method provides more options than {@link #getItem(Item)}, like whether reads should be consistent. * * Usage Example: * <code> * try (DynamoDbDocumentClient client = DynamoDb.documentClient()) { * Table table = client.getTable("my-table"); * UUID id = UUID.randomUUID(); * table.putItem(Item.builder() * .putAttribute("partition-key", id) * .putAttribute("creation-time", Instant.now()) * .build()); * * GetItemResponse response = * table.getItem(GetItemRequest.builder() * .item(Item.builder() * .putAttribute("partition-key", id) * .build()) * .consistentRead(true) * .build()); * * // Times are stored as numbers, by default, so they can also be used as sort keys. * assert response.item().attribute("creation-time").isNumber(); * assert response.item().attribute("creation-time").as(Instant.class).isBetween(Instant.now().minus(1, MINUTE), * Instant.now()); * } catch (NoSuchItemException e) { * System.out.println("Item was deleted between creation and retrieval."); * throw e; * } * </code> */ GetItemResponse getItem(GetItemRequest getRequest) throws NoSuchItemException; /** * Invoke DynamoDB to retrieve an Item in this table. * * This will use the partition and sort keys from the provided object and convert the DynamoDB response to a Java object * automatically using the default Object-to-Item {@link ItemAttributeValueConverter}, unless an alternate converter * has been overridden for the provided type. * * This method is optimized for performance, and provides no additional response data. For additional options * like consistent reads, see {@link #getObject(GetObjectRequest)}. * * Usage Example: * <code> * public class MyItem { * @Attribute("partition-key") * @Index(AttributeIndexType.PARTITION_KEY) * private String partitionKey; * * @Attribute("creation-time") * private Instant creationTime; * * public String getPartitionKey() { return this.partitionKey; } * public Instant getCreationTime() { return this.creationTime; } * public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } * public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } * } * * try (DynamoDbDocumentClient client = DynamoDb.documentClient()) { * Table table = client.getTable("my-table"); * * UUID id = UUID.randomUUID(); * * MyItem itemToCreate = new MyItem(); * itemToCreate.setPartitionKey(id); * itemToCreate.setCreationTime(Instant.now()); * * table.putObject(itemToCreate); * * // Wait a little bit, because getObject is eventually consistent by default. * Thread.sleep(5_000); * * MyItem itemToRetrieve = new MyItem(); * itemToRetrieve.setPartitionKey(id); * * MyItem retrievedItem = table.getObject(itemToRetrieve); * assert retrievedItem.getCreationTime().isBetween(Instant.now().minus(1, MINUTE), * Instant.now()); * } catch (NoSuchItemException e) { * System.out.println("Item could not be found. Maybe we didn't wait long enough for consistency?"); * throw e; * } * </code> */ <T> T getObject(T item) throws NoSuchItemException; /** * Invoke DynamoDB to retrieve an Item in this table. * * This will use the partition and sort keys from the provided object and convert the DynamoDB response to a Java object * automatically using the default Object-to-Item {@link ItemAttributeValueConverter}, unless an alternate converter * has been overridden for the provided type. * * This method provides more options than {@link #getObject(GetObjectRequest)}, like whether reads should be consistent. * * Usage Example: * <code> * public class MyItem { * @Attribute("partition-key") * @Index(AttributeIndexType.PARTITION_KEY) * private String partitionKey; * * @Attribute("creation-time") * private Instant creationTime; * * public String getPartitionKey() { return this.partitionKey; } * public Instant getCreationTime() { return this.creationTime; } * public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } * public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } * } * * try (DynamoDbDocumentClient client = DynamoDb.documentClient()) { * Table table = client.getTable("my-table"); * * UUID id = UUID.randomUUID(); * * MyItem itemToCreate = new MyItem(); * itemToCreate.setPartitionKey(id); * itemToCreate.setCreationTime(Instant.now()); * * table.putObject(itemToCreate); * * MyItem itemToRetrieve = new MyItem(); * itemToRetrieve.setPartitionKey(id); * * GetObjectResponse<MyItem> response = table.getObject(GetObjectRequest.builder(itemToRetrieve) * .consistentReads(true) * .build()); * MyItem retrievedItem = response.item(); * assert retrievedItem.getCreationTime().isBetween(Instant.now().minus(1, MINUTE), * Instant.now()); * } catch (NoSuchItemException e) { * System.out.println("Item was deleted between creation and retrieval."); * throw e; * } * </code> */ <T> GetObjectResponse<T> getObject(GetObjectRequest<T> getRequest) throws NoSuchItemException; } /** * Additional information about a {@link Table}, retrieved via {@link Table#metadata()}. */ @ThreadSafe public interface TableMetadata { /** * All global secondary indexes that can be used for querying or retrieving from the table. */ List<GlobalSecondaryIndexMetadata> globalSecondaryIndexMetadata(); /** * All local secondary indexes that can be used for querying or retrieving from the table. */ List<LocalSecondaryIndexMetadata> localSecondaryIndexMetadata(); } /** * An item in a {@link Table}. This is similar to a "row" in a traditional relational database. * * In the following table, { "User ID": 1, "Username": "joe" } is an item: * * <pre> * Table: Users * | ------------------ | * | User ID | Username | * | ------------------ | * | 1 | joe | * | 2 | jane | * | ------------------ | * </pre> */ @ThreadSafe public interface Item { /** * Create a builder for configuring and creating a {@link Item}. */ static Item.Builder builder(); /** * Retrieve all {@link ItemAttributeValue}s in this item. */ Map<String, ItemAttributeValue> attributes(); /** * Retrieve a specific attribute from this item. */ ItemAttributeValue attribute(String attributeKey); interface Builder { /** * Add an attribute to this item. The methods accepting "Object", will be converted using the default * {@link ItemAttributeValueConverter}s. */ Item.Builder putAttribute(String attributeKey, ItemAttributeValue attributeValue); Item.Builder putAttribute(String attributeKey, ItemAttributeValue attributeValue, ItemAttributeSchema attributeSchema); Item.Builder putAttribute(String attributeKey, Object attributeValue); Item.Builder putAttribute(String attributeKey, Object attributeValue, ItemAttributeSchema attributeSchema); Item.Builder removeAttribute(String attributeKey); Item.Builder clearAttributes(); /** * Add converters that should be used for this item and its attributes. These converters are used with a higher * precidence than those configured in the {@link DocumentClientConfiguration}. * * See {@link DocumentClientConfiguration.Builder#addConverter(ItemAttributeValueConverter)} for example usage. */ Item.Builder converters(List<ItemAttributeValueConverter<?>> converters); Item.Builder addConverter(ItemAttributeValueConverter<?> converter); Item.Builder clearConverters(); /** * Create an {@link Item} using the current configuration on the builder. */ Item build(); } } /** * The value of an attribute within an {@link Item}. In a traditional relational database, this would be analogous to a cell * in the table. * * In the following table, "joe" and "jane" are both attribute values: * <pre> * Table: Users * | ------------------ | * | User ID | Username | * | ------------------ | * | 1 | joe | * | 2 | jane | * | ------------------ | * </pre> */ @ThreadSafe public interface ItemAttributeValue { /** * Create an {@link ItemAttributeValue} from the provided object. */ static ItemAttributeValue from(Object object); /** * Create an {@link ItemAttributeValue} from the provided object, and associate this value with the provided * {@link ItemAttributeValueConverter}. This allows it to be immediately converted with {@link #as(Class)}. * * This is equivalent to {@code ItemAttributeValue.from(object).convertFromJavaType(converter)}. */ static ItemAttributeValue from(Object object, ItemAttributeValueConverter<?> converter); /** * Create an {@link ItemAttributeValue} that represents the DynamoDB-specific null type. */ static ItemAttributeValue nullValue(); /** * Convert this item attribute value into the requested Java type. * * This uses the {@link ItemAttributeValueConverter} configured on this type via * {@link #from(Object, ItemAttributeValueConverter)} or {@link #convertFromJavaType(ItemAttributeValueConverter)}. */ <T> T as(Class<T> type); /** * Retrieve the {@link ItemAttributeValueType} of this value. */ ItemAttributeValueType type(); /** * The {@code is*} methods can be used to check the underlying DynamoDB-specific type of the attribute value. * * If the type isn't known (eg. because it was created via {@link ItemAttributeValue#from(Object)}), {@link #isJavaType()} * will return true. Such types will be converted into DynamoDB-specific types by the document client before they are * persisted. */ boolean isItem(); boolean isString(); boolean isNumber(); boolean isBytes(); boolean isBoolean(); boolean isListOfStrings(); boolean isListOfNumbers(); boolean isListOfBytes(); boolean isListOfAttributeValues(); boolean isNull(); boolean isJavaType(); /** * The {@code as*} methods can be used to retrieve this value without the overhead of type conversion of {@link #as(Class)}. * * An exception will be thrown from these methods if the requested type does not match the actual underlying type. When * the type isn't know, the {@code is*} or {@link #type()} methods can be used to query the underlying type before * invoking these {@code as*} methods. */ Item asItem(); String asString(); BigDecimal asNumber(); SdkBytes asBytes(); Boolean asBoolean(); List<String> asListOfStrings(); List<BigDecimal> asListOfNumbers(); List<SdkBytes> asListOfBytes(); List<ItemAttributeValue> asListOfAttributeValues(); Object asJavaType(); /** * Convert this attribute value from a {@link ItemAttributeValueType#JAVA_TYPE} to a type that can be persisted in DynamoDB. * * This will throw an exception if {@link #isJavaType()} is false. */ ItemAttributeValue convertFromJavaType(ItemAttributeValueConverter<?> converter); } /** * The schema for a specific item. This describes the item's structure and which attributes it contains. * * This is mostly an implementation detail, and can be ignored except by developers interested in creating * {@link ItemAttributeValueConverter}. */ @ThreadSafe public interface ItemSchema { /** * Create a builder for configuring and creating an {@link ItemSchema}. */ static ItemSchema.Builder builder(); interface Builder { /** * Specify the attribute schemas that describe each attribute of this item. */ ItemSchema.Builder attributeSchemas(Map<String, ItemAttributeSchema> attributeSchemas); ItemSchema.Builder putAttributeSchema(String attributeName, ItemAttributeSchema attributeSchema); ItemSchema.Builder removeAttributeSchema(String attributeName); ItemSchema.Builder clearAttributeSchemas(); /** * The converter that should be used for converting all items that conform to this schema. */ ItemSchema.Builder converter(ItemAttributeValueConverter<?> converter); /** * Create an {@link ItemSchema} using the current configuration on the builder. */ ItemSchema build(); } } /** * The schema for a specific item attribute. This describes the attribute's structure, including whether it is known to be an * index, what the Java-specific type representation is for this attribute, etc. * * This is mostly an implementation detail, and can be ignored except by developers interested in creating * {@link ItemAttributeValueConverter}. */ @ThreadSafe public interface ItemAttributeSchema { /** * Create a builder for configuring and creating an {@link ItemAttributeSchema}. */ static ItemAttributeSchema.Builder builder(); interface Builder { /** * Specify whether this field is known to be an index. */ ItemAttributeSchema.Builder indexType(AttributeIndexType attributeIndexType); /** * Specify the Java-specific type representation for this type. */ ItemAttributeSchema.Builder javaType(Class<?> attributeJavaType); /** * The DynamoDB-specific type representation for this type. */ ItemAttributeSchema.Builder dynamoType(ItemAttributeValueType attributeDynamoType); /** * The converter that should be used for converting all items that conform to this schema. */ ItemAttributeSchema.Builder converter(ItemAttributeValueConverter<?> converter); /** * Create an {@link ItemAttributeSchema} using the current configuration on the builder. */ ItemAttributeSchema build(); } } /** * The index type of an {@link ItemAttributeValue}. */ @ThreadSafe public enum ItemAttributeIndexType { PARTITION_KEY, SORT_KEY, NOT_AN_INDEX } /** * The underlying type of an {@link ItemAttributeValue}. */ @ThreadSafe public enum ItemAttributeValueType { ITEM, STRING, NUMBER, BYTES, BOOLEAN, LIST_OF_STRINGS, LIST_OF_NUMBERS, LIST_OF_BYTES, LIST_OF_ATTRIBUTE_VALUES, NULL, JAVA_TYPE }
3,071
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/eventstream/defaultinputeventone.java
package software.amazon.awssdk.services.json.model.inputeventstreamtwo; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.json.model.InputEvent; import software.amazon.awssdk.services.json.model.InputEventStreamTwo; /** * A specialization of {@code software.amazon.awssdk.services.json.model.InputEvent} that represents the * {@code InputEventStreamTwo$InputEventOne} event. Do not use this class directly. Instead, use the static builder * methods on {@link software.amazon.awssdk.services.json.model.InputEventStreamTwo}. */ @SdkInternalApi @Generated("software.amazon.awssdk:codegen") public final class DefaultInputEventOne extends InputEvent { private static final long serialVersionUID = 1L; DefaultInputEventOne(BuilderImpl builderImpl) { super(builderImpl); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } @Override public InputEventStreamTwo.EventType sdkEventType() { return InputEventStreamTwo.EventType.INPUT_EVENT_ONE; } public interface Builder extends InputEvent.Builder { @Override DefaultInputEventOne build(); } private static final class BuilderImpl extends InputEvent.BuilderImpl implements Builder { private BuilderImpl() { } private BuilderImpl(DefaultInputEventOne event) { super(event); } @Override public DefaultInputEventOne build() { return new DefaultInputEventOne(this); } } }
3,072
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/eventstream/defaultsecondeventone.java
package software.amazon.awssdk.services.json.model.eventstream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.json.model.EventOne; import software.amazon.awssdk.services.json.model.EventStream; import software.amazon.awssdk.services.json.model.EventStreamOperationResponseHandler; import software.amazon.awssdk.services.json.model.EventStreamOperationWithOnlyOutputResponseHandler; /** * A specialization of {@code software.amazon.awssdk.services.json.model.EventOne} that represents the * {@code EventStream$secondEventOne} event. Do not use this class directly. Instead, use the static builder methods on * {@link software.amazon.awssdk.services.json.model.EventStream}. */ @SdkInternalApi @Generated("software.amazon.awssdk:codegen") public final class DefaultSecondEventOne extends EventOne { private static final long serialVersionUID = 1L; DefaultSecondEventOne(BuilderImpl builderImpl) { super(builderImpl); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } @Override public void accept(EventStreamOperationResponseHandler.Visitor visitor) { visitor.visitSecondEventOne(this); } @Override public void accept(EventStreamOperationWithOnlyOutputResponseHandler.Visitor visitor) { visitor.visitSecondEventOne(this); } @Override public EventStream.EventType sdkEventType() { return EventStream.EventType.SECOND_EVENT_ONE; } public interface Builder extends EventOne.Builder { @Override DefaultSecondEventOne build(); } private static final class BuilderImpl extends EventOne.BuilderImpl implements Builder { private BuilderImpl() { } private BuilderImpl(DefaultSecondEventOne event) { super(event); } @Override public DefaultSecondEventOne build() { return new DefaultSecondEventOne(this); } } }
3,073
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/eventstream/defaulteventtwo.java
package software.amazon.awssdk.services.json.model.eventstream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.json.model.EventStream; import software.amazon.awssdk.services.json.model.EventStreamOperationResponseHandler; import software.amazon.awssdk.services.json.model.EventStreamOperationWithOnlyOutputResponseHandler; import software.amazon.awssdk.services.json.model.EventTwo; /** * A specialization of {@code software.amazon.awssdk.services.json.model.EventTwo} that represents the * {@code EventStream$EventTwo} event. Do not use this class directly. Instead, use the static builder methods on * {@link software.amazon.awssdk.services.json.model.EventStream}. */ @SdkInternalApi @Generated("software.amazon.awssdk:codegen") public final class DefaultEventTwo extends EventTwo { private static final long serialVersionUID = 1L; DefaultEventTwo(BuilderImpl builderImpl) { super(builderImpl); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } @Override public void accept(EventStreamOperationResponseHandler.Visitor visitor) { visitor.visitEventTwo(this); } @Override public void accept(EventStreamOperationWithOnlyOutputResponseHandler.Visitor visitor) { visitor.visitEventTwo(this); } @Override public EventStream.EventType sdkEventType() { return EventStream.EventType.EVENT_TWO; } public interface Builder extends EventTwo.Builder { @Override DefaultEventTwo build(); } private static final class BuilderImpl extends EventTwo.BuilderImpl implements Builder { private BuilderImpl() { } private BuilderImpl(DefaultEventTwo event) { super(event); } @Override public DefaultEventTwo build() { return new DefaultEventTwo(this); } } }
3,074
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/eventstream/test-visitor-builder.java
package software.amazon.awssdk.services.json.model; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi final class DefaultEventStreamOperationVisitorBuilder implements EventStreamOperationResponseHandler.Visitor.Builder { private Consumer<EventStream> onDefault; private Consumer<EventOne> onEventOne; private Consumer<EventTwo> onEventTheSecond; private Consumer<EventOne> onSecondEventOne; private Consumer<LegacyEventThree> onLegacyEventThree; @Override public EventStreamOperationResponseHandler.Visitor.Builder onDefault(Consumer<EventStream> c) { this.onDefault = c; return this; } @Override public EventStreamOperationResponseHandler.Visitor build() { return new VisitorFromBuilder(this); } @Override public EventStreamOperationResponseHandler.Visitor.Builder onEventOne(Consumer<EventOne> c) { this.onEventOne = c; return this; } @Override public EventStreamOperationResponseHandler.Visitor.Builder onEventTheSecond(Consumer<EventTwo> c) { this.onEventTheSecond = c; return this; } @Override public EventStreamOperationResponseHandler.Visitor.Builder onSecondEventOne(Consumer<EventOne> c) { this.onSecondEventOne = c; return this; } @Override public EventStreamOperationResponseHandler.Visitor.Builder onLegacyEventThree(Consumer<LegacyEventThree> c) { this.onLegacyEventThree = c; return this; } @Generated("software.amazon.awssdk:codegen") static class VisitorFromBuilder implements EventStreamOperationResponseHandler.Visitor { private final Consumer<EventStream> onDefault; private final Consumer<EventOne> onEventOne; private final Consumer<EventTwo> onEventTheSecond; private final Consumer<EventOne> onSecondEventOne; private final Consumer<LegacyEventThree> onLegacyEventThree; VisitorFromBuilder(DefaultEventStreamOperationVisitorBuilder builder) { this.onDefault = builder.onDefault != null ? builder.onDefault : EventStreamOperationResponseHandler.Visitor.super::visitDefault; this.onEventOne = builder.onEventOne != null ? builder.onEventOne : EventStreamOperationResponseHandler.Visitor.super::visit; this.onEventTheSecond = builder.onEventTheSecond != null ? builder.onEventTheSecond : EventStreamOperationResponseHandler.Visitor.super::visitEventTheSecond; this.onSecondEventOne = builder.onSecondEventOne != null ? builder.onSecondEventOne : EventStreamOperationResponseHandler.Visitor.super::visitSecondEventOne; this.onLegacyEventThree = builder.onLegacyEventThree != null ? builder.onLegacyEventThree : EventStreamOperationResponseHandler.Visitor.super::visit; } @Override public void visitDefault(EventStream event) { onDefault.accept(event); } @Override public void visit(EventOne event) { onEventOne.accept(event); } @Override public void visitEventTheSecond(EventTwo event) { onEventTheSecond.accept(event); } @Override public void visitSecondEventOne(EventOne event) { onSecondEventOne.accept(event); } @Override public void visit(LegacyEventThree event) { onLegacyEventThree.accept(event); } } }
3,075
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/eventstream/defaultinputevent.java
package software.amazon.awssdk.services.json.model.inputeventstream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.json.model.InputEvent; import software.amazon.awssdk.services.json.model.InputEventStream; /** * A specialization of {@code software.amazon.awssdk.services.json.model.InputEvent} that represents the * {@code InputEventStream$InputEvent} event. Do not use this class directly. Instead, use the static builder methods on * {@link software.amazon.awssdk.services.json.model.InputEventStream}. */ @SdkInternalApi @Generated("software.amazon.awssdk:codegen") public final class DefaultInputEvent extends InputEvent { private static final long serialVersionUID = 1L; DefaultInputEvent(BuilderImpl builderImpl) { super(builderImpl); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } @Override public InputEventStream.EventType sdkEventType() { return InputEventStream.EventType.INPUT_EVENT; } public interface Builder extends InputEvent.Builder { @Override DefaultInputEvent build(); } private static final class BuilderImpl extends InputEvent.BuilderImpl implements Builder { private BuilderImpl() { } private BuilderImpl(DefaultInputEvent event) { super(event); } @Override public DefaultInputEvent build() { return new DefaultInputEvent(this); } } }
3,076
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/eventstream/test-response-handler.java
package software.amazon.awssdk.services.json.model; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.awscore.eventstream.EventStreamResponseHandler; /** * Response handler for the EventStreamOperation API. */ @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public interface EventStreamOperationResponseHandler extends EventStreamResponseHandler<EventStreamOperationResponse, EventStream> { /** * Create a {@link Builder}, used to create a {@link EventStreamOperationResponseHandler}. */ static Builder builder() { return new DefaultEventStreamOperationResponseHandlerBuilder(); } /** * Builder for {@link EventStreamOperationResponseHandler}. This can be used to create the * {@link EventStreamOperationResponseHandler} in a more functional way, you may also directly implement the * {@link EventStreamOperationResponseHandler} interface if preferred. */ @Generated("software.amazon.awssdk:codegen") interface Builder extends EventStreamResponseHandler.Builder<EventStreamOperationResponse, EventStream, Builder> { /** * Sets the subscriber to the {@link org.reactivestreams.Publisher} of events. The given {@link Visitor} will be * called for each event received by the publisher. Events are requested sequentially after each event is * processed. If you need more control over the backpressure strategy consider using * {@link #subscriber(java.util.function.Supplier)} instead. * * @param visitor * Visitor that will be invoked for each incoming event. * @return This builder for method chaining */ Builder subscriber(Visitor visitor); /** * @return A {@link EventStreamOperationResponseHandler} implementation that can be used in the * EventStreamOperation API call. */ EventStreamOperationResponseHandler build(); } /** * Visitor for subtypes of {@link EventStream}. */ @Generated("software.amazon.awssdk:codegen") interface Visitor { /** * @return A new {@link Builder}. */ static Builder builder() { return new DefaultEventStreamOperationVisitorBuilder(); } /** * A required "else" or "default" block, invoked when no other more-specific "visit" method is appropriate. This * is invoked under two circumstances: * <ol> * <li>The event encountered is newer than the current version of the SDK, so no other more-specific "visit" * method could be called. In this case, the provided event will be a generic {@link EventStream}. These events * can be processed by upgrading the SDK.</li> * <li>The event is known by the SDK, but the "visit" was not overridden above. In this case, the provided event * will be a specific type of {@link EventStream}.</li> * </ol> * * @param event * The event that was not handled by a more-specific "visit" method. */ default void visitDefault(EventStream event) { } /** * Invoked when a {@link EventOne} is encountered. If this is not overridden, the event will be given to * {@link #visitDefault(EventStream)}. * * @param event * Event being visited */ default void visit(EventOne event) { visitDefault(event); } /** * Invoked when a {@link EventTwo} is encountered. If this is not overridden, the event will be given to * {@link #visitDefault(EventStream)}. * * @param event * Event being visited */ default void visitEventTheSecond(EventTwo event) { visitDefault(event); } /** * Invoked when a {@link EventOne} is encountered. If this is not overridden, the event will be given to * {@link #visitDefault(EventStream)}. * * @param event * Event being visited */ default void visitSecondEventOne(EventOne event) { visitDefault(event); } /** * Invoked when a {@link LegacyEventThree} is encountered. If this is not overridden, the event will be given to * {@link #visitDefault(EventStream)}. * * @param event * Event being visited */ default void visit(LegacyEventThree event) { visitDefault(event); } /** * Builder for {@link Visitor}. The {@link Visitor} class may also be extended for a more traditional style but * this builder allows for a more functional way of creating a visitor will callback methods. */ @Generated("software.amazon.awssdk:codegen") interface Builder { /** * Callback to invoke when either an unknown event is visited or an unhandled event is visited. * * @param c * Callback to process the event. * @return This builder for method chaining. */ Builder onDefault(Consumer<EventStream> c); /** * @return Visitor implementation. */ Visitor build(); /** * Callback to invoke when a {@link EventOne} is visited. * * @param c * Callback to process the event. * @return This builder for method chaining. */ Builder onEventOne(Consumer<EventOne> c); /** * Callback to invoke when a {@link EventTwo} is visited. * * @param c * Callback to process the event. * @return This builder for method chaining. */ Builder onEventTheSecond(Consumer<EventTwo> c); /** * Callback to invoke when a {@link EventOne} is visited. * * @param c * Callback to process the event. * @return This builder for method chaining. */ Builder onSecondEventOne(Consumer<EventOne> c); /** * Callback to invoke when a {@link LegacyEventThree} is visited. * * @param c * Callback to process the event. * @return This builder for method chaining. */ Builder onLegacyEventThree(Consumer<LegacyEventThree> c); } } }
3,077
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/eventstream/defaulteventone.java
package software.amazon.awssdk.services.json.model.eventstream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.json.model.EventOne; import software.amazon.awssdk.services.json.model.EventStream; import software.amazon.awssdk.services.json.model.EventStreamOperationResponseHandler; import software.amazon.awssdk.services.json.model.EventStreamOperationWithOnlyOutputResponseHandler; /** * A specialization of {@code software.amazon.awssdk.services.json.model.EventOne} that represents the * {@code EventStream$EventOne} event. Do not use this class directly. Instead, use the static builder methods on * {@link software.amazon.awssdk.services.json.model.EventStream}. */ @SdkInternalApi @Generated("software.amazon.awssdk:codegen") public final class DefaultEventOne extends EventOne { private static final long serialVersionUID = 1L; DefaultEventOne(BuilderImpl builderImpl) { super(builderImpl); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } @Override public void accept(EventStreamOperationResponseHandler.Visitor visitor) { visitor.visitEventOne(this); } @Override public void accept(EventStreamOperationWithOnlyOutputResponseHandler.Visitor visitor) { visitor.visitEventOne(this); } @Override public EventStream.EventType sdkEventType() { return EventStream.EventType.EVENT_ONE; } public interface Builder extends EventOne.Builder { @Override DefaultEventOne build(); } private static final class BuilderImpl extends EventOne.BuilderImpl implements Builder { private BuilderImpl() { } private BuilderImpl(DefaultEventOne event) { super(event); } @Override public DefaultEventOne build() { return new DefaultEventOne(this); } } }
3,078
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/eventstream/defaultsecondeventtwo.java
package software.amazon.awssdk.services.json.model.eventstream; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.json.model.EventStream; import software.amazon.awssdk.services.json.model.EventStreamOperationResponseHandler; import software.amazon.awssdk.services.json.model.EventStreamOperationWithOnlyOutputResponseHandler; import software.amazon.awssdk.services.json.model.EventTwo; /** * A specialization of {@code software.amazon.awssdk.services.json.model.EventTwo} that represents the * {@code EventStream$secondeventtwo} event. Do not use this class directly. Instead, use the static builder methods on * {@link software.amazon.awssdk.services.json.model.EventStream}. */ @SdkInternalApi @Generated("software.amazon.awssdk:codegen") public final class DefaultSecondeventtwo extends EventTwo { private static final long serialVersionUID = 1L; DefaultSecondeventtwo(BuilderImpl builderImpl) { super(builderImpl); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } @Override public void accept(EventStreamOperationResponseHandler.Visitor visitor) { visitor.visitSecondeventtwo(this); } @Override public void accept(EventStreamOperationWithOnlyOutputResponseHandler.Visitor visitor) { visitor.visitSecondeventtwo(this); } @Override public EventStream.EventType sdkEventType() { return EventStream.EventType.SECONDEVENTTWO; } public interface Builder extends EventTwo.Builder { @Override DefaultSecondeventtwo build(); } private static final class BuilderImpl extends EventTwo.BuilderImpl implements Builder { private BuilderImpl() { } private BuilderImpl(DefaultSecondeventtwo event) { super(event); } @Override public DefaultSecondeventtwo build() { return new DefaultSecondeventtwo(this); } } }
3,079
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/eventstream/test-response-handler-builder.java
package software.amazon.awssdk.services.json.model; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.eventstream.DefaultEventStreamResponseHandlerBuilder; import software.amazon.awssdk.awscore.eventstream.EventStreamResponseHandlerFromBuilder; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi final class DefaultEventStreamOperationResponseHandlerBuilder extends DefaultEventStreamResponseHandlerBuilder<EventStreamOperationResponse, EventStream, EventStreamOperationResponseHandler.Builder> implements EventStreamOperationResponseHandler.Builder { @Override public EventStreamOperationResponseHandler.Builder subscriber(EventStreamOperationResponseHandler.Visitor visitor) { subscriber(e -> e.accept(visitor)); return this; } @Override public EventStreamOperationResponseHandler build() { return new Impl(this); } @Generated("software.amazon.awssdk:codegen") private static final class Impl extends EventStreamResponseHandlerFromBuilder<EventStreamOperationResponse, EventStream> implements EventStreamOperationResponseHandler { private Impl(DefaultEventStreamOperationResponseHandlerBuilder builder) { super(builder); } } }
3,080
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/eventstream/defaultinputeventtwo.java
package software.amazon.awssdk.services.json.model.inputeventstreamtwo; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.json.model.InputEventStreamTwo; import software.amazon.awssdk.services.json.model.InputEventTwo; /** * A specialization of {@code software.amazon.awssdk.services.json.model.InputEventTwo} that represents the * {@code InputEventStreamTwo$InputEventTwo} event. Do not use this class directly. Instead, use the static builder * methods on {@link software.amazon.awssdk.services.json.model.InputEventStreamTwo}. */ @SdkInternalApi @Generated("software.amazon.awssdk:codegen") public final class DefaultInputEventTwo extends InputEventTwo { private static final long serialVersionUID = 1L; DefaultInputEventTwo(BuilderImpl builderImpl) { super(builderImpl); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } @Override public InputEventStreamTwo.EventType sdkEventType() { return InputEventStreamTwo.EventType.INPUT_EVENT_TWO; } public interface Builder extends InputEventTwo.Builder { @Override DefaultInputEventTwo build(); } private static final class BuilderImpl extends InputEventTwo.BuilderImpl implements Builder { private BuilderImpl() { } private BuilderImpl(DefaultInputEventTwo event) { super(event); } @Override public DefaultInputEventTwo build() { return new DefaultInputEventTwo(this); } } }
3,081
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/paginators/PaginatedOperationWithoutResultKeyPublisher.java
package software.amazon.awssdk.services.jsonprotocoltests.paginators; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.pagination.async.AsyncPageFetcher; import software.amazon.awssdk.core.pagination.async.ResponsesSubscription; import software.amazon.awssdk.core.util.PaginatorUtils; import software.amazon.awssdk.services.jsonprotocoltests.JsonProtocolTestsAsyncClient; import software.amazon.awssdk.services.jsonprotocoltests.internal.UserAgentUtils; import software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithoutResultKeyRequest; import software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithoutResultKeyResponse; /** * <p> * Represents the output for the * {@link software.amazon.awssdk.services.jsonprotocoltests.JsonProtocolTestsAsyncClient#paginatedOperationWithoutResultKeyPaginator(software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithoutResultKeyRequest)} * operation which is a paginated operation. This class is a type of {@link org.reactivestreams.Publisher} which can be * used to provide a sequence of * {@link software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithoutResultKeyResponse} response * pages as per demand from the subscriber. * </p> * <p> * When the operation is called, an instance of this class is returned. At this point, no service calls are made yet and * so there is no guarantee that the request is valid. If there are errors in your request, you will see the failures * only after you start streaming the data. The subscribe method should be called as a request to start streaming data. * For more info, see {@link org.reactivestreams.Publisher#subscribe(org.reactivestreams.Subscriber)}. Each call to the * subscribe method will result in a new {@link org.reactivestreams.Subscription} i.e., a new contract to stream data * from the starting request. * </p> * * <p> * The following are few ways to use the response class: * </p> * 1) Using the subscribe helper method * * <pre> * {@code * software.amazon.awssdk.services.jsonprotocoltests.paginators.PaginatedOperationWithoutResultKeyPublisher publisher = client.paginatedOperationWithoutResultKeyPaginator(request); * CompletableFuture<Void> future = publisher.subscribe(res -> { // Do something with the response }); * future.get(); * } * </pre> * * 2) Using a custom subscriber * * <pre> * {@code * software.amazon.awssdk.services.jsonprotocoltests.paginators.PaginatedOperationWithoutResultKeyPublisher publisher = client.paginatedOperationWithoutResultKeyPaginator(request); * publisher.subscribe(new Subscriber<software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithoutResultKeyResponse>() { * * public void onSubscribe(org.reactivestreams.Subscriber subscription) { //... }; * * * public void onNext(software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithoutResultKeyResponse response) { //... }; * });} * </pre> * * As the response is a publisher, it can work well with third party reactive streams implementations like RxJava2. * <p> * <b>Please notice that the configuration of MaxResults won't limit the number of results you get with the paginator. * It only limits the number of results in each page.</b> * </p> * <p> * <b>Note: If you prefer to have control on service calls, use the * {@link #paginatedOperationWithoutResultKey(software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithoutResultKeyRequest)} * operation.</b> * </p> */ @Generated("software.amazon.awssdk:codegen") public class PaginatedOperationWithoutResultKeyPublisher implements SdkPublisher<PaginatedOperationWithoutResultKeyResponse> { private final JsonProtocolTestsAsyncClient client; private final PaginatedOperationWithoutResultKeyRequest firstRequest; private final AsyncPageFetcher nextPageFetcher; private boolean isLastPage; public PaginatedOperationWithoutResultKeyPublisher(JsonProtocolTestsAsyncClient client, PaginatedOperationWithoutResultKeyRequest firstRequest) { this(client, firstRequest, false); } private PaginatedOperationWithoutResultKeyPublisher(JsonProtocolTestsAsyncClient client, PaginatedOperationWithoutResultKeyRequest firstRequest, boolean isLastPage) { this.client = client; this.firstRequest = UserAgentUtils.applyPaginatorUserAgent(firstRequest); this.isLastPage = isLastPage; this.nextPageFetcher = new PaginatedOperationWithoutResultKeyResponseFetcher(); } @Override public void subscribe(Subscriber<? super PaginatedOperationWithoutResultKeyResponse> subscriber) { subscriber.onSubscribe(ResponsesSubscription.builder().subscriber(subscriber).nextPageFetcher(nextPageFetcher).build()); } private class PaginatedOperationWithoutResultKeyResponseFetcher implements AsyncPageFetcher<PaginatedOperationWithoutResultKeyResponse> { @Override public boolean hasNextPage(final PaginatedOperationWithoutResultKeyResponse previousPage) { return PaginatorUtils.isOutputTokenAvailable(previousPage.nextToken()); } @Override public CompletableFuture<PaginatedOperationWithoutResultKeyResponse> nextPage( final PaginatedOperationWithoutResultKeyResponse previousPage) { if (previousPage == null) { return client.paginatedOperationWithoutResultKey(firstRequest); } return client .paginatedOperationWithoutResultKey(firstRequest.toBuilder().nextToken(previousPage.nextToken()).build()); } } }
3,082
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/paginators/PaginatedOperationWithResultKeyPublisher.java
package software.amazon.awssdk.services.jsonprotocoltests.paginators; import java.util.Collections; import java.util.Iterator; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.pagination.async.AsyncPageFetcher; import software.amazon.awssdk.core.pagination.async.PaginatedItemsPublisher; import software.amazon.awssdk.core.pagination.async.ResponsesSubscription; import software.amazon.awssdk.core.util.PaginatorUtils; import software.amazon.awssdk.services.jsonprotocoltests.JsonProtocolTestsAsyncClient; import software.amazon.awssdk.services.jsonprotocoltests.internal.UserAgentUtils; import software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithResultKeyRequest; import software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithResultKeyResponse; import software.amazon.awssdk.services.jsonprotocoltests.model.SimpleStruct; /** * <p> * Represents the output for the * {@link software.amazon.awssdk.services.jsonprotocoltests.JsonProtocolTestsAsyncClient#paginatedOperationWithResultKeyPaginator(software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithResultKeyRequest)} * operation which is a paginated operation. This class is a type of {@link org.reactivestreams.Publisher} which can be * used to provide a sequence of * {@link software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithResultKeyResponse} response * pages as per demand from the subscriber. * </p> * <p> * When the operation is called, an instance of this class is returned. At this point, no service calls are made yet and * so there is no guarantee that the request is valid. If there are errors in your request, you will see the failures * only after you start streaming the data. The subscribe method should be called as a request to start streaming data. * For more info, see {@link org.reactivestreams.Publisher#subscribe(org.reactivestreams.Subscriber)}. Each call to the * subscribe method will result in a new {@link org.reactivestreams.Subscription} i.e., a new contract to stream data * from the starting request. * </p> * * <p> * The following are few ways to use the response class: * </p> * 1) Using the subscribe helper method * * <pre> * {@code * software.amazon.awssdk.services.jsonprotocoltests.paginators.PaginatedOperationWithResultKeyPublisher publisher = client.paginatedOperationWithResultKeyPaginator(request); * CompletableFuture<Void> future = publisher.subscribe(res -> { // Do something with the response }); * future.get(); * } * </pre> * * 2) Using a custom subscriber * * <pre> * {@code * software.amazon.awssdk.services.jsonprotocoltests.paginators.PaginatedOperationWithResultKeyPublisher publisher = client.paginatedOperationWithResultKeyPaginator(request); * publisher.subscribe(new Subscriber<software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithResultKeyResponse>() { * * public void onSubscribe(org.reactivestreams.Subscriber subscription) { //... }; * * * public void onNext(software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithResultKeyResponse response) { //... }; * });} * </pre> * * As the response is a publisher, it can work well with third party reactive streams implementations like RxJava2. * <p> * <b>Please notice that the configuration of MaxResults won't limit the number of results you get with the paginator. * It only limits the number of results in each page.</b> * </p> * <p> * <b>Note: If you prefer to have control on service calls, use the * {@link #paginatedOperationWithResultKey(software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithResultKeyRequest)} * operation.</b> * </p> */ @Generated("software.amazon.awssdk:codegen") public class PaginatedOperationWithResultKeyPublisher implements SdkPublisher<PaginatedOperationWithResultKeyResponse> { private final JsonProtocolTestsAsyncClient client; private final PaginatedOperationWithResultKeyRequest firstRequest; private final AsyncPageFetcher nextPageFetcher; private boolean isLastPage; public PaginatedOperationWithResultKeyPublisher(JsonProtocolTestsAsyncClient client, PaginatedOperationWithResultKeyRequest firstRequest) { this(client, firstRequest, false); } private PaginatedOperationWithResultKeyPublisher(JsonProtocolTestsAsyncClient client, PaginatedOperationWithResultKeyRequest firstRequest, boolean isLastPage) { this.client = client; this.firstRequest = UserAgentUtils.applyPaginatorUserAgent(firstRequest); this.isLastPage = isLastPage; this.nextPageFetcher = new PaginatedOperationWithResultKeyResponseFetcher(); } @Override public void subscribe(Subscriber<? super PaginatedOperationWithResultKeyResponse> subscriber) { subscriber.onSubscribe(ResponsesSubscription.builder().subscriber(subscriber).nextPageFetcher(nextPageFetcher).build()); } /** * Returns a publisher that can be used to get a stream of data. You need to subscribe to the publisher to request * the stream of data. The publisher has a helper forEach method that takes in a {@link java.util.function.Consumer} * and then applies that consumer to each response returned by the service. */ public final SdkPublisher<SimpleStruct> items() { Function<PaginatedOperationWithResultKeyResponse, Iterator<SimpleStruct>> getIterator = response -> { if (response != null && response.items() != null) { return response.items().iterator(); } return Collections.emptyIterator(); }; return PaginatedItemsPublisher.builder().nextPageFetcher(new PaginatedOperationWithResultKeyResponseFetcher()) .iteratorFunction(getIterator).isLastPage(isLastPage).build(); } private class PaginatedOperationWithResultKeyResponseFetcher implements AsyncPageFetcher<PaginatedOperationWithResultKeyResponse> { @Override public boolean hasNextPage(final PaginatedOperationWithResultKeyResponse previousPage) { return PaginatorUtils.isOutputTokenAvailable(previousPage.nextToken()); } @Override public CompletableFuture<PaginatedOperationWithResultKeyResponse> nextPage( final PaginatedOperationWithResultKeyResponse previousPage) { if (previousPage == null) { return client.paginatedOperationWithResultKey(firstRequest); } return client.paginatedOperationWithResultKey(firstRequest.toBuilder().nextToken(previousPage.nextToken()).build()); } } }
3,083
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/paginators/PaginatedOperationWithoutResultKeyIterable.java
package software.amazon.awssdk.services.jsonprotocoltests.paginators; import java.util.Iterator; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.core.pagination.sync.PaginatedResponsesIterator; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.core.pagination.sync.SyncPageFetcher; import software.amazon.awssdk.core.util.PaginatorUtils; import software.amazon.awssdk.services.jsonprotocoltests.JsonProtocolTestsClient; import software.amazon.awssdk.services.jsonprotocoltests.internal.UserAgentUtils; import software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithoutResultKeyRequest; import software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithoutResultKeyResponse; /** * <p> * Represents the output for the * {@link software.amazon.awssdk.services.jsonprotocoltests.JsonProtocolTestsClient#paginatedOperationWithoutResultKeyPaginator(software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithoutResultKeyRequest)} * operation which is a paginated operation. This class is an iterable of * {@link software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithoutResultKeyResponse} that can * be used to iterate through all the response pages of the operation. * </p> * <p> * When the operation is called, an instance of this class is returned. At this point, no service calls are made yet and * so there is no guarantee that the request is valid. As you iterate through the iterable, SDK will start lazily * loading response pages by making service calls until there are no pages left or your iteration stops. If there are * errors in your request, you will see the failures only after you start iterating through the iterable. * </p> * * <p> * The following are few ways to iterate through the response pages: * </p> * 1) Using a Stream * * <pre> * {@code * software.amazon.awssdk.services.jsonprotocoltests.paginators.PaginatedOperationWithoutResultKeyIterable responses = client.paginatedOperationWithoutResultKeyPaginator(request); * responses.stream().forEach(....); * } * </pre> * * 2) Using For loop * * <pre> * { * &#064;code * software.amazon.awssdk.services.jsonprotocoltests.paginators.PaginatedOperationWithoutResultKeyIterable responses = client * .paginatedOperationWithoutResultKeyPaginator(request); * for (software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithoutResultKeyResponse response : responses) { * // do something; * } * } * </pre> * * 3) Use iterator directly * * <pre> * {@code * software.amazon.awssdk.services.jsonprotocoltests.paginators.PaginatedOperationWithoutResultKeyIterable responses = client.paginatedOperationWithoutResultKeyPaginator(request); * responses.iterator().forEachRemaining(....); * } * </pre> * <p> * <b>Please notice that the configuration of MaxResults won't limit the number of results you get with the paginator. * It only limits the number of results in each page.</b> * </p> * <p> * <b>Note: If you prefer to have control on service calls, use the * {@link #paginatedOperationWithoutResultKey(software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithoutResultKeyRequest)} * operation.</b> * </p> */ @Generated("software.amazon.awssdk:codegen") public class PaginatedOperationWithoutResultKeyIterable implements SdkIterable<PaginatedOperationWithoutResultKeyResponse> { private final JsonProtocolTestsClient client; private final PaginatedOperationWithoutResultKeyRequest firstRequest; private final SyncPageFetcher nextPageFetcher; public PaginatedOperationWithoutResultKeyIterable(JsonProtocolTestsClient client, PaginatedOperationWithoutResultKeyRequest firstRequest) { this.client = client; this.firstRequest = UserAgentUtils.applyPaginatorUserAgent(firstRequest); this.nextPageFetcher = new PaginatedOperationWithoutResultKeyResponseFetcher(); } @Override public Iterator<PaginatedOperationWithoutResultKeyResponse> iterator() { return PaginatedResponsesIterator.builder().nextPageFetcher(nextPageFetcher).build(); } private class PaginatedOperationWithoutResultKeyResponseFetcher implements SyncPageFetcher<PaginatedOperationWithoutResultKeyResponse> { @Override public boolean hasNextPage(PaginatedOperationWithoutResultKeyResponse previousPage) { return PaginatorUtils.isOutputTokenAvailable(previousPage.nextToken()); } @Override public PaginatedOperationWithoutResultKeyResponse nextPage(PaginatedOperationWithoutResultKeyResponse previousPage) { if (previousPage == null) { return client.paginatedOperationWithoutResultKey(firstRequest); } return client .paginatedOperationWithoutResultKey(firstRequest.toBuilder().nextToken(previousPage.nextToken()).build()); } } }
3,084
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/paginators/PaginatedOperationWithResultKeyIterable.java
package software.amazon.awssdk.services.jsonprotocoltests.paginators; import java.util.Collections; import java.util.Iterator; import java.util.function.Function; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.core.pagination.sync.PaginatedItemsIterable; import software.amazon.awssdk.core.pagination.sync.PaginatedResponsesIterator; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.core.pagination.sync.SyncPageFetcher; import software.amazon.awssdk.core.util.PaginatorUtils; import software.amazon.awssdk.services.jsonprotocoltests.JsonProtocolTestsClient; import software.amazon.awssdk.services.jsonprotocoltests.internal.UserAgentUtils; import software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithResultKeyRequest; import software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithResultKeyResponse; import software.amazon.awssdk.services.jsonprotocoltests.model.SimpleStruct; /** * <p> * Represents the output for the * {@link software.amazon.awssdk.services.jsonprotocoltests.JsonProtocolTestsClient#paginatedOperationWithResultKeyPaginator(software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithResultKeyRequest)} * operation which is a paginated operation. This class is an iterable of * {@link software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithResultKeyResponse} that can be * used to iterate through all the response pages of the operation. * </p> * <p> * When the operation is called, an instance of this class is returned. At this point, no service calls are made yet and * so there is no guarantee that the request is valid. As you iterate through the iterable, SDK will start lazily * loading response pages by making service calls until there are no pages left or your iteration stops. If there are * errors in your request, you will see the failures only after you start iterating through the iterable. * </p> * * <p> * The following are few ways to iterate through the response pages: * </p> * 1) Using a Stream * * <pre> * {@code * software.amazon.awssdk.services.jsonprotocoltests.paginators.PaginatedOperationWithResultKeyIterable responses = client.paginatedOperationWithResultKeyPaginator(request); * responses.stream().forEach(....); * } * </pre> * * 2) Using For loop * * <pre> * { * &#064;code * software.amazon.awssdk.services.jsonprotocoltests.paginators.PaginatedOperationWithResultKeyIterable responses = client * .paginatedOperationWithResultKeyPaginator(request); * for (software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithResultKeyResponse response : responses) { * // do something; * } * } * </pre> * * 3) Use iterator directly * * <pre> * {@code * software.amazon.awssdk.services.jsonprotocoltests.paginators.PaginatedOperationWithResultKeyIterable responses = client.paginatedOperationWithResultKeyPaginator(request); * responses.iterator().forEachRemaining(....); * } * </pre> * <p> * <b>Please notice that the configuration of MaxResults won't limit the number of results you get with the paginator. * It only limits the number of results in each page.</b> * </p> * <p> * <b>Note: If you prefer to have control on service calls, use the * {@link #paginatedOperationWithResultKey(software.amazon.awssdk.services.jsonprotocoltests.model.PaginatedOperationWithResultKeyRequest)} * operation.</b> * </p> */ @Generated("software.amazon.awssdk:codegen") public class PaginatedOperationWithResultKeyIterable implements SdkIterable<PaginatedOperationWithResultKeyResponse> { private final JsonProtocolTestsClient client; private final PaginatedOperationWithResultKeyRequest firstRequest; private final SyncPageFetcher nextPageFetcher; public PaginatedOperationWithResultKeyIterable(JsonProtocolTestsClient client, PaginatedOperationWithResultKeyRequest firstRequest) { this.client = client; this.firstRequest = UserAgentUtils.applyPaginatorUserAgent(firstRequest); this.nextPageFetcher = new PaginatedOperationWithResultKeyResponseFetcher(); } @Override public Iterator<PaginatedOperationWithResultKeyResponse> iterator() { return PaginatedResponsesIterator.builder().nextPageFetcher(nextPageFetcher).build(); } /** * Returns an iterable to iterate through the paginated {@link PaginatedOperationWithResultKeyResponse#items()} * member. The returned iterable is used to iterate through the results across all response pages and not a single * page. * * This method is useful if you are interested in iterating over the paginated member in the response pages instead * of the top level pages. Similar to iteration over pages, this method internally makes service calls to get the * next list of results until the iteration stops or there are no more results. */ public final SdkIterable<SimpleStruct> items() { Function<PaginatedOperationWithResultKeyResponse, Iterator<SimpleStruct>> getIterator = response -> { if (response != null && response.items() != null) { return response.items().iterator(); } return Collections.emptyIterator(); }; return PaginatedItemsIterable.<PaginatedOperationWithResultKeyResponse, SimpleStruct> builder().pagesIterable(this) .itemIteratorFunction(getIterator).build(); } private class PaginatedOperationWithResultKeyResponseFetcher implements SyncPageFetcher<PaginatedOperationWithResultKeyResponse> { @Override public boolean hasNextPage(PaginatedOperationWithResultKeyResponse previousPage) { return PaginatorUtils.isOutputTokenAvailable(previousPage.nextToken()); } @Override public PaginatedOperationWithResultKeyResponse nextPage(PaginatedOperationWithResultKeyResponse previousPage) { if (previousPage == null) { return client.paginatedOperationWithResultKey(firstRequest); } return client.paginatedOperationWithResultKey(firstRequest.toBuilder().nextToken(previousPage.nextToken()).build()); } } }
3,085
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/paginators
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/paginators/customizations/SameTokenPaginationApiIterable.java
package software.amazon.awssdk.services.jsonprotocoltests.paginators; import java.util.Collections; import java.util.Iterator; import java.util.function.Function; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.core.pagination.sync.PaginatedItemsIterable; import software.amazon.awssdk.core.pagination.sync.PaginatedResponsesIterator; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.core.pagination.sync.SyncPageFetcher; import software.amazon.awssdk.core.util.PaginatorUtils; import software.amazon.awssdk.services.jsonprotocoltests.JsonProtocolTestsClient; import software.amazon.awssdk.services.jsonprotocoltests.model.SameTokenPaginationApiRequest; import software.amazon.awssdk.services.jsonprotocoltests.model.SameTokenPaginationApiResponse; import software.amazon.awssdk.services.jsonprotocoltests.model.SimpleStruct; /** * <p> * Represents the output for the * {@link software.amazon.awssdk.services.jsonprotocoltests.JsonProtocolTestsClient#sameTokenPaginationApiPaginator(software.amazon.awssdk.services.jsonprotocoltests.model.SameTokenPaginationApiRequest)} * operation which is a paginated operation. This class is an iterable of * {@link software.amazon.awssdk.services.jsonprotocoltests.model.SameTokenPaginationApiResponse} that can be used to * iterate through all the response pages of the operation. * </p> * <p> * When the operation is called, an instance of this class is returned. At this point, no service calls are made yet and * so there is no guarantee that the request is valid. As you iterate through the iterable, SDK will start lazily * loading response pages by making service calls until there are no pages left or your iteration stops. If there are * errors in your request, you will see the failures only after you start iterating through the iterable. * </p> * * <p> * The following are few ways to iterate through the response pages: * </p> * 1) Using a Stream * * <pre> * {@code * software.amazon.awssdk.services.jsonprotocoltests.paginators.SameTokenPaginationApiIterable responses = client.sameTokenPaginationApiPaginator(request); * responses.stream().forEach(....); * } * </pre> * * 2) Using For loop * * <pre> * { * &#064;code * software.amazon.awssdk.services.jsonprotocoltests.paginators.SameTokenPaginationApiIterable responses = client * .sameTokenPaginationApiPaginator(request); * for (software.amazon.awssdk.services.jsonprotocoltests.model.SameTokenPaginationApiResponse response : responses) { * // do something; * } * } * </pre> * * 3) Use iterator directly * * <pre> * {@code * software.amazon.awssdk.services.jsonprotocoltests.paginators.SameTokenPaginationApiIterable responses = client.sameTokenPaginationApiPaginator(request); * responses.iterator().forEachRemaining(....); * } * </pre> * <p> * <b>Please notice that the configuration of MaxResults won't limit the number of results you get with the paginator. * It only limits the number of results in each page.</b> * </p> * <p> * <b>Note: If you prefer to have control on service calls, use the * {@link #sameTokenPaginationApi(software.amazon.awssdk.services.jsonprotocoltests.model.SameTokenPaginationApiRequest)} * operation.</b> * </p> */ @Generated("software.amazon.awssdk:codegen") public class SameTokenPaginationApiIterable implements SdkIterable<SameTokenPaginationApiResponse> { private final JsonProtocolTestsClient client; private final SameTokenPaginationApiRequest firstRequest; public SameTokenPaginationApiIterable(JsonProtocolTestsClient client, SameTokenPaginationApiRequest firstRequest) { this.client = client; this.firstRequest = firstRequest; } @Override public Iterator<SameTokenPaginationApiResponse> iterator() { return PaginatedResponsesIterator.builder().nextPageFetcher(new SameTokenPaginationApiResponseFetcher()).build(); } /** * Returns an iterable to iterate through the paginated {@link SameTokenPaginationApiResponse#items()} member. The * returned iterable is used to iterate through the results across all response pages and not a single page. * * This method is useful if you are interested in iterating over the paginated member in the response pages instead * of the top level pages. Similar to iteration over pages, this method internally makes service calls to get the * next list of results until the iteration stops or there are no more results. */ public final SdkIterable<SimpleStruct> items() { Function<SameTokenPaginationApiResponse, Iterator<SimpleStruct>> getIterator = response -> { if (response != null && response.items() != null) { return response.items().iterator(); } return Collections.emptyIterator(); }; return PaginatedItemsIterable.<SameTokenPaginationApiResponse, SimpleStruct> builder().pagesIterable(this) .itemIteratorFunction(getIterator).build(); } private class SameTokenPaginationApiResponseFetcher implements SyncPageFetcher<SameTokenPaginationApiResponse> { private Object lastToken; @Override public boolean hasNextPage(SameTokenPaginationApiResponse previousPage) { return PaginatorUtils.isOutputTokenAvailable(previousPage.nextToken()) && !previousPage.nextToken().equals(lastToken); } @Override public SameTokenPaginationApiResponse nextPage(SameTokenPaginationApiResponse previousPage) { if (previousPage == null) { lastToken = null; return client.sameTokenPaginationApi(firstRequest); } lastToken = previousPage.nextToken(); return client.sameTokenPaginationApi(firstRequest.toBuilder().nextToken(previousPage.nextToken()).build()); } } }
3,086
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/paginators
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/paginators/customizations/SameTokenPaginationApiPublisher.java
package software.amazon.awssdk.services.jsonprotocoltests.paginators; import java.util.Collections; import java.util.Iterator; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.pagination.async.AsyncPageFetcher; import software.amazon.awssdk.core.pagination.async.PaginatedItemsPublisher; import software.amazon.awssdk.core.pagination.async.ResponsesSubscription; import software.amazon.awssdk.core.util.PaginatorUtils; import software.amazon.awssdk.services.jsonprotocoltests.JsonProtocolTestsAsyncClient; import software.amazon.awssdk.services.jsonprotocoltests.model.SameTokenPaginationApiRequest; import software.amazon.awssdk.services.jsonprotocoltests.model.SameTokenPaginationApiResponse; import software.amazon.awssdk.services.jsonprotocoltests.model.SimpleStruct; /** * <p> * Represents the output for the * {@link software.amazon.awssdk.services.jsonprotocoltests.JsonProtocolTestsAsyncClient#sameTokenPaginationApiPaginator(software.amazon.awssdk.services.jsonprotocoltests.model.SameTokenPaginationApiRequest)} * operation which is a paginated operation. This class is a type of {@link org.reactivestreams.Publisher} which can be * used to provide a sequence of * {@link software.amazon.awssdk.services.jsonprotocoltests.model.SameTokenPaginationApiResponse} response pages as per * demand from the subscriber. * </p> * <p> * When the operation is called, an instance of this class is returned. At this point, no service calls are made yet and * so there is no guarantee that the request is valid. If there are errors in your request, you will see the failures * only after you start streaming the data. The subscribe method should be called as a request to start streaming data. * For more info, see {@link org.reactivestreams.Publisher#subscribe(org.reactivestreams.Subscriber)}. Each call to the * subscribe method will result in a new {@link org.reactivestreams.Subscription} i.e., a new contract to stream data * from the starting request. * </p> * * <p> * The following are few ways to use the response class: * </p> * 1) Using the subscribe helper method * * <pre> * {@code * software.amazon.awssdk.services.jsonprotocoltests.paginators.SameTokenPaginationApiPublisher publisher = client.sameTokenPaginationApiPaginator(request); * CompletableFuture<Void> future = publisher.subscribe(res -> { // Do something with the response }); * future.get(); * } * </pre> * * 2) Using a custom subscriber * * <pre> * {@code * software.amazon.awssdk.services.jsonprotocoltests.paginators.SameTokenPaginationApiPublisher publisher = client.sameTokenPaginationApiPaginator(request); * publisher.subscribe(new Subscriber<software.amazon.awssdk.services.jsonprotocoltests.model.SameTokenPaginationApiResponse>() { * * public void onSubscribe(org.reactivestreams.Subscriber subscription) { //... }; * * * public void onNext(software.amazon.awssdk.services.jsonprotocoltests.model.SameTokenPaginationApiResponse response) { //... }; * });} * </pre> * * As the response is a publisher, it can work well with third party reactive streams implementations like RxJava2. * <p> * <b>Please notice that the configuration of MaxResults won't limit the number of results you get with the paginator. * It only limits the number of results in each page.</b> * </p> * <p> * <b>Note: If you prefer to have control on service calls, use the * {@link #sameTokenPaginationApi(software.amazon.awssdk.services.jsonprotocoltests.model.SameTokenPaginationApiRequest)} * operation.</b> * </p> */ @Generated("software.amazon.awssdk:codegen") public class SameTokenPaginationApiPublisher implements SdkPublisher<SameTokenPaginationApiResponse> { private final JsonProtocolTestsAsyncClient client; private final SameTokenPaginationApiRequest firstRequest; private boolean isLastPage; public SameTokenPaginationApiPublisher(JsonProtocolTestsAsyncClient client, SameTokenPaginationApiRequest firstRequest) { this(client, firstRequest, false); } private SameTokenPaginationApiPublisher(JsonProtocolTestsAsyncClient client, SameTokenPaginationApiRequest firstRequest, boolean isLastPage) { this.client = client; this.firstRequest = firstRequest; this.isLastPage = isLastPage; } @Override public void subscribe(Subscriber<? super SameTokenPaginationApiResponse> subscriber) { subscriber.onSubscribe(ResponsesSubscription.builder().subscriber(subscriber) .nextPageFetcher(new SameTokenPaginationApiResponseFetcher()).build()); } /** * Returns a publisher that can be used to get a stream of data. You need to subscribe to the publisher to request * the stream of data. The publisher has a helper forEach method that takes in a {@link java.util.function.Consumer} * and then applies that consumer to each response returned by the service. */ public final SdkPublisher<SimpleStruct> items() { Function<SameTokenPaginationApiResponse, Iterator<SimpleStruct>> getIterator = response -> { if (response != null && response.items() != null) { return response.items().iterator(); } return Collections.emptyIterator(); }; return PaginatedItemsPublisher.builder().nextPageFetcher(new SameTokenPaginationApiResponseFetcher()) .iteratorFunction(getIterator).isLastPage(isLastPage).build(); } private class SameTokenPaginationApiResponseFetcher implements AsyncPageFetcher<SameTokenPaginationApiResponse> { private Object lastToken; @Override public boolean hasNextPage(final SameTokenPaginationApiResponse previousPage) { return PaginatorUtils.isOutputTokenAvailable(previousPage.nextToken()) && !previousPage.nextToken().equals(lastToken); } @Override public CompletableFuture<SameTokenPaginationApiResponse> nextPage(final SameTokenPaginationApiResponse previousPage) { if (previousPage == null) { lastToken = null; return client.sameTokenPaginationApi(firstRequest); } lastToken = previousPage.nextToken(); return client.sameTokenPaginationApi(firstRequest.toBuilder().nextToken(previousPage.nextToken()).build()); } } }
3,087
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth/scheme/granular-auth-scheme-default-provider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.database.auth.scheme.internal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.services.database.auth.scheme.DatabaseAuthSchemeParams; import software.amazon.awssdk.services.database.auth.scheme.DatabaseAuthSchemeProvider; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi public final class DefaultDatabaseAuthSchemeProvider implements DatabaseAuthSchemeProvider { private static final DefaultDatabaseAuthSchemeProvider DEFAULT = new DefaultDatabaseAuthSchemeProvider(); private DefaultDatabaseAuthSchemeProvider() { } public static DefaultDatabaseAuthSchemeProvider create() { return DEFAULT; } @Override public List<AuthSchemeOption> resolveAuthScheme(DatabaseAuthSchemeParams params) { List<AuthSchemeOption> options = new ArrayList<>(); switch (params.operation()) { case "GetRow": case "GetRowV2": options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "database-service") .putSignerProperty(AwsV4HttpSigner.REGION_NAME, params.region().id()).build()); options.add(AuthSchemeOption.builder().schemeId("smithy.api#httpBearerAuth").build()); break; case "ListRows": options.add(AuthSchemeOption.builder().schemeId("smithy.api#httpBearerAuth").build()); break; case "PutRow": options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "database-service") .putSignerProperty(AwsV4HttpSigner.REGION_NAME, params.region().id()).build()); break; case "WriteRowResponse": options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "database-service") .putSignerProperty(AwsV4HttpSigner.REGION_NAME, params.region().id()) .putSignerProperty(AwsV4HttpSigner.PAYLOAD_SIGNING_ENABLED, false).build()); break; default: options.add(AuthSchemeOption.builder().schemeId("smithy.api#httpBearerAuth").build()); options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "database-service") .putSignerProperty(AwsV4HttpSigner.REGION_NAME, params.region().id()).build()); break; } return Collections.unmodifiableList(options); } }
3,088
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth/scheme/all-ops-auth-different-value-auth-scheme-default-provider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.database.auth.scheme.internal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.services.database.auth.scheme.DatabaseAuthSchemeParams; import software.amazon.awssdk.services.database.auth.scheme.DatabaseAuthSchemeProvider; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi public final class DefaultDatabaseAuthSchemeProvider implements DatabaseAuthSchemeProvider { private static final DefaultDatabaseAuthSchemeProvider DEFAULT = new DefaultDatabaseAuthSchemeProvider(); private DefaultDatabaseAuthSchemeProvider() { } public static DefaultDatabaseAuthSchemeProvider create() { return DEFAULT; } @Override public List<AuthSchemeOption> resolveAuthScheme(DatabaseAuthSchemeParams params) { List<AuthSchemeOption> options = new ArrayList<>(); switch (params.operation()) { case "DeleteRow": options.add(AuthSchemeOption.builder().schemeId("smithy.api#httpBearerAuth").build()); options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "database-service") .putSignerProperty(AwsV4HttpSigner.REGION_NAME, params.region().id()).build()); break; case "GetRow": options.add(AuthSchemeOption.builder().schemeId("smithy.api#httpBearerAuth").build()); break; case "PutRow": options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "database-service") .putSignerProperty(AwsV4HttpSigner.REGION_NAME, params.region().id()).build()); break; default: options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "database-service") .putSignerProperty(AwsV4HttpSigner.REGION_NAME, params.region().id()).build()); options.add(AuthSchemeOption.builder().schemeId("smithy.api#httpBearerAuth").build()); break; } return Collections.unmodifiableList(options); } }
3,089
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth/scheme/query-endpoint-auth-params-auth-scheme-default-params-with-allowlist.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.query.auth.scheme.internal; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.query.auth.scheme.QueryAuthSchemeParams; import software.amazon.awssdk.utils.Validate; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi public final class DefaultQueryAuthSchemeParams implements QueryAuthSchemeParams { private final String operation; private final Region region; private final Boolean defaultTrueParam; private final String defaultStringParam; private final String deprecatedParam; private final Boolean booleanContextParam; private final String stringContextParam; private final String operationContextParam; private DefaultQueryAuthSchemeParams(Builder builder) { this.operation = Validate.paramNotNull(builder.operation, "operation"); this.region = builder.region; this.defaultTrueParam = Validate.paramNotNull(builder.defaultTrueParam, "defaultTrueParam"); this.defaultStringParam = Validate.paramNotNull(builder.defaultStringParam, "defaultStringParam"); this.deprecatedParam = builder.deprecatedParam; this.booleanContextParam = builder.booleanContextParam; this.stringContextParam = builder.stringContextParam; this.operationContextParam = builder.operationContextParam; } public static QueryAuthSchemeParams.Builder builder() { return new Builder(); } @Override public String operation() { return operation; } @Override public Region region() { return region; } @Override public Boolean defaultTrueParam() { return defaultTrueParam; } @Override public String defaultStringParam() { return defaultStringParam; } @Deprecated @Override public String deprecatedParam() { return deprecatedParam; } @Override public Boolean booleanContextParam() { return booleanContextParam; } @Override public String stringContextParam() { return stringContextParam; } @Override public String operationContextParam() { return operationContextParam; } @Override public QueryAuthSchemeParams.Builder toBuilder() { return new Builder(this); } private static final class Builder implements QueryAuthSchemeParams.Builder { private String operation; private Region region; private Boolean defaultTrueParam = true; private String defaultStringParam = "hello endpoints"; private String deprecatedParam; private Boolean booleanContextParam; private String stringContextParam; private String operationContextParam; Builder() { } Builder(DefaultQueryAuthSchemeParams params) { this.operation = params.operation; this.region = params.region; this.defaultTrueParam = params.defaultTrueParam; this.defaultStringParam = params.defaultStringParam; this.deprecatedParam = params.deprecatedParam; this.booleanContextParam = params.booleanContextParam; this.stringContextParam = params.stringContextParam; this.operationContextParam = params.operationContextParam; } @Override public Builder operation(String operation) { this.operation = operation; return this; } @Override public Builder region(Region region) { this.region = region; return this; } @Override public Builder defaultTrueParam(Boolean defaultTrueParam) { this.defaultTrueParam = defaultTrueParam; if (this.defaultTrueParam == null) { this.defaultTrueParam = true; } return this; } @Override public Builder defaultStringParam(String defaultStringParam) { this.defaultStringParam = defaultStringParam; if (this.defaultStringParam == null) { this.defaultStringParam = "hello endpoints"; } return this; } @Deprecated @Override public Builder deprecatedParam(String deprecatedParam) { this.deprecatedParam = deprecatedParam; return this; } @Override public Builder booleanContextParam(Boolean booleanContextParam) { this.booleanContextParam = booleanContextParam; return this; } @Override public Builder stringContextParam(String stringContextParam) { this.stringContextParam = stringContextParam; return this; } @Override public Builder operationContextParam(String operationContextParam) { this.operationContextParam = operationContextParam; return this; } @Override public QueryAuthSchemeParams build() { return new DefaultQueryAuthSchemeParams(this); } } }
3,090
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth/scheme/query-endpoint-auth-params-auth-scheme-provider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.query.auth.scheme; import java.util.List; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeProvider; import software.amazon.awssdk.services.query.auth.scheme.internal.DefaultQueryAuthSchemeProvider; /** * An auth scheme provider for Query service. The auth scheme provider takes a set of parameters using * {@link QueryAuthSchemeParams}, and resolves a list of {@link AuthSchemeOption} based on the given parameters. */ @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public interface QueryAuthSchemeProvider extends AuthSchemeProvider { /** * Resolve the auth schemes based on the given set of parameters. */ List<AuthSchemeOption> resolveAuthScheme(QueryAuthSchemeParams authSchemeParams); /** * Resolve the auth schemes based on the given set of parameters. */ default List<AuthSchemeOption> resolveAuthScheme(Consumer<QueryAuthSchemeParams.Builder> consumer) { QueryAuthSchemeParams.Builder builder = QueryAuthSchemeParams.builder(); consumer.accept(builder); return resolveAuthScheme(builder.build()); } /** * Get the default auth scheme provider. */ static QueryAuthSchemeProvider defaultProvider() { return DefaultQueryAuthSchemeProvider.create(); } }
3,091
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth/scheme/auth-with-legacy-trait-auth-scheme-default-provider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.authwithlegacytrait.auth.scheme.internal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.services.authwithlegacytrait.auth.scheme.AuthWithLegacyTraitAuthSchemeParams; import software.amazon.awssdk.services.authwithlegacytrait.auth.scheme.AuthWithLegacyTraitAuthSchemeProvider; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi public final class DefaultAuthWithLegacyTraitAuthSchemeProvider implements AuthWithLegacyTraitAuthSchemeProvider { private static final DefaultAuthWithLegacyTraitAuthSchemeProvider DEFAULT = new DefaultAuthWithLegacyTraitAuthSchemeProvider(); private DefaultAuthWithLegacyTraitAuthSchemeProvider() { } public static DefaultAuthWithLegacyTraitAuthSchemeProvider create() { return DEFAULT; } @Override public List<AuthSchemeOption> resolveAuthScheme(AuthWithLegacyTraitAuthSchemeParams params) { List<AuthSchemeOption> options = new ArrayList<>(); switch (params.operation()) { case "OperationWithBearerAuth": options.add(AuthSchemeOption.builder().schemeId("smithy.api#httpBearerAuth").build()); break; case "OperationWithNoAuth": options.add(AuthSchemeOption.builder().schemeId("smithy.api#noAuth").build()); break; default: options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "authwithlegacytraitservice") .putSignerProperty(AwsV4HttpSigner.REGION_NAME, params.region().id()).build()); break; } return Collections.unmodifiableList(options); } }
3,092
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth/scheme/query-auth-scheme-interceptor.java
package software.amazon.awssdk.services.query.auth.scheme.internal; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.internal.util.MetricUtils; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.identity.spi.ResolveIdentityRequest; import software.amazon.awssdk.identity.spi.TokenIdentity; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.query.auth.scheme.QueryAuthSchemeParams; import software.amazon.awssdk.services.query.auth.scheme.QueryAuthSchemeProvider; import software.amazon.awssdk.services.query.endpoints.internal.AuthSchemeUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi public final class QueryAuthSchemeInterceptor implements ExecutionInterceptor { private static Logger LOG = Logger.loggerFor(QueryAuthSchemeInterceptor.class); @Override public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { List<AuthSchemeOption> authOptions = resolveAuthOptions(context, executionAttributes); SelectedAuthScheme<? extends Identity> selectedAuthScheme = selectAuthScheme(authOptions, executionAttributes); AuthSchemeUtils.putSelectedAuthScheme(executionAttributes, selectedAuthScheme); } private List<AuthSchemeOption> resolveAuthOptions(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { QueryAuthSchemeProvider authSchemeProvider = Validate.isInstanceOf(QueryAuthSchemeProvider.class, executionAttributes.getAttribute(SdkInternalExecutionAttribute.AUTH_SCHEME_RESOLVER), "Expected an instance of QueryAuthSchemeProvider"); QueryAuthSchemeParams params = authSchemeParams(context.request(), executionAttributes); return authSchemeProvider.resolveAuthScheme(params); } private SelectedAuthScheme<? extends Identity> selectAuthScheme(List<AuthSchemeOption> authOptions, ExecutionAttributes executionAttributes) { MetricCollector metricCollector = executionAttributes.getAttribute(SdkExecutionAttribute.API_CALL_METRIC_COLLECTOR); Map<String, AuthScheme<?>> authSchemes = executionAttributes.getAttribute(SdkInternalExecutionAttribute.AUTH_SCHEMES); IdentityProviders identityProviders = executionAttributes .getAttribute(SdkInternalExecutionAttribute.IDENTITY_PROVIDERS); List<Supplier<String>> discardedReasons = new ArrayList<>(); for (AuthSchemeOption authOption : authOptions) { AuthScheme<?> authScheme = authSchemes.get(authOption.schemeId()); SelectedAuthScheme<? extends Identity> selectedAuthScheme = trySelectAuthScheme(authOption, authScheme, identityProviders, discardedReasons, metricCollector); if (selectedAuthScheme != null) { if (!discardedReasons.isEmpty()) { LOG.debug(() -> String.format("%s auth will be used, discarded: '%s'", authOption.schemeId(), discardedReasons.stream().map(Supplier::get).collect(Collectors.joining(", ")))); } return selectedAuthScheme; } } throw SdkException .builder() .message( "Failed to determine how to authenticate the user: " + discardedReasons.stream().map(Supplier::get).collect(Collectors.joining(", "))).build(); } private QueryAuthSchemeParams authSchemeParams(SdkRequest request, ExecutionAttributes executionAttributes) { String operation = executionAttributes.getAttribute(SdkExecutionAttribute.OPERATION_NAME); Region region = executionAttributes.getAttribute(AwsExecutionAttribute.AWS_REGION); return QueryAuthSchemeParams.builder().operation(operation).region(region).build(); } private <T extends Identity> SelectedAuthScheme<T> trySelectAuthScheme(AuthSchemeOption authOption, AuthScheme<T> authScheme, IdentityProviders identityProviders, List<Supplier<String>> discardedReasons, MetricCollector metricCollector) { if (authScheme == null) { discardedReasons.add(() -> String.format("'%s' is not enabled for this request.", authOption.schemeId())); return null; } IdentityProvider<T> identityProvider = authScheme.identityProvider(identityProviders); if (identityProvider == null) { discardedReasons .add(() -> String.format("'%s' does not have an identity provider configured.", authOption.schemeId())); return null; } ResolveIdentityRequest.Builder identityRequestBuilder = ResolveIdentityRequest.builder(); authOption.forEachIdentityProperty(identityRequestBuilder::putProperty); CompletableFuture<? extends T> identity; SdkMetric<Duration> metric = getIdentityMetric(identityProvider); if (metric == null) { identity = identityProvider.resolveIdentity(identityRequestBuilder.build()); } else { identity = MetricUtils.reportDuration(() -> identityProvider.resolveIdentity(identityRequestBuilder.build()), metricCollector, metric); } return new SelectedAuthScheme<>(identity, authScheme.signer(), authOption); } private SdkMetric<Duration> getIdentityMetric(IdentityProvider<?> identityProvider) { Class<?> identityType = identityProvider.identityType(); if (identityType == AwsCredentialsIdentity.class) { return CoreMetric.CREDENTIALS_FETCH_DURATION; } if (identityType == TokenIdentity.class) { return CoreMetric.TOKEN_FETCH_DURATION; } return null; } }
3,093
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth/scheme/query-auth-scheme-provider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.query.auth.scheme; import java.util.List; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeProvider; import software.amazon.awssdk.services.query.auth.scheme.internal.DefaultQueryAuthSchemeProvider; /** * An auth scheme provider for Query service. The auth scheme provider takes a set of parameters using * {@link QueryAuthSchemeParams}, and resolves a list of {@link AuthSchemeOption} based on the given parameters. */ @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public interface QueryAuthSchemeProvider extends AuthSchemeProvider { /** * Resolve the auth schemes based on the given set of parameters. */ List<AuthSchemeOption> resolveAuthScheme(QueryAuthSchemeParams authSchemeParams); /** * Resolve the auth schemes based on the given set of parameters. */ default List<AuthSchemeOption> resolveAuthScheme(Consumer<QueryAuthSchemeParams.Builder> consumer) { QueryAuthSchemeParams.Builder builder = QueryAuthSchemeParams.builder(); consumer.accept(builder); return resolveAuthScheme(builder.build()); } /** * Get the default auth scheme provider. */ static QueryAuthSchemeProvider defaultProvider() { return DefaultQueryAuthSchemeProvider.create(); } }
3,094
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth/scheme/auth-scheme-provider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.query.auth.scheme; import java.util.List; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeProvider; import software.amazon.awssdk.services.query.auth.scheme.internal.DefaultQueryAuthSchemeProvider; /** * An auth scheme provider for Query service. The auth scheme provider takes a set of parameters using * {@link QueryAuthSchemeParams}, and resolves a list of {@link AuthSchemeOption} based on the given parameters. */ @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public interface QueryAuthSchemeProvider extends AuthSchemeProvider { /** * Resolve the auth schemes based on the given set of parameters. */ List<AuthSchemeOption> resolveAuthScheme(QueryAuthSchemeParams authSchemeParams); /** * Resolve the auth schemes based on the given set of parameters. */ default List<AuthSchemeOption> resolveAuthScheme(Consumer<QueryAuthSchemeParams.Builder> consumer) { QueryAuthSchemeParams.Builder builder = QueryAuthSchemeParams.builder(); consumer.accept(builder); return resolveAuthScheme(builder.build()); } /** * Get the default auth scheme provider. */ static QueryAuthSchemeProvider defaultProvider() { return DefaultQueryAuthSchemeProvider.create(); } }
3,095
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth/scheme/default-auth-scheme-params.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.query.auth.scheme.internal; import java.util.Optional; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.query.auth.scheme.QueryAuthSchemeParams; import software.amazon.awssdk.utils.Validate; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi public final class DefaultQueryAuthSchemeParams implements QueryAuthSchemeParams { private final String operation; private final String region; private DefaultQueryAuthSchemeParams(Builder builder) { this.operation = Validate.paramNotNull(builder.operation, "operation"); this.region = builder.region; } public static QueryAuthSchemeParams.Builder builder() { return new Builder(); } @Override public String operation() { return operation; } @Override public Optional<String> region() { return region == null ? Optional.empty() : Optional.of(region); } private static final class Builder implements QueryAuthSchemeParams.Builder { private String operation; private String region; @Override public Builder operation(String operation) { this.operation = operation; return this; } @Override public Builder region(String region) { this.region = region; return this; } @Override public QueryAuthSchemeParams build() { return new DefaultQueryAuthSchemeParams(this); } } }
3,096
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth/scheme/query-endpoint-auth-params-auth-scheme-modeled-provider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.query.auth.scheme.internal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.services.query.auth.scheme.QueryAuthSchemeParams; import software.amazon.awssdk.services.query.auth.scheme.QueryAuthSchemeProvider; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi public final class ModeledQueryAuthSchemeProvider implements QueryAuthSchemeProvider { private static final ModeledQueryAuthSchemeProvider DEFAULT = new ModeledQueryAuthSchemeProvider(); private ModeledQueryAuthSchemeProvider() { } public static ModeledQueryAuthSchemeProvider create() { return DEFAULT; } @Override public List<AuthSchemeOption> resolveAuthScheme(QueryAuthSchemeParams params) { List<AuthSchemeOption> options = new ArrayList<>(); switch (params.operation()) { case "BearerAuthOperation": options.add(AuthSchemeOption.builder().schemeId("smithy.api#httpBearerAuth").build()); break; case "OperationWithNoneAuthType": options.add(AuthSchemeOption.builder().schemeId("smithy.api#noAuth").build()); break; default: options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "query-service") .putSignerProperty(AwsV4HttpSigner.REGION_NAME, params.region().id()).build()); break; } return Collections.unmodifiableList(options); } }
3,097
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth/scheme/query-endpoint-auth-params-with-allowlist-auth-scheme-interceptor.java
package software.amazon.awssdk.services.query.auth.scheme.internal; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.internal.util.MetricUtils; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.identity.spi.ResolveIdentityRequest; import software.amazon.awssdk.identity.spi.TokenIdentity; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.metrics.SdkMetric; import software.amazon.awssdk.services.query.auth.scheme.QueryAuthSchemeParams; import software.amazon.awssdk.services.query.auth.scheme.QueryAuthSchemeProvider; import software.amazon.awssdk.services.query.endpoints.QueryEndpointParams; import software.amazon.awssdk.services.query.endpoints.internal.AuthSchemeUtils; import software.amazon.awssdk.services.query.endpoints.internal.QueryResolveEndpointInterceptor; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi public final class QueryAuthSchemeInterceptor implements ExecutionInterceptor { private static Logger LOG = Logger.loggerFor(QueryAuthSchemeInterceptor.class); @Override public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { List<AuthSchemeOption> authOptions = resolveAuthOptions(context, executionAttributes); SelectedAuthScheme<? extends Identity> selectedAuthScheme = selectAuthScheme(authOptions, executionAttributes); AuthSchemeUtils.putSelectedAuthScheme(executionAttributes, selectedAuthScheme); } private List<AuthSchemeOption> resolveAuthOptions(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { QueryAuthSchemeProvider authSchemeProvider = Validate.isInstanceOf(QueryAuthSchemeProvider.class, executionAttributes.getAttribute(SdkInternalExecutionAttribute.AUTH_SCHEME_RESOLVER), "Expected an instance of QueryAuthSchemeProvider"); QueryAuthSchemeParams params = authSchemeParams(context.request(), executionAttributes); return authSchemeProvider.resolveAuthScheme(params); } private SelectedAuthScheme<? extends Identity> selectAuthScheme(List<AuthSchemeOption> authOptions, ExecutionAttributes executionAttributes) { MetricCollector metricCollector = executionAttributes.getAttribute(SdkExecutionAttribute.API_CALL_METRIC_COLLECTOR); Map<String, AuthScheme<?>> authSchemes = executionAttributes.getAttribute(SdkInternalExecutionAttribute.AUTH_SCHEMES); IdentityProviders identityProviders = executionAttributes .getAttribute(SdkInternalExecutionAttribute.IDENTITY_PROVIDERS); List<Supplier<String>> discardedReasons = new ArrayList<>(); for (AuthSchemeOption authOption : authOptions) { AuthScheme<?> authScheme = authSchemes.get(authOption.schemeId()); SelectedAuthScheme<? extends Identity> selectedAuthScheme = trySelectAuthScheme(authOption, authScheme, identityProviders, discardedReasons, metricCollector); if (selectedAuthScheme != null) { if (!discardedReasons.isEmpty()) { LOG.debug(() -> String.format("%s auth will be used, discarded: '%s'", authOption.schemeId(), discardedReasons.stream().map(Supplier::get).collect(Collectors.joining(", ")))); } return selectedAuthScheme; } } throw SdkException .builder() .message( "Failed to determine how to authenticate the user: " + discardedReasons.stream().map(Supplier::get).collect(Collectors.joining(", "))).build(); } private QueryAuthSchemeParams authSchemeParams(SdkRequest request, ExecutionAttributes executionAttributes) { QueryEndpointParams endpointParams = QueryResolveEndpointInterceptor.ruleParams(request, executionAttributes); QueryAuthSchemeParams.Builder builder = QueryAuthSchemeParams.builder(); builder.region(endpointParams.region()); builder.defaultTrueParam(endpointParams.defaultTrueParam()); builder.defaultStringParam(endpointParams.defaultStringParam()); builder.deprecatedParam(endpointParams.deprecatedParam()); builder.booleanContextParam(endpointParams.booleanContextParam()); builder.stringContextParam(endpointParams.stringContextParam()); builder.operationContextParam(endpointParams.operationContextParam()); String operation = executionAttributes.getAttribute(SdkExecutionAttribute.OPERATION_NAME); builder.operation(operation); return builder.build(); } private <T extends Identity> SelectedAuthScheme<T> trySelectAuthScheme(AuthSchemeOption authOption, AuthScheme<T> authScheme, IdentityProviders identityProviders, List<Supplier<String>> discardedReasons, MetricCollector metricCollector) { if (authScheme == null) { discardedReasons.add(() -> String.format("'%s' is not enabled for this request.", authOption.schemeId())); return null; } IdentityProvider<T> identityProvider = authScheme.identityProvider(identityProviders); if (identityProvider == null) { discardedReasons .add(() -> String.format("'%s' does not have an identity provider configured.", authOption.schemeId())); return null; } ResolveIdentityRequest.Builder identityRequestBuilder = ResolveIdentityRequest.builder(); authOption.forEachIdentityProperty(identityRequestBuilder::putProperty); CompletableFuture<? extends T> identity; SdkMetric<Duration> metric = getIdentityMetric(identityProvider); if (metric == null) { identity = identityProvider.resolveIdentity(identityRequestBuilder.build()); } else { identity = MetricUtils.reportDuration(() -> identityProvider.resolveIdentity(identityRequestBuilder.build()), metricCollector, metric); } return new SelectedAuthScheme<>(identity, authScheme.signer(), authOption); } private SdkMetric<Duration> getIdentityMetric(IdentityProvider<?> identityProvider) { Class<?> identityType = identityProvider.identityType(); if (identityType == AwsCredentialsIdentity.class) { return CoreMetric.CREDENTIALS_FETCH_DURATION; } if (identityType == TokenIdentity.class) { return CoreMetric.TOKEN_FETCH_DURATION; } return null; } }
3,098
0
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth
Create_ds/aws-sdk-java-v2/codegen/src/test/resources/software/amazon/awssdk/codegen/poet/auth/scheme/query-auth-scheme-params.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.query.auth.scheme; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.query.auth.scheme.internal.DefaultQueryAuthSchemeParams; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * The parameters object used to resolve the auth schemes for the Query service. */ @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public interface QueryAuthSchemeParams extends ToCopyableBuilder<QueryAuthSchemeParams.Builder, QueryAuthSchemeParams> { /** * Get a new builder for creating a {@link QueryAuthSchemeParams}. */ static Builder builder() { return DefaultQueryAuthSchemeParams.builder(); } /** * Returns the operation for which to resolve the auth scheme. */ String operation(); /** * Returns the region. The region parameter may be used with the "aws.auth#sigv4" auth scheme. */ Region region(); /** * Returns a {@link Builder} to customize the parameters. */ Builder toBuilder(); /** * A builder for a {@link QueryAuthSchemeParams}. */ interface Builder extends CopyableBuilder<Builder, QueryAuthSchemeParams> { /** * Set the operation for which to resolve the auth scheme. */ Builder operation(String operation); /** * Set the region. The region parameter may be used with the "aws.auth#sigv4" auth scheme. */ Builder region(Region region); /** * Returns a {@link QueryAuthSchemeParams} object that is created from the properties that have been set on the * builder. */ QueryAuthSchemeParams build(); } }
3,099