index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/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,300
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,301
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,302
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,303
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,304
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,305
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,306
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,307
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,308
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,309
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,310
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,311
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,312
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,313
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,314
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,315
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,316
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,317
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,318
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,319
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,320
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,321
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,322
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,323
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,324
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,325
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,326
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,327
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,328
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,329
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,330
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,331
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,332
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,333
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,334
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,335
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,336
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,337
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,338
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,339
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,340
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,341
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,342
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,343
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,344
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,345
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,346
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,347
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,348
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,349
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,350
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,351
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,352
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,353
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,354
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,355
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,356
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,357
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,358
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,359
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,360
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,361
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,362
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,363
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,364
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,365
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,366
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,367
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,368
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,369
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,370
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,371
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,372
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-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 java.util.Optional; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.services.query.auth.scheme.internal.DefaultQueryAuthSchemeParams; /** * The parameters object used to resolve the auth schemes for the Query service. */ @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public interface 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 is optional. The region parameter may be used with "aws.auth#sigv4" auth scheme. * By default, the region will be empty. */ Optional<String> region(); /** * A builder for a {@link QueryAuthSchemeParams}. */ interface Builder { /** * 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(String region); /** * Returns a {@link QueryAuthSchemeParams} object that is created from the properties that have been set on the builder. */ QueryAuthSchemeParams build(); } }
3,373
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-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; 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(); /** * A param that defauls to true */ Boolean defaultTrueParam(); String defaultStringParam(); @Deprecated String deprecatedParam(); Boolean booleanContextParam(); String stringContextParam(); String operationContextParam(); /** * 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); /** * A param that defauls to true */ Builder defaultTrueParam(Boolean defaultTrueParam); Builder defaultStringParam(String defaultStringParam); @Deprecated Builder deprecatedParam(String deprecatedParam); Builder booleanContextParam(Boolean booleanContextParam); Builder stringContextParam(String stringContextParam); Builder operationContextParam(String operationContextParam); /** * Returns a {@link QueryAuthSchemeParams} object that is created from the properties that have been set on the * builder. */ QueryAuthSchemeParams build(); } }
3,374
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-without-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 useDualStackEndpoint; private final Boolean useFIPSEndpoint; private final String endpointId; 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.useDualStackEndpoint = builder.useDualStackEndpoint; this.useFIPSEndpoint = builder.useFIPSEndpoint; this.endpointId = builder.endpointId; 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 useDualStackEndpoint() { return useDualStackEndpoint; } @Override public Boolean useFipsEndpoint() { return useFIPSEndpoint; } @Override public String endpointId() { return endpointId; } @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 useDualStackEndpoint; private Boolean useFIPSEndpoint; private String endpointId; 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.useDualStackEndpoint = params.useDualStackEndpoint; this.useFIPSEndpoint = params.useFIPSEndpoint; this.endpointId = params.endpointId; 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 useDualStackEndpoint(Boolean useDualStackEndpoint) { this.useDualStackEndpoint = useDualStackEndpoint; return this; } @Override public Builder useFipsEndpoint(Boolean useFIPSEndpoint) { this.useFIPSEndpoint = useFIPSEndpoint; return this; } @Override public Builder endpointId(String endpointId) { this.endpointId = endpointId; 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,375
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/ops-with-no-auth-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 "GetDatabaseVersion": options.add(AuthSchemeOption.builder().schemeId("smithy.api#noAuth").build()); break; case "GetRow": 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()); options.add(AuthSchemeOption.builder().schemeId("smithy.api#noAuth").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,376
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-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.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 DefaultQueryAuthSchemeProvider implements QueryAuthSchemeProvider { private static final DefaultQueryAuthSchemeProvider DEFAULT = new DefaultQueryAuthSchemeProvider(); private DefaultQueryAuthSchemeProvider() { } public static DefaultQueryAuthSchemeProvider 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,377
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-endpoint-provider.java
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.awscore.endpoints.AwsEndpointAttribute; import software.amazon.awssdk.awscore.endpoints.authscheme.EndpointAuthScheme; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4AuthScheme; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4aAuthScheme; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner; import software.amazon.awssdk.http.auth.aws.signer.RegionSet; 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; import software.amazon.awssdk.services.query.endpoints.QueryEndpointParams; import software.amazon.awssdk.services.query.endpoints.QueryEndpointProvider; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.Validate; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi public final class DefaultQueryAuthSchemeProvider implements QueryAuthSchemeProvider { private static final DefaultQueryAuthSchemeProvider DEFAULT = new DefaultQueryAuthSchemeProvider(); private static final QueryAuthSchemeProvider MODELED_RESOLVER = ModeledQueryAuthSchemeProvider.create(); private static final QueryEndpointProvider DELEGATE = QueryEndpointProvider.defaultProvider(); private DefaultQueryAuthSchemeProvider() { } public static QueryAuthSchemeProvider create() { return DEFAULT; } @Override public List<AuthSchemeOption> resolveAuthScheme(QueryAuthSchemeParams params) { QueryEndpointParams endpointParameters = QueryEndpointParams.builder().region(params.region()) .defaultTrueParam(params.defaultTrueParam()).defaultStringParam(params.defaultStringParam()) .deprecatedParam(params.deprecatedParam()).booleanContextParam(params.booleanContextParam()) .stringContextParam(params.stringContextParam()).operationContextParam(params.operationContextParam()).build(); Endpoint endpoint = CompletableFutureUtils.joinLikeSync(DELEGATE.resolveEndpoint(endpointParameters)); List<EndpointAuthScheme> authSchemes = endpoint.attribute(AwsEndpointAttribute.AUTH_SCHEMES); if (authSchemes == null) { return MODELED_RESOLVER.resolveAuthScheme(params); } List<AuthSchemeOption> options = new ArrayList<>(); for (EndpointAuthScheme authScheme : authSchemes) { String name = authScheme.name(); switch (name) { case "sigv4": SigV4AuthScheme sigv4AuthScheme = Validate.isInstanceOf(SigV4AuthScheme.class, authScheme, "Expecting auth scheme of class SigV4AuthScheme, got instead object of class %s", authScheme.getClass() .getName()); options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, sigv4AuthScheme.signingName()) .putSignerProperty(AwsV4HttpSigner.REGION_NAME, sigv4AuthScheme.signingRegion()) .putSignerProperty(AwsV4HttpSigner.DOUBLE_URL_ENCODE, !sigv4AuthScheme.disableDoubleEncoding()).build()); break; case "sigv4a": SigV4aAuthScheme sigv4aAuthScheme = Validate.isInstanceOf(SigV4aAuthScheme.class, authScheme, "Expecting auth scheme of class SigV4AuthScheme, got instead object of class %s", authScheme.getClass() .getName()); RegionSet regionSet = RegionSet.create(sigv4aAuthScheme.signingRegionSet()); options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4a") .putSignerProperty(AwsV4aHttpSigner.SERVICE_SIGNING_NAME, sigv4aAuthScheme.signingName()) .putSignerProperty(AwsV4aHttpSigner.REGION_SET, regionSet) .putSignerProperty(AwsV4aHttpSigner.DOUBLE_URL_ENCODE, !sigv4aAuthScheme.disableDoubleEncoding()).build()); break; default: throw new IllegalArgumentException("Unknown auth scheme: " + name); } } return Collections.unmodifiableList(options); } }
3,378
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-default-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 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 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 Region region() { return region; } @Override public QueryAuthSchemeParams.Builder toBuilder() { return new Builder(this); } private static final class Builder implements QueryAuthSchemeParams.Builder { private String operation; private Region region; Builder() { } Builder(DefaultQueryAuthSchemeParams params) { this.operation = params.operation; this.region = params.region; } @Override public Builder operation(String operation) { this.operation = operation; return this; } @Override public Builder region(Region region) { this.region = region; return this; } @Override public QueryAuthSchemeParams build() { return new DefaultQueryAuthSchemeParams(this); } } }
3,379
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-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.List; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; 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 DefaultQueryAuthSchemeProvider implements QueryAuthSchemeProvider { private static final DefaultQueryAuthSchemeProvider DEFAULT = new DefaultQueryAuthSchemeProvider(); private DefaultQueryAuthSchemeProvider() { } public static DefaultQueryAuthSchemeProvider create() { return DEFAULT; } @Override public List<AuthSchemeOption> resolveAuthScheme(QueryAuthSchemeParams authSchemeParams) { return new ArrayList<>(); } }
3,380
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-params-without-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; 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(); Boolean useDualStackEndpoint(); Boolean useFipsEndpoint(); String endpointId(); /** * A param that defauls to true */ Boolean defaultTrueParam(); String defaultStringParam(); @Deprecated String deprecatedParam(); Boolean booleanContextParam(); String stringContextParam(); String operationContextParam(); /** * 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); Builder useDualStackEndpoint(Boolean useDualStackEndpoint); Builder useFipsEndpoint(Boolean useFIPSEndpoint); Builder endpointId(String endpointId); /** * A param that defauls to true */ Builder defaultTrueParam(Boolean defaultTrueParam); Builder defaultStringParam(String defaultStringParam); @Deprecated Builder deprecatedParam(String deprecatedParam); Builder booleanContextParam(Boolean booleanContextParam); Builder stringContextParam(String stringContextParam); Builder operationContextParam(String operationContextParam); /** * Returns a {@link QueryAuthSchemeParams} object that is created from the properties that have been set on the * builder. */ QueryAuthSchemeParams build(); } }
3,381
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-same-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<>(); 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()); return Collections.unmodifiableList(options); } }
3,382
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/mini-s3-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.minis3.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.minis3.auth.scheme.MiniS3AuthSchemeParams; import software.amazon.awssdk.services.minis3.auth.scheme.MiniS3AuthSchemeProvider; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi public final class DefaultMiniS3AuthSchemeProvider implements MiniS3AuthSchemeProvider { private static final DefaultMiniS3AuthSchemeProvider DEFAULT = new DefaultMiniS3AuthSchemeProvider(); private DefaultMiniS3AuthSchemeProvider() { } public static DefaultMiniS3AuthSchemeProvider create() { return DEFAULT; } @Override public List<AuthSchemeOption> resolveAuthScheme(MiniS3AuthSchemeParams params) { List<AuthSchemeOption> options = new ArrayList<>(); options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, "mini-s3-service") .putSignerProperty(AwsV4HttpSigner.REGION_NAME, params.region().id()) .putSignerProperty(AwsV4HttpSigner.DOUBLE_URL_ENCODE, false) .putSignerProperty(AwsV4HttpSigner.NORMALIZE_PATH, false) .putSignerProperty(AwsV4HttpSigner.PAYLOAD_SIGNING_ENABLED, false).build()); return Collections.unmodifiableList(options); } }
3,383
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-endpoint-provider-without-allowlist.java
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.awscore.endpoints.AwsEndpointAttribute; import software.amazon.awssdk.awscore.endpoints.authscheme.EndpointAuthScheme; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4AuthScheme; import software.amazon.awssdk.awscore.endpoints.authscheme.SigV4aAuthScheme; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner; import software.amazon.awssdk.http.auth.aws.signer.RegionSet; 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; import software.amazon.awssdk.services.query.endpoints.QueryEndpointParams; import software.amazon.awssdk.services.query.endpoints.QueryEndpointProvider; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.Validate; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi public final class DefaultQueryAuthSchemeProvider implements QueryAuthSchemeProvider { private static final DefaultQueryAuthSchemeProvider DEFAULT = new DefaultQueryAuthSchemeProvider(); private static final QueryAuthSchemeProvider MODELED_RESOLVER = ModeledQueryAuthSchemeProvider.create(); private static final QueryEndpointProvider DELEGATE = QueryEndpointProvider.defaultProvider(); private DefaultQueryAuthSchemeProvider() { } public static QueryAuthSchemeProvider create() { return DEFAULT; } @Override public List<AuthSchemeOption> resolveAuthScheme(QueryAuthSchemeParams params) { QueryEndpointParams endpointParameters = QueryEndpointParams.builder().region(params.region()) .useDualStackEndpoint(params.useDualStackEndpoint()).useFipsEndpoint(params.useFipsEndpoint()) .endpointId(params.endpointId()).defaultTrueParam(params.defaultTrueParam()) .defaultStringParam(params.defaultStringParam()).deprecatedParam(params.deprecatedParam()) .booleanContextParam(params.booleanContextParam()).stringContextParam(params.stringContextParam()) .operationContextParam(params.operationContextParam()).build(); Endpoint endpoint = CompletableFutureUtils.joinLikeSync(DELEGATE.resolveEndpoint(endpointParameters)); List<EndpointAuthScheme> authSchemes = endpoint.attribute(AwsEndpointAttribute.AUTH_SCHEMES); if (authSchemes == null) { return MODELED_RESOLVER.resolveAuthScheme(params); } List<AuthSchemeOption> options = new ArrayList<>(); for (EndpointAuthScheme authScheme : authSchemes) { String name = authScheme.name(); switch (name) { case "sigv4": SigV4AuthScheme sigv4AuthScheme = Validate.isInstanceOf(SigV4AuthScheme.class, authScheme, "Expecting auth scheme of class SigV4AuthScheme, got instead object of class %s", authScheme.getClass() .getName()); options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4") .putSignerProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, sigv4AuthScheme.signingName()) .putSignerProperty(AwsV4HttpSigner.REGION_NAME, sigv4AuthScheme.signingRegion()) .putSignerProperty(AwsV4HttpSigner.DOUBLE_URL_ENCODE, !sigv4AuthScheme.disableDoubleEncoding()).build()); break; case "sigv4a": SigV4aAuthScheme sigv4aAuthScheme = Validate.isInstanceOf(SigV4aAuthScheme.class, authScheme, "Expecting auth scheme of class SigV4AuthScheme, got instead object of class %s", authScheme.getClass() .getName()); RegionSet regionSet = RegionSet.create(sigv4aAuthScheme.signingRegionSet()); options.add(AuthSchemeOption.builder().schemeId("aws.auth#sigv4a") .putSignerProperty(AwsV4aHttpSigner.SERVICE_SIGNING_NAME, sigv4aAuthScheme.signingName()) .putSignerProperty(AwsV4aHttpSigner.REGION_SET, regionSet) .putSignerProperty(AwsV4aHttpSigner.DOUBLE_URL_ENCODE, !sigv4aAuthScheme.disableDoubleEncoding()).build()); break; default: throw new IllegalArgumentException("Unknown auth scheme: " + name); } } return Collections.unmodifiableList(options); } }
3,384
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-without-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.useDualStackEndpoint(endpointParams.useDualStackEndpoint()); builder.useFipsEndpoint(endpointParams.useFipsEndpoint()); builder.endpointId(endpointParams.endpointId()); 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,385
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/plugins/InternalTestPlugin2.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.plugins; import software.amazon.awssdk.core.SdkPlugin; import software.amazon.awssdk.core.SdkServiceClientConfiguration; public class InternalTestPlugin2 implements SdkPlugin { @Override public void configureClient(SdkServiceClientConfiguration.Builder config) { } }
3,386
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/plugins/InternalTestPlugin1.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.poet.plugins; import software.amazon.awssdk.core.SdkPlugin; import software.amazon.awssdk.core.SdkServiceClientConfiguration; public class InternalTestPlugin1 implements SdkPlugin { @Override public void configureClient(SdkServiceClientConfiguration.Builder config) { } }
3,387
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/endpointdiscovery/test-sync-cache-loader.java
package software.amazon.awssdk.services.endpointdiscoverytest; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryCacheLoader; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryEndpoint; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryRequest; import software.amazon.awssdk.services.endpointdiscoverytest.model.DescribeEndpointsResponse; import software.amazon.awssdk.services.endpointdiscoverytest.model.Endpoint; import software.amazon.awssdk.utils.Validate; @SdkInternalApi @Generated("software.amazon.awssdk:codegen") class EndpointDiscoveryTestEndpointDiscoveryCacheLoader implements EndpointDiscoveryCacheLoader { private final EndpointDiscoveryTestClient client; private EndpointDiscoveryTestEndpointDiscoveryCacheLoader(EndpointDiscoveryTestClient client) { this.client = client; } public static EndpointDiscoveryTestEndpointDiscoveryCacheLoader create(EndpointDiscoveryTestClient client) { return new EndpointDiscoveryTestEndpointDiscoveryCacheLoader(client); } @Override public CompletableFuture<EndpointDiscoveryEndpoint> discoverEndpoint(EndpointDiscoveryRequest endpointDiscoveryRequest) { return CompletableFuture.supplyAsync(() -> { AwsRequestOverrideConfiguration requestConfig = AwsRequestOverrideConfiguration.from(endpointDiscoveryRequest .overrideConfiguration().orElse(null)); DescribeEndpointsResponse response = client .describeEndpoints(software.amazon.awssdk.services.endpointdiscoverytest.model.DescribeEndpointsRequest .builder().overrideConfiguration(requestConfig).build()); List<Endpoint> endpoints = response.endpoints(); Validate.notEmpty(endpoints, "Endpoints returned by service for endpoint discovery must not be empty."); Endpoint endpoint = endpoints.get(0); return EndpointDiscoveryEndpoint.builder() .endpoint(toUri(endpoint.address(), endpointDiscoveryRequest.defaultEndpoint())) .expirationTime(Instant.now().plus(endpoint.cachePeriodInMinutes(), ChronoUnit.MINUTES)).build(); }); } }
3,388
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/endpointdiscovery/test-async-cache-loader.java
package software.amazon.awssdk.services.endpointdiscoverytest; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryCacheLoader; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryEndpoint; import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryRequest; import software.amazon.awssdk.services.endpointdiscoverytest.model.Endpoint; import software.amazon.awssdk.utils.Validate; @SdkInternalApi @Generated("software.amazon.awssdk:codegen") class EndpointDiscoveryTestAsyncEndpointDiscoveryCacheLoader implements EndpointDiscoveryCacheLoader { private final EndpointDiscoveryTestAsyncClient client; EndpointDiscoveryTestAsyncEndpointDiscoveryCacheLoader(EndpointDiscoveryTestAsyncClient client) { this.client = client; } public static EndpointDiscoveryTestAsyncEndpointDiscoveryCacheLoader create(EndpointDiscoveryTestAsyncClient client) { return new EndpointDiscoveryTestAsyncEndpointDiscoveryCacheLoader(client); } @Override public CompletableFuture<EndpointDiscoveryEndpoint> discoverEndpoint(EndpointDiscoveryRequest endpointDiscoveryRequest) { AwsRequestOverrideConfiguration requestConfig = AwsRequestOverrideConfiguration.from(endpointDiscoveryRequest .overrideConfiguration().orElse(null)); return client.describeEndpoints( software.amazon.awssdk.services.endpointdiscoverytest.model.DescribeEndpointsRequest.builder() .overrideConfiguration(requestConfig).build()).thenApply( r -> { List<Endpoint> endpoints = r.endpoints(); Validate.notEmpty(endpoints, "Endpoints returned by service for endpoint discovery must not be empty."); Endpoint endpoint = endpoints.get(0); return EndpointDiscoveryEndpoint.builder() .endpoint(toUri(endpoint.address(), endpointDiscoveryRequest.defaultEndpoint())) .expirationTime(Instant.now().plus(endpoint.cachePeriodInMinutes(), ChronoUnit.MINUTES)).build(); }); } }
3,389
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/waiters/query-async-waiter-class.java
package software.amazon.awssdk.services.query.waiters; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.core.internal.waiters.WaiterAttribute; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; import software.amazon.awssdk.core.waiters.AsyncWaiter; import software.amazon.awssdk.core.waiters.WaiterAcceptor; import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.core.waiters.WaiterState; import software.amazon.awssdk.services.query.QueryAsyncClient; import software.amazon.awssdk.services.query.model.APostOperationRequest; import software.amazon.awssdk.services.query.model.APostOperationResponse; import software.amazon.awssdk.services.query.model.QueryRequest; import software.amazon.awssdk.services.query.waiters.internal.WaitersRuntime; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.ThreadFactoryBuilder; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi @ThreadSafe final class DefaultQueryAsyncWaiter implements QueryAsyncWaiter { private static final WaiterAttribute<SdkAutoCloseable> CLIENT_ATTRIBUTE = new WaiterAttribute<>(SdkAutoCloseable.class); private static final WaiterAttribute<ScheduledExecutorService> SCHEDULED_EXECUTOR_SERVICE_ATTRIBUTE = new WaiterAttribute<>( ScheduledExecutorService.class); private final QueryAsyncClient client; private final AttributeMap managedResources; private final AsyncWaiter<APostOperationResponse> postOperationSuccessWaiter; private final ScheduledExecutorService executorService; private DefaultQueryAsyncWaiter(DefaultBuilder builder) { AttributeMap.Builder attributeMapBuilder = AttributeMap.builder(); if (builder.client == null) { this.client = QueryAsyncClient.builder().build(); attributeMapBuilder.put(CLIENT_ATTRIBUTE, this.client); } else { this.client = builder.client; } if (builder.executorService == null) { this.executorService = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().threadNamePrefix("waiters-ScheduledExecutor").build()); attributeMapBuilder.put(SCHEDULED_EXECUTOR_SERVICE_ATTRIBUTE, this.executorService); } else { this.executorService = builder.executorService; } managedResources = attributeMapBuilder.build(); this.postOperationSuccessWaiter = AsyncWaiter.builder(APostOperationResponse.class) .acceptors(postOperationSuccessWaiterAcceptors()) .overrideConfiguration(postOperationSuccessWaiterConfig(builder.overrideConfiguration)) .scheduledExecutorService(executorService).build(); } private static String errorCode(Throwable error) { if (error instanceof AwsServiceException) { return ((AwsServiceException) error).awsErrorDetails().errorCode(); } return null; } @Override public CompletableFuture<WaiterResponse<APostOperationResponse>> waitUntilPostOperationSuccess( APostOperationRequest aPostOperationRequest) { return postOperationSuccessWaiter.runAsync(() -> client.aPostOperation(applyWaitersUserAgent(aPostOperationRequest))); } @Override public CompletableFuture<WaiterResponse<APostOperationResponse>> waitUntilPostOperationSuccess( APostOperationRequest aPostOperationRequest, WaiterOverrideConfiguration overrideConfig) { return postOperationSuccessWaiter.runAsync(() -> client.aPostOperation(applyWaitersUserAgent(aPostOperationRequest)), postOperationSuccessWaiterConfig(overrideConfig)); } private static List<WaiterAcceptor<? super APostOperationResponse>> postOperationSuccessWaiterAcceptors() { List<WaiterAcceptor<? super APostOperationResponse>> result = new ArrayList<>(); result.add(new WaitersRuntime.ResponseStatusAcceptor(200, WaiterState.SUCCESS)); result.add(new WaitersRuntime.ResponseStatusAcceptor(404, WaiterState.RETRY)); result.add(WaiterAcceptor.successOnResponseAcceptor(response -> { WaitersRuntime.Value input = new WaitersRuntime.Value(response); List<Object> resultValues = input.field("foo").field("bar").values(); return !resultValues.isEmpty() && resultValues.stream().anyMatch(v -> Objects.equals(v, "baz")); })); result.addAll(WaitersRuntime.DEFAULT_ACCEPTORS); return result; } private static WaiterOverrideConfiguration postOperationSuccessWaiterConfig(WaiterOverrideConfiguration overrideConfig) { Optional<WaiterOverrideConfiguration> optionalOverrideConfig = Optional.ofNullable(overrideConfig); int maxAttempts = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::maxAttempts).orElse(40); BackoffStrategy backoffStrategy = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::backoffStrategy).orElse( FixedDelayBackoffStrategy.create(Duration.ofSeconds(1))); Duration waitTimeout = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::waitTimeout).orElse(null); return WaiterOverrideConfiguration.builder().maxAttempts(maxAttempts).backoffStrategy(backoffStrategy) .waitTimeout(waitTimeout).build(); } @Override public void close() { managedResources.close(); } public static QueryAsyncWaiter.Builder builder() { return new DefaultBuilder(); } private <T extends QueryRequest> T applyWaitersUserAgent(T request) { Consumer<AwsRequestOverrideConfiguration.Builder> userAgentApplier = b -> b.addApiName(ApiName.builder() .version("waiter").name("hll").build()); AwsRequestOverrideConfiguration overrideConfiguration = request.overrideConfiguration() .map(c -> c.toBuilder().applyMutation(userAgentApplier).build()) .orElse((AwsRequestOverrideConfiguration.builder().applyMutation(userAgentApplier).build())); return (T) request.toBuilder().overrideConfiguration(overrideConfiguration).build(); } public static final class DefaultBuilder implements QueryAsyncWaiter.Builder { private QueryAsyncClient client; private WaiterOverrideConfiguration overrideConfiguration; private ScheduledExecutorService executorService; private DefaultBuilder() { } @Override public QueryAsyncWaiter.Builder scheduledExecutorService(ScheduledExecutorService executorService) { this.executorService = executorService; return this; } @Override public QueryAsyncWaiter.Builder overrideConfiguration(WaiterOverrideConfiguration overrideConfiguration) { this.overrideConfiguration = overrideConfiguration; return this; } @Override public QueryAsyncWaiter.Builder client(QueryAsyncClient client) { this.client = client; return this; } public QueryAsyncWaiter build() { return new DefaultQueryAsyncWaiter(this); } } }
3,390
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/waiters/query-sync-waiter-interface.java
package software.amazon.awssdk.services.query.waiters; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.services.query.QueryClient; import software.amazon.awssdk.services.query.model.APostOperationRequest; import software.amazon.awssdk.services.query.model.APostOperationResponse; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Waiter utility class that polls a resource until a desired state is reached or until it is determined that the * resource will never enter into the desired state. This can be created using the static {@link #builder()} method */ @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public interface QueryWaiter extends SdkAutoCloseable { /** * Polls {@link QueryClient#aPostOperation} API until the desired condition {@code PostOperationSuccess} is met, or * until it is determined that the resource will never enter into the desired state * * @param aPostOperationRequest * the request to be used for polling * @return WaiterResponse containing either a response or an exception that has matched with the waiter success * condition */ default WaiterResponse<APostOperationResponse> waitUntilPostOperationSuccess(APostOperationRequest aPostOperationRequest) { throw new UnsupportedOperationException(); } /** * Polls {@link QueryClient#aPostOperation} API until the desired condition {@code PostOperationSuccess} is met, or * until it is determined that the resource will never enter into the desired state. * <p> * This is a convenience method to create an instance of the request builder without the need to create one manually * using {@link APostOperationRequest#builder()} * * @param aPostOperationRequest * The consumer that will configure the request to be used for polling * @return WaiterResponse containing either a response or an exception that has matched with the waiter success * condition */ default WaiterResponse<APostOperationResponse> waitUntilPostOperationSuccess( Consumer<APostOperationRequest.Builder> aPostOperationRequest) { return waitUntilPostOperationSuccess(APostOperationRequest.builder().applyMutation(aPostOperationRequest).build()); } /** * Polls {@link QueryClient#aPostOperation} API until the desired condition {@code PostOperationSuccess} is met, or * until it is determined that the resource will never enter into the desired state * * @param aPostOperationRequest * The request to be used for polling * @param overrideConfig * Per request override configuration for waiters * @return WaiterResponse containing either a response or an exception that has matched with the waiter success * condition */ default WaiterResponse<APostOperationResponse> waitUntilPostOperationSuccess(APostOperationRequest aPostOperationRequest, WaiterOverrideConfiguration overrideConfig) { throw new UnsupportedOperationException(); } /** * Polls {@link QueryClient#aPostOperation} API until the desired condition {@code PostOperationSuccess} is met, or * until it is determined that the resource will never enter into the desired state. * <p> * This is a convenience method to create an instance of the request builder and instance of the override config * builder * * @param aPostOperationRequest * The consumer that will configure the request to be used for polling * @param overrideConfig * The consumer that will configure the per request override configuration for waiters * @return WaiterResponse containing either a response or an exception that has matched with the waiter success * condition */ default WaiterResponse<APostOperationResponse> waitUntilPostOperationSuccess( Consumer<APostOperationRequest.Builder> aPostOperationRequest, Consumer<WaiterOverrideConfiguration.Builder> overrideConfig) { return waitUntilPostOperationSuccess(APostOperationRequest.builder().applyMutation(aPostOperationRequest).build(), WaiterOverrideConfiguration.builder().applyMutation(overrideConfig).build()); } /** * Create a builder that can be used to configure and create a {@link QueryWaiter}. * * @return a builder */ static Builder builder() { return DefaultQueryWaiter.builder(); } /** * Create an instance of {@link QueryWaiter} with the default configuration. * <p> * <b>A default {@link QueryClient} will be created to poll resources. It is recommended to share a single instance * of the waiter created via this method. If it is not desirable to share a waiter instance, invoke {@link #close()} * to release the resources once the waiter is not needed.</b> * * @return an instance of {@link QueryWaiter} */ static QueryWaiter create() { return DefaultQueryWaiter.builder().build(); } interface Builder { /** * Defines overrides to the default SDK waiter configuration that should be used for waiters created from this * builder * * @param overrideConfiguration * the override configuration to set * @return a reference to this object so that method calls can be chained together. */ Builder overrideConfiguration(WaiterOverrideConfiguration overrideConfiguration); /** * This is a convenient method to pass the override configuration without the need to create an instance * manually via {@link WaiterOverrideConfiguration#builder()} * * @param overrideConfiguration * The consumer that will configure the overrideConfiguration * @return a reference to this object so that method calls can be chained together. * @see #overrideConfiguration(WaiterOverrideConfiguration) */ default Builder overrideConfiguration(Consumer<WaiterOverrideConfiguration.Builder> overrideConfiguration) { WaiterOverrideConfiguration.Builder builder = WaiterOverrideConfiguration.builder(); overrideConfiguration.accept(builder); return overrideConfiguration(builder.build()); } /** * Sets a custom {@link QueryClient} that will be used to poll the resource * <p> * This SDK client must be closed by the caller when it is ready to be disposed. The SDK will not close the * client when the waiter is closed * * @param client * the client to send the request * @return a reference to this object so that method calls can be chained together. */ Builder client(QueryClient client); /** * Builds an instance of {@link QueryWaiter} based on the configurations supplied to this builder * * @return An initialized {@link QueryWaiter} */ QueryWaiter build(); } }
3,391
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/waiters/query-async-waiter-interface.java
package software.amazon.awssdk.services.query.waiters; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.services.query.QueryAsyncClient; import software.amazon.awssdk.services.query.model.APostOperationRequest; import software.amazon.awssdk.services.query.model.APostOperationResponse; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Waiter utility class that polls a resource until a desired state is reached or until it is determined that the * resource will never enter into the desired state. This can be created using the static {@link #builder()} method */ @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public interface QueryAsyncWaiter extends SdkAutoCloseable { /** * Polls {@link QueryAsyncClient#aPostOperation} API until the desired condition {@code PostOperationSuccess} is * met, or until it is determined that the resource will never enter into the desired state * * @param aPostOperationRequest * the request to be used for polling * @return CompletableFuture containing the WaiterResponse. It completes successfully when the resource enters into * a desired state or exceptionally when it is determined that the resource will never enter into the * desired state. */ default CompletableFuture<WaiterResponse<APostOperationResponse>> waitUntilPostOperationSuccess( APostOperationRequest aPostOperationRequest) { throw new UnsupportedOperationException(); } /** * Polls {@link QueryAsyncClient#aPostOperation} API until the desired condition {@code PostOperationSuccess} is * met, or until it is determined that the resource will never enter into the desired state. * <p> * This is a convenience method to create an instance of the request builder without the need to create one manually * using {@link APostOperationRequest#builder()} * * @param aPostOperationRequest * The consumer that will configure the request to be used for polling * @return CompletableFuture of the WaiterResponse containing either a response or an exception that has matched * with the waiter success condition */ default CompletableFuture<WaiterResponse<APostOperationResponse>> waitUntilPostOperationSuccess( Consumer<APostOperationRequest.Builder> aPostOperationRequest) { return waitUntilPostOperationSuccess(APostOperationRequest.builder().applyMutation(aPostOperationRequest).build()); } /** * Polls {@link QueryAsyncClient#aPostOperation} API until the desired condition {@code PostOperationSuccess} is * met, or until it is determined that the resource will never enter into the desired state * * @param aPostOperationRequest * The request to be used for polling * @param overrideConfig * Per request override configuration for waiters * @return WaiterResponse containing either a response or an exception that has matched with the waiter success * condition */ default CompletableFuture<WaiterResponse<APostOperationResponse>> waitUntilPostOperationSuccess( APostOperationRequest aPostOperationRequest, WaiterOverrideConfiguration overrideConfig) { throw new UnsupportedOperationException(); } /** * Polls {@link QueryAsyncClient#aPostOperation} API until the desired condition {@code PostOperationSuccess} is * met, or until it is determined that the resource will never enter into the desired state. * <p> * This is a convenience method to create an instance of the request builder and instance of the override config * builder * * @param aPostOperationRequest * The consumer that will configure the request to be used for polling * @param overrideConfig * The consumer that will configure the per request override configuration for waiters * @return WaiterResponse containing either a response or an exception that has matched with the waiter success * condition */ default CompletableFuture<WaiterResponse<APostOperationResponse>> waitUntilPostOperationSuccess( Consumer<APostOperationRequest.Builder> aPostOperationRequest, Consumer<WaiterOverrideConfiguration.Builder> overrideConfig) { return waitUntilPostOperationSuccess(APostOperationRequest.builder().applyMutation(aPostOperationRequest).build(), WaiterOverrideConfiguration.builder().applyMutation(overrideConfig).build()); } /** * Create a builder that can be used to configure and create a {@link QueryAsyncWaiter}. * * @return a builder */ static Builder builder() { return DefaultQueryAsyncWaiter.builder(); } /** * Create an instance of {@link QueryAsyncWaiter} with the default configuration. * <p> * <b>A default {@link QueryAsyncClient} will be created to poll resources. It is recommended to share a single * instance of the waiter created via this method. If it is not desirable to share a waiter instance, invoke * {@link #close()} to release the resources once the waiter is not needed.</b> * * @return an instance of {@link QueryAsyncWaiter} */ static QueryAsyncWaiter create() { return DefaultQueryAsyncWaiter.builder().build(); } interface Builder { /** * Sets a custom {@link ScheduledExecutorService} that will be used to schedule async polling attempts * <p> * This executorService must be closed by the caller when it is ready to be disposed. The SDK will not close the * executorService when the waiter is closed * * @param executorService * the executorService to set * @return a reference to this object so that method calls can be chained together. */ Builder scheduledExecutorService(ScheduledExecutorService executorService); /** * Defines overrides to the default SDK waiter configuration that should be used for waiters created from this * builder * * @param overrideConfiguration * the override configuration to set * @return a reference to this object so that method calls can be chained together. */ Builder overrideConfiguration(WaiterOverrideConfiguration overrideConfiguration); /** * This is a convenient method to pass the override configuration without the need to create an instance * manually via {@link WaiterOverrideConfiguration#builder()} * * @param overrideConfiguration * The consumer that will configure the overrideConfiguration * @return a reference to this object so that method calls can be chained together. * @see #overrideConfiguration(WaiterOverrideConfiguration) */ default Builder overrideConfiguration(Consumer<WaiterOverrideConfiguration.Builder> overrideConfiguration) { WaiterOverrideConfiguration.Builder builder = WaiterOverrideConfiguration.builder(); overrideConfiguration.accept(builder); return overrideConfiguration(builder.build()); } /** * Sets a custom {@link QueryAsyncClient} that will be used to poll the resource * <p> * This SDK client must be closed by the caller when it is ready to be disposed. The SDK will not close the * client when the waiter is closed * * @param client * the client to send the request * @return a reference to this object so that method calls can be chained together. */ Builder client(QueryAsyncClient client); /** * Builds an instance of {@link QueryAsyncWaiter} based on the configurations supplied to this builder * * @return An initialized {@link QueryAsyncWaiter} */ QueryAsyncWaiter build(); } }
3,392
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/waiters/query-sync-waiter-class.java
package software.amazon.awssdk.services.query.waiters; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.core.internal.waiters.WaiterAttribute; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; import software.amazon.awssdk.core.waiters.Waiter; import software.amazon.awssdk.core.waiters.WaiterAcceptor; import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.core.waiters.WaiterState; import software.amazon.awssdk.services.query.QueryClient; import software.amazon.awssdk.services.query.model.APostOperationRequest; import software.amazon.awssdk.services.query.model.APostOperationResponse; import software.amazon.awssdk.services.query.model.QueryRequest; import software.amazon.awssdk.services.query.waiters.internal.WaitersRuntime; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.SdkAutoCloseable; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi @ThreadSafe final class DefaultQueryWaiter implements QueryWaiter { private static final WaiterAttribute<SdkAutoCloseable> CLIENT_ATTRIBUTE = new WaiterAttribute<>(SdkAutoCloseable.class); private final QueryClient client; private final AttributeMap managedResources; private final Waiter<APostOperationResponse> postOperationSuccessWaiter; private DefaultQueryWaiter(DefaultBuilder builder) { AttributeMap.Builder attributeMapBuilder = AttributeMap.builder(); if (builder.client == null) { this.client = QueryClient.builder().build(); attributeMapBuilder.put(CLIENT_ATTRIBUTE, this.client); } else { this.client = builder.client; } managedResources = attributeMapBuilder.build(); this.postOperationSuccessWaiter = Waiter.builder(APostOperationResponse.class) .acceptors(postOperationSuccessWaiterAcceptors()) .overrideConfiguration(postOperationSuccessWaiterConfig(builder.overrideConfiguration)).build(); } private static String errorCode(Throwable error) { if (error instanceof AwsServiceException) { return ((AwsServiceException) error).awsErrorDetails().errorCode(); } return null; } @Override public WaiterResponse<APostOperationResponse> waitUntilPostOperationSuccess(APostOperationRequest aPostOperationRequest) { return postOperationSuccessWaiter.run(() -> client.aPostOperation(applyWaitersUserAgent(aPostOperationRequest))); } @Override public WaiterResponse<APostOperationResponse> waitUntilPostOperationSuccess(APostOperationRequest aPostOperationRequest, WaiterOverrideConfiguration overrideConfig) { return postOperationSuccessWaiter.run(() -> client.aPostOperation(applyWaitersUserAgent(aPostOperationRequest)), postOperationSuccessWaiterConfig(overrideConfig)); } private static List<WaiterAcceptor<? super APostOperationResponse>> postOperationSuccessWaiterAcceptors() { List<WaiterAcceptor<? super APostOperationResponse>> result = new ArrayList<>(); result.add(new WaitersRuntime.ResponseStatusAcceptor(200, WaiterState.SUCCESS)); result.add(new WaitersRuntime.ResponseStatusAcceptor(404, WaiterState.RETRY)); result.add(WaiterAcceptor.successOnResponseAcceptor(response -> { WaitersRuntime.Value input = new WaitersRuntime.Value(response); List<Object> resultValues = input.field("foo").field("bar").values(); return !resultValues.isEmpty() && resultValues.stream().anyMatch(v -> Objects.equals(v, "baz")); })); result.addAll(WaitersRuntime.DEFAULT_ACCEPTORS); return result; } private static WaiterOverrideConfiguration postOperationSuccessWaiterConfig(WaiterOverrideConfiguration overrideConfig) { Optional<WaiterOverrideConfiguration> optionalOverrideConfig = Optional.ofNullable(overrideConfig); int maxAttempts = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::maxAttempts).orElse(40); BackoffStrategy backoffStrategy = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::backoffStrategy).orElse( FixedDelayBackoffStrategy.create(Duration.ofSeconds(1))); Duration waitTimeout = optionalOverrideConfig.flatMap(WaiterOverrideConfiguration::waitTimeout).orElse(null); return WaiterOverrideConfiguration.builder().maxAttempts(maxAttempts).backoffStrategy(backoffStrategy) .waitTimeout(waitTimeout).build(); } @Override public void close() { managedResources.close(); } public static QueryWaiter.Builder builder() { return new DefaultBuilder(); } private <T extends QueryRequest> T applyWaitersUserAgent(T request) { Consumer<AwsRequestOverrideConfiguration.Builder> userAgentApplier = b -> b.addApiName(ApiName.builder() .version("waiter").name("hll").build()); AwsRequestOverrideConfiguration overrideConfiguration = request.overrideConfiguration() .map(c -> c.toBuilder().applyMutation(userAgentApplier).build()) .orElse((AwsRequestOverrideConfiguration.builder().applyMutation(userAgentApplier).build())); return (T) request.toBuilder().overrideConfiguration(overrideConfiguration).build(); } public static final class DefaultBuilder implements QueryWaiter.Builder { private QueryClient client; private WaiterOverrideConfiguration overrideConfiguration; private DefaultBuilder() { } @Override public QueryWaiter.Builder overrideConfiguration(WaiterOverrideConfiguration overrideConfiguration) { this.overrideConfiguration = overrideConfiguration; return this; } @Override public QueryWaiter.Builder client(QueryClient client) { this.client = client; return this; } public QueryWaiter build() { return new DefaultQueryWaiter(this); } } }
3,393
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/common/test-user-agent-class.java
package software.amazon.awssdk.services.json.internal; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.core.util.VersionInfo; import software.amazon.awssdk.services.json.model.JsonRequest; @Generated("software.amazon.awssdk:codegen") @SdkInternalApi public class UserAgentUtils { private UserAgentUtils() { } public static <T extends JsonRequest> T applyUserAgentInfo(T request, Consumer<AwsRequestOverrideConfiguration.Builder> userAgentApplier) { AwsRequestOverrideConfiguration overrideConfiguration = request.overrideConfiguration() .map(c -> c.toBuilder().applyMutation(userAgentApplier).build()) .orElse((AwsRequestOverrideConfiguration.builder().applyMutation(userAgentApplier).build())); return (T) request.toBuilder().overrideConfiguration(overrideConfiguration).build(); } public static <T extends JsonRequest> T applyPaginatorUserAgent(T request) { return applyUserAgentInfo(request, b -> b.addApiName(ApiName.builder().version(VersionInfo.SDK_VERSION).name("PAGINATED").build())); } }
3,394
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/common/test-enum-class.java
package software.amazon.awssdk.codegen.poet.common.model; import java.util.EnumSet; import java.util.Map; import java.util.Set; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.utils.internal.EnumUtils; /** * Some comment on the class itself */ @Generated("software.amazon.awssdk:codegen") public enum TestEnumClass { AVAILABLE("available"), PERMANENT_FAILURE("permanent-failure"), UNKNOWN_TO_SDK_VERSION(null); private static final Map<String, TestEnumClass> VALUE_MAP = EnumUtils.uniqueIndex(TestEnumClass.class, TestEnumClass::toString); private final String value; private TestEnumClass(String value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } /** * Use this in place of valueOf to convert the raw string returned by the service into the enum value. * * @param value * real value * @return TestEnumClass corresponding to the value */ public static TestEnumClass fromValue(String value) { if (value == null) { return null; } return VALUE_MAP.getOrDefault(value, UNKNOWN_TO_SDK_VERSION); } /** * Use this in place of {@link #values()} to return a {@link Set} of all values known to the SDK. This will return * all known enum values except {@link #UNKNOWN_TO_SDK_VERSION}. * * @return a {@link Set} of known {@link TestEnumClass}s */ public static Set<TestEnumClass> knownValues() { Set<TestEnumClass> knownValues = EnumSet.allOf(TestEnumClass.class); knownValues.remove(UNKNOWN_TO_SDK_VERSION); return knownValues; } }
3,395
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/model/listoflistofstringscopier.java
package software.amazon.awssdk.services.jsonprotocoltests.model; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.core.util.DefaultSdkAutoConstructList; import software.amazon.awssdk.core.util.SdkAutoConstructList; @Generated("software.amazon.awssdk:codegen") final class ListOfListOfStringsCopier { static List<List<String>> copy(Collection<? extends Collection<String>> listOfListOfStringsParam) { List<List<String>> list; if (listOfListOfStringsParam == null || listOfListOfStringsParam instanceof SdkAutoConstructList) { list = DefaultSdkAutoConstructList.getInstance(); } else { List<List<String>> modifiableList = new ArrayList<>(); listOfListOfStringsParam.forEach(entry -> { List<String> list1; if (entry == null || entry instanceof SdkAutoConstructList) { list1 = DefaultSdkAutoConstructList.getInstance(); } else { List<String> modifiableList1 = new ArrayList<>(); entry.forEach(entry1 -> { modifiableList1.add(entry1); }); list1 = Collections.unmodifiableList(modifiableList1); } modifiableList.add(list1); }); list = Collections.unmodifiableList(modifiableList); } return list; } }
3,396
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/model/operationwithnoinputoroutputresponse.java
package software.amazon.awssdk.services.jsonprotocoltests.model; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; @Generated("software.amazon.awssdk:codegen") public final class OperationWithNoInputOrOutputResponse extends JsonProtocolTestsResponse implements ToCopyableBuilder<OperationWithNoInputOrOutputResponse.Builder, OperationWithNoInputOrOutputResponse> { private static final List<SdkField<?>> SDK_FIELDS = Collections.unmodifiableList(Arrays.asList()); private OperationWithNoInputOrOutputResponse(BuilderImpl builder) { super(builder); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public static Class<? extends Builder> serializableBuilderClass() { return BuilderImpl.class; } @Override public final int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + super.hashCode(); return hashCode; } @Override public final boolean equals(Object obj) { return super.equals(obj) && equalsBySdkFields(obj); } @Override public final boolean equalsBySdkFields(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof OperationWithNoInputOrOutputResponse)) { return false; } return true; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. */ @Override public final String toString() { return ToString.builder("OperationWithNoInputOrOutputResponse").build(); } public final <T> Optional<T> getValueForField(String fieldName, Class<T> clazz) { return Optional.empty(); } @Override public final List<SdkField<?>> sdkFields() { return SDK_FIELDS; } public interface Builder extends JsonProtocolTestsResponse.Builder, SdkPojo, CopyableBuilder<Builder, OperationWithNoInputOrOutputResponse> { } static final class BuilderImpl extends JsonProtocolTestsResponse.BuilderImpl implements Builder { private BuilderImpl() { } private BuilderImpl(OperationWithNoInputOrOutputResponse model) { super(model); } @Override public OperationWithNoInputOrOutputResponse build() { return new OperationWithNoInputOrOutputResponse(this); } @Override public List<SdkField<?>> sdkFields() { return SDK_FIELDS; } } }
3,397
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/model/documentinputoperationresponse.java
package software.amazon.awssdk.services.jsonprotocoltests.model; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; @Generated("software.amazon.awssdk:codegen") public final class DocumentInputOperationResponse extends JsonProtocolTestsResponse implements ToCopyableBuilder<DocumentInputOperationResponse.Builder, DocumentInputOperationResponse> { private static final List<SdkField<?>> SDK_FIELDS = Collections.unmodifiableList(Arrays.asList()); private DocumentInputOperationResponse(BuilderImpl builder) { super(builder); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public static Class<? extends Builder> serializableBuilderClass() { return BuilderImpl.class; } @Override public final int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + super.hashCode(); return hashCode; } @Override public final boolean equals(Object obj) { return super.equals(obj) && equalsBySdkFields(obj); } @Override public final boolean equalsBySdkFields(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof DocumentInputOperationResponse)) { return false; } return true; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. */ @Override public final String toString() { return ToString.builder("DocumentInputOperationResponse").build(); } public final <T> Optional<T> getValueForField(String fieldName, Class<T> clazz) { return Optional.empty(); } @Override public final List<SdkField<?>> sdkFields() { return SDK_FIELDS; } public interface Builder extends JsonProtocolTestsResponse.Builder, SdkPojo, CopyableBuilder<Builder, DocumentInputOperationResponse> { } static final class BuilderImpl extends JsonProtocolTestsResponse.BuilderImpl implements Builder { private BuilderImpl() { } private BuilderImpl(DocumentInputOperationResponse model) { super(model); } @Override public DocumentInputOperationResponse build() { return new DocumentInputOperationResponse(this); } @Override public List<SdkField<?>> sdkFields() { return SDK_FIELDS; } } }
3,398
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/model/simplestruct.java
package software.amazon.awssdk.services.jsonprotocoltests.model; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Function; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.LocationTrait; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** */ @Generated("software.amazon.awssdk:codegen") public final class SimpleStruct implements SdkPojo, Serializable, ToCopyableBuilder<SimpleStruct.Builder, SimpleStruct> { private static final SdkField<String> STRING_MEMBER_FIELD = SdkField.<String> builder(MarshallingType.STRING) .memberName("StringMember").getter(getter(SimpleStruct::stringMember)).setter(setter(Builder::stringMember)) .traits(LocationTrait.builder().location(MarshallLocation.PAYLOAD).locationName("StringMember").build()).build(); private static final List<SdkField<?>> SDK_FIELDS = Collections.unmodifiableList(Arrays.asList(STRING_MEMBER_FIELD)); private static final long serialVersionUID = 1L; private final String stringMember; private SimpleStruct(BuilderImpl builder) { this.stringMember = builder.stringMember; } /** * Returns the value of the StringMember property for this object. * * @return The value of the StringMember property for this object. */ public final String stringMember() { return stringMember; } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public static Class<? extends Builder> serializableBuilderClass() { return BuilderImpl.class; } @Override public final int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + Objects.hashCode(stringMember()); return hashCode; } @Override public final boolean equals(Object obj) { return equalsBySdkFields(obj); } @Override public final boolean equalsBySdkFields(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof SimpleStruct)) { return false; } SimpleStruct other = (SimpleStruct) obj; return Objects.equals(stringMember(), other.stringMember()); } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. */ @Override public final String toString() { return ToString.builder("SimpleStruct").add("StringMember", stringMember()).build(); } public final <T> Optional<T> getValueForField(String fieldName, Class<T> clazz) { switch (fieldName) { case "StringMember": return Optional.ofNullable(clazz.cast(stringMember())); default: return Optional.empty(); } } @Override public final List<SdkField<?>> sdkFields() { return SDK_FIELDS; } private static <T> Function<Object, T> getter(Function<SimpleStruct, T> g) { return obj -> g.apply((SimpleStruct) obj); } private static <T> BiConsumer<Object, T> setter(BiConsumer<Builder, T> s) { return (obj, val) -> s.accept((Builder) obj, val); } public interface Builder extends SdkPojo, CopyableBuilder<Builder, SimpleStruct> { /** * Sets the value of the StringMember property for this object. * * @param stringMember * The new value for the StringMember property for this object. * @return Returns a reference to this object so that method calls can be chained together. */ Builder stringMember(String stringMember); } static final class BuilderImpl implements Builder { private String stringMember; private BuilderImpl() { } private BuilderImpl(SimpleStruct model) { stringMember(model.stringMember); } public final String getStringMember() { return stringMember; } public final void setStringMember(String stringMember) { this.stringMember = stringMember; } @Override public final Builder stringMember(String stringMember) { this.stringMember = stringMember; return this; } @Override public SimpleStruct build() { return new SimpleStruct(this); } @Override public List<SdkField<?>> sdkFields() { return SDK_FIELDS; } } }
3,399