index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/test/java/software/amazon/awssdk/metrics | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/test/java/software/amazon/awssdk/metrics/internal/DefaultMetricCollectorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics.internal;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.stream.Stream;
import org.junit.AfterClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.metrics.MetricCategory;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.metrics.MetricLevel;
import software.amazon.awssdk.metrics.SdkMetric;
public class DefaultMetricCollectorTest {
private static final SdkMetric<Integer> M1 = SdkMetric.create("m1", Integer.class, MetricLevel.INFO, MetricCategory.CORE);
@Rule
public ExpectedException thrown = ExpectedException.none();
@AfterClass
public static void teardown() {
DefaultSdkMetric.clearDeclaredMetrics();
}
@Test
public void testName_returnsName() {
MetricCollector collector = MetricCollector.create("collector");
assertThat(collector.name()).isEqualTo("collector");
}
@Test
public void testCreateChild_returnsChildWithCorrectName() {
MetricCollector parent = MetricCollector.create("parent");
MetricCollector child = parent.createChild("child");
assertThat(child.name()).isEqualTo("child");
}
@Test
public void testCollect_allReportedMetricsInCollection() {
MetricCollector collector = MetricCollector.create("collector");
Integer[] values = {1, 2, 3};
Stream.of(values).forEach(v -> collector.reportMetric(M1, v));
MetricCollection collect = collector.collect();
assertThat(collect.metricValues(M1)).containsExactly(values);
}
@Test
public void testCollect_returnedCollectionContainsAllChildren() {
MetricCollector parent = MetricCollector.create("parent");
String[] childNames = {"c1", "c2", "c3" };
Stream.of(childNames).forEach(parent::createChild);
MetricCollection collected = parent.collect();
assertThat(collected.children().stream().map(MetricCollection::name)).containsExactly(childNames);
}
}
| 2,100 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/test/java/software/amazon/awssdk/metrics | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/test/java/software/amazon/awssdk/metrics/internal/DefaultMetricCollectionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics.internal;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.metrics.MetricCategory;
import software.amazon.awssdk.metrics.MetricLevel;
import software.amazon.awssdk.metrics.MetricRecord;
import software.amazon.awssdk.metrics.SdkMetric;
public class DefaultMetricCollectionTest {
private static final SdkMetric<Integer> M1 = SdkMetric.create("m1", Integer.class, MetricLevel.INFO, MetricCategory.CORE);
@AfterAll
public static void teardown() {
DefaultSdkMetric.clearDeclaredMetrics();
}
@Test
public void testMetricValues_noValues_returnsEmptyList() {
DefaultMetricCollection foo = new DefaultMetricCollection("foo", Collections.emptyMap(), Collections.emptyList());
assertThat(foo.metricValues(M1)).isEmpty();
}
@Test
public void testChildren_noChildren_returnsEmptyList() {
DefaultMetricCollection foo = new DefaultMetricCollection("foo", Collections.emptyMap(), Collections.emptyList());
assertThat(foo.children()).isEmpty();
}
@Test
public void testIterator_iteratesOverAllValues() {
Integer[] values = {1, 2, 3};
Map<SdkMetric<?>, List<MetricRecord<?>>> recordMap = new HashMap<>();
List<MetricRecord<?>> records = Stream.of(values).map(v -> new DefaultMetricRecord<>(M1, v)).collect(Collectors.toList());
recordMap.put(M1, records);
DefaultMetricCollection collection = new DefaultMetricCollection("foo", recordMap, Collections.emptyList());
final Set<Integer> iteratorValues = StreamSupport.stream(collection.spliterator(), false)
.map(MetricRecord::value)
.map(Integer.class::cast)
.collect(Collectors.toSet());
assertThat(iteratorValues).containsExactly(values);
}
}
| 2,101 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/test/java/software/amazon/awssdk/metrics | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/test/java/software/amazon/awssdk/metrics/internal/DefaultSdkMetricRecordTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics.internal;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.metrics.MetricCategory;
import software.amazon.awssdk.metrics.MetricLevel;
import software.amazon.awssdk.metrics.MetricRecord;
import software.amazon.awssdk.metrics.SdkMetric;
/**
* Tests for {@link DefaultMetricRecord}.
*/
public class DefaultSdkMetricRecordTest {
@Test
public void testGetters() {
SdkMetric<Integer> event = SdkMetric.create("foo", Integer.class, MetricLevel.INFO, MetricCategory.CORE);
MetricRecord<Integer> record = new DefaultMetricRecord<>(event, 2);
assertThat(record.metric()).isEqualTo(event);
assertThat(record.value()).isEqualTo(2);
}
}
| 2,102 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/MetricRecord.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A container associating a metric and its value.
*/
@SdkPublicApi
public interface MetricRecord<T> {
/**
* @return The metric.
*/
SdkMetric<T> metric();
/**
* @return The value of this metric.
*/
T value();
}
| 2,103 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/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.
*/
package software.amazon.awssdk.metrics;
import java.time.Instant;
import java.util.List;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* An immutable collection of metrics.
*/
@SdkPublicApi
public interface MetricCollection extends Iterable<MetricRecord<?>> {
/**
* @return The name of this metric collection.
*/
String name();
/**
* Return a stream of records in this collection.
*/
default Stream<MetricRecord<?>> stream() {
return StreamSupport.stream(spliterator(), false);
}
/**
* Return all the values of 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);
/**
* @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.
*/
default Stream<MetricCollection> childrenWithName(String name) {
return children().stream().filter(c -> c.name().equals(name));
}
/**
* @return The time at which this collection was created.
*/
Instant creationTime();
}
| 2,104 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/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.
*/
package software.amazon.awssdk.metrics;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.metrics.internal.DefaultMetricCollector;
/**
* Used to collect metrics reported by the SDK.
*/
@NotThreadSafe
@SdkPublicApi
public interface MetricCollector {
/**
* @return The name of this collector.
*/
String name();
/**
* Report a metric.
*/
<T> void reportMetric(SdkMetric<T> metric, T data);
/**
* Create a child of this metric collector.
*
* @param name The name of the child collector.
* @return The child collector.
*/
MetricCollector createChild(String name);
/**
* Return the collected metrics.
* <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);
}
}
| 2,105 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/MetricLevel.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* The {@code MetricLevel} associated with a {@link SdkMetric}, similar to log levels, defines the 'scenario' in which the metric
* is useful. This makes it easy to reduce the cost of metric publishing (e.g. by setting it to {@link #INFO}), and then increase
* it when additional data level is needed for debugging purposes (e.g. by setting it to {@link #TRACE}.
*/
@SdkPublicApi
public enum MetricLevel {
/**
* The metric level that includes every other metric level, as well as some highly-technical metrics that may only be useful
* in very specific performance or failure scenarios.
*/
TRACE,
/**
* The "default" metric level that includes metrics that are useful for identifying <i>why</i> errors or performance issues
* are occurring within the SDK. This excludes technical metrics that are only useful in very specific performance or failure
* scenarios.
*/
INFO,
/**
* Includes metrics that report <i>when</i> API call errors are occurring within the SDK. This <b>does not</b> include all
* of the information that may be generally useful when debugging <i>why</i> errors are occurring (e.g. latency).
*/
ERROR;
public boolean includesLevel(MetricLevel level) {
return this.compareTo(level) <= 0;
}
}
| 2,106 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/MetricCategory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A enum class representing the different types of metric categories in the SDK.
* <p>
* A metric can be tagged with multiple categories. Clients can enable/disable metric collection
* at a {@link MetricCategory} level.
*/
@SdkPublicApi
public enum MetricCategory {
/**
* Metrics collected by the core SDK are classified under this category.
*/
CORE("Core"),
/**
* Metrics collected at the http client level are classified under this category.
*/
HTTP_CLIENT("HttpClient"),
/**
* Metrics specified by the customer should be classified under this category.
*/
CUSTOM("Custom"),
/**
* This is an umbrella category (provided for convenience) that records metrics belonging to every category
* defined in this enum. Clients who wish to collect lot of SDK metrics data should use this.
* <p>
* Note: Enabling this option along with {@link MetricLevel#TRACE} is verbose and can be expensive based on the platform
* the metrics are uploaded to. Please make sure you need all this data before using this category.
*/
ALL("All");
private final String value;
MetricCategory(String value) {
this.value = value;
}
public String getValue() {
return value;
}
/**
* Create a {@link MetricCategory} from the given String value. This method is case insensitive.
*
* @param value the value to create the {@link MetricCategory} from
* @return A {@link MetricCategory} if the given {@link #value} matches one of the enum values.
* Otherwise throws {@link IllegalArgumentException}
*/
public static MetricCategory fromString(String value) {
for (MetricCategory mc : MetricCategory.values()) {
if (mc.value.equalsIgnoreCase(value)) {
return mc;
}
}
throw new IllegalArgumentException("MetricCategory cannot be created from value: " + value);
}
}
| 2,107 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/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.
*/
package software.amazon.awssdk.metrics;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.metrics.internal.DefaultSdkMetric;
/**
* A specific SDK metric.
*
* @param <T> The type for values of this metric.
*/
@SdkPublicApi
public interface SdkMetric<T> {
/**
* @return The name of this metric.
*/
String name();
/**
* @return The categories of this metric.
*/
Set<MetricCategory> categories();
/**
* @return The level of this metric.
*/
MetricLevel level();
/**
* @return The class of the value associated with this metric.
*/
Class<T> valueClass();
/**
* Create a new metric.
*
* @param name The name of this metric.
* @param clzz The class of the object containing the associated value for this metric.
* @param c1 A category associated with this metric.
* @param cn Additional categories associated with this metric.
* @param <T> The type of the object containing the associated value for this metric.
* @return The created metric.
*
* @throws IllegalArgumentException If a metric of the same name has already been created.
*/
static <T> SdkMetric<T> create(String name, Class<T> clzz, MetricLevel level, MetricCategory c1, MetricCategory... cn) {
return DefaultSdkMetric.create(name, clzz, level, c1, cn);
}
/**
* Create a new metric.
*
* @param name The name of this metric.
* @param clzz The class of the object containing the associated value for this metric.
* @param categories The categories associated with this metric.
* @param <T> The type of the object containing the associated value for this metric.
* @return The created metric.
*
* @throws IllegalArgumentException If a metric of the same name has already been created.
*/
static <T> SdkMetric<T> create(String name, Class<T> clzz, MetricLevel level, Set<MetricCategory> categories) {
return DefaultSdkMetric.create(name, clzz, level, categories);
}
}
| 2,108 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/MetricPublisher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.utils.SdkAutoCloseable;
/**
* 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.
* <p>
* The SDK may invoke methods on the interface from multiple threads
* concurrently so implementations must be 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();
}
| 2,109 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/LoggingMetricPublisher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics;
import static software.amazon.awssdk.utils.StringUtils.repeat;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.event.Level;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link MetricPublisher} that logs all published metrics under the {@code
* software.amazon.awssdk.metrics.LoggingMetricPublisher} namespace.
* <p>
* {@link LoggingMetricPublisher} can be configured with a {@link Level} to control the log level at which metrics are recorded
* and a {@link Format} to control the format that metrics are printed in.
* <p>
* {@link Format#PLAIN} can be used to print all metrics on a single line. E.g.,
* <pre>
* Metrics published: MetricCollection(name=ApiCall, metrics=[MetricRecord(metric=MarshallingDuration, value=PT0.000202197S),
* MetricRecord(metric=RetryCount, value=0), MetricRecord(metric=ApiCallSuccessful, value=true),
* MetricRecord(metric=OperationName, value=HeadObject), MetricRecord(metric=ApiCallDuration, value=PT0.468369S),
* MetricRecord(metric=CredentialsFetchDuration, value=PT0.000003191S), MetricRecord(metric=ServiceId, value=S3)],
* children=[MetricCollection(name=ApiCallAttempt, metrics=[MetricRecord(metric=SigningDuration, value=PT0.000667268S),
* MetricRecord(metric=ServiceCallDuration, value=PT0.460529977S), MetricRecord(metric=AwsExtendedRequestId,
* value=jY/Co5Ge6WjRYk78kGOYQ4Z/CqUBr6pAAPZtexgOQR3Iqs3QP0OfZz3fDraQiXtmx7eXCZ4sbO0=), MetricRecord(metric=HttpStatusCode,
* value=200), MetricRecord(metric=BackoffDelayDuration, value=PT0S), MetricRecord(metric=AwsRequestId, value=6SJ82R65SADHX098)],
* children=[MetricCollection(name=HttpClient, metrics=[MetricRecord(metric=AvailableConcurrency, value=0),
* MetricRecord(metric=LeasedConcurrency, value=0), MetricRecord(metric=ConcurrencyAcquireDuration, value=PT0.230757S),
* MetricRecord(metric=PendingConcurrencyAcquires, value=0), MetricRecord(metric=MaxConcurrency, value=50),
* MetricRecord(metric=HttpClientName, value=NettyNio)], children=[])])])
* </pre>
* {@link Format#PRETTY} can be used to print metrics over multiple lines in a readable fashion suitable for debugging. E.g.,
* <pre>
* [18e5092e] ApiCall
* [18e5092e] ββββββββββββββββββββββββββββββββββββββββββ
* [18e5092e] β MarshallingDuration=PT0.000227427S β
* [18e5092e] β RetryCount=0 β
* [18e5092e] β ApiCallSuccessful=true β
* [18e5092e] β OperationName=HeadObject β
* [18e5092e] β ApiCallDuration=PT0.541751S β
* [18e5092e] β CredentialsFetchDuration=PT0.00000306S β
* [18e5092e] β ServiceId=S3 β
* [18e5092e] ββββββββββββββββββββββββββββββββββββββββββ
* [18e5092e] ApiCallAttempt
* [18e5092e] βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
* [18e5092e] β SigningDuration=PT0.000974924S β
* [18e5092e] β ServiceCallDuration=PT0.531462375S β
* [18e5092e] β AwsExtendedRequestId=eGfwjV3mSwQZQD4YxHLswYguvhQoGcDTkr2jRvpio37a6QmhWd18C8wagC8LkBzzcnOOKoMuiXw= β
* [18e5092e] β HttpStatusCode=200 β
* [18e5092e] β BackoffDelayDuration=PT0S β
* [18e5092e] β AwsRequestId=ED46TP7NN62DDG4Q β
* [18e5092e] βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
* [18e5092e] HttpClient
* [18e5092e] ββββββββββββββββββββββββββββββββββββββββββ
* [18e5092e] β AvailableConcurrency=0 β
* [18e5092e] β LeasedConcurrency=0 β
* [18e5092e] β ConcurrencyAcquireDuration=PT0.235851S β
* [18e5092e] β PendingConcurrencyAcquires=0 β
* [18e5092e] β MaxConcurrency=50 β
* [18e5092e] β HttpClientName=NettyNio β
* [18e5092e] ββββββββββββββββββββββββββββββββββββββββββ
* </pre>
* Note that the output format may be subject to small changes in future versions and should not be relied upon as a strict public
* contract.
*/
@SdkPublicApi
public final class LoggingMetricPublisher implements MetricPublisher {
public enum Format {
PLAIN,
PRETTY
}
private static final Logger LOGGER = Logger.loggerFor(LoggingMetricPublisher.class);
private static final Integer PRETTY_INDENT_SIZE = 4;
private final Level logLevel;
private final Format format;
private LoggingMetricPublisher(Level logLevel, Format format) {
this.logLevel = Validate.notNull(logLevel, "logLevel");
this.format = Validate.notNull(format, "format");
}
/**
* Create a {@link LoggingMetricPublisher} with the default configuration of {@link Level#INFO} and {@link Format#PLAIN}.
*/
public static LoggingMetricPublisher create() {
return new LoggingMetricPublisher(Level.INFO, Format.PLAIN);
}
/**
* Create a {@link LoggingMetricPublisher} with a custom {@link Format} and log {@link Level}.
*
* @param logLevel the SLF4J log level to log metrics with
* @param format the format to print the metrics with (see class-level documentation for examples)
*/
public static LoggingMetricPublisher create(Level logLevel, Format format) {
return new LoggingMetricPublisher(logLevel, format);
}
@Override
public void publish(MetricCollection metrics) {
if (!LOGGER.isLoggingLevelEnabled(logLevel)) {
return;
}
switch (format) {
case PLAIN:
LOGGER.log(logLevel, () -> "Metrics published: " + metrics);
break;
case PRETTY:
String guid = Integer.toHexString(metrics.hashCode());
logPretty(guid, metrics, 0);
break;
default:
throw new IllegalStateException("Unsupported format: " + format);
}
}
private void logPretty(String guid, MetricCollection metrics, int indent) {
// Pre-determine metric key-value-pairs so that we can calculate the necessary padding
List<String> metricValues = new ArrayList<>();
metrics.forEach(m -> {
metricValues.add(String.format("%s=%s", m.metric().name(), m.value()));
});
int maxLen = getMaxLen(metricValues);
// MetricCollection name
LOGGER.log(logLevel, () -> String.format("[%s]%s %s",
guid,
repeat(" ", indent),
metrics.name()));
// Open box
LOGGER.log(logLevel, () -> String.format("[%s]%s β%sβ",
guid,
repeat(" ", indent),
repeat("β", maxLen + 2)));
// Metric key-value-pairs
metricValues.forEach(metric -> LOGGER.log(logLevel, () -> {
return String.format("[%s]%s β %s β",
guid,
repeat(" ", indent),
pad(metric, maxLen));
}));
// Close box
LOGGER.log(logLevel, () -> String.format("[%s]%s β%sβ",
guid,
repeat(" ", indent),
repeat("β", maxLen + 2)));
// Recursively repeat for any children
metrics.children().forEach(child -> logPretty(guid, child, indent + PRETTY_INDENT_SIZE));
}
private static int getMaxLen(List<String> strings) {
int maxLen = 0;
for (String str : strings) {
maxLen = Math.max(maxLen, str.length());
}
return maxLen;
}
private static String pad(String str, int length) {
return str + repeat(" ", length - str.length());
}
@Override
public void close() {
}
}
| 2,110 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/NoOpMetricCollector.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.metrics.internal.EmptyMetricCollection;
/**
* A metric collector that doesn't do anything.
*/
@SdkPublicApi
public final class NoOpMetricCollector implements MetricCollector {
private static final NoOpMetricCollector INSTANCE = new NoOpMetricCollector();
private NoOpMetricCollector() {
}
@Override
public String name() {
return "NoOp";
}
@Override
public <T> void reportMetric(SdkMetric<T> metric, T data) {
}
@Override
public MetricCollector createChild(String name) {
return INSTANCE;
}
@Override
public MetricCollection collect() {
return EmptyMetricCollection.create();
}
public static NoOpMetricCollector create() {
return INSTANCE;
}
}
| 2,111 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/internal/DefaultMetricCollector.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics.internal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.metrics.MetricRecord;
import software.amazon.awssdk.metrics.SdkMetric;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class DefaultMetricCollector implements MetricCollector {
private static final Logger log = Logger.loggerFor(DefaultMetricCollector.class);
private final String name;
private final Map<SdkMetric<?>, List<MetricRecord<?>>> metrics = new LinkedHashMap<>();
private final List<MetricCollector> children = new ArrayList<>();
public DefaultMetricCollector(String name) {
this.name = name;
}
@Override
public String name() {
return name;
}
@Override
public synchronized <T> void reportMetric(SdkMetric<T> metric, T data) {
metrics.computeIfAbsent(metric, (m) -> new ArrayList<>())
.add(new DefaultMetricRecord<>(metric, data));
}
@Override
public synchronized MetricCollector createChild(String name) {
MetricCollector child = new DefaultMetricCollector(name);
children.add(child);
return child;
}
@Override
public synchronized MetricCollection collect() {
List<MetricCollection> collectedChildren = children.stream()
.map(MetricCollector::collect)
.collect(Collectors.toList());
DefaultMetricCollection metricRecords = new DefaultMetricCollection(name, metrics, collectedChildren);
log.debug(() -> "Collected metrics records: " + metricRecords);
return metricRecords;
}
public static MetricCollector create(String name) {
Validate.notEmpty(name, "name");
return new DefaultMetricCollector(name);
}
@Override
public String toString() {
return ToString.builder("DefaultMetricCollector")
.add("metrics", metrics).build();
}
}
| 2,112 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/internal/DefaultMetricRecord.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.MetricRecord;
import software.amazon.awssdk.metrics.SdkMetric;
import software.amazon.awssdk.utils.ToString;
@SdkInternalApi
public final class DefaultMetricRecord<T> implements MetricRecord<T> {
private final SdkMetric<T> metric;
private final T value;
public DefaultMetricRecord(SdkMetric<T> metric, T value) {
this.metric = metric;
this.value = value;
}
@Override
public SdkMetric<T> metric() {
return metric;
}
@Override
public T value() {
return value;
}
@Override
public String toString() {
return ToString.builder("MetricRecord")
.add("metric", metric.name())
.add("value", value)
.build();
}
}
| 2,113 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/internal/DefaultSdkMetric.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics.internal;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.metrics.MetricCategory;
import software.amazon.awssdk.metrics.MetricLevel;
import software.amazon.awssdk.metrics.SdkMetric;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class DefaultSdkMetric<T> extends AttributeMap.Key<T> implements SdkMetric<T> {
private static final ConcurrentHashMap<SdkMetric<?>, Boolean> SDK_METRICS = new ConcurrentHashMap<>();
private final String name;
private final Class<T> clzz;
private final Set<MetricCategory> categories;
private final MetricLevel level;
private DefaultSdkMetric(String name, Class<T> clzz, MetricLevel level, Set<MetricCategory> categories) {
super(clzz);
this.name = Validate.notBlank(name, "name must not be blank");
this.clzz = Validate.notNull(clzz, "clzz must not be null");
this.level = Validate.notNull(level, "level must not be null");
Validate.notEmpty(categories, "categories must not be empty");
this.categories = EnumSet.copyOf(categories);
}
/**
* @return The name of this event.
*/
@Override
public String name() {
return name;
}
/**
* @return The categories of this event.
*/
@Override
public Set<MetricCategory> categories() {
return Collections.unmodifiableSet(categories);
}
@Override
public MetricLevel level() {
return level;
}
/**
* @return The class of the value associated with this event.
*/
@Override
public Class<T> valueClass() {
return clzz;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultSdkMetric<?> that = (DefaultSdkMetric<?>) o;
return name.equals(that.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return ToString.builder("DefaultMetric")
.add("name", name)
.add("categories", categories())
.build();
}
/**
* Create a new metric.
*
* @param name The name of this metric.
* @param clzz The class of the object containing the associated value for this metric.
* @param c1 A category associated with this metric.
* @param cn Additional categories associated with this metric.
* @param <T> The type of the object containing the associated value for this metric.
* @return The created metric.
*
* @throws IllegalArgumentException If a metric of the same name has already been created.
*/
public static <T> SdkMetric<T> create(String name, Class<T> clzz, MetricLevel level,
MetricCategory c1, MetricCategory... cn) {
Stream<MetricCategory> categoryStream = Stream.of(c1);
if (cn != null) {
categoryStream = Stream.concat(categoryStream, Stream.of(cn));
}
Set<MetricCategory> categories = categoryStream.collect(Collectors.toSet());
return create(name, clzz, level, categories);
}
/**
* Create a new metric.
*
* @param name The name of this metric.
* @param clzz The class of the object containing the associated value for this metric.
* @param categories The categories associated with this metric.
* @param <T> The type of the object containing the associated value for this metric.
* @return The created metric.
*
* @throws IllegalArgumentException If a metric of the same name has already been created.
*/
public static <T> SdkMetric<T> create(String name, Class<T> clzz, MetricLevel level, Set<MetricCategory> categories) {
Validate.noNullElements(categories, "categories must not contain null elements");
SdkMetric<T> event = new DefaultSdkMetric<>(name, clzz, level, categories);
if (SDK_METRICS.putIfAbsent(event, Boolean.TRUE) != null) {
throw new IllegalArgumentException("Metric with name " + name + " has already been created");
}
return event;
}
@SdkTestInternalApi
static void clearDeclaredMetrics() {
SDK_METRICS.clear();
}
@SdkTestInternalApi
static Set<SdkMetric<?>> declaredEvents() {
return SDK_METRICS.keySet();
}
}
| 2,114 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/internal/EmptyMetricCollection.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics.internal;
import java.time.Instant;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricRecord;
import software.amazon.awssdk.metrics.SdkMetric;
@SdkInternalApi
public final class EmptyMetricCollection implements MetricCollection {
private final Instant creationTime = Instant.now();
@Override
public String name() {
return "NoOp";
}
@Override
public <T> List<T> metricValues(SdkMetric<T> metric) {
return Collections.emptyList();
}
@Override
public List<MetricCollection> children() {
return Collections.emptyList();
}
@Override
public Instant creationTime() {
return creationTime;
}
@Override
public Iterator<MetricRecord<?>> iterator() {
return Collections.emptyIterator();
}
public static EmptyMetricCollection create() {
return new EmptyMetricCollection();
}
}
| 2,115 |
0 | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics | Create_ds/aws-sdk-java-v2/core/metrics-spi/src/main/java/software/amazon/awssdk/metrics/internal/DefaultMetricCollection.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.metrics.internal;
import static java.util.stream.Collectors.toList;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricRecord;
import software.amazon.awssdk.metrics.SdkMetric;
import software.amazon.awssdk.utils.ToString;
@SdkInternalApi
public final class DefaultMetricCollection implements MetricCollection {
private final String name;
private final Map<SdkMetric<?>, List<MetricRecord<?>>> metrics;
private final List<MetricCollection> children;
private final Instant creationTime;
public DefaultMetricCollection(String name, Map<SdkMetric<?>,
List<MetricRecord<?>>> metrics, List<MetricCollection> children) {
this.name = name;
this.metrics = new HashMap<>(metrics);
this.children = children != null ? new ArrayList<>(children) : Collections.emptyList();
this.creationTime = Instant.now();
}
@Override
public String name() {
return name;
}
@SuppressWarnings("unchecked")
@Override
public <T> List<T> metricValues(SdkMetric<T> metric) {
if (metrics.containsKey(metric)) {
List<MetricRecord<?>> metricRecords = metrics.get(metric);
List<?> values = metricRecords.stream()
.map(MetricRecord::value)
.collect(toList());
return (List<T>) Collections.unmodifiableList(values);
}
return Collections.emptyList();
}
@Override
public List<MetricCollection> children() {
return Collections.unmodifiableList(children);
}
@Override
public Instant creationTime() {
return creationTime;
}
@Override
public Iterator<MetricRecord<?>> iterator() {
return metrics.values().stream()
.flatMap(List::stream)
.iterator();
}
@Override
public String toString() {
return ToString.builder("MetricCollection")
.add("name", name)
.add("metrics", metrics.values().stream().flatMap(List::stream).collect(toList()))
.add("children", children)
.build();
}
}
| 2,116 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/test/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/test/java/software/amazon/awssdk/identity/spi/IdentityProvidersTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class IdentityProvidersTest {
@Test
public void builder_empty_builds() {
assertNotNull(IdentityProviders.builder().build());
}
@Test
public void identityProvider_withUnknownType_returnsNull() {
IdentityProvider<AwsCredentialsIdentity> awsCredentialsProvider = new AwsCredentialsProvider();
IdentityProviders identityProviders =
IdentityProviders.builder().putIdentityProvider(awsCredentialsProvider).build();
assertNull(identityProviders.identityProvider(TokenIdentity.class));
}
@Test
public void identityProvider_canBeRetrieved() {
IdentityProvider<AwsCredentialsIdentity> awsCredentialsProvider = new AwsCredentialsProvider();
IdentityProviders identityProviders =
IdentityProviders.builder().putIdentityProvider(awsCredentialsProvider).build();
assertSame(awsCredentialsProvider, identityProviders.identityProvider(AwsCredentialsIdentity.class));
}
@Test
public void putIdentityProvider_ofSameType_isReplaced() {
IdentityProvider<AwsCredentialsIdentity> awsCredentialsProvider1 = new AwsCredentialsProvider();
IdentityProvider<AwsCredentialsIdentity> awsCredentialsProvider2 = new AwsCredentialsProvider();
IdentityProviders identityProviders =
IdentityProviders.builder()
.putIdentityProvider(awsCredentialsProvider1)
.putIdentityProvider(awsCredentialsProvider2).build();
assertSame(awsCredentialsProvider2, identityProviders.identityProvider(AwsCredentialsIdentity.class));
}
@Test
public void identityProvider_withSubType_returnsAppropriateSubType() {
IdentityProvider<AwsCredentialsIdentity> awsCredentialsProvider = new AwsCredentialsProvider();
IdentityProvider<AwsSessionCredentialsIdentity> awsSessionCredentialsProvider = new AwsSessionCredentialsProvider();
IdentityProviders identityProviders =
IdentityProviders.builder()
.putIdentityProvider(awsCredentialsProvider)
.putIdentityProvider(awsSessionCredentialsProvider)
.build();
assertSame(awsCredentialsProvider, identityProviders.identityProvider(AwsCredentialsIdentity.class));
assertSame(awsSessionCredentialsProvider, identityProviders.identityProvider(AwsSessionCredentialsIdentity.class));
}
@Test
public void identityProvider_withOnlySubType_returnsNullForParentType() {
IdentityProvider<AwsSessionCredentialsIdentity> awsSessionCredentialsProvider = new AwsSessionCredentialsProvider();
IdentityProviders identityProviders =
IdentityProviders.builder()
.putIdentityProvider(awsSessionCredentialsProvider)
.build();
assertNull(identityProviders.identityProvider(AwsCredentialsIdentity.class));
}
@Test
public void copyBuilder_addIdentityProvider_works() {
IdentityProvider<AwsCredentialsIdentity> awsCredentialsProvider = new AwsCredentialsProvider();
IdentityProviders identityProviders =
IdentityProviders.builder()
.putIdentityProvider(awsCredentialsProvider)
.build();
IdentityProvider<TokenIdentity> tokenProvider = new TokenProvider();
identityProviders = identityProviders.copy(builder -> builder.putIdentityProvider(tokenProvider));
assertSame(awsCredentialsProvider, identityProviders.identityProvider(AwsCredentialsIdentity.class));
assertSame(tokenProvider, identityProviders.identityProvider(TokenIdentity.class));
}
@Test
public void identityProviders_notTouched_untilNeeded() {
// TODO(sra-identity-auth): This should be removed once everything is on useSraAuth = true
IdentityProvider<AwsCredentialsIdentity> awsCredentialsProvider = Mockito.mock(IdentityProvider.class);
IdentityProviders providers =
IdentityProviders.builder()
.putIdentityProvider(awsCredentialsProvider)
.build()
.toBuilder()
.putIdentityProvider(awsCredentialsProvider)
.build()
.toBuilder()
.build();
providers.toString();
Mockito.verifyNoMoreInteractions(awsCredentialsProvider);
}
private static final class AwsCredentialsProvider implements IdentityProvider<AwsCredentialsIdentity> {
@Override
public Class<AwsCredentialsIdentity> identityType() {
return AwsCredentialsIdentity.class;
}
@Override
public CompletableFuture<? extends AwsCredentialsIdentity> resolveIdentity(ResolveIdentityRequest request) {
return null;
}
}
private static final class AwsSessionCredentialsProvider implements IdentityProvider<AwsSessionCredentialsIdentity> {
@Override
public Class<AwsSessionCredentialsIdentity> identityType() {
return AwsSessionCredentialsIdentity.class;
}
@Override
public CompletableFuture<? extends AwsSessionCredentialsIdentity> resolveIdentity(ResolveIdentityRequest request) {
return null;
}
}
private static final class TokenProvider implements IdentityProvider<TokenIdentity> {
@Override
public Class<TokenIdentity> identityType() {
return TokenIdentity.class;
}
@Override
public CompletableFuture<? extends TokenIdentity> resolveIdentity(ResolveIdentityRequest request) {
return null;
}
}
}
| 2,117 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/test/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/test/java/software/amazon/awssdk/identity/spi/IdentityPropertyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.UUID;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
public class IdentityPropertyTest {
@Test
public void equalsHashcode() {
EqualsVerifier.forClass(IdentityProperty.class)
.withNonnullFields("namespace", "name")
.verify();
}
@Test
public void namesMustBeUnique() {
String propertyName = UUID.randomUUID().toString();
IdentityProperty.create(getClass(), propertyName);
assertThatThrownBy(() -> IdentityProperty.create(getClass(), propertyName))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(getClass().getName())
.hasMessageContaining(propertyName);
}
}
| 2,118 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/test/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/test/java/software/amazon/awssdk/identity/spi/AwsSessionCredentialsIdentityTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity;
import software.amazon.awssdk.identity.spi.internal.DefaultAwsSessionCredentialsIdentity;
public class AwsSessionCredentialsIdentityTest {
private static final String ACCESS_KEY_ID = "accessKeyId";
private static final String SECRET_ACCESS_KEY = "secretAccessKey";
private static final String SESSION_TOKEN = "sessionToken";
@Test
public void equalsHashcode() {
EqualsVerifier.forClass(DefaultAwsSessionCredentialsIdentity.class)
.verify();
}
@Test
public void emptyBuilder_ThrowsException() {
assertThrows(NullPointerException.class, () -> AwsSessionCredentialsIdentity.builder().build());
}
@Test
public void builderMissingSessionToken_ThrowsException() {
assertThrows(NullPointerException.class, () -> AwsSessionCredentialsIdentity.builder()
.accessKeyId(ACCESS_KEY_ID)
.secretAccessKey(SECRET_ACCESS_KEY)
.build());
}
@Test
public void builderMissingAccessKeyId_ThrowsException() {
assertThrows(NullPointerException.class, () -> AwsSessionCredentialsIdentity.builder()
.secretAccessKey(SECRET_ACCESS_KEY)
.sessionToken(SESSION_TOKEN)
.build());
}
@Test
public void create_isSuccessful() {
AwsSessionCredentialsIdentity identity = AwsSessionCredentialsIdentity.create(ACCESS_KEY_ID,
SECRET_ACCESS_KEY,
SESSION_TOKEN);
assertEquals(ACCESS_KEY_ID, identity.accessKeyId());
assertEquals(SECRET_ACCESS_KEY, identity.secretAccessKey());
assertEquals(SESSION_TOKEN, identity.sessionToken());
}
@Test
public void build_isSuccessful() {
AwsSessionCredentialsIdentity identity = AwsSessionCredentialsIdentity.builder()
.accessKeyId(ACCESS_KEY_ID)
.secretAccessKey(SECRET_ACCESS_KEY)
.sessionToken(SESSION_TOKEN)
.build();
assertEquals(ACCESS_KEY_ID, identity.accessKeyId());
assertEquals(SECRET_ACCESS_KEY, identity.secretAccessKey());
assertEquals(SESSION_TOKEN, identity.sessionToken());
}
}
| 2,119 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/test/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/test/java/software/amazon/awssdk/identity/spi/ResolveIdentityRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.identity.spi.internal.DefaultResolveIdentityRequest;
public class ResolveIdentityRequestTest {
private static final IdentityProperty<String> PROPERTY_1 =
IdentityProperty.create(ResolveIdentityRequestTest.class, "key_1");
private static final IdentityProperty<String> PROPERTY_2 =
IdentityProperty.create(ResolveIdentityRequestTest.class, "key_2");
@Test
public void equalsHashcode() {
EqualsVerifier.forClass(DefaultResolveIdentityRequest.class)
.withNonnullFields("properties")
.verify();
}
@Test
public void emptyBuilder_isSuccessful() {
assertNotNull(ResolveIdentityRequest.builder().build());
}
@Test
public void build_withProperty_isSuccessful() {
ResolveIdentityRequest request = ResolveIdentityRequest.builder()
.putProperty(PROPERTY_1, "value")
.build();
assertEquals("value", request.property(PROPERTY_1));
}
@Test
public void putProperty_sameProperty_isReplaced() {
ResolveIdentityRequest request = ResolveIdentityRequest.builder()
.putProperty(PROPERTY_1, "value")
.putProperty(PROPERTY_1, "value2")
.build();
assertEquals("value2", request.property(PROPERTY_1));
}
@Test
public void copyBuilder_addProperty_retains() {
ResolveIdentityRequest request = ResolveIdentityRequest.builder()
.putProperty(PROPERTY_1, "key1value1")
.build();
request = request.copy(builder -> builder.putProperty(PROPERTY_2, "key2value1"));
assertEquals("key1value1", request.property(PROPERTY_1));
assertEquals("key2value1", request.property(PROPERTY_2));
}
@Test
public void copyBuilder_updateAddProperty_works() {
ResolveIdentityRequest request = ResolveIdentityRequest.builder()
.putProperty(PROPERTY_1, "key1value1")
.build();
request = request.copy(builder -> builder.putProperty(PROPERTY_1, "key1value2").putProperty(PROPERTY_2, "key2value1"));
assertEquals("key1value2", request.property(PROPERTY_1));
assertEquals("key2value1", request.property(PROPERTY_2));
}
}
| 2,120 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/test/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/test/java/software/amazon/awssdk/identity/spi/AwsCredentialsIdentityTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.internal.DefaultAwsCredentialsIdentity;
public class AwsCredentialsIdentityTest {
private static final String ACCESS_KEY_ID = "accessKeyId";
private static final String SECRET_ACCESS_KEY = "secretAccessKey";
@Test
public void equalsHashcode() {
EqualsVerifier.forClass(DefaultAwsCredentialsIdentity.class)
.verify();
}
@Test
public void emptyBuilder_ThrowsException() {
assertThrows(NullPointerException.class, () -> AwsCredentialsIdentity.builder().build());
}
@Test
public void builderMissingSecretAccessKey_ThrowsException() {
assertThrows(NullPointerException.class, () -> AwsCredentialsIdentity.builder().accessKeyId(ACCESS_KEY_ID).build());
}
@Test
public void builderMissingAccessKeyId_ThrowsException() {
assertThrows(NullPointerException.class, () -> AwsCredentialsIdentity.builder().secretAccessKey(SECRET_ACCESS_KEY).build());
}
@Test
public void create_isSuccessful() {
AwsCredentialsIdentity identity = AwsCredentialsIdentity.create(ACCESS_KEY_ID, SECRET_ACCESS_KEY);
assertEquals(ACCESS_KEY_ID, identity.accessKeyId());
assertEquals(SECRET_ACCESS_KEY, identity.secretAccessKey());
}
@Test
public void build_isSuccessful() {
AwsCredentialsIdentity identity = AwsCredentialsIdentity.builder()
.accessKeyId(ACCESS_KEY_ID)
.secretAccessKey(SECRET_ACCESS_KEY)
.build();
assertEquals(ACCESS_KEY_ID, identity.accessKeyId());
assertEquals(SECRET_ACCESS_KEY, identity.secretAccessKey());
}
}
| 2,121 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/IdentityProviders.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.identity.spi.internal.DefaultIdentityProviders;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* An interface to allow retrieving an IdentityProvider based on the identity type.
*/
@SdkPublicApi
public interface IdentityProviders extends ToCopyableBuilder<IdentityProviders.Builder, IdentityProviders> {
/**
* Retrieve an identity provider for the provided identity type.
*/
<T extends Identity> IdentityProvider<T> identityProvider(Class<T> identityType);
/**
* Get a new builder for creating a {@link IdentityProviders}.
*/
static Builder builder() {
return DefaultIdentityProviders.builder();
}
/**
* A builder for a {@link IdentityProviders}.
*/
interface Builder extends CopyableBuilder<Builder, IdentityProviders> {
/**
* Add the {@link IdentityProvider} for a given type. If a provider of that type, as determined by {@link
* IdentityProvider#identityType()} is already added, it will be replaced.
*/
<T extends Identity> Builder putIdentityProvider(IdentityProvider<T> identityProvider);
}
}
| 2,122 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/IdentityProperty.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* A strongly-typed property for input to an {@link IdentityProvider}.
* @param <T> The type of the attribute.
*/
@SdkPublicApi
@Immutable
@ThreadSafe
public final class IdentityProperty<T> {
private static final ConcurrentMap<Pair<String, String>, IdentityProperty<?>> NAME_HISTORY = new ConcurrentHashMap<>();
private final String namespace;
private final String name;
private IdentityProperty(String namespace, String name) {
Validate.paramNotBlank(namespace, "namespace");
Validate.paramNotBlank(name, "name");
this.namespace = namespace;
this.name = name;
ensureUnique();
}
/**
* Create a property.
*
* @param <T> the type of the property.
* @param namespace the class *where* the property is being defined
* @param name the name for the property
* @throws IllegalArgumentException if a property with this namespace and name already exist
*/
public static <T> IdentityProperty<T> create(Class<?> namespace, String name) {
return new IdentityProperty<>(namespace.getName(), name);
}
private void ensureUnique() {
IdentityProperty<?> prev = NAME_HISTORY.putIfAbsent(Pair.of(namespace, name), this);
Validate.isTrue(prev == null,
"No duplicate IdentityProperty names allowed but both IdentityProperties %s and %s have the same "
+ "namespace (%s) and name (%s). IdentityProperty should be referenced from a shared static constant to "
+ "protect against erroneous or unexpected collisions.",
Integer.toHexString(System.identityHashCode(prev)),
Integer.toHexString(System.identityHashCode(this)),
namespace,
name);
}
@Override
public String toString() {
return ToString.builder("IdentityProperty")
.add("namespace", namespace)
.add("name", name)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
IdentityProperty<?> that = (IdentityProperty<?>) o;
return Objects.equals(namespace, that.namespace) &&
Objects.equals(name, that.name);
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + Objects.hashCode(namespace);
hashCode = 31 * hashCode + Objects.hashCode(name);
return hashCode;
}
}
| 2,123 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/IdentityProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
/**
* Interface for loading {@link Identity} that is used for authentication.
*/
@SdkPublicApi
@ThreadSafe
public interface IdentityProvider<IdentityT extends Identity> {
/**
* Retrieve the class of identity this identity provider produces.
*
* This is necessary for the SDK core to determine which identity provider should be used to resolve a specific type of
* identity.
*/
Class<IdentityT> identityType();
/**
* Resolve the identity from this identity provider.
* @param request The request to resolve an Identity
*/
CompletableFuture<? extends IdentityT> resolveIdentity(ResolveIdentityRequest request);
/**
* Resolve the identity from this identity provider.
*
* Similar to {@link #resolveIdentity(ResolveIdentityRequest)}, but takes a lambda to configure a new
* {@link ResolveIdentityRequest.Builder}. This removes the need to call {@link ResolveIdentityRequest#builder()} and
* {@link ResolveIdentityRequest.Builder#build()}.
*
* @param consumer A {@link Consumer} to which an empty {@link ResolveIdentityRequest.Builder} will be given.
*/
default CompletableFuture<? extends IdentityT> resolveIdentity(Consumer<ResolveIdentityRequest.Builder> consumer) {
return resolveIdentity(ResolveIdentityRequest.builder().applyMutation(consumer).build());
}
/**
* Resolve the identity from this identity provider.
*/
default CompletableFuture<? extends IdentityT> resolveIdentity() {
return resolveIdentity(ResolveIdentityRequest.builder().build());
}
}
| 2,124 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/AwsSessionCredentialsIdentity.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.identity.spi.internal.DefaultAwsSessionCredentialsIdentity;
/**
* A special type of {@link AwsCredentialsIdentity} that provides a session token to be used in service authentication. Session
* tokens are typically provided by a token broker service, like AWS Security Token Service, and provide temporary access to an
* AWS service.
*/
@SdkPublicApi
@ThreadSafe
public interface AwsSessionCredentialsIdentity extends AwsCredentialsIdentity {
/**
* Retrieve the AWS session token. This token is retrieved from an AWS token service, and is used for authenticating that this
* user has received temporary permission to access some resource.
*/
String sessionToken();
static AwsSessionCredentialsIdentity.Builder builder() {
return DefaultAwsSessionCredentialsIdentity.builder();
}
/**
* Constructs a new session credentials object, with the specified AWS access key, AWS secret key and AWS session token.
*
* @param accessKeyId The AWS access key, used to identify the user interacting with services.
* @param secretAccessKey The AWS secret access key, used to authenticate the user interacting with services.
* @param sessionToken The AWS session token, retrieved from an AWS token service, used for authenticating that this user has
* received temporary permission to access some resource.
*/
static AwsSessionCredentialsIdentity create(String accessKeyId, String secretAccessKey, String sessionToken) {
return builder().accessKeyId(accessKeyId)
.secretAccessKey(secretAccessKey)
.sessionToken(sessionToken)
.build();
}
interface Builder extends AwsCredentialsIdentity.Builder {
@Override
Builder accessKeyId(String accessKeyId);
@Override
Builder secretAccessKey(String secretAccessKey);
/**
* The AWS session token, retrieved from an AWS token service, used for authenticating that this user has
* received temporary permission to access some resource.
*/
Builder sessionToken(String sessionToken);
@Override
AwsSessionCredentialsIdentity build();
}
}
| 2,125 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/Identity.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import java.time.Instant;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
/**
* Interface to represent <b>who</b> is using the SDK, i.e., the identity of the caller, used for authentication.
*
* <p>Examples include {@link AwsCredentialsIdentity} and {@link TokenIdentity}.</p>
*
* @see IdentityProvider
*/
@SdkPublicApi
@ThreadSafe
public interface Identity {
/**
* The time after which this identity will no longer be valid. If this is empty,
* an expiration time is not known (but the identity may still expire at some
* time in the future).
*/
default Optional<Instant> expirationTime() {
return Optional.empty();
}
}
| 2,126 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/AwsCredentialsIdentity.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.identity.spi.internal.DefaultAwsCredentialsIdentity;
/**
* Provides access to the AWS credentials used for accessing services: AWS access key ID and secret access key. These
* credentials are used to securely sign requests to services (e.g., AWS services) that use them for authentication.
*
* <p>For more details on AWS access keys, see:
* <a href="https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys">
* https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys</a></p>
*
* @see AwsSessionCredentialsIdentity
*/
@SdkPublicApi
@ThreadSafe
public interface AwsCredentialsIdentity extends Identity {
/**
* Retrieve the AWS access key, used to identify the user interacting with services.
*/
String accessKeyId();
/**
* Retrieve the AWS secret access key, used to authenticate the user interacting with services.
*/
String secretAccessKey();
static Builder builder() {
return DefaultAwsCredentialsIdentity.builder();
}
/**
* Constructs a new credentials object, with the specified AWS access key and AWS secret key.
*
* @param accessKeyId The AWS access key, used to identify the user interacting with services.
* @param secretAccessKey The AWS secret access key, used to authenticate the user interacting with services.
*/
static AwsCredentialsIdentity create(String accessKeyId, String secretAccessKey) {
return builder().accessKeyId(accessKeyId)
.secretAccessKey(secretAccessKey)
.build();
}
interface Builder {
/**
* The AWS access key, used to identify the user interacting with services.
*/
Builder accessKeyId(String accessKeyId);
/**
* The AWS secret access key, used to authenticate the user interacting with services.
*/
Builder secretAccessKey(String secretAccessKey);
AwsCredentialsIdentity build();
}
}
| 2,127 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/ResolveIdentityRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.identity.spi.internal.DefaultResolveIdentityRequest;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A request to resolve an {@link Identity}.
* <p>
* The Identity may be determined for each request based on properties of the request (e.g. different credentials per bucket
* for S3).
*
* @see IdentityProvider
*/
@SdkPublicApi
@Immutable
@ThreadSafe
public interface ResolveIdentityRequest extends ToCopyableBuilder<ResolveIdentityRequest.Builder, ResolveIdentityRequest> {
/**
* Get a new builder for creating a {@link ResolveIdentityRequest}.
*/
static Builder builder() {
return DefaultResolveIdentityRequest.builder();
}
/**
* Returns the value of a property that the {@link IdentityProvider} can use while resolving the identity.
*/
<T> T property(IdentityProperty<T> property);
/**
* A builder for a {@link ResolveIdentityRequest}.
*/
interface Builder extends CopyableBuilder<Builder, ResolveIdentityRequest> {
/**
* Set a property that the {@link IdentityProvider} can use while resolving the identity.
*/
<T> Builder putProperty(IdentityProperty<T> key, T value);
}
}
| 2,128 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/TokenIdentity.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Provides token which is used to securely authorize requests to services that use token based auth, e.g., OAuth.
*
* <p>For more details on OAuth tokens, see:
* <a href="https://oauth.net/2/access-tokens">
* https://oauth.net/2/access-tokens</a></p>
*/
@SdkPublicApi
@ThreadSafe
public interface TokenIdentity extends Identity {
/**
* Retrieves string field representing the literal token string.
*/
String token();
/**
* Constructs a new token object, which can be used to authorize requests to services that use token based auth
*
* @param token The token used to authorize requests.
*/
static TokenIdentity create(String token) {
Validate.paramNotNull(token, "token");
return new TokenIdentity() {
@Override
public String token() {
return token;
}
@Override
public String toString() {
return ToString.builder("TokenIdentity")
.add("token", token)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TokenIdentity that = (TokenIdentity) o;
return Objects.equals(token, that.token());
}
@Override
public int hashCode() {
return Objects.hashCode(token());
}
};
}
}
| 2,129 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/internal/DefaultResolveIdentityRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi.internal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.identity.spi.IdentityProperty;
import software.amazon.awssdk.identity.spi.ResolveIdentityRequest;
import software.amazon.awssdk.utils.ToString;
@SdkInternalApi
@Immutable
@ThreadSafe
public final class DefaultResolveIdentityRequest implements ResolveIdentityRequest {
private final Map<IdentityProperty<?>, Object> properties;
private DefaultResolveIdentityRequest(BuilderImpl builder) {
this.properties = new HashMap<>(builder.properties);
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public <T> T property(IdentityProperty<T> property) {
return (T) properties.get(property);
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
@Override
public String toString() {
return ToString.builder("ResolveIdentityRequest")
.add("properties", properties)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultResolveIdentityRequest that = (DefaultResolveIdentityRequest) o;
return properties.equals(that.properties);
}
@Override
public int hashCode() {
return Objects.hashCode(properties);
}
@SdkInternalApi
public static final class BuilderImpl implements Builder {
private final Map<IdentityProperty<?>, Object> properties = new HashMap<>();
private BuilderImpl() {
}
private BuilderImpl(DefaultResolveIdentityRequest resolveIdentityRequest) {
this.properties.putAll(resolveIdentityRequest.properties);
}
public <T> Builder putProperty(IdentityProperty<T> key, T value) {
this.properties.put(key, value);
return this;
}
public ResolveIdentityRequest build() {
return new DefaultResolveIdentityRequest(this);
}
}
}
| 2,130 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/internal/DefaultAwsSessionCredentialsIdentity.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi.internal;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class DefaultAwsSessionCredentialsIdentity implements AwsSessionCredentialsIdentity {
private final String accessKeyId;
private final String secretAccessKey;
private final String sessionToken;
private DefaultAwsSessionCredentialsIdentity(Builder builder) {
this.accessKeyId = builder.accessKeyId;
this.secretAccessKey = builder.secretAccessKey;
this.sessionToken = builder.sessionToken;
Validate.paramNotNull(accessKeyId, "accessKeyId");
Validate.paramNotNull(secretAccessKey, "secretAccessKey");
Validate.paramNotNull(sessionToken, "sessionToken");
}
public static AwsSessionCredentialsIdentity.Builder builder() {
return new Builder();
}
@Override
public String accessKeyId() {
return accessKeyId;
}
@Override
public String secretAccessKey() {
return secretAccessKey;
}
@Override
public String sessionToken() {
return sessionToken;
}
@Override
public String toString() {
return ToString.builder("AwsSessionCredentialsIdentity")
.add("accessKeyId", accessKeyId)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AwsSessionCredentialsIdentity that = (AwsSessionCredentialsIdentity) o;
return Objects.equals(accessKeyId, that.accessKeyId()) &&
Objects.equals(secretAccessKey, that.secretAccessKey()) &&
Objects.equals(sessionToken, that.sessionToken());
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + Objects.hashCode(accessKeyId);
hashCode = 31 * hashCode + Objects.hashCode(secretAccessKey);
hashCode = 31 * hashCode + Objects.hashCode(sessionToken);
return hashCode;
}
private static final class Builder implements AwsSessionCredentialsIdentity.Builder {
private String accessKeyId;
private String secretAccessKey;
private String sessionToken;
private Builder() {
}
@Override
public Builder accessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
return this;
}
@Override
public Builder secretAccessKey(String secretAccessKey) {
this.secretAccessKey = secretAccessKey;
return this;
}
@Override
public Builder sessionToken(String sessionToken) {
this.sessionToken = sessionToken;
return this;
}
@Override
public AwsSessionCredentialsIdentity build() {
return new DefaultAwsSessionCredentialsIdentity(this);
}
}
}
| 2,131 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/internal/DefaultAwsCredentialsIdentity.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi.internal;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class DefaultAwsCredentialsIdentity implements AwsCredentialsIdentity {
private final String accessKeyId;
private final String secretAccessKey;
private DefaultAwsCredentialsIdentity(Builder builder) {
this.accessKeyId = builder.accessKeyId;
this.secretAccessKey = builder.secretAccessKey;
Validate.paramNotNull(accessKeyId, "accessKeyId");
Validate.paramNotNull(secretAccessKey, "secretAccessKey");
}
public static AwsCredentialsIdentity.Builder builder() {
return new Builder();
}
@Override
public String accessKeyId() {
return accessKeyId;
}
@Override
public String secretAccessKey() {
return secretAccessKey;
}
@Override
public String toString() {
return ToString.builder("AwsCredentialsIdentity")
.add("accessKeyId", accessKeyId)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AwsCredentialsIdentity that = (AwsCredentialsIdentity) o;
return Objects.equals(accessKeyId, that.accessKeyId()) &&
Objects.equals(secretAccessKey, that.secretAccessKey());
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + Objects.hashCode(accessKeyId);
hashCode = 31 * hashCode + Objects.hashCode(secretAccessKey);
return hashCode;
}
private static final class Builder implements AwsCredentialsIdentity.Builder {
private String accessKeyId;
private String secretAccessKey;
private Builder() {
}
@Override
public Builder accessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
return this;
}
@Override
public Builder secretAccessKey(String secretAccessKey) {
this.secretAccessKey = secretAccessKey;
return this;
}
@Override
public AwsCredentialsIdentity build() {
return new DefaultAwsCredentialsIdentity(this);
}
}
}
| 2,132 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/internal/DefaultIdentityProviders.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi.internal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
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.utils.Lazy;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* A default implementation of {@link IdentityProviders}. This implementation holds a map of {@link IdentityProvider}s and
* retrieves from the collection based on identity type.
*/
@Immutable
@SdkInternalApi
public final class DefaultIdentityProviders implements IdentityProviders {
/**
* TODO(sra-identity-auth): Currently, some customers assume we won't interact with the identity providers when we create
* the client. This isn't true - we need to call identityType. To TEMPORARILY work around those customer's tests failing,
* this is marked lazy. Once we fully migrate over to the SRA as the default code path, we should remove this lazy and
* ticket everyone in live who is making those bad assumptions.
*/
private final Lazy<Map<Class<?>, IdentityProvider<?>>> identityProviders;
private final List<IdentityProvider<?>> identityProvidersList;
private DefaultIdentityProviders(BuilderImpl builder) {
this.identityProvidersList = new ArrayList<>(builder.identityProviders);
this.identityProviders = new Lazy<>(() -> {
Map<Class<?>, IdentityProvider<?>> result = new HashMap<>();
for (IdentityProvider<?> identityProvider : identityProvidersList) {
result.put(identityProvider.identityType(), identityProvider);
}
return result;
});
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public <T extends Identity> IdentityProvider<T> identityProvider(Class<T> identityType) {
return (IdentityProvider<T>) identityProviders.getValue().get(identityType);
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
@Override
public String toString() {
return ToString.builder("IdentityProviders")
.add("identityProviders", identityProvidersList)
.build();
}
private static final class BuilderImpl implements Builder {
private final List<IdentityProvider<?>> identityProviders = new ArrayList<>();
private BuilderImpl() {
}
private BuilderImpl(DefaultIdentityProviders identityProviders) {
this.identityProviders.addAll(identityProviders.identityProvidersList);
}
@Override
public <T extends Identity> Builder putIdentityProvider(IdentityProvider<T> identityProvider) {
Validate.paramNotNull(identityProvider, "identityProvider");
identityProviders.add(identityProvider);
return this;
}
public IdentityProviders build() {
return new DefaultIdentityProviders(this);
}
}
}
| 2,133 |
0 | Create_ds/aws-sdk-java-v2/core/arns/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/arns/src/test/java/software/amazon/awssdk/arns/ArnTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.arns;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
public class ArnTest {
@Test
public void arnWithBasicResource_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1:12345678910:myresource";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.accountId()).hasValue("12345678910");
assertThat(arn.resourceAsString()).isEqualTo("myresource");
System.out.println(arn.resource());
}
@Test
public void arnWithMinimalRequirementFromString() {
Arn arn = Arn.fromString("arn:aws:foobar:::myresource");
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("foobar");
assertThat(arn.resourceAsString()).isEqualTo("myresource");
}
@Test
public void arn_ParsesBackToString() {
String arnString = "arn:aws:s3:us-east-1:12345678910:myresource";
Arn arn = Arn.fromString(arnString);
assertThat(arn.toString()).isEqualTo(arnString);
}
@Test
public void arnWithQualifiedResource_ParsesBackToString() {
String arnString = "arn:aws:s3:us-east-1:12345678910:myresource:foobar:1";
Arn arn = Arn.fromString(arnString);
assertThat(arn.toString()).isEqualTo(arnString);
assertThat(arn.resourceAsString()).isEqualTo("myresource:foobar:1");
}
@Test
public void arnWithResourceTypeAndResource_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1:12345678910:bucket:foobar";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.resourceAsString()).isEqualTo("bucket:foobar");
verifyArnResource(arn.resource());
}
private void verifyArnResource(ArnResource arnResource) {
assertThat(arnResource.resource()).isEqualTo("foobar");
assertThat(arnResource.resourceType()).isPresent();
assertThat(arnResource.resourceType().get()).isEqualTo("bucket");
}
@Test
public void arnWithResourceTypeAndResourceAndQualifier_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1:12345678910:bucket:foobar:1";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.resourceAsString()).isEqualTo("bucket:foobar:1");
ArnResource arnResource = arn.resource();
verifyArnResource(arnResource);
assertThat(arnResource.qualifier()).isPresent();
assertThat(arnResource.qualifier().get()).isEqualTo("1");
}
@Test
public void arnWithResourceTypeAndResource_SlashSplitter_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1:12345678910:bucket/foobar";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.resourceAsString()).isEqualTo("bucket/foobar");
verifyArnResource(arn.resource());
}
@Test
public void arnWithResourceTypeAndResourceAndQualifier_SlashSplitter_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1:12345678910:bucket/foobar/1";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.resourceAsString()).isEqualTo("bucket/foobar/1");
verifyArnResource(arn.resource());
assertThat(arn.resource().qualifier().get()).isEqualTo("1");
}
@Test
public void oneArnEqualsEquivalentArn() {
String arnString = "arn:aws:s3:us-east-1:12345678910:myresource:foobar";
Arn arn1 = Arn.fromString(arnString);
Arn arn2 = Arn.fromString(arnString);
assertThat(arn1).isEqualTo(arn2);
assertThat(arn1.resource()).isEqualTo(arn2.resource());
}
@Test
public void arnFromBuilder_ParsesCorrectly() {
Arn arn = Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("bucket:foobar:1")
.build();
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.accountId()).hasValue("123456789012");
assertThat(arn.resourceAsString()).isEqualTo("bucket:foobar:1");
verifyArnResource(arn.resource());
assertThat(arn.resource().qualifier()).isPresent();
assertThat(arn.resource().qualifier().get()).isEqualTo("1");
}
@Test
public void arnResourceWithColonAndSlash_ParsesOnFirstSplitter() {
String resourceWithColonAndSlash = "object:foobar/myobjectname:1";
Arn arn = Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource(resourceWithColonAndSlash)
.build();
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.accountId()).hasValue("123456789012");
assertThat(arn.resourceAsString()).isEqualTo(resourceWithColonAndSlash);
assertThat(arn.resource().resource()).isEqualTo("foobar/myobjectname");
assertThat(arn.resource().qualifier()).hasValue("1");
assertThat(arn.resource().resourceType()).hasValue("object");
}
@Test
public void arnWithoutRegion_ParsesCorrectly() {
String arnString = "arn:aws:s3::123456789012:myresource";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).isEmpty();
assertThat(arn.accountId()).hasValue("123456789012");
assertThat(arn.resourceAsString()).isEqualTo("myresource");
}
@Test
public void arnWithoutAccountId_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1::myresource";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.accountId()).isEmpty();
assertThat(arn.resourceAsString()).isEqualTo("myresource");
}
@Test
public void arnResourceContainingDots_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1:12345678910:myresource:foobar.1";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.accountId()).hasValue("12345678910");
assertThat(arn.resourceAsString()).isEqualTo("myresource:foobar.1");
}
@Test
public void toBuilder() {
Arn oneArn = Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("bucket:foobar:1")
.build();
Arn anotherArn = oneArn.toBuilder().build();
assertThat(oneArn).isEqualTo(anotherArn);
assertThat(oneArn.hashCode()).isEqualTo(anotherArn.hashCode());
}
@Test
public void hashCodeEquals() {
Arn oneArn = Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("bucket:foobar:1")
.build();
Arn anotherArn = oneArn.toBuilder().region("somethingelse").build();
assertThat(oneArn).isNotEqualTo(anotherArn);
assertThat(oneArn.hashCode()).isNotEqualTo(anotherArn.hashCode());
}
@Test
public void hashCodeEquals_minimalProperties() {
Arn arn = Arn.builder()
.partition("aws")
.service("foobar")
.resource("resource")
.build();
Arn anotherArn = arn.toBuilder().build();
assertThat(arn.hashCode()).isEqualTo(anotherArn.hashCode());
assertThat(arn.region()).isEmpty();
assertThat(arn.accountId()).isEmpty();
assertThat(arn.equals(anotherArn)).isTrue();
}
@Test
public void arnWithoutPartition_ThrowsIllegalArgumentException() {
String arnString = "arn::s3:us-east-1:12345678910:myresource";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("artition must not be blank or empty.");
}
@Test
public void arnWithoutService_ThrowsIllegalArgumentException() {
String arnString = "arn:aws::us-east-1:12345678910:myresource";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("service must not be blank or empty");
}
@Test
public void arnWithoutResource_ThrowsIllegalArgumentException() {
String arnString = "arn:aws:s3:us-east-1:12345678910:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
@Test
public void invalidArn_ThrowsIllegalArgumentException() {
String arnString = "arn:aws:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
@Test
public void arnDoesntStartWithArn_ThrowsIllegalArgumentException() {
String arnString = "fakearn:aws:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
@Test
public void invalidArnWithoutPartition_ThrowsIllegalArgumentException() {
String arnString = "arn:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
@Test
public void invalidArnWithoutService_ThrowsIllegalArgumentException() {
String arnString = "arn:aws:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
@Test
public void invalidArnWithoutRegion_ThrowsIllegalArgumentException() {
String arnString = "arn:aws:s3:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
@Test
public void invalidArnWithoutAccountId_ThrowsIllegalArgumentException() {
String arnString = "arn:aws:s3:us-east-1:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
}
| 2,134 |
0 | Create_ds/aws-sdk-java-v2/core/arns/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/arns/src/test/java/software/amazon/awssdk/arns/ArnResourceTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.arns;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Optional;
import org.junit.jupiter.api.Test;
public class ArnResourceTest {
@Test
public void toBuilder() {
ArnResource oneResource = ArnResource.fromString("bucket:foobar:1");
ArnResource anotherResource = oneResource.toBuilder().build();
assertThat(oneResource).isEqualTo(anotherResource);
assertThat(oneResource.hashCode()).isEqualTo(anotherResource.hashCode());
}
@Test
public void hashCodeEquals() {
ArnResource oneResource = ArnResource.fromString("bucket:foobar:1");
ArnResource anotherResource = oneResource.toBuilder().qualifier("test").build();
assertThat(oneResource).isNotEqualTo(anotherResource);
assertThat(oneResource.hashCode()).isNotEqualTo(anotherResource.hashCode());
}
@Test
public void arnResource_nullResource_shouldThrowException() {
assertThatThrownBy(() -> ArnResource.builder()
.build()).hasMessageContaining("resource must not be null.");
}
@Test
public void arnResourceFromBuilder_shouldParseCorrectly() {
ArnResource arnResource = ArnResource.builder()
.resource("bucket:foobar:1")
.resourceType("foobar")
.qualifier("1").build();
assertThat(arnResource.qualifier()).isEqualTo(Optional.of("1"));
assertThat(arnResource.resourceType()).isEqualTo(Optional.of("foobar"));
assertThat(arnResource.resource()).isEqualTo("bucket:foobar:1");
}
@Test
public void hashCodeEquals_minimalProperties() {
ArnResource arnResource = ArnResource.builder().resource("resource").build();
ArnResource anotherResource = arnResource.toBuilder().build();
assertThat(arnResource.equals(anotherResource)).isTrue();
assertThat(arnResource.hashCode()).isEqualTo(anotherResource.hashCode());
}
}
| 2,135 |
0 | Create_ds/aws-sdk-java-v2/core/arns/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/arns/src/main/java/software/amazon/awssdk/arns/Arn.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.arns;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* The Arns generated and recognized by this code are the Arns described here:
*
* https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
*
* <p>
* The primary supported Arn format is:
*
* <code>
* arn:<partition>:<service>:<region>:<account>:<resource>
* </code>
*
* <p>
* {@link #resourceAsString()} returns everything after the account section of the Arn
* as a single string.
*
* <p>
* However, the following Arn formats are supported where the values are present and well
* formatted through {@link #resource()}:
*
* <pre>
* arn:<partition>:<service>:<region>:<account>:<resourcetype>/resource
* arn:<partition>:<service>:<region>:<account>:<resourcetype>/resource/qualifier
* arn:<partition>:<service>:<region>:<account>:<resourcetype>/resource:qualifier
* arn:<partition>:<service>:<region>:<account>:<resourcetype>:resource
* arn:<partition>:<service>:<region>:<account>:<resourcetype>:resource:qualifier
* </pre>
*
* {@link #resource()} returns a {@link ArnResource} which has access
* to {@link ArnResource#resourceType()}, {@link ArnResource#resource()} and
* {@link ArnResource#qualifier()}.
*
* <p>
* To parse an Arn from a string use Arn.fromString(). To convert an Arn to it's
* string representation use Arn.toString().
*
* <p>
* For instance, for a string s, containing a well-formed Arn the
* following should always be true:
*
* <pre>
* Arn theArn = Arn.fromString(s);
* s.equals(theArn.toString());
* </pre>
*
* @see ArnResource
*/
@SdkPublicApi
public final class Arn implements ToCopyableBuilder<Arn.Builder, Arn> {
private final String partition;
private final String service;
private final String region;
private final String accountId;
private final String resource;
private final ArnResource arnResource;
private Arn(DefaultBuilder builder) {
this.partition = Validate.paramNotBlank(builder.partition, "partition");
this.service = Validate.paramNotBlank(builder.service, "service");
this.region = builder.region;
this.accountId = builder.accountId;
this.resource = Validate.paramNotBlank(builder.resource, "resource");
this.arnResource = ArnResource.fromString(resource);
}
/**
* @return The partition that the resource is in.
*/
public String partition() {
return partition;
}
/**
* @return The service namespace that identifies the AWS product (for example, Amazon S3, IAM, or Amazon RDS).
*/
public String service() {
return service;
}
/**
* @return The Region that the resource resides in.
*/
public Optional<String> region() {
return StringUtils.isEmpty(region) ? Optional.empty() : Optional.of(region);
}
/**
* @return The ID of the AWS account that owns the resource, without the hyphens.
*/
public Optional<String> accountId() {
return StringUtils.isEmpty(accountId) ? Optional.empty() : Optional.of(accountId);
}
/**
* @return {@link ArnResource}
*/
public ArnResource resource() {
return arnResource;
}
/**
* @return the resource as string
*/
public String resourceAsString() {
return resource;
}
/**
* @return a builder for {@link Arn}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Parses a given string into an {@link Arn}. The resource is accessible entirely as a
* string through {@link #resourceAsString()}. Where correctly formatted, a parsed
* resource containing resource type, resource and qualifier is available through
* {@link #resource()}.
*
* @param arn - A string containing an Arn.
* @return {@link Arn} - A modeled Arn.
*/
public static Arn fromString(String arn) {
int arnColonIndex = arn.indexOf(':');
if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) {
throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'");
}
int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1);
if (partitionColonIndex < 0) {
throw new IllegalArgumentException("Malformed ARN - no AWS partition specified");
}
String partition = arn.substring(arnColonIndex + 1, partitionColonIndex);
int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1);
if (serviceColonIndex < 0) {
throw new IllegalArgumentException("Malformed ARN - no service specified");
}
String service = arn.substring(partitionColonIndex + 1, serviceColonIndex);
int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1);
if (regionColonIndex < 0) {
throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified");
}
String region = arn.substring(serviceColonIndex + 1, regionColonIndex);
int accountColonIndex = arn.indexOf(':', regionColonIndex + 1);
if (accountColonIndex < 0) {
throw new IllegalArgumentException("Malformed ARN - no AWS account specified");
}
String accountId = arn.substring(regionColonIndex + 1, accountColonIndex);
String resource = arn.substring(accountColonIndex + 1);
if (resource.isEmpty()) {
throw new IllegalArgumentException("Malformed ARN - no resource specified");
}
return Arn.builder()
.partition(partition)
.service(service)
.region(region)
.accountId(accountId)
.resource(resource)
.build();
}
@Override
public String toString() {
return "arn:"
+ this.partition
+ ":"
+ this.service
+ ":"
+ region
+ ":"
+ this.accountId
+ ":"
+ this.resource;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Arn arn = (Arn) o;
if (!Objects.equals(partition, arn.partition)) {
return false;
}
if (!Objects.equals(service, arn.service)) {
return false;
}
if (!Objects.equals(region, arn.region)) {
return false;
}
if (!Objects.equals(accountId, arn.accountId)) {
return false;
}
if (!Objects.equals(resource, arn.resource)) {
return false;
}
return Objects.equals(arnResource, arn.arnResource);
}
@Override
public int hashCode() {
int result = partition.hashCode();
result = 31 * result + service.hashCode();
result = 31 * result + (region != null ? region.hashCode() : 0);
result = 31 * result + (accountId != null ? accountId.hashCode() : 0);
result = 31 * result + resource.hashCode();
return result;
}
@Override
public Builder toBuilder() {
return builder().accountId(accountId)
.partition(partition)
.region(region)
.resource(resource)
.service(service)
;
}
/**
* A builder for a {@link Arn}. See {@link #builder()}.
*/
public interface Builder extends CopyableBuilder<Builder, Arn> {
/**
* Define the partition that the resource is in.
*
* @param partition the partition that the resource is in
* @return Returns a reference to this builder
*/
Builder partition(String partition);
/**
* Define the service name that identifies the AWS product
*
* @param service The service name that identifies the AWS product
* @return Returns a reference to this builder
*/
Builder service(String service);
/**
* Define the Region that the resource resides in.
*
* @param region The Region that the resource resides in.
* @return Returns a reference to this builder
*/
Builder region(String region);
/**
* Define the ID of the AWS account that owns the resource, without the hyphens.
*
* @param accountId The ID of the AWS account that owns the resource, without the hyphens.
* @return Returns a reference to this builder
*/
Builder accountId(String accountId);
/**
* Define the resource identifier. A resource identifier can be the name or ID of the resource
* or a resource path.
*
* @param resource resource identifier
* @return Returns a reference to this builder
*/
Builder resource(String resource);
/**
* @return an instance of {@link Arn} that is created from the builder
*/
@Override
Arn build();
}
private static final class DefaultBuilder implements Builder {
private String partition;
private String service;
private String region;
private String accountId;
private String resource;
private DefaultBuilder() {
}
public void setPartition(String partition) {
this.partition = partition;
}
@Override
public Builder partition(String partition) {
setPartition(partition);
return this;
}
public void setService(String service) {
this.service = service;
}
@Override
public Builder service(String service) {
setService(service);
return this;
}
public void setRegion(String region) {
this.region = region;
}
@Override
public Builder region(String region) {
setRegion(region);
return this;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
@Override
public Builder accountId(String accountId) {
setAccountId(accountId);
return this;
}
public void setResource(String resource) {
this.resource = resource;
}
@Override
public Builder resource(String resource) {
setResource(resource);
return this;
}
@Override
public Arn build() {
return new Arn(this);
}
}
}
| 2,136 |
0 | Create_ds/aws-sdk-java-v2/core/arns/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/arns/src/main/java/software/amazon/awssdk/arns/ArnResource.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.arns;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* An additional model within {@link Arn} that provides the Resource Type, Resource, and
* Resource Qualifier of an AWS Arn when those values are present and correctly formatted
* within an Arn.
*
* <p>
* If {@link #resourceType} is not present, {@link #resource} will return the entire resource
* as a string the same as {@link Arn#resource()}.
*
* @see Arn
*/
@SdkPublicApi
public final class ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> {
private final String resourceType;
private final String resource;
private final String qualifier;
private ArnResource(DefaultBuilder builder) {
this.resourceType = builder.resourceType;
this.resource = Validate.paramNotBlank(builder.resource, "resource");
this.qualifier = builder.qualifier;
}
/**
* @return the optional resource type
*/
public Optional<String> resourceType() {
return Optional.ofNullable(resourceType);
}
/**
* @return the entire resource as a string
*/
public String resource() {
return resource;
}
/**
* @return the optional resource qualifier
*/
public Optional<String> qualifier() {
return Optional.ofNullable(qualifier);
}
/**
* @return a builder for {@link ArnResource}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Parses a string containing either a resource, resource type and resource or
* resource type, resource and qualifier into an {@link ArnResource}.
*
* <p>
* Supports fields separated by either ":" or "/".
*
* <p>
* For legacy AWS Arns not following the resourceType:resource:qualifier pattern,
* the qualifier field will contain everything after the first two sections separated
* by either ":" or "/".
*
* @param resource - The resource string to parse.
* @return {@link ArnResource}
*/
public static ArnResource fromString(String resource) {
Character splitter = StringUtils.findFirstOccurrence(resource, ':', '/');
if (splitter == null) {
return ArnResource.builder().resource(resource).build();
}
int resourceTypeColonIndex = resource.indexOf(splitter);
ArnResource.Builder builder = ArnResource.builder().resourceType(resource.substring(0, resourceTypeColonIndex));
int resourceColonIndex = resource.indexOf(splitter, resourceTypeColonIndex);
int qualifierColonIndex = resource.indexOf(splitter, resourceColonIndex + 1);
if (qualifierColonIndex < 0) {
builder.resource(resource.substring(resourceTypeColonIndex + 1));
} else {
builder.resource(resource.substring(resourceTypeColonIndex + 1, qualifierColonIndex));
builder.qualifier(resource.substring(qualifierColonIndex + 1));
}
return builder.build();
}
@Override
public String toString() {
return this.resourceType
+ ":"
+ this.resource
+ ":"
+ this.qualifier;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ArnResource that = (ArnResource) o;
if (!Objects.equals(resourceType, that.resourceType)) {
return false;
}
if (!Objects.equals(resource, that.resource)) {
return false;
}
return Objects.equals(qualifier, that.qualifier);
}
@Override
public int hashCode() {
int result = resourceType != null ? resourceType.hashCode() : 0;
result = 31 * result + (resource != null ? resource.hashCode() : 0);
result = 31 * result + (qualifier != null ? qualifier.hashCode() : 0);
return result;
}
@Override
public Builder toBuilder() {
return builder()
.resource(resource)
.resourceType(resourceType)
.qualifier(qualifier);
}
public interface Builder extends CopyableBuilder<ArnResource.Builder, ArnResource> {
/**
* Define the type of the resource.
*
* @param resourceType the partition that the resource is in
* @return Returns a reference to this builder
*/
Builder resourceType(String resourceType);
/**
* Define the entire resource.
*
* @param resource the entire resource
* @return Returns a reference to this builder
*/
Builder resource(String resource);
/**
* Define the qualifier of the resource.
*
* @param qualifier the qualifier of the resource
* @return Returns a reference to this builder
*/
Builder qualifier(String qualifier);
/**
* @return an instance of {@link ArnResource} that is created from the builder
*/
@Override
ArnResource build();
}
public static final class DefaultBuilder implements Builder {
private String resourceType;
private String resource;
private String qualifier;
private DefaultBuilder() {
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
@Override
public Builder resourceType(String resourceType) {
setResourceType(resourceType);
return this;
}
public void setResource(String resource) {
this.resource = resource;
}
@Override
public Builder resource(String resource) {
setResource(resource);
return this;
}
public void setQualifier(String qualifier) {
this.qualifier = qualifier;
}
@Override
public Builder qualifier(String qualifier) {
setQualifier(qualifier);
return this;
}
@Override
public ArnResource build() {
return new ArnResource(this);
}
}
} | 2,137 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/test/java/software/amazon/awssdk/profiles/ProfileFileSupplierTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import static org.assertj.core.api.Assertions.assertThat;
import com.google.common.jimfs.Jimfs;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.TemporalAmount;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.StringInputStream;
class ProfileFileSupplierTest {
private static FileSystem jimfs;
private static Path testDirectory;
@BeforeAll
public static void setup() {
jimfs = Jimfs.newFileSystem();
testDirectory = jimfs.getPath("test");
}
@AfterAll
public static void tearDown() {
try {
jimfs.close();
} catch (IOException e) {
// no-op
}
}
@Test
void get_profileFileFixed_doesNotReloadProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
ProfileFileSupplier supplier = builder()
.fixedProfileFile(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build();
ProfileFile file1 = supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
ProfileFile file2 = supplier.get();
assertThat(file2).isSameAs(file1);
}
@Test
void get_profileModifiedWithinJitterPeriod_doesNotReloadCredentials() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
Duration durationWithinJitter = Duration.ofMillis(10);
ProfileFileSupplier supplier = builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build();
ProfileFile file1 = supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plus(durationWithinJitter));
clock.tickForward(durationWithinJitter);
ProfileFile file2 = supplier.get();
assertThat(file2).isSameAs(file1);
}
@Test
void get_profileModifiedOutsideJitterPeriod_reloadsCredentials() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileSupplier supplier = builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build();
Duration durationOutsideJitter = Duration.ofSeconds(1);
supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plus(durationOutsideJitter));
clock.tickForward(durationOutsideJitter);
Optional<Profile> fileOptional = supplier.get().profile("default");
assertThat(fileOptional).isPresent();
assertThat(fileOptional.get()).satisfies(profile -> {
Optional<String> awsAccessKeyIdOptional = profile.property("aws_access_key_id");
assertThat(awsAccessKeyIdOptional).isPresent();
String awsAccessKeyId = awsAccessKeyIdOptional.get();
assertThat(awsAccessKeyId).isEqualTo("modifiedAccessKey");
Optional<String> awsSecretAccessKeyOptional = profile.property("aws_secret_access_key");
assertThat(awsSecretAccessKeyOptional).isPresent();
String awsSecretAccessKey = awsSecretAccessKeyOptional.get();
assertThat(awsSecretAccessKey).isEqualTo("modifiedSecretAccessKey");
});
}
@Test
void get_profileModified_reloadsProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileSupplier supplier = builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build();
Duration duration = Duration.ofSeconds(10);
ProfileFile file1 = supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file2 = supplier.get();
assertThat(file2).isNotSameAs(file1);
}
@Test
void get_profileModifiedOnceButRefreshedMultipleTimes_reloadsProfileFileOnce() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileSupplier supplier = builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build();
ProfileFile file1 = supplier.get();
clock.tickForward(Duration.ofSeconds(5));
ProfileFile file2 = supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(Duration.ofSeconds(5));
ProfileFile file3 = supplier.get();
assertThat(file2).isSameAs(file1);
assertThat(file3).isNotSameAs(file2);
}
@Test
void get_profileModifiedMultipleTimes_reloadsProfileFileOncePerChange() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileSupplier supplier = builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build();
Duration duration = Duration.ofSeconds(5);
ProfileFile file1 = supplier.get();
clock.tickForward(duration);
ProfileFile file2 = supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file3 = supplier.get();
generateTestCredentialsFile("updatedAccessKey", "updatedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file4 = supplier.get();
clock.tickForward(duration);
ProfileFile file5 = supplier.get();
assertThat(file2).isSameAs(file1);
assertThat(file3).isNotSameAs(file2);
assertThat(file4).isNotSameAs(file3);
assertThat(file5).isSameAs(file4);
}
@Test
void get_supplierBuiltByReloadWhenModified_loadsProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
ProfileFileSupplier supplier = ProfileFileSupplier.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS);
ProfileFile file = supplier.get();
Optional<Profile> profileOptional = file.profile("default");
assertThat(profileOptional).isPresent();
assertThat(profileOptional.get()).satisfies(profile -> {
Optional<String> awsAccessKeyIdOptional = profile.property("aws_access_key_id");
assertThat(awsAccessKeyIdOptional).isPresent();
String awsAccessKeyId = awsAccessKeyIdOptional.get();
assertThat(awsAccessKeyId).isEqualTo("defaultAccessKey");
Optional<String> awsSecretAccessKeyOptional = profile.property("aws_secret_access_key");
assertThat(awsSecretAccessKeyOptional).isPresent();
String awsSecretAccessKey = awsSecretAccessKeyOptional.get();
assertThat(awsSecretAccessKey).isEqualTo("defaultSecretAccessKey");
});
}
@Test
void get_supplierBuiltByFixedProfileFile_returnsProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
ProfileFileSupplier supplier = ProfileFileSupplier.fixedProfileFile(ProfileFile.builder()
.content(credentialsFilePath)
.type(ProfileFile.Type.CREDENTIALS)
.build());
ProfileFile file = supplier.get();
Optional<Profile> profileOptional = file.profile("default");
assertThat(profileOptional).isPresent();
assertThat(profileOptional.get()).satisfies(profile -> {
Optional<String> awsAccessKeyIdOptional = profile.property("aws_access_key_id");
assertThat(awsAccessKeyIdOptional).isPresent();
String awsAccessKeyId = awsAccessKeyIdOptional.get();
assertThat(awsAccessKeyId).isEqualTo("defaultAccessKey");
Optional<String> awsSecretAccessKeyOptional = profile.property("aws_secret_access_key");
assertThat(awsSecretAccessKeyOptional).isPresent();
String awsSecretAccessKey = awsSecretAccessKeyOptional.get();
assertThat(awsSecretAccessKey).isEqualTo("defaultSecretAccessKey");
});
}
@Test
void get_supplierBuiltByReloadWhenModifiedAggregate_reloadsCredentials() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
Path configFilePath = generateTestConfigFile(Pair.of("region", "us-west-2"));
ProfileFileSupplier credentialsProfileFileSupplier = ProfileFileSupplier.reloadWhenModified(credentialsFilePath,
ProfileFile.Type.CREDENTIALS);
ProfileFileSupplier configProfileFileSupplier = ProfileFileSupplier.reloadWhenModified(configFilePath,
ProfileFile.Type.CONFIGURATION);
ProfileFileSupplier supplier = ProfileFileSupplier.aggregate(credentialsProfileFileSupplier, configProfileFileSupplier);
Optional<Profile> fileOptional = supplier.get().profile("default");
assertThat(fileOptional).isPresent();
assertThat(fileOptional.get()).satisfies(profile -> {
Optional<String> awsAccessKeyIdOptional = profile.property("aws_access_key_id");
assertThat(awsAccessKeyIdOptional).isPresent();
String awsAccessKeyId = awsAccessKeyIdOptional.get();
assertThat(awsAccessKeyId).isEqualTo("defaultAccessKey");
Optional<String> awsSecretAccessKeyOptional = profile.property("aws_secret_access_key");
assertThat(awsSecretAccessKeyOptional).isPresent();
String awsSecretAccessKey = awsSecretAccessKeyOptional.get();
assertThat(awsSecretAccessKey).isEqualTo("defaultSecretAccessKey");
Optional<String> regionOptional = profile.property("region");
assertThat(regionOptional).isPresent();
String region = regionOptional.get();
assertThat(region).isEqualTo("us-west-2");
});
}
@Test
void get_supplierBuiltByFixedProfileFileAggregate_returnsAggregateProfileFileInstance() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
Path configFilePath = generateTestConfigFile(Pair.of("region", "us-west-2"));
ProfileFileSupplier credentialsProfileFileSupplier
= ProfileFileSupplier.fixedProfileFile(ProfileFile.builder()
.content(credentialsFilePath)
.type(ProfileFile.Type.CREDENTIALS)
.build());
ProfileFileSupplier configProfileFileSupplier
= ProfileFileSupplier.fixedProfileFile(ProfileFile.builder()
.content(configFilePath)
.type(ProfileFile.Type.CONFIGURATION)
.build());
ProfileFileSupplier supplier = ProfileFileSupplier.aggregate(credentialsProfileFileSupplier, configProfileFileSupplier);
ProfileFile file = supplier.get();
Optional<Profile> profileOptional = file.profile("default");
assertThat(profileOptional).isPresent();
assertThat(profileOptional.get()).satisfies(profile -> {
Optional<String> awsAccessKeyIdOptional = profile.property("aws_access_key_id");
assertThat(awsAccessKeyIdOptional).isPresent();
String awsAccessKeyId = awsAccessKeyIdOptional.get();
assertThat(awsAccessKeyId).isEqualTo("defaultAccessKey");
Optional<String> awsSecretAccessKeyOptional = profile.property("aws_secret_access_key");
assertThat(awsSecretAccessKeyOptional).isPresent();
String awsSecretAccessKey = awsSecretAccessKeyOptional.get();
assertThat(awsSecretAccessKey).isEqualTo("defaultSecretAccessKey");
Optional<String> regionOptional = profile.property("region");
assertThat(regionOptional).isPresent();
String region = regionOptional.get();
assertThat(region).isEqualTo("us-west-2");
});
}
@Test
void aggregate_supplierReturnsSameInstanceMultipleTimesAggregatingProfileFile_aggregatesOnlyDistinctInstances() {
ProfileFile credentialFile1 = credentialFile("test1", "key1", "secret1");
ProfileFile credentialFile2 = credentialFile("test2", "key2", "secret2");
ProfileFile credentialFile3 = credentialFile("test3", "key3", "secret3");
ProfileFile credentialFile4 = credentialFile("test4", "key4", "secret4");
ProfileFile configFile = configFile("profile test", Pair.of("region", "us-west-2"));
List<ProfileFile> orderedCredentialsFiles
= Arrays.asList(credentialFile1, credentialFile1, credentialFile2, credentialFile3, credentialFile3, credentialFile4,
credentialFile4, credentialFile4);
ProfileFile aggregateFile1 = ProfileFile.aggregator().addFile(credentialFile1).addFile(configFile).build();
ProfileFile aggregateFile2 = ProfileFile.aggregator().addFile(credentialFile2).addFile(configFile).build();
ProfileFile aggregateFile3 = ProfileFile.aggregator().addFile(credentialFile3).addFile(configFile).build();
ProfileFile aggregateFile4 = ProfileFile.aggregator().addFile(credentialFile4).addFile(configFile).build();
List<ProfileFile> distinctAggregateFiles = Arrays.asList(aggregateFile1, aggregateFile2, aggregateFile3, aggregateFile4);
ProfileFileSupplier supplier = ProfileFileSupplier.aggregate(supply(orderedCredentialsFiles), () -> configFile);
List<ProfileFile> suppliedProfileFiles = Stream.generate(supplier)
.limit(orderedCredentialsFiles.size())
.filter(uniqueInstances())
.collect(Collectors.toList());
assertThat(suppliedProfileFiles).isEqualTo(distinctAggregateFiles);
}
@Test
void aggregate_supplierReturnsSameInstanceMultipleTimesAggregatingProfileFileSupplier_aggregatesOnlyDistinctInstances() {
ProfileFile credentialFile1 = credentialFile("test1", "key1", "secret1");
ProfileFile credentialFile2 = credentialFile("test2", "key2", "secret2");
ProfileFile credentialFile3 = credentialFile("test3", "key3", "secret3");
ProfileFile credentialFile4 = credentialFile("test4", "key4", "secret4");
ProfileFile configFile1 = configFile("profile test", Pair.of("region", "us-west-1"));
ProfileFile configFile2 = configFile("profile test", Pair.of("region", "us-west-2"));
ProfileFile configFile3 = configFile("profile test", Pair.of("region", "us-west-3"));
List<ProfileFile> orderedCredentialsFiles
= Arrays.asList(credentialFile1, credentialFile1, credentialFile2, credentialFile2, credentialFile3,
credentialFile4, credentialFile4, credentialFile4);
List<ProfileFile> orderedConfigFiles
= Arrays.asList(configFile1, configFile1, configFile1, configFile2, configFile3, configFile3, configFile3,
configFile3);
ProfileFile aggregateFile11 = ProfileFile.aggregator().addFile(credentialFile1).addFile(configFile1).build();
ProfileFile aggregateFile21 = ProfileFile.aggregator().addFile(credentialFile2).addFile(configFile1).build();
ProfileFile aggregateFile22 = ProfileFile.aggregator().addFile(credentialFile2).addFile(configFile2).build();
ProfileFile aggregateFile33 = ProfileFile.aggregator().addFile(credentialFile3).addFile(configFile3).build();
ProfileFile aggregateFile43 = ProfileFile.aggregator().addFile(credentialFile4).addFile(configFile3).build();
List<ProfileFile> aggregateProfileFiles
= Arrays.asList(aggregateFile11, aggregateFile11, aggregateFile21, aggregateFile22, aggregateFile33,
aggregateFile43, aggregateFile43, aggregateFile43);
List<ProfileFile> distinctAggregateProfileFiles
= Arrays.asList(aggregateFile11, aggregateFile21, aggregateFile22, aggregateFile33, aggregateFile43);
ProfileFileSupplier supplier = ProfileFileSupplier.aggregate(supply(orderedCredentialsFiles), supply(orderedConfigFiles));
List<ProfileFile> suppliedProfileFiles = Stream.generate(supplier)
.filter(Objects::nonNull)
.limit(aggregateProfileFiles.size())
.filter(uniqueInstances())
.collect(Collectors.toList());
assertThat(suppliedProfileFiles).isEqualTo(distinctAggregateProfileFiles);
}
@Test
void aggregate_duplicateOptionsGivenFixedProfileFirst_preservesPrecedence() {
ProfileFile configFile1 = configFile("profile default", Pair.of("aws_access_key_id", "config-key"));
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
ProfileFileSupplier supplier = ProfileFileSupplier.aggregate(
ProfileFileSupplier.fixedProfileFile(configFile1),
ProfileFileSupplier.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS));
ProfileFile profileFile = supplier.get();
String accessKeyId = profileFile.profile("default").get().property("aws_access_key_id").get();
assertThat(accessKeyId).isEqualTo("config-key");
generateTestCredentialsFile("defaultAccessKey2", "defaultSecretAccessKey2");
profileFile = supplier.get();
accessKeyId = profileFile.profile("default").get().property("aws_access_key_id").get();
assertThat(accessKeyId).isEqualTo("config-key");
}
@Test
void aggregate_duplicateOptionsGivenReloadingProfileFirst_preservesPrecedence() throws IOException {
Instant startTime = Instant.now();
AdjustableClock clock = new AdjustableClock(startTime);
ProfileFile configFile1 = configFile("profile default", Pair.of("aws_access_key_id", "config-key"));
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
ProfileFileSupplier supplier = ProfileFileSupplier.aggregate(
builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build(),
ProfileFileSupplier.fixedProfileFile(configFile1));
ProfileFile profileFile = supplier.get();
String accessKeyId = profileFile.profile("default").get().property("aws_access_key_id").get();
assertThat(accessKeyId).isEqualTo("defaultAccessKey");
generateTestCredentialsFile("defaultAccessKey2", "defaultSecretAccessKey2");
Duration tick = Duration.ofMillis(1_000);
// The refresh logic uses the last modified attribute of the profile file to determine if it's changed and should be
// reloaded; unfortunately that means that if things happen quickly enough, the last modified time of the first version
// of the file, and the new version will be the same. Ensure that there is a change in the last modified time for the
// test file.
Files.setLastModifiedTime(getTestCredentialsFilePath(), FileTime.from(startTime.plus(tick)));
clock.tickForward(tick);
profileFile = supplier.get();
accessKeyId = profileFile.profile("default").get().property("aws_access_key_id").get();
assertThat(accessKeyId).isEqualTo("defaultAccessKey2");
}
@Test
void fixedProfileFile_nullProfileFile_returnsNonNullSupplier() {
ProfileFile file = null;
ProfileFileSupplier supplier = ProfileFileSupplier.fixedProfileFile(file);
assertThat(supplier).isNotNull();
}
@Test
void get_givenOnLoadAction_callsActionOncePerNewProfileFile() {
int actualProfilesCount = 3;
AtomicInteger blockCount = new AtomicInteger();
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileSupplier supplier = builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.onProfileFileLoad(f -> blockCount.incrementAndGet())
.build();
Duration duration = Duration.ofSeconds(5);
supplier.get();
clock.tickForward(duration);
supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
supplier.get();
generateTestCredentialsFile("updatedAccessKey", "updatedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
supplier.get();
clock.tickForward(duration);
supplier.get();
assertThat(blockCount.get()).isEqualTo(actualProfilesCount);
}
private Path writeTestFile(String contents, Path path) {
try {
Files.createDirectories(testDirectory);
return Files.write(path, contents.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Path generateTestCredentialsFile(String accessKeyId, String secretAccessKey) {
String contents = String.format("[default]\naws_access_key_id = %s\naws_secret_access_key = %s\n",
accessKeyId, secretAccessKey);
return writeTestFile(contents, getTestCredentialsFilePath());
}
private Path getTestCredentialsFilePath() {
return testDirectory.resolve("credentials.txt");
}
private Path generateTestConfigFile(Pair<Object, Object>... pairs) {
String values = Arrays.stream(pairs)
.map(pair -> String.format("%s=%s", pair.left(), pair.right()))
.collect(Collectors.joining(System.lineSeparator()));
String contents = String.format("[default]\n%s", values);
return writeTestFile(contents, testDirectory.resolve("config.txt"));
}
private void updateModificationTime(Path path, Instant instant) {
try {
Files.setLastModifiedTime(path, FileTime.from(instant));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private ProfileFile credentialFile(String credentialFile) {
return ProfileFile.builder()
.content(new StringInputStream(credentialFile))
.type(ProfileFile.Type.CREDENTIALS)
.build();
}
private ProfileFile credentialFile(String name, String accessKeyId, String secretAccessKey) {
String contents = String.format("[%s]\naws_access_key_id = %s\naws_secret_access_key = %s\n",
name, accessKeyId, secretAccessKey);
return credentialFile(contents);
}
private ProfileFile configFile(String credentialFile) {
return ProfileFile.builder()
.content(new StringInputStream(credentialFile))
.type(ProfileFile.Type.CONFIGURATION)
.build();
}
private ProfileFile configFile(String name, Pair<?, ?>... pairs) {
String values = Arrays.stream(pairs)
.map(pair -> String.format("%s=%s", pair.left(), pair.right()))
.collect(Collectors.joining(System.lineSeparator()));
String contents = String.format("[%s]\n%s", name, values);
return configFile(contents);
}
private static <T> Predicate<T> uniqueInstances() {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return e -> {
boolean unique = seen.stream().noneMatch(o -> o == e);
if (unique) {
seen.add(e);
}
return unique;
};
}
private static ProfileFileSupplier supply(Iterable<ProfileFile> iterable) {
return iterable.iterator()::next;
}
private ProfileFileSupplierBuilder builder() {
return new ProfileFileSupplierBuilder();
}
private ProfileFileSupplierBuilder builderWithClock(Clock clock) {
return new ProfileFileSupplierBuilder().clock(clock);
}
private static final class AdjustableClock extends Clock {
private Instant time;
private AdjustableClock() {
this.time = Instant.now();
}
private AdjustableClock(Instant time) {
this.time = time;
}
@Override
public ZoneId getZone() {
return ZoneOffset.UTC;
}
@Override
public Clock withZone(ZoneId zone) {
throw new UnsupportedOperationException();
}
@Override
public Instant instant() {
return time;
}
public void tickForward(TemporalAmount amount) {
time = time.plus(amount);
}
public void tickBackward(TemporalAmount amount) {
time = time.minus(amount);
}
}
} | 2,138 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/test/java/software/amazon/awssdk/profiles/ProfileFileTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.StringInputStream;
/**
* Validate the functionality of {@link ProfileFile}.
*/
public class ProfileFileTest {
@Test
public void emptyFilesHaveNoProfiles() {
assertThat(configFileProfiles("")).isEmpty();
}
@Test
public void emptyProfilesHaveNoProperties() {
assertThat(configFileProfiles("[profile foo]"))
.isEqualTo(profiles(profile("foo")));
}
@Test
public void profileDefinitionsMustEndWithBrackets() {
assertThatThrownBy(() -> configFileProfiles("[profile foo"))
.hasMessageContaining("Profile definition must end with ']'");
}
@Test
public void profileNamesShouldBeTrimmed() {
assertThat(configFileProfiles("[profile \tfoo \t]"))
.isEqualTo(profiles(profile("foo")));
}
@Test
public void tabsCanSeparateProfileNamesFromProfilePrefix() {
assertThat(configFileProfiles("[profile\tfoo]"))
.isEqualTo(profiles(profile("foo")));
}
@Test
public void propertiesMustBeDefinedInAProfile() {
assertThatThrownBy(() -> configFileProfiles("name = value"))
.hasMessageContaining("Expected a profile definition");
}
@Test
public void profilesCanContainProperties() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void windowsStyleLineEndingsAreSupported() {
assertThat(configFileProfiles("[profile foo]\r\n" +
"name = value"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void equalsSignsAreSupportedInPropertyNames() {
assertThat(configFileProfiles("[profile foo]\r\n" +
"name = val=ue"))
.isEqualTo(profiles(profile("foo", property("name", "val=ue"))));
}
@Test
public void unicodeCharactersAreSupportedInPropertyValues() {
assertThat(configFileProfiles("[profile foo]\r\n" +
"name = \uD83D\uDE02"))
.isEqualTo(profiles(profile("foo", property("name", "\uD83D\uDE02"))));
}
@Test
public void profilesCanContainMultipleProperties() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
"name2 = value2"))
.isEqualTo(profiles(profile("foo",
property("name", "value"),
property("name2", "value2"))));
}
@Test
public void propertyKeysAndValuesAreTrimmed() {
assertThat(configFileProfiles("[profile foo]\n" +
"name \t= \tvalue \t"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void propertyValuesCanBeEmpty() {
assertThat(configFileProfiles("[profile foo]\n" +
"name ="))
.isEqualTo(profiles(profile("foo", property("name", ""))));
}
@Test
public void propertyKeysCannotBeEmpty() {
assertThatThrownBy(() -> configFileProfiles("[profile foo]\n" +
"= value"))
.hasMessageContaining("Property did not have a name");
}
@Test
public void propertyDefinitionsMustContainAnEqualsSign() {
assertThatThrownBy(() -> configFileProfiles("[profile foo]\n" +
"key : value"))
.hasMessageContaining("Expected an '=' sign defining a property");
}
@Test
public void multipleProfilesCanBeEmpty() {
assertThat(configFileProfiles("[profile foo]\n" +
"[profile bar]"))
.isEqualTo(profiles(profile("foo"),
profile("bar")));
}
@Test
public void multipleProfilesCanHaveProperties() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
"[profile bar]\n" +
"name2 = value2"))
.isEqualTo(profiles(profile("foo", property("name", "value")),
profile("bar", property("name2", "value2"))));
}
@Test
public void blankLinesAreIgnored() {
assertThat(configFileProfiles("\t \n" +
"[profile foo]\n" +
"\t\n" +
" \n" +
"name = value\n" +
"\t \n" +
"[profile bar]\n" +
" \t"))
.isEqualTo(profiles(profile("foo", property("name", "value")),
profile("bar")));
}
@Test
public void poundSignCommentsAreIgnored() {
assertThat(configFileProfiles("# Comment\n" +
"[profile foo] # Comment\n" +
"name = value # Comment with # sign"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void semicolonCommentsAreIgnored() {
assertThat(configFileProfiles("; Comment\n" +
"[profile foo] ; Comment\n" +
"name = value ; Comment with ; sign"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void commentTypesCanBeUsedTogether() {
assertThat(configFileProfiles("# Comment\n" +
"[profile foo] ; Comment\n" +
"name = value # Comment with ; sign"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void commentsCanBeEmpty() {
assertThat(configFileProfiles(";\n" +
"[profile foo];\n" +
"name = value ;\n"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void commentsCanBeAdjacentToProfileNames() {
assertThat(configFileProfiles("[profile foo]; Adjacent semicolons\n" +
"[profile bar]# Adjacent pound signs"))
.isEqualTo(profiles(profile("foo"),
profile("bar")));
}
@Test
public void commentsAdjacentToValuesAreIncludedInTheValue() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value; Adjacent semicolons\n" +
"name2 = value# Adjacent pound signs"))
.isEqualTo(profiles(profile("foo",
property("name", "value; Adjacent semicolons"),
property("name2", "value# Adjacent pound signs"))));
}
@Test
public void propertyValuesCanBeContinuedOnTheNextLine() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
" -continued"))
.isEqualTo(profiles(profile("foo",
property("name", "value\n-continued"))));
}
@Test
public void propertyValuesCanBeContinuedAcrossMultipleLines() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
" -continued\n" +
" -and-continued"))
.isEqualTo(profiles(profile("foo",
property("name", "value\n-continued\n-and-continued"))));
}
@Test
public void continuationValuesIncludeSemicolonComments() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
" -continued ; Comment"))
.isEqualTo(profiles(profile("foo",
property("name", "value\n-continued ; Comment"))));
}
@Test
public void continuationsCannotBeUsedOutsideOfAProfile() {
assertThatThrownBy(() -> configFileProfiles(" -continued"))
.hasMessageContaining("Expected a profile or property definition");
}
@Test
public void continuationsCannotBeUsedOutsideOfAProperty() {
assertThatThrownBy(() -> configFileProfiles("[profile foo]\n" +
" -continued"))
.hasMessageContaining("Expected a profile or property definition");
}
@Test
public void continuationsResetWithProfileDefinition() {
assertThatThrownBy(() -> configFileProfiles("[profile foo]\n" +
"name = value\n" +
"[profile foo]\n" +
" -continued"))
.hasMessageContaining("Expected a profile or property definition");
}
@Test
public void duplicateProfilesInTheSameFileMergeProperties() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
"[profile foo]\n" +
"name2 = value2"))
.isEqualTo(profiles(profile("foo",
property("name", "value"),
property("name2", "value2"))));
}
@Test
public void duplicatePropertiesInAProfileUseTheLastOneDefined() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
"name = value2"))
.isEqualTo(profiles(profile("foo", property("name", "value2"))));
}
@Test
public void duplicatePropertiesInDuplicateProfilesUseTheLastOneDefined() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
"[profile foo]\n" +
"name = value2"))
.isEqualTo(profiles(profile("foo", property("name", "value2"))));
}
@Test
public void defaultProfileWithProfilePrefixOverridesDefaultProfileWithoutPrefixWhenPrefixedIsFirst() {
assertThat(configFileProfiles("[profile default]\n" +
"name = value\n" +
"[default]\n" +
"name2 = value2"))
.isEqualTo(profiles(profile("default", property("name", "value"))));
}
@Test
public void defaultProfileWithProfilePrefixOverridesDefaultProfileWithoutPrefixWhenPrefixedIsLast() {
assertThat(configFileProfiles("[default]\n" +
"name2 = value2\n" +
"[profile default]\n" +
"name = value"))
.isEqualTo(profiles(profile("default", property("name", "value"))));
}
@Test
public void invalidProfilesNamesAreIgnored() {
assertThat(aggregateFileProfiles("[profile in valid]\n" +
"name = value\n",
"[in valid 2]\n" +
"name2 = value2"))
.isEqualTo(profiles());
}
@Test
public void invalidPropertyNamesAreIgnored() {
assertThat(configFileProfiles("[profile foo]\n" +
"in valid = value"))
.isEqualTo(profiles(profile("foo")));
}
@Test
public void allValidProfileNameCharactersAreSupported() {
assertThat(configFileProfiles("[profile ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_./%@:+]"))
.isEqualTo(profiles(profile("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_./%@:+")));
}
@Test
public void allValidPropertyNameCharactersAreSupported() {
assertThat(configFileProfiles("[profile foo]\nABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_./%@:+ = value"))
.isEqualTo(profiles(profile("foo", property("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_./%@:+",
"value"))));
}
@Test
public void propertiesCanHaveSubProperties() {
assertThat(configFileProfiles("[profile foo]\n" +
"s3 =\n" +
" name = value"))
.isEqualTo(profiles(profile("foo", property("s3", "\nname = value"))));
}
@Test
public void invalidSubPropertiesCauseAnError() {
assertThatThrownBy(() -> configFileProfiles("[profile foo]\n" +
"s3 =\n" +
" invalid"))
.hasMessageContaining("Expected an '=' sign defining a property");
}
@Test
public void subPropertiesCanHaveEmptyValues() {
assertThat(configFileProfiles("[profile foo]\n" +
"s3 =\n" +
" name ="))
.isEqualTo(profiles(profile("foo", property("s3", "\nname ="))));
}
@Test
public void invalidSubPropertiesCannotHaveEmptyNames() {
assertThatThrownBy(() -> configFileProfiles("[profile foo]\n" +
"s3 =\n" +
" = value"))
.hasMessageContaining("Property did not have a name");
}
@Test
public void subPropertiesCanHaveInvalidNames() {
assertThat(configFileProfiles("[profile foo]\n" +
"s3 =\n" +
" in valid = value"))
.isEqualTo(profiles(profile("foo", property("s3", "\nin valid = value"))));
}
@Test
public void subPropertiesCanHaveBlankLines() {
assertThat(configFileProfiles("[profile foo]\n" +
"s3 =\n" +
" name = value\n" +
"\t \n" +
" name2 = value2"))
.isEqualTo(profiles(profile("foo", property("s3", "\nname = value\nname2 = value2"))));
}
@Test
public void profilesDuplicatedInMultipleFilesAreMerged() {
assertThat(aggregateFileProfiles("[profile foo]\n" +
"name = value\n",
"[foo]\n" +
"name2 = value2"))
.isEqualTo(profiles(profile("foo",
property("name", "value"),
property("name2", "value2"))));
}
@Test
public void defaultProfilesWithMixedPrefixesInConfigFileIgnoreOneWithoutPrefixWhenMerging() {
assertThat(configFileProfiles("[profile default]\n" +
"name = value\n" +
"[default]\n" +
"name2 = value2\n" +
"[profile default]\n" +
"name3 = value3"))
.isEqualTo(profiles(profile("default",
property("name", "value"),
property("name3", "value3"))));
}
@Test
public void duplicatePropertiesBetweenFilesUsesCredentialsProperty() {
assertThat(aggregateFileProfiles("[profile foo]\n" +
"name = value",
"[foo]\n" +
"name = value2"))
.isEqualTo(profiles(profile("foo", property("name", "value2"))));
}
@Test
public void configProfilesWithoutPrefixAreIgnored() {
assertThat(configFileProfiles("[foo]\n" +
"name = value"))
.isEqualTo(profiles());
}
@Test
public void credentialsProfilesWithPrefixAreIgnored() {
assertThat(credentialFileProfiles("[profile foo]\n" +
"name = value"))
.isEqualTo(profiles());
}
@Test
public void sectionsInCredentialsFilesIsIgnored() {
String ASSUME_ROLE_PROFILE =
"[test]\n"
+ "region = us-west-1\n"
+ "credential_source = Environment\n"
+ "sso_session = session\n"
+ "role_arn = some_Arn\n"
+ "[sso-session session]\n"
+ "sso_region = us-west-1\n"
+ "start_url = someUrl\n";
ProfileFile profileFile = credentialFile(ASSUME_ROLE_PROFILE);
Map<String, Profile> profileMap = profileFile.profiles();
assertThat(profileMap)
.isEqualTo(profiles(profile("test", property("region", "us-west-1")
, property("credential_source", "Environment")
, property("sso_session", "session"),
property("role_arn", "some_Arn"))));
;
assertThat(profileFile.getSection("sso-session", "session")).isNotPresent();
}
@Test
public void invalidSectionNamesAreNotAddedInSectionListOfProfileFiles() {
ProfileFile aggregatedProfileFiles = ProfileFile.aggregator()
.addFile(credentialFile("[in valid 2]\n"
+ "name2 = value2"))
.addFile(configFile("[profile validSection]\n"
+ "sso_session = validSso\n"
+ "[sso-session validSso]\n"
+ "start_url = Valid-url\n"))
.addFile(configFile("[profile section]\n"
+ "sso_session = sso invalid\n"
+ "[sso-session sso invalid]\n"
+ "start_url = url\n"))
.build();
assertThat(aggregatedProfileFiles.profiles())
.isEqualTo(profiles(profile("section", property("sso_session", "sso invalid")),
profile("validSection", property("sso_session", "validSso"))));
assertThat(aggregatedProfileFiles.getSection("sso-session", "sso")).isNotPresent();
assertThat(aggregatedProfileFiles.getSection("sso-session", "sso invalid")).isNotPresent();
assertThat(aggregatedProfileFiles.getSection("sso-session", "validSso").get())
.isEqualTo(profile("validSso", property("start_url", "Valid-url")));
}
@Test
public void defaultSessionNameIsNotSupported_when_session_doesNot_exist() {
String nonExistentSessionName = "nonExistentSession";
ProfileFile aggregatedProfileFiles = ProfileFile.aggregator()
.addFile(configFile("[profile validSection]\n"
+ "sso_session = " + nonExistentSessionName + "\n"
+ "[profile " + nonExistentSessionName + "]\n"
+ "start_url = Valid-url-2\n"
+ "[sso-session default]\n"
+ "start_url = Valid-url\n"))
.build();
assertThat(aggregatedProfileFiles.profiles())
.isEqualTo(profiles(profile("validSection", property("sso_session", nonExistentSessionName)),
profile(nonExistentSessionName, property("start_url", "Valid-url-2"))));
assertThat(aggregatedProfileFiles.getSection("sso-session", nonExistentSessionName)).isNotPresent();
}
@Test
public void sessionIsNotAdjacentToProfile() {
ProfileFile aggregatedProfileFiles = ProfileFile.aggregator()
.addFile(configFile("[profile profile1]\n"
+ "sso_session = sso-token1\n"
+ "[profile profile2]\n"
+ "region = us-west-2\n"
+ "[default]\n"
+ "default_property = property1\n"))
.addFile(configFile("[sso-session sso-token1]\n"
+ "start_url = startUrl1\n"
+ "[profile profile3]\n"
+ "region = us-east-1\n")
).build();
assertThat(aggregatedProfileFiles.profiles())
.isEqualTo(profiles(profile("profile1", property("sso_session", "sso-token1")),
profile("default", property("default_property", "property1")),
profile("profile2", property("region", "us-west-2")),
profile("profile3", property("region", "us-east-1"))
));
assertThat(aggregatedProfileFiles.getSection("sso-session", "sso-token1")).isPresent();
assertThat(aggregatedProfileFiles.getSection("sso-session", "sso-token1").get()).isEqualTo(
profile("sso-token1", property("start_url", "startUrl1")) );
}
@Test
public void exceptionIsThrown_when_sectionDoesnotHaveASquareBracket() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(
() -> ProfileFile.aggregator()
.addFile(configFile("[profile profile1]\n"
+ "sso_session = sso-token1\n"
+ "[sso-session sso-token1\n"
+ "start_url = startUrl1\n")
).build()).withMessageContaining("Section definition must end with ']' on line 3");
}
@Test
public void loadingDefaultProfileFileWorks() {
ProfileFile.defaultProfileFile();
}
@Test
public void returnsEmptyMap_when_AwsFilesDoNotExist() {
ProfileFile missingProfile = ProfileFile.aggregator()
.build();
assertThat(missingProfile.profiles()).isEmpty();
assertThat(missingProfile.profiles()).isInstanceOf(Map.class);
}
private ProfileFile configFile(String configFile) {
return ProfileFile.builder()
.content(new StringInputStream(configFile))
.type(ProfileFile.Type.CONFIGURATION)
.build();
}
private Map<String, Profile> configFileProfiles(String configFile) {
return configFile(configFile).profiles();
}
private ProfileFile credentialFile(String credentialFile) {
return ProfileFile.builder()
.content(new StringInputStream(credentialFile))
.type(ProfileFile.Type.CREDENTIALS)
.build();
}
private Map<String, Profile> credentialFileProfiles(String credentialFile) {
return credentialFile(credentialFile).profiles();
}
private Map<String, Profile> aggregateFileProfiles(String configFile, String credentialFile) {
return ProfileFile.aggregator()
.addFile(credentialFile(credentialFile))
.addFile(configFile(configFile))
.build()
.profiles();
}
private Map<String, Profile> profiles(Profile... profiles) {
Map<String, Profile> result = new HashMap<>();
Stream.of(profiles).forEach(p -> result.put(p.name(), p));
return result;
}
@SafeVarargs
private final Profile profile(String name, Map.Entry<String, String>... properties) {
Map<String, String> propertiesMap = new HashMap<>();
Stream.of(properties).forEach(p -> propertiesMap.put(p.getKey(), p.getValue()));
return Profile.builder().name(name).properties(propertiesMap).build();
}
private Map.Entry<String, String> property(String name, String value) {
return new AbstractMap.SimpleImmutableEntry<>(name, value);
}
}
| 2,139 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/test/java/software/amazon/awssdk/profiles | Create_ds/aws-sdk-java-v2/core/profiles/src/test/java/software/amazon/awssdk/profiles/internal/ProfileFileRefresherTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles.internal;
import com.google.common.jimfs.Jimfs;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.TemporalAmount;
import java.util.concurrent.atomic.AtomicInteger;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.utils.StringInputStream;
public class ProfileFileRefresherTest {
private static FileSystem jimfs;
private static Path testDirectory;
@BeforeAll
public static void setup() {
jimfs = Jimfs.newFileSystem();
testDirectory = jimfs.getPath("test");
}
@AfterAll
public static void tearDown() {
try {
jimfs.close();
} catch (IOException e) {
// no-op
}
}
@Test
void refreshIfStale_profileModifiedNoPathSpecified_doesNotReloadProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.build();
Duration intervalWithinJitter = Duration.ofMillis(100);
ProfileFile file1 = refresher.refreshIfStale();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(intervalWithinJitter);
ProfileFile file2 = refresher.refreshIfStale();
Assertions.assertThat(file2).isSameAs(file1);
}
@Test
void refreshIfStale_profileModifiedWithinJitterPeriod_doesNotReloadProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.profileFilePath(credentialsFilePath)
.build();
Duration intervalWithinJitter = Duration.ofMillis(100);
ProfileFile file1 = refresher.refreshIfStale();
clock.tickForward(intervalWithinJitter);
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant());
ProfileFile file2 = refresher.refreshIfStale();
Assertions.assertThat(file2).isSameAs(file1);
}
@Test
void refreshIfStale_profileModifiedOutsideJitterPeriod_reloadsProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.profileFilePath(credentialsFilePath)
.build();
Duration intervalOutsideJitter = Duration.ofMillis(1_000);
ProfileFile file1 = refresher.refreshIfStale();
clock.tickForward(intervalOutsideJitter);
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant());
ProfileFile file2 = refresher.refreshIfStale();
Assertions.assertThat(file2).isNotSameAs(file1);
}
@Test
void refreshIfStale_profileModified_reloadsProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.profileFilePath(credentialsFilePath)
.build();
Duration refreshInterval = Duration.ofSeconds(15);
ProfileFile file1 = refresher.refreshIfStale();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(refreshInterval.plusSeconds(10));
ProfileFile file2 = refresher.refreshIfStale();
Assertions.assertThat(file2).isNotSameAs(file1);
}
@Test
void refreshIfStale_profileModifiedOnceButRefreshedMultipleTimes_reloadsProfileFileOnce() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.profileFilePath(credentialsFilePath)
.build();
ProfileFile file1 = refresher.refreshIfStale();
clock.tickForward(Duration.ofSeconds(5));
ProfileFile file2 = refresher.refreshIfStale();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(Duration.ofSeconds(5));
ProfileFile file3 = refresher.refreshIfStale();
Assertions.assertThat(file2).isSameAs(file1);
Assertions.assertThat(file3).isNotSameAs(file2);
}
@Test
void refreshIfStale_profileModifiedMultipleTimes_reloadsProfileFileOncePerChange() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.profileFilePath(credentialsFilePath)
.build();
Duration duration = Duration.ofSeconds(5);
ProfileFile file1 = refresher.refreshIfStale();
clock.tickForward(duration);
ProfileFile file2 = refresher.refreshIfStale();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file3 = refresher.refreshIfStale();
generateTestCredentialsFile("updatedAccessKey", "updatedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file4 = refresher.refreshIfStale();
clock.tickForward(duration);
ProfileFile file5 = refresher.refreshIfStale();
Assertions.assertThat(file2).isSameAs(file1);
Assertions.assertThat(file3).isNotSameAs(file2);
Assertions.assertThat(file4).isNotSameAs(file3);
}
@Test
void refreshIfStale_givenOnReloadConsumer_callsConsumerOncePerChange() {
int actualRefreshOperations = 3;
AtomicInteger refreshOperationsCounter = new AtomicInteger();
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.profileFilePath(credentialsFilePath)
.onProfileFileReload(f -> refreshOperationsCounter.incrementAndGet())
.build();
Duration duration = Duration.ofSeconds(5);
ProfileFile file1 = refresher.refreshIfStale();
clock.tickForward(duration);
ProfileFile file2 = refresher.refreshIfStale();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file3 = refresher.refreshIfStale();
generateTestCredentialsFile("updatedAccessKey", "updatedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file4 = refresher.refreshIfStale();
clock.tickForward(duration);
ProfileFile file5 = refresher.refreshIfStale();
Assertions.assertThat(file2).isSameAs(file1);
Assertions.assertThat(file3).isNotSameAs(file2);
Assertions.assertThat(file4).isNotSameAs(file3);
Assertions.assertThat(file5).isSameAs(file4);
Assertions.assertThat(refreshOperationsCounter.get()).isEqualTo(actualRefreshOperations);
}
private ProfileFile credentialFile(String credentialFile) {
return ProfileFile.builder()
.content(new StringInputStream(credentialFile))
.type(ProfileFile.Type.CREDENTIALS)
.build();
}
private Path generateTestFile(String contents, String filename) {
try {
Files.createDirectories(testDirectory);
return Files.write(testDirectory.resolve(filename), contents.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Path generateTestCredentialsFile(String accessKeyId, String secretAccessKey) {
String contents = String.format("[default]\naws_access_key_id = %s\naws_secret_access_key = %s\n",
accessKeyId, secretAccessKey);
return generateTestFile(contents, "credentials.txt");
}
private void updateModificationTime(Path path, Instant instant) {
try {
Files.setLastModifiedTime(path, FileTime.from(instant));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private ProfileFile profileFile(Path path) {
return ProfileFile.builder().content(path).type(ProfileFile.Type.CREDENTIALS).build();
}
private ProfileFileRefresher.Builder refresherWithClock(Clock clock) {
return ProfileFileRefresher.builder()
.clock(clock);
}
private static final class AdjustableClock extends Clock {
private Instant time;
private AdjustableClock() {
this.time = Instant.now();
}
@Override
public ZoneId getZone() {
return ZoneOffset.UTC;
}
@Override
public Clock withZone(ZoneId zone) {
throw new UnsupportedOperationException();
}
@Override
public Instant instant() {
return time;
}
public void tickForward(TemporalAmount amount) {
time = time.plus(amount);
}
public void tickBackward(TemporalAmount amount) {
time = time.minus(amount);
}
}
}
| 2,140 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/Profile.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.SystemSetting;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A named collection of configuration stored in a {@link ProfileFile}.
* <p>
* Raw property access can be made via {@link #property(String)} and {@link #properties()}.
*
* @see ProfileFile
*/
@SdkPublicApi
public final class Profile implements ToCopyableBuilder<Profile.Builder, Profile> {
/**
* The name of this profile (minus any profile prefixes).
*/
private final String name;
/**
* The raw properties in this profile.
*/
private final Map<String, String> properties;
/**
* @see ProfileFile
* @see #builder()
*/
private Profile(BuilderImpl builder) {
this.name = Validate.paramNotNull(builder.name, "name");
this.properties = Validate.paramNotNull(builder.properties, "properties");
}
/**
* Create a builder for defining a profile with specific attributes. For reading profiles from a file, see
* {@link ProfileFile}.
*/
public static Builder builder() {
return new BuilderImpl();
}
/**
* Retrieve the name of this profile.
*/
public String name() {
return name;
}
/**
* Retrieve a specific raw property from this profile.
*
* @param propertyKey The name of the property to retrieve.
* @return The value of the property, if configured.
*/
public Optional<String> property(String propertyKey) {
return Optional.ofNullable(properties.get(propertyKey));
}
/**
* Retrieve a specific property from this profile, and convert it to a boolean using the same algorithm as
* {@link SystemSetting#getBooleanValue()}.
*
* @param propertyKey The name of the property to retrieve.
* @return The boolean value of the property, if configured.
* @throws IllegalStateException If the property is set, but it is not boolean.
*/
public Optional<Boolean> booleanProperty(String propertyKey) {
return property(propertyKey).map(property -> parseBooleanProperty(propertyKey, property));
}
private Boolean parseBooleanProperty(String propertyKey, String property) {
if (property.equalsIgnoreCase("true")) {
return true;
} else if (property.equalsIgnoreCase("false")) {
return false;
}
throw new IllegalStateException("Profile property '" + propertyKey + "' must be set to 'true', 'false' or unset, but "
+ "was set to '" + property + "'.");
}
/**
* Retrieve an unmodifiable view of all of the properties currently in this profile.
*/
public Map<String, String> properties() {
return Collections.unmodifiableMap(properties);
}
@Override
public Builder toBuilder() {
return builder().name(name)
.properties(properties);
}
@Override
public String toString() {
return ToString.builder("Profile")
.add("name", name)
.add("properties", properties.keySet())
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Profile profile = (Profile) o;
return Objects.equals(name, profile.name) &&
Objects.equals(properties, profile.properties);
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + Objects.hashCode(name());
hashCode = 31 * hashCode + Objects.hashCode(properties());
return hashCode;
}
/**
* A builder for a {@link Profile}. See {@link #builder()}.
*/
public interface Builder extends CopyableBuilder<Builder, Profile> {
/**
* Define the name of this profile, without the legacy "profile" prefix.
*/
Builder name(String name);
/**
* Define the properties configured in this profile.
*/
Builder properties(Map<String, String> properties);
/**
* Create a profile using the current state of this builder.
*/
@Override
Profile build();
}
private static final class BuilderImpl implements Builder {
private String name;
private Map<String, String> properties;
/**
* @see #builder()
*/
private BuilderImpl() {
}
@Override
public Builder name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
name(name);
}
@Override
public Builder properties(Map<String, String> properties) {
this.properties = Collections.unmodifiableMap(new LinkedHashMap<>(properties));
return this;
}
public void setProperties(Map<String, String> properties) {
properties(properties);
}
@Override
public Profile build() {
return new Profile(this);
}
}
}
| 2,141 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/ProfileFileSupplierBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import java.nio.file.Path;
import java.time.Clock;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.profiles.internal.ProfileFileRefresher;
@SdkInternalApi
final class ProfileFileSupplierBuilder {
private boolean reloadingSupplier = false;
private Supplier<ProfileFile> profileFile;
private Path profileFilePath;
private Clock clock;
private Consumer<ProfileFile> onProfileFileLoad;
public ProfileFileSupplierBuilder reloadWhenModified(Path path, ProfileFile.Type type) {
ProfileFile.Builder builder = ProfileFile.builder()
.content(path)
.type(type);
this.profileFile = builder::build;
this.profileFilePath = path;
this.reloadingSupplier = true;
return this;
}
public ProfileFileSupplierBuilder fixedProfileFile(Path path, ProfileFile.Type type) {
return fixedProfileFile(ProfileFile.builder()
.content(path)
.type(type)
.build());
}
public ProfileFileSupplierBuilder fixedProfileFile(ProfileFile profileFile) {
this.profileFile = () -> profileFile;
this.profileFilePath = null;
this.reloadingSupplier = false;
return this;
}
public ProfileFileSupplierBuilder onProfileFileLoad(Consumer<ProfileFile> action) {
this.onProfileFileLoad = action;
return this;
}
public ProfileFileSupplierBuilder clock(Clock clock) {
this.clock = clock;
return this;
}
public ProfileFileSupplier build() {
return fromBuilder(this);
}
/**
* Completes {@link ProfileFileSupplier} build.
* @param builder Object to complete build.
* @return Implementation of {@link ProfileFileSupplier}.
*/
static ProfileFileSupplier fromBuilder(ProfileFileSupplierBuilder builder) {
if (builder.reloadingSupplier) {
ProfileFileRefresher.Builder refresherBuilder = ProfileFileRefresher.builder()
.profileFile(builder.profileFile)
.profileFilePath(builder.profileFilePath);
if (Objects.nonNull(builder.clock)) {
refresherBuilder.clock(builder.clock);
}
if (Objects.nonNull(builder.onProfileFileLoad)) {
refresherBuilder.onProfileFileReload(builder.onProfileFileLoad);
}
ProfileFileRefresher refresher = refresherBuilder.build();
return new ProfileFileSupplier() {
@Override
public ProfileFile get() {
return refresher.refreshIfStale();
}
};
}
return builder.profileFile::get;
}
}
| 2,142 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/ProfileFileLocation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import static software.amazon.awssdk.utils.UserHomeDirectoryUtils.userHomeDirectory;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.regex.Pattern;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A collection of static methods for loading the location for configuration and credentials files.
*/
@SdkPublicApi
public final class ProfileFileLocation {
private static final Pattern HOME_DIRECTORY_PATTERN =
Pattern.compile("^~(/|" + Pattern.quote(FileSystems.getDefault().getSeparator()) + ").*$");
private ProfileFileLocation() {
}
/**
* Resolve the path for the configuration file, regardless of whether it exists or not.
*
* @see #configurationFileLocation()
*/
public static Path configurationFilePath() {
return resolveProfileFilePath(
ProfileFileSystemSetting.AWS_CONFIG_FILE.getStringValue()
.orElseGet(() -> Paths.get(userHomeDirectory(),
".aws", "config").toString()));
}
/**
* Resolve the location for the credentials file, regardless of whether it exists or not.
*
* @see #credentialsFileLocation()
*/
public static Path credentialsFilePath() {
return resolveProfileFilePath(
ProfileFileSystemSetting.AWS_SHARED_CREDENTIALS_FILE.getStringValue()
.orElseGet(() -> Paths.get(userHomeDirectory(),
".aws", "credentials").toString()));
}
/**
* Load the location for the configuration file, usually ~/.aws/config unless it's overridden using an environment variable
* or system property.
*/
public static Optional<Path> configurationFileLocation() {
return resolveIfExists(configurationFilePath());
}
/**
* Load the location for the credentials file, usually ~/.aws/credentials unless it's overridden using an environment variable
* or system property.
*/
public static Optional<Path> credentialsFileLocation() {
return resolveIfExists(credentialsFilePath());
}
private static Path resolveProfileFilePath(String path) {
// Resolve ~ using the CLI's logic, not whatever Java decides to do with it.
if (HOME_DIRECTORY_PATTERN.matcher(path).matches()) {
path = userHomeDirectory() + path.substring(1);
}
return Paths.get(path);
}
private static Optional<Path> resolveIfExists(Path path) {
return Optional.ofNullable(path).filter(Files::isRegularFile).filter(Files::isReadable);
}
}
| 2,143 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/ProfileProperty.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* The properties used by the Java SDK from the credentials and config files.
*
* @see ProfileFile
*/
@SdkPublicApi
public final class ProfileProperty {
/**
* Property name for specifying the Amazon AWS Access Key
*/
public static final String AWS_ACCESS_KEY_ID = "aws_access_key_id";
/**
* Property name for specifying the Amazon AWS Secret Access Key
*/
public static final String AWS_SECRET_ACCESS_KEY = "aws_secret_access_key";
/**
* Property name for specifying the Amazon AWS Session Token
*/
public static final String AWS_SESSION_TOKEN = "aws_session_token";
/**
* Property name for specifying the IAM role to assume
*/
public static final String ROLE_ARN = "role_arn";
/**
* Property name for specifying the IAM role session name
*/
public static final String ROLE_SESSION_NAME = "role_session_name";
/**
* Property name for specifying how long in seconds to assume the role
*/
public static final String DURATION_SECONDS = "duration_seconds";
/**
* Property name for specifying the IAM role external id
*/
public static final String EXTERNAL_ID = "external_id";
/**
* Property name for specifying the profile credentials to use when assuming a role
*/
public static final String SOURCE_PROFILE = "source_profile";
/**
* Property name for specifying the credential source to use when assuming a role
*/
public static final String CREDENTIAL_SOURCE = "credential_source";
/**
* AWS Region to use when creating clients.
*/
public static final String REGION = "region";
/**
* Property name for specifying the identification number of the MFA device
*/
public static final String MFA_SERIAL = "mfa_serial";
/**
* Property name for specifying whether or not endpoint discovery is enabled.
*/
public static final String ENDPOINT_DISCOVERY_ENABLED = "aws_endpoint_discovery_enabled";
/**
* An external process that should be invoked to load credentials.
*/
public static final String CREDENTIAL_PROCESS = "credential_process";
public static final String WEB_IDENTITY_TOKEN_FILE = "web_identity_token_file";
/**
* The S3 regional endpoint setting for the {@code us-east-1} region. Setting the value to {@code regional} causes
* the SDK to use the {@code s3.us-east-1.amazonaws.com} endpoint when using the {@code US_EAST_1} region instead of
* the global {@code s3.amazonaws.com}. Using the regional endpoint is disabled by default.
*/
public static final String S3_US_EAST_1_REGIONAL_ENDPOINT = "s3_us_east_1_regional_endpoint";
/**
* The "retry mode" to be used for clients created using the currently-configured profile. Values supported by all SDKs are
* "legacy" and "standard". See the {@code RetryMode} class JavaDoc for more information.
*/
public static final String RETRY_MODE = "retry_mode";
/**
* The "defaults mode" to be used for clients created using the currently-configured profile. Defaults mode determins how SDK
* default configuration should be resolved. See the {@code DefaultsMode} class JavaDoc for more
* information.
*/
public static final String DEFAULTS_MODE = "defaults_mode";
/**
* Aws region where the SSO directory for the given 'sso_start_url' is hosted. This is independent of the general 'region'.
*/
public static final String SSO_REGION = "sso_region";
/**
* The corresponding IAM role in the AWS account that temporary AWS credentials will be resolved for.
*/
public static final String SSO_ROLE_NAME = "sso_role_name";
/**
* AWS account ID that temporary AWS credentials will be resolved for.
*/
public static final String SSO_ACCOUNT_ID = "sso_account_id";
/**
* Start url provided by the SSO service via the console. It's the main URL used for login to the SSO directory.
* This is also referred to as the "User Portal URL" and can also be used to login to the SSO web interface for AWS
* console access.
*/
public static final String SSO_START_URL = "sso_start_url";
public static final String USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint";
public static final String USE_FIPS_ENDPOINT = "use_fips_endpoint";
public static final String EC2_METADATA_SERVICE_ENDPOINT_MODE = "ec2_metadata_service_endpoint_mode";
public static final String EC2_METADATA_SERVICE_ENDPOINT = "ec2_metadata_service_endpoint";
/**
* Whether request compression is disabled for operations marked with the RequestCompression trait. The default value is
* false, i.e., request compression is enabled.
*/
public static final String DISABLE_REQUEST_COMPRESSION = "disable_request_compression";
/**
* The minimum compression size in bytes, inclusive, for a request to be compressed. The default value is 10_240.
* The value must be non-negative and no greater than 10_485_760.
*/
public static final String REQUEST_MIN_COMPRESSION_SIZE_BYTES = "request_min_compression_size_bytes";
private ProfileProperty() {
}
}
| 2,144 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/ProfileFileSystemSetting.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.SystemSetting;
/**
* System settings for loading configuration from profile files.
*/
@SdkProtectedApi
public enum ProfileFileSystemSetting implements SystemSetting {
/**
* Configure the default configuration file used in the ProfileFile. When not explicitly
* overridden in a client (eg. by specifying the region or credentials provider), this will be the location used when an
* AWS client is created.
*
* See http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html for more information on configuring the
* SDK via a configuration file.
*/
AWS_CONFIG_FILE("aws.configFile", null),
/**
* Configure the default credentials file used in the ProfileFile. When not explicitly
* overridden in a client (eg. by specifying the region or credentials provider), this will be the location used when an
* AWS client is created.
*
* See http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html for more information on configuring the
* SDK via a credentials file.
*/
AWS_SHARED_CREDENTIALS_FILE("aws.sharedCredentialsFile", null),
/**
* Configure the default profile that should be loaded from the {@link #AWS_CONFIG_FILE}
*
* @see #AWS_CONFIG_FILE
*/
AWS_PROFILE("aws.profile", "default");
private final String systemProperty;
private final String defaultValue;
ProfileFileSystemSetting(String systemProperty, String defaultValue) {
this.systemProperty = systemProperty;
this.defaultValue = defaultValue;
}
@Override
public String property() {
return systemProperty;
}
@Override
public String environmentVariable() {
return name();
}
@Override
public String defaultValue() {
return defaultValue;
}
}
| 2,145 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/ProfileFileSupplier.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import java.nio.file.Path;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.profiles.internal.ProfileFileRefresher;
/**
* Encapsulates the logic for supplying either a single or multiple ProfileFile instances.
* <p>
* Each call to the {@link #get()} method will result in either a new or previously supplied profile based on the
* implementation's rules.
*/
@SdkPublicApi
@FunctionalInterface
public interface ProfileFileSupplier extends Supplier<ProfileFile> {
/**
* Creates a {@link ProfileFileSupplier} capable of producing multiple profile objects by aggregating the default
* credentials and configuration files as determined by {@link ProfileFileLocation#credentialsFileLocation()} abd
* {@link ProfileFileLocation#configurationFileLocation()}. This supplier will return a new ProfileFile instance only once
* either disk file has been modified. Multiple calls to the supplier while both disk files are unchanged will return the
* same object.
*
* @return Implementation of {@link ProfileFileSupplier} that is capable of supplying a new aggregate profile when either file
* has been modified.
*/
static ProfileFileSupplier defaultSupplier() {
Optional<ProfileFileSupplier> credentialsSupplierOptional
= ProfileFileLocation.credentialsFileLocation()
.map(path -> reloadWhenModified(path, ProfileFile.Type.CREDENTIALS));
Optional<ProfileFileSupplier> configurationSupplierOptional
= ProfileFileLocation.configurationFileLocation()
.map(path -> reloadWhenModified(path, ProfileFile.Type.CONFIGURATION));
ProfileFileSupplier supplier = () -> ProfileFile.builder().build();
if (credentialsSupplierOptional.isPresent() && configurationSupplierOptional.isPresent()) {
supplier = aggregate(credentialsSupplierOptional.get(), configurationSupplierOptional.get());
} else if (credentialsSupplierOptional.isPresent()) {
supplier = credentialsSupplierOptional.get();
} else if (configurationSupplierOptional.isPresent()) {
supplier = configurationSupplierOptional.get();
}
return supplier;
}
/**
* Creates a {@link ProfileFileSupplier} capable of producing multiple profile objects from a file. This supplier will
* return a new ProfileFile instance only once the disk file has been modified. Multiple calls to the supplier while the
* disk file is unchanged will return the same object.
*
* @param path Path to the file to read from.
* @param type The type of file. See {@link ProfileFile.Type} for possible values.
* @return Implementation of {@link ProfileFileSupplier} that is capable of supplying a new profile when the file
* has been modified.
*/
static ProfileFileSupplier reloadWhenModified(Path path, ProfileFile.Type type) {
return new ProfileFileSupplier() {
final ProfileFile.Builder builder = ProfileFile.builder()
.content(path)
.type(type);
final ProfileFileRefresher refresher = ProfileFileRefresher.builder()
.profileFile(builder::build)
.profileFilePath(path)
.build();
@Override
public ProfileFile get() {
return refresher.refreshIfStale();
}
};
}
/**
* Creates a {@link ProfileFileSupplier} that produces an existing profile.
*
* @param profileFile Profile object to supply.
* @return Implementation of {@link ProfileFileSupplier} that is capable of supplying a single profile.
*/
static ProfileFileSupplier fixedProfileFile(ProfileFile profileFile) {
return () -> profileFile;
}
/**
* Creates a {@link ProfileFileSupplier} by combining the {@link ProfileFile} objects from multiple {@code
* ProfileFileSupplier}s. Objects are passed into {@link ProfileFile.Aggregator}.
*
* @param suppliers Array of {@code ProfileFileSupplier} objects. {@code ProfileFile} objects are passed to
* {@link ProfileFile.Aggregator#addFile(ProfileFile)} in the same argument order as the supplier that
* generated it.
* @return Implementation of {@link ProfileFileSupplier} aggregating results from the supplier objects.
*/
static ProfileFileSupplier aggregate(ProfileFileSupplier... suppliers) {
return new ProfileFileSupplier() {
final AtomicReference<ProfileFile> currentAggregateProfileFile = new AtomicReference<>();
final Map<Supplier<ProfileFile>, ProfileFile> currentValuesBySupplier
= Collections.synchronizedMap(new LinkedHashMap<>());
@Override
public ProfileFile get() {
boolean refreshAggregate = false;
for (ProfileFileSupplier supplier : suppliers) {
if (didSuppliedValueChange(supplier)) {
refreshAggregate = true;
}
}
if (refreshAggregate) {
refreshCurrentAggregate();
}
return currentAggregateProfileFile.get();
}
private boolean didSuppliedValueChange(Supplier<ProfileFile> supplier) {
ProfileFile next = supplier.get();
ProfileFile current = currentValuesBySupplier.put(supplier, next);
return !Objects.equals(next, current);
}
private void refreshCurrentAggregate() {
ProfileFile.Aggregator aggregator = ProfileFile.aggregator();
currentValuesBySupplier.values().forEach(aggregator::addFile);
ProfileFile current = currentAggregateProfileFile.get();
ProfileFile next = aggregator.build();
if (!Objects.equals(current, next)) {
currentAggregateProfileFile.compareAndSet(current, next);
}
}
};
}
}
| 2,146 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/ProfileFile.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.profiles.internal.ProfileFileReader;
import software.amazon.awssdk.utils.FunctionalUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.SdkBuilder;
/**
* Provides programmatic access to the contents of an AWS configuration profile file.
*
* AWS configuration profiles allow you to share multiple sets of AWS security credentials between different tools such as the
* AWS SDK for Java and the AWS CLI.
*
* <p>
* For more information on setting up AWS configuration profiles, see:
* http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
*
* <p>
* A profile file can be created with {@link #builder()} and merged with other profiles files with {@link #aggregator()}. By
* default, the SDK will use the {@link #defaultProfileFile()} when that behavior hasn't been explicitly overridden.
*/
@SdkPublicApi
public final class ProfileFile {
public static final String PROFILES_SECTION_TITLE = "profiles";
private final Map<String, Map<String, Profile>> profilesAndSectionsMap;
/**
* @see #builder()
*/
private ProfileFile(Map<String, Map<String, Map<String, String>>> profilesSectionMap) {
Validate.paramNotNull(profilesSectionMap, "profilesSectionMap");
this.profilesAndSectionsMap = convertToProfilesSectionsMap(profilesSectionMap);
}
public Optional<Profile> getSection(String sectionName, String sectionTitle) {
Map<String, Profile> sectionMap = profilesAndSectionsMap.get(sectionName);
if (sectionMap != null) {
return Optional.ofNullable(sectionMap.get(sectionTitle));
}
return Optional.empty();
}
/**
* Create a builder for a {@link ProfileFile}.
*/
public static Builder builder() {
return new BuilderImpl();
}
/**
* Create a builder that can merge multiple {@link ProfileFile}s together.
*/
public static Aggregator aggregator() {
return new Aggregator();
}
/**
* Get the default profile file, using the credentials file from "~/.aws/credentials", the config file from "~/.aws/config"
* and the "default" profile. This default behavior can be customized using the
* {@link ProfileFileSystemSetting#AWS_SHARED_CREDENTIALS_FILE}, {@link ProfileFileSystemSetting#AWS_CONFIG_FILE} and
* {@link ProfileFileSystemSetting#AWS_PROFILE} settings or by specifying a different profile file and profile name.
*
* <p>
* The file is read each time this method is invoked.
*/
public static ProfileFile defaultProfileFile() {
return ProfileFile.aggregator()
.applyMutation(ProfileFile::addCredentialsFile)
.applyMutation(ProfileFile::addConfigFile)
.build();
}
/**
* Retrieve the profile from this file with the given name.
*
* @param profileName The name of the profile that should be retrieved from this file.
* @return The profile, if available.
*/
public Optional<Profile> profile(String profileName) {
Map<String, Profile> profileMap = profilesAndSectionsMap.get(PROFILES_SECTION_TITLE);
return profileMap != null ? Optional.ofNullable(profileMap.get(profileName)) : Optional.empty();
}
/**
* Retrieve an unmodifiable collection including all of the profiles in this file.
* @return An unmodifiable collection of the profiles in this file, keyed by profile name.
*/
public Map<String, Profile> profiles() {
Map<String, Profile> profileMap = profilesAndSectionsMap.get(PROFILES_SECTION_TITLE);
return profileMap != null ? Collections.unmodifiableMap(profileMap) : Collections.emptyMap();
}
@Override
public String toString() {
Map<String, Profile> profiles = profilesAndSectionsMap.get(PROFILES_SECTION_TITLE);
return ToString.builder("ProfileFile")
.add("sections", profilesAndSectionsMap.keySet())
.add("profiles", profiles == null ? null : profiles.values())
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProfileFile that = (ProfileFile) o;
return Objects.equals(profilesAndSectionsMap, that.profilesAndSectionsMap);
}
@Override
public int hashCode() {
return Objects.hashCode(this.profilesAndSectionsMap);
}
private static void addCredentialsFile(ProfileFile.Aggregator builder) {
ProfileFileLocation.credentialsFileLocation()
.ifPresent(l -> builder.addFile(ProfileFile.builder()
.content(l)
.type(ProfileFile.Type.CREDENTIALS)
.build()));
}
private static void addConfigFile(ProfileFile.Aggregator builder) {
ProfileFileLocation.configurationFileLocation()
.ifPresent(l -> builder.addFile(ProfileFile.builder()
.content(l)
.type(ProfileFile.Type.CONFIGURATION)
.build()));
}
/**
* Convert the sorted map of profile and section properties into a sorted list of profiles and sections.
* Example: sortedProfilesSectionMap
* @param sortedProfilesSectionMap : Map of String to Profile/Sessions defined.
* <pre>
* {@code
* [profile sso-token]
* sso_session = admin
* [sso-session admin]
* sso_start_url = https://view.awsapps.com/start
* }
* </pre> would look like
* <pre>
* {@code
* sortedProfilesSectionMap
* profiles -- // Profile Section Title
* sso-token -- // Profile Name
* sso_session = admin // Property definition
* sso-session -- // Section title for Sso-sessions
* admin --
* sso_start_url = https://view.awsapps.com/start
*
* }
* </pre>
* @return Map with keys representing Profiles and sections and value as Map with keys as profile/section name and value as
* property definition.
*/
private Map<String, Map<String, Profile>> convertToProfilesSectionsMap(
Map<String, Map<String, Map<String, String>>> sortedProfilesSectionMap) {
Map<String, Map<String, Profile>> result = new LinkedHashMap<>();
sortedProfilesSectionMap.entrySet()
.forEach(sections -> {
result.put(sections.getKey(), new LinkedHashMap<>());
Map<String, Profile> stringProfileMap = result.get(sections.getKey());
sections.getValue().entrySet()
.forEach(section -> {
Profile profile = Profile.builder()
.name(section.getKey())
.properties(section.getValue())
.build();
stringProfileMap.put(section.getKey(), profile);
});
});
return result;
}
/**
* The supported types of profile files. The type of profile determines the way in which it is parsed.
*/
public enum Type {
/**
* A configuration profile file, typically located at ~/.aws/config, that expects all profile names (except the default
* profile) to be prefixed with "profile ". Any non-default profiles without this prefix will be ignored.
*/
CONFIGURATION,
/**
* A credentials profile file, typically located at ~/.aws/credentials, that expects all profile name to have no
* "profile " prefix. Any profiles with a profile prefix will be ignored.
*/
CREDENTIALS
}
/**
* A builder for a {@link ProfileFile}. {@link #content(Path)} (or {@link #content(InputStream)}) and {@link #type(Type)} are
* required fields.
*/
public interface Builder extends SdkBuilder<Builder, ProfileFile> {
/**
* Configure the content of the profile file. This stream will be read from and then closed when {@link #build()} is
* invoked.
*/
Builder content(InputStream contentStream);
/**
* Configure the location from which the profile file should be loaded.
*/
Builder content(Path contentLocation);
/**
* Configure the {@link Type} of file that should be loaded.
*/
Builder type(Type type);
@Override
ProfileFile build();
}
private static final class BuilderImpl implements Builder {
private InputStream content;
private Path contentLocation;
private Type type;
private BuilderImpl() {
}
@Override
public Builder content(InputStream contentStream) {
this.contentLocation = null;
this.content = contentStream;
return this;
}
public void setContent(InputStream contentStream) {
content(contentStream);
}
@Override
public Builder content(Path contentLocation) {
Validate.paramNotNull(contentLocation, "profileLocation");
Validate.validState(Files.exists(contentLocation), "Profile file '%s' does not exist.", contentLocation);
this.content = null;
this.contentLocation = contentLocation;
return this;
}
public void setContentLocation(Path contentLocation) {
content(contentLocation);
}
/**
* Configure the {@link Type} of file that should be loaded.
*/
@Override
public Builder type(Type type) {
this.type = type;
return this;
}
public void setType(Type type) {
type(type);
}
@Override
public ProfileFile build() {
InputStream stream = content != null ? content :
FunctionalUtils.invokeSafely(() -> Files.newInputStream(contentLocation));
Validate.paramNotNull(type, "type");
Validate.paramNotNull(stream, "content");
try {
return new ProfileFile(ProfileFileReader.parseFile(stream, type));
} finally {
IoUtils.closeQuietly(stream, null);
}
}
}
/**
* A mechanism for merging multiple {@link ProfileFile}s together into a single file. This will merge their profiles and
* properties together.
*/
public static final class Aggregator implements SdkBuilder<Aggregator, ProfileFile> {
private List<ProfileFile> files = new ArrayList<>();
/**
* Add a file to be aggregated. In the event that there is a duplicate profile/property pair in the files, files added
* earliest to this aggregator will take precedence, dropping the duplicated properties in the later files.
*/
public Aggregator addFile(ProfileFile file) {
files.add(file);
return this;
}
@Override
public ProfileFile build() {
Map<String, Map<String, Map<String, String>>> aggregateRawProfiles = new LinkedHashMap<>();
for (int i = files.size() - 1; i >= 0; --i) {
files.get(i).profilesAndSectionsMap.entrySet()
.forEach(sectionKeyValue -> addToAggregate(aggregateRawProfiles,
sectionKeyValue.getValue(),
sectionKeyValue.getKey()));
}
return new ProfileFile(aggregateRawProfiles);
}
private void addToAggregate(Map<String, Map<String, Map<String, String>>> aggregateRawProfiles,
Map<String, Profile> profiles, String sectionName) {
aggregateRawProfiles.putIfAbsent(sectionName, new LinkedHashMap<>());
Map<String, Map<String, String>> profileMap = aggregateRawProfiles.get(sectionName);
for (Entry<String, Profile> profile : profiles.entrySet()) {
profileMap.compute(profile.getKey(), (k, current) -> {
if (current == null) {
return new HashMap<>(profile.getValue().properties());
} else {
current.putAll(profile.getValue().properties());
return current;
}
});
}
}
}
}
| 2,147 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/internal/ProfileSection.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Enum describing all the valid section names supported by SDK.
* The section declares that the attributes that follow are part of a named collection of attributes.
*/
@SdkInternalApi
public enum ProfileSection {
/**
* An `sso-session` section declares that the attributes that follow (until another section definition is encountered)
* are part of a named collection of attributes.
* This `sso-session` section is referenced by the user when configuring a profile to derive an SSO token.
*/
SSO_SESSION("sso-session", "sso_session");
private final String sectionTitle;
private final String propertyKeyName;
ProfileSection(String title, String propertyKeyName) {
this.sectionTitle = title;
this.propertyKeyName = propertyKeyName;
}
/**
*
* @param sectionTitle The section title in the config or credential file.
* @return ProfileSection enum that has title name as sectionTitle
*/
public static ProfileSection fromSectionTitle(String sectionTitle) {
if (sectionTitle == null) {
return null;
}
for (ProfileSection profileSection : values()) {
if (profileSection.sectionTitle.equals(sectionTitle)) {
return profileSection;
}
}
throw new IllegalArgumentException("Unknown enum value for ProfileSection : " + sectionTitle);
}
/**
*
* @param propertyName The property definition of a key that points to a Section.
* @return ProfileSection enum that corresponds to a propertyKeyName for the given propertyName.
*/
public static ProfileSection fromPropertyKeyName(String propertyName) {
if (propertyName == null) {
return null;
}
for (ProfileSection section : values()) {
if (section.getPropertyKeyName().equals(propertyName)) {
return section;
}
}
throw new IllegalArgumentException("Unknown enum value for ProfileSection : " + propertyName);
}
/**
*
* @return Gets the section title name for the given {@link ProfileSection}.
*/
public String getSectionTitle() {
return sectionTitle;
}
/**
*
* @return Gets the property Hey name for the given {@link ProfileSection}.
*/
public String getPropertyKeyName() {
return propertyKeyName;
}
} | 2,148 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/internal/ProfileFileRefresher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles.internal;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Clock;
import java.time.Instant;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.utils.cache.CachedSupplier;
import software.amazon.awssdk.utils.cache.RefreshResult;
/**
* Class used for caching and reloading ProfileFile objects from a Supplier.
*/
@SdkInternalApi
public final class ProfileFileRefresher {
private static final ProfileFileRefreshRecord EMPTY_REFRESH_RECORD = ProfileFileRefreshRecord.builder()
.refreshTime(Instant.MIN)
.build();
private final CachedSupplier<ProfileFileRefreshRecord> profileFileCache;
private volatile ProfileFileRefreshRecord currentRefreshRecord;
private final Supplier<ProfileFile> profileFile;
private final Path profileFilePath;
private final Consumer<ProfileFile> onProfileFileReload;
private final Clock clock;
private ProfileFileRefresher(Builder builder) {
this.clock = builder.clock;
this.profileFile = builder.profileFile;
this.profileFilePath = builder.profileFilePath;
this.onProfileFileReload = builder.onProfileFileReload;
this.profileFileCache = CachedSupplier.builder(this::refreshResult)
.cachedValueName("ProfileFileSupplier()")
.clock(this.clock)
.build();
this.currentRefreshRecord = EMPTY_REFRESH_RECORD;
}
/**
* Builder method to construct instance of ProfileFileRefresher.
*/
public static ProfileFileRefresher.Builder builder() {
return new ProfileFileRefresher.Builder();
}
/**
* Retrieves the cache value or refreshes it if stale.
*/
public ProfileFile refreshIfStale() {
ProfileFileRefreshRecord cachedOrRefreshedRecord = profileFileCache.get();
ProfileFile cachedOrRefreshedProfileFile = cachedOrRefreshedRecord.profileFile;
if (isNewProfileFile(cachedOrRefreshedProfileFile)) {
currentRefreshRecord = cachedOrRefreshedRecord;
}
return cachedOrRefreshedProfileFile;
}
private RefreshResult<ProfileFileRefreshRecord> refreshResult() {
return reloadAsRefreshResultIfStale();
}
private RefreshResult<ProfileFileRefreshRecord> reloadAsRefreshResultIfStale() {
Instant now = clock.instant();
ProfileFileRefreshRecord refreshRecord;
if (canReloadProfileFile() || hasNotBeenPreviouslyLoaded()) {
ProfileFile reloadedProfileFile = reload(profileFile, onProfileFileReload);
refreshRecord = ProfileFileRefreshRecord.builder()
.profileFile(reloadedProfileFile)
.refreshTime(now)
.build();
} else {
refreshRecord = currentRefreshRecord;
}
return wrapIntoRefreshResult(refreshRecord, now);
}
private <T> RefreshResult<T> wrapIntoRefreshResult(T value, Instant staleTime) {
return RefreshResult.builder(value)
.staleTime(staleTime)
.build();
}
private static ProfileFile reload(Supplier<ProfileFile> supplier) {
return supplier.get();
}
private static ProfileFile reload(Supplier<ProfileFile> supplier, Consumer<ProfileFile> consumer) {
ProfileFile reloadedProfileFile = reload(supplier);
consumer.accept(reloadedProfileFile);
return reloadedProfileFile;
}
private boolean isNewProfileFile(ProfileFile profileFile) {
return !Objects.equals(currentRefreshRecord.profileFile, profileFile);
}
private boolean canReloadProfileFile() {
if (Objects.isNull(profileFilePath)) {
return false;
}
try {
Instant lastModifiedInstant = Files.getLastModifiedTime(profileFilePath).toInstant();
return currentRefreshRecord.refreshTime.isBefore(lastModifiedInstant);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private boolean hasNotBeenPreviouslyLoaded() {
return currentRefreshRecord == EMPTY_REFRESH_RECORD;
}
public static final class Builder {
private Supplier<ProfileFile> profileFile;
private Path profileFilePath;
private Consumer<ProfileFile> onProfileFileReload = p -> { };
private Clock clock = Clock.systemUTC();
private Builder() {
}
public Builder profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
public Builder profileFilePath(Path profileFilePath) {
this.profileFilePath = profileFilePath;
return this;
}
/**
* Sets a clock for managing stale and prefetch durations.
*/
@SdkTestInternalApi
public Builder clock(Clock clock) {
this.clock = clock;
return this;
}
/**
* Sets a custom action to perform when a profile file is reloaded. This action is executed when both the cache is stale
* and the disk file associated with the profile file has been modified since the last load.
*
* @param consumer The action to perform.
*/
public Builder onProfileFileReload(Consumer<ProfileFile> consumer) {
this.onProfileFileReload = consumer;
return this;
}
public ProfileFileRefresher build() {
return new ProfileFileRefresher(this);
}
}
/**
* Class used to encapsulate additional refresh information.
*/
public static final class ProfileFileRefreshRecord {
private final Instant refreshTime;
private final ProfileFile profileFile;
private ProfileFileRefreshRecord(Builder builder) {
this.profileFile = builder.profileFile;
this.refreshTime = builder.refreshTime;
}
/**
* The refreshed ProfileFile instance.
*/
public ProfileFile profileFile() {
return profileFile;
}
/**
* The time at which the RefreshResult was created.
*/
public Instant refreshTime() {
return refreshTime;
}
static Builder builder() {
return new Builder();
}
private static final class Builder {
private Instant refreshTime;
private ProfileFile profileFile;
Builder refreshTime(Instant refreshTime) {
this.refreshTime = refreshTime;
return this;
}
Builder profileFile(ProfileFile profileFile) {
this.profileFile = profileFile;
return this;
}
ProfileFileRefreshRecord build() {
return new ProfileFileRefreshRecord(this);
}
}
}
}
| 2,149 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/internal/ProfileFileReader.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles.internal;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
/**
* Converts an {@link InputStream} to a configuration or credentials file into a map of profiles and their properties.
*
* @see #parseFile(InputStream, ProfileFile.Type)
*/
@SdkInternalApi
public final class ProfileFileReader {
private static final Logger log = Logger.loggerFor(ProfileFileReader.class);
private static final Pattern EMPTY_LINE = Pattern.compile("^[\t ]*$");
private static final Pattern VALID_IDENTIFIER = Pattern.compile("^[A-Za-z0-9_\\-/.%@:\\+]*$");
private ProfileFileReader() {
}
/**
* Parses the input and returns a mutable map from profile name to a map of properties. This will not close the provided
* stream.
*/
public static Map<String, Map<String, Map<String, String>>> parseFile(InputStream profileStream, ProfileFile.Type fileType) {
ParserState state = new ParserState(fileType);
BufferedReader profileReader = new BufferedReader(new InputStreamReader(profileStream, StandardCharsets.UTF_8));
profileReader.lines().forEach(line -> parseLine(state, line));
return state.profiles;
}
/**
* Parse a line and update the parser state.
*/
private static void parseLine(ParserState state, String line) {
++state.currentLineNumber;
if (isEmptyLine(line) || isCommentLine(line)) {
return; // Skip line
}
Optional<String> sectionDefined = sectionDefinitionLine(line);
if (sectionDefined.isPresent()) {
state.sectionReadInProgress = sectionDefined.get();
readSectionProfileDefinitionLine(state, line);
} else if (isProfileDefinitionLine(line)) {
state.sectionReadInProgress = ProfileFile.PROFILES_SECTION_TITLE;
readProfileDefinitionLine(state, line);
} else if (isPropertyContinuationLine(line)) {
readPropertyContinuationLine(state, line);
} else {
readPropertyDefinitionLine(state, line);
}
}
/**
* Read a profile line and update the parser state with the results. This marks future properties as being in this profile.
*
* Configuration Files: [ Whitespace? profile Whitespace Identifier Whitespace? ] Whitespace? CommentLine?
* Credentials Files: [ Whitespace? Identifier Whitespace? ] Whitespace? CommentLine?
*/
private static void readProfileDefinitionLine(ParserState state, String line) {
// Profile definitions do not require a space between the closing bracket and the comment delimiter
String lineWithoutComments = removeTrailingComments(line, "#", ";");
String lineWithoutWhitespace = StringUtils.trim(lineWithoutComments);
Validate.isTrue(lineWithoutWhitespace.endsWith("]"),
"Profile definition must end with ']' on line " + state.currentLineNumber);
Optional<String> profileName = parseProfileDefinition(state, lineWithoutWhitespace);
updateStateBasedOnProfileName(state, profileName);
}
/**
* Read a property definition line and update the parser state with the results. This adds the property to the current profile
* and marks future property continuations as being part of this property.
*
* Identifier Whitespace? = Whitespace? Value? Whitespace? (Whitespace CommentLine)?
*/
private static void readPropertyDefinitionLine(ParserState state, String line) {
// If we're in an invalid profile, ignore its properties
if (state.ignoringCurrentProfile) {
return;
}
Validate.isTrue(state.currentProfileBeingRead != null,
"Expected a profile definition on line " + state.currentLineNumber);
// Property definition comments must have whitespace before them, or they will be considered part of the value
String lineWithoutComments = removeTrailingComments(line, " #", " ;", "\t#", "\t;");
String lineWithoutWhitespace = StringUtils.trim(lineWithoutComments);
Optional<Pair<String, String>> propertyDefinition = parsePropertyDefinition(state, lineWithoutWhitespace);
// If we couldn't get the property key and value, ignore this entire property.
if (!propertyDefinition.isPresent()) {
state.ignoringCurrentProperty = true;
return;
}
Pair<String, String> property = propertyDefinition.get();
if (state.profiles.get(state.sectionReadInProgress).get(state.currentProfileBeingRead).containsKey(property.left())) {
log.warn(() -> "Warning: Duplicate property '" + property.left() + "' detected on line " + state.currentLineNumber +
". The later one in the file will be used.");
}
state.currentPropertyBeingRead = property.left();
state.ignoringCurrentProperty = false;
state.validatingContinuationsAsSubProperties = property.right().equals("");
state.profiles.get(state.sectionReadInProgress)
.get(state.currentProfileBeingRead).put(property.left(), property.right());
}
/**
* Read a property continuation line and update the parser state with the results. This adds the value in the continuation
* to the current property, prefixed with a newline.
*
* Non-Blank Parent Property: Whitespace Value Whitespace?
* Blank Parent Property (Sub-Property): Whitespace Identifier Whitespace? = Whitespace? Value Whitespace?
*/
private static void readPropertyContinuationLine(ParserState state, String line) {
// If we're in an invalid profile or property, ignore its continuations
if (state.ignoringCurrentProfile || state.ignoringCurrentProperty) {
return;
}
Validate.isTrue(state.currentProfileBeingRead != null && state.currentPropertyBeingRead != null,
"Expected a profile or property definition on line " + state.currentLineNumber);
// Comments are not removed on property continuation lines. They're considered part of the value.
line = StringUtils.trim(line);
Map<String, String> profileProperties = state.profiles.get(state.sectionReadInProgress)
.get(state.currentProfileBeingRead);
String currentPropertyValue = profileProperties.get(state.currentPropertyBeingRead);
String newPropertyValue = currentPropertyValue + "\n" + line;
// If this is a sub-property, make sure it can be parsed correctly by the CLI.
if (state.validatingContinuationsAsSubProperties) {
parsePropertyDefinition(state, line);
}
profileProperties.put(state.currentPropertyBeingRead, newPropertyValue);
}
/**
* Given a profile line, load the profile name based on the file type. If the profile name is invalid for the file type,
* this will return empty.
*/
private static Optional<String> parseProfileDefinition(ParserState state, String lineWithoutWhitespace) {
String lineWithoutBrackets = lineWithoutWhitespace.substring(1, lineWithoutWhitespace.length() - 1);
String rawProfileName = StringUtils.trim(lineWithoutBrackets);
boolean hasProfilePrefix = rawProfileName.startsWith("profile ") || rawProfileName.startsWith("profile\t");
String standardizedProfileName;
if (state.fileType == ProfileFile.Type.CONFIGURATION) {
if (hasProfilePrefix) {
standardizedProfileName = StringUtils.trim(rawProfileName.substring(ProfileFile.PROFILES_SECTION_TITLE.length()));
} else if (rawProfileName.equals("default")) {
standardizedProfileName = "default";
} else {
log.warn(() -> "Ignoring profile '" + rawProfileName + "' on line " + state.currentLineNumber + " because it " +
"did not start with 'profile ' and it was not 'default'.");
return Optional.empty();
}
} else if (state.fileType == ProfileFile.Type.CREDENTIALS) {
standardizedProfileName = rawProfileName;
} else {
throw new IllegalStateException("Unknown profile file type: " + state.fileType);
}
String profileName = StringUtils.trim(standardizedProfileName);
// If the profile name includes invalid characters, it should be ignored.
if (!isValidIdentifier(profileName)) {
log.warn(() -> "Ignoring profile '" + standardizedProfileName + "' on line " + state.currentLineNumber + " because " +
"it was not alphanumeric with only these special characters: - / . % @ _ : +");
return Optional.empty();
}
// [profile default] must take priority over [default] in configuration files.
boolean isDefaultProfile = profileName.equals("default");
boolean seenProfileBefore = state.profiles.get(ProfileFile.PROFILES_SECTION_TITLE).containsKey(profileName);
if (state.fileType == ProfileFile.Type.CONFIGURATION && isDefaultProfile && seenProfileBefore) {
if (!hasProfilePrefix && state.seenDefaultProfileWithProfilePrefix) {
log.warn(() -> "Ignoring profile '[default]' on line " + state.currentLineNumber + ", because " +
"'[profile default]' was already seen in the same file.");
return Optional.empty();
} else if (hasProfilePrefix && !state.seenDefaultProfileWithProfilePrefix) {
log.warn(() -> "Ignoring earlier-seen '[default]', because '[profile default]' was found on line " +
state.currentLineNumber);
state.profiles.get(ProfileFile.PROFILES_SECTION_TITLE).remove("default");
}
}
if (isDefaultProfile && hasProfilePrefix) {
state.seenDefaultProfileWithProfilePrefix = true;
}
return Optional.of(profileName);
}
/**
* Given a property line, load the property key and value. If the property line is invalid and should be ignored, this will
* return empty.
*/
private static Optional<Pair<String, String>> parsePropertyDefinition(ParserState state, String line) {
int firstEqualsLocation = line.indexOf('=');
Validate.isTrue(firstEqualsLocation != -1, "Expected an '=' sign defining a property on line " + state.currentLineNumber);
String propertyKey = StringUtils.trim(line.substring(0, firstEqualsLocation));
String propertyValue = StringUtils.trim(line.substring(firstEqualsLocation + 1));
Validate.isTrue(!propertyKey.isEmpty(), "Property did not have a name on line " + state.currentLineNumber);
// If the profile name includes invalid characters, it should be ignored.
if (!isValidIdentifier(propertyKey)) {
log.warn(() -> "Ignoring property '" + propertyKey + "' on line " + state.currentLineNumber + " because " +
"its name was not alphanumeric with only these special characters: - / . % @ _ : +");
return Optional.empty();
}
return Optional.of(Pair.of(propertyKey, propertyValue));
}
/**
* Remove trailing comments from the provided line, using the provided patterns to find where the comment starts.
*
* Profile definitions don't require spaces before comments.
* Property definitions require spaces before comments.
* Property continuations don't allow trailing comments. They're considered part of the value.
*/
private static String removeTrailingComments(String line, String... commentPatterns) {
return line.substring(0, findEarliestMatch(line, commentPatterns));
}
/**
* Search the provided string for the requested patterns, returning the index of the match that is closest to the front of the
* string. If no match is found, this returns the length of the string (one past the final index in the string).
*/
private static int findEarliestMatch(String line, String... searchPatterns) {
return Stream.of(searchPatterns)
.mapToInt(line::indexOf)
.filter(location -> location >= 0)
.min()
.orElseGet(line::length);
}
private static boolean isEmptyLine(String line) {
return EMPTY_LINE.matcher(line).matches();
}
private static boolean isCommentLine(String line) {
return line.startsWith("#") || line.startsWith(";");
}
private static boolean isProfileDefinitionLine(String line) {
return line.startsWith("[");
}
private static boolean isPropertyContinuationLine(String line) {
return line.startsWith(" ") || line.startsWith("\t");
}
private static boolean isValidIdentifier(String value) {
return VALID_IDENTIFIER.matcher(value).matches();
}
private static Optional<String> sectionDefinitionLine(String line) {
if (line.startsWith("[")) {
String lineWithoutBrackets = line.substring(1, line.length() - 1);
String rawProfileName = StringUtils.trim(lineWithoutBrackets);
return Arrays.stream(ProfileSection.values())
.filter(x -> !ProfileFile.PROFILES_SECTION_TITLE.equals(x.getSectionTitle()))
.map(title -> title.getSectionTitle())
.filter(reservedTitle -> rawProfileName.startsWith(String.format("%s ", reservedTitle))
|| rawProfileName.startsWith(String.format("%s\t", reservedTitle)))
.findFirst();
}
return Optional.empty();
}
private static void readSectionProfileDefinitionLine(ParserState state, String line) {
// Profile definitions do not require a space between the closing bracket and the comment delimiter
String lineWithoutComments = removeTrailingComments(line, "#", ";");
String lineWithoutWhitespace = StringUtils.trim(lineWithoutComments);
Validate.isTrue(lineWithoutWhitespace.endsWith("]"),
"Section definition must end with ']' on line " + state.currentLineNumber);
Optional<String> profileName = parseSpecialProfileDefinition(state, lineWithoutWhitespace);
updateStateBasedOnProfileName(state, profileName);
}
private static void updateStateBasedOnProfileName(ParserState state, Optional<String> profileName) {
// If we couldn't get the profile name, ignore this entire profile.
if (!profileName.isPresent()) {
state.ignoringCurrentProfile = true;
return;
}
state.currentProfileBeingRead = profileName.get();
state.currentPropertyBeingRead = null;
state.ignoringCurrentProfile = false;
state.ignoringCurrentProperty = false;
// If we've seen this profile before, don't override the existing properties. We'll be merging them.
state.profiles.get(state.sectionReadInProgress).computeIfAbsent(profileName.get(),
i -> new LinkedHashMap<>());
}
private static Optional<String> parseSpecialProfileDefinition(ParserState state, String lineWithoutWhitespace) {
String lineWithoutBrackets = lineWithoutWhitespace.substring(1, lineWithoutWhitespace.length() - 1);
String rawProfileName = StringUtils.trim(lineWithoutBrackets);
String profilePrefix =
Arrays.stream(ProfileSection.values())
.filter(x -> !x.getSectionTitle().equals(ProfileFile.PROFILES_SECTION_TITLE))
.map(x -> x.getSectionTitle())
.filter(
title -> rawProfileName.startsWith(String.format("%s ", title))
|| rawProfileName.startsWith(String.format("%s\t", title)))
.findFirst()
.orElse(null);
if (state.fileType != ProfileFile.Type.CONFIGURATION || profilePrefix == null) {
return Optional.empty();
}
String standardizedProfileName = StringUtils.trim(rawProfileName.substring(profilePrefix.length()));
String profilePrefixName = StringUtils.trim(standardizedProfileName);
// If the profile name includes invalid characters, it should be ignored.
if (!isValidIdentifier(profilePrefixName)) {
log.warn(() -> "Ignoring " + standardizedProfileName + "' on line " + state.currentLineNumber + " because " +
"it was not alphanumeric with only these special characters: - / . % @ _ : +");
return Optional.empty();
}
return Optional.of(profilePrefixName);
}
/**
* When {@link #parseFile(InputStream, ProfileFile.Type)} is invoked, this is used to track the state of the parser as it
* reads the input stream.
*/
private static final class ParserState {
/**
* The type of file being parsed.
*/
private final ProfileFile.Type fileType;
/**
* The line currently being parsed. Useful for error messages.
*/
private int currentLineNumber = 0;
/**
* Which profile is currently being read. Updated after each [profile] has been successfully read.
*
* Properties read will be added to this profile.
*/
private String currentProfileBeingRead = null;
/**
* Which property is currently being read. Updated after each foo = bar has been successfully read.
*
* Property continuations read will be appended to this property.
*/
private String currentPropertyBeingRead = null;
/**
* Whether we are ignoring the current profile. Updated after a [profile] has been identified as being invalid, but we
* do not want to fail parsing the whole file.
*
* All lines other than property definitions read while this is true are dropped.
*/
private boolean ignoringCurrentProfile = false;
/**
* Whether we are ignoring the current property. Updated after a foo = bar has been identified as being invalid, but we
* do not want to fail parsing the whole file.
*
* All property continuations read while this are true are dropped.
*/
private boolean ignoringCurrentProperty = false;
/**
* Whether we are validating the current property value continuations are formatted like sub-properties. This will ensure
* that when the same file is used with the CLI, it won't cause failures.
*/
private boolean validatingContinuationsAsSubProperties = false;
/**
* Whether within the current file, we've seen the [profile default] profile definition. This is only used for
* configuration files. If this is true we'll ignore [default] profile definitions, because [profile default] takes
* precedence.
*/
private boolean seenDefaultProfileWithProfilePrefix = false;
/**
* Whether a section read is in progress. This is used to segregate section properties and profile properties.
*/
private String sectionReadInProgress;
/**
* The profiles read so far by the parser.
*/
private Map<String, Map<String, Map<String, String>>> profiles = new LinkedHashMap<>();
private ParserState(ProfileFile.Type fileType) {
profiles.put(ProfileFile.PROFILES_SECTION_TITLE, new LinkedHashMap<>());
Arrays.stream(ProfileSection.values())
.forEach(profileSection -> profiles.put(profileSection.getSectionTitle(), new LinkedHashMap<>()));
this.fileType = fileType;
}
}
}
| 2,150 |
0 | Create_ds/aws-sdk-java-v2/core/http-auth-aws-eventstream/src/main/java/software/amazon/awssdk/http/auth/aws | Create_ds/aws-sdk-java-v2/core/http-auth-aws-eventstream/src/main/java/software/amazon/awssdk/http/auth/aws/eventstream/HttpAuthAwsEventStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.auth.aws.eventstream;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* This is a place-holder class for this module, http-auth-aws-eventstream. In the event that we decide to move back
* event-stream signer logic back to this dedicated module, no issues will arise. This module should be an optional
* dependency in consumers (http-auth-aws), and should bring in the required dependencies (eventstream).
*/
@SdkProtectedApi
public final class HttpAuthAwsEventStream {
}
| 2,151 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/test/java/software/amazon/awssdk/protocols/core/GreedyPathMarshallerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class GreedyPathMarshallerTest {
private final PathMarshaller marshaller = PathMarshaller.GREEDY;
@Test(expected = NullPointerException.class)
public void nullPathValue_ThrowsException() {
marshaller.marshall("/foo/{greedyParam+}", "greedyParam", null);
}
@Test(expected = IllegalArgumentException.class)
public void emptyPathValue_ThrowsException() {
marshaller.marshall("/foo/{greedyParam+}", "greedyParam", "");
}
@Test
public void nonEmptyPathValue_ReplacesPlaceholder() {
assertEquals("/foo/nonEmpty", marshaller.marshall("/foo/{greedyParam+}", "greedyParam", "nonEmpty"));
}
@Test
public void pathValueWithSlashes_NotUrlEncodedWhenReplaced() {
assertEquals("/foo/my/greedy/value", marshaller.marshall("/foo/{greedyParam+}", "greedyParam", "my/greedy/value"));
}
@Test
public void pathValueWithLeadingSlash_TrimmedBeforeReplaced() {
assertEquals("/foo/my/greedy/value", marshaller.marshall("/foo/{greedyParam+}", "greedyParam", "/my/greedy/value"));
}
}
| 2,152 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/test/java/software/amazon/awssdk/protocols/core/NonGreedyPathMarshallerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class NonGreedyPathMarshallerTest {
private final PathMarshaller marshaller = PathMarshaller.NON_GREEDY;
@Test(expected = NullPointerException.class)
public void nullPathValue_ThrowsException() {
marshaller.marshall("/foo/{pathParam}", "pathParam", null);
}
@Test(expected = IllegalArgumentException.class)
public void emptyPathValue_ThrowsException() {
marshaller.marshall("/foo/{pathParam}", "pathParam", "");
}
@Test
public void nonEmptyPathValue_ReplacesPlaceholder() {
assertEquals("/foo/nonEmpty", marshaller.marshall("/foo/{pathParam}", "pathParam", "nonEmpty"));
}
@Test
public void pathValueWithSlashes_UrlEncodedWhenReplaced() {
assertEquals("/foo/has%2Fslash", marshaller.marshall("/foo/{pathParam}", "pathParam", "has/slash"));
}
}
| 2,153 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/test/java/software/amazon/awssdk/protocols/core/ProtocolUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.URI;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
public class ProtocolUtilsTest {
@Test
public void createSdkHttpRequest_SetsHttpMethodAndEndpointCorrectly() {
SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
OperationInfo.builder()
.httpMethod(SdkHttpMethod.DELETE)
.build(), URI.create("http://localhost:8080"));
assertThat(sdkHttpRequest.protocol()).isEqualTo("http");
assertThat(sdkHttpRequest.host()).isEqualTo("localhost");
assertThat(sdkHttpRequest.port()).isEqualTo(8080);
assertThat(sdkHttpRequest.method()).isEqualTo(SdkHttpMethod.DELETE);
}
@Test
public void createSdkHttpRequest_EndpointWithPathSetCorrectly() {
SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
OperationInfo.builder()
.httpMethod(SdkHttpMethod.DELETE)
.build(), URI.create("http://localhost/foo/bar"));
assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar");
}
@Test
public void createSdkHttpRequest_RequestUriAppendedToEndpointPath() {
SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
OperationInfo.builder()
.httpMethod(SdkHttpMethod.DELETE)
.requestUri("/baz")
.build(), URI.create("http://localhost/foo/bar/"));
assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz");
}
@Test
public void createSdkHttpRequest_NoTrailingSlashInEndpointPath_RequestUriAppendedToEndpointPath() {
SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
OperationInfo.builder()
.httpMethod(SdkHttpMethod.DELETE)
.requestUri("/baz")
.build(), URI.create("http://localhost/foo/bar"));
assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz");
}
@Test
public void createSdkHttpRequest_NoLeadingSlashInRequestUri_RequestUriAppendedToEndpointPath() {
SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
OperationInfo.builder()
.httpMethod(SdkHttpMethod.DELETE)
.requestUri("baz")
.build(), URI.create("http://localhost/foo/bar/"));
assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz");
}
@Test
public void createSdkHttpRequest_NoTrailingOrLeadingSlash_RequestUriAppendedToEndpointPath() {
SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
OperationInfo.builder()
.httpMethod(SdkHttpMethod.DELETE)
.requestUri("baz")
.build(), URI.create("http://localhost/foo/bar"));
assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz");
}
@Test
public void request_null_returns_null() {
assertNull(ProtocolUtils.addStaticQueryParametersToRequest(null,
"foo"));
}
@Test
public void uri_resource_path_null_returns_null() {
assertNull(ProtocolUtils
.addStaticQueryParametersToRequest(emptyRequest(), null));
}
private SdkHttpFullRequest.Builder emptyRequest() {
return SdkHttpFullRequest.builder();
}
@Test
public void uri_resource_path_doesnot_have_static_query_params_returns_uri_resource_path() {
final String uriResourcePath = "/foo/bar";
assertEquals(uriResourcePath, ProtocolUtils
.addStaticQueryParametersToRequest(emptyRequest(), uriResourcePath));
}
@Test
public void uri_resource_path_ends_with_question_mark_returns_path_removed_with_question_mark() {
final String expectedResourcePath = "/foo/bar";
final String pathWithEmptyStaticQueryParams = expectedResourcePath + "?";
assertEquals(expectedResourcePath, ProtocolUtils
.addStaticQueryParametersToRequest(emptyRequest(), pathWithEmptyStaticQueryParams));
}
@Test
public void queryparam_value_empty_adds_parameter_with_empty_string_to_request() {
final String uriResourcePath = "/foo/bar";
final String uriResourcePathWithParams =
uriResourcePath + "?param1=";
SdkHttpFullRequest.Builder request = emptyRequest();
assertEquals(uriResourcePath, ProtocolUtils
.addStaticQueryParametersToRequest(request,
uriResourcePathWithParams));
assertTrue(request.rawQueryParameters().containsKey("param1"));
assertEquals(singletonList(""), request.rawQueryParameters().get("param1"));
}
@Test
public void static_queryparams_in_path_added_to_request() {
final String uriResourcePath = "/foo/bar";
final String uriResourcePathWithParams =
uriResourcePath + "?param1=value1¶m2=value2";
SdkHttpFullRequest.Builder request = emptyRequest();
assertEquals(uriResourcePath, ProtocolUtils
.addStaticQueryParametersToRequest(request,
uriResourcePathWithParams));
assertTrue(request.rawQueryParameters().containsKey("param1"));
assertTrue(request.rawQueryParameters().containsKey("param2"));
assertEquals(singletonList("value1"), request.rawQueryParameters().get("param1"));
assertEquals(singletonList("value2"), request.rawQueryParameters().get("param2"));
}
@Test
public void queryparam_without_value_returns_list_containing_null_value() {
final String uriResourcePath = "/foo/bar";
final String uriResourcePathWithParams =
uriResourcePath + "?param";
SdkHttpFullRequest.Builder request = emptyRequest();
assertEquals(uriResourcePath, ProtocolUtils.addStaticQueryParametersToRequest(request, uriResourcePathWithParams));
assertTrue(request.rawQueryParameters().containsKey("param"));
assertEquals(singletonList((String) null), request.rawQueryParameters().get("param"));
}
}
| 2,154 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/Marshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Marker interface for marshallers.
*
* @param <T> Type being marshalled.
*/
@SdkProtectedApi
public interface Marshaller<T> {
}
| 2,155 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/ProtocolMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkPojo;
/**
* Interface used by generated marshallers to marshall a Java POJO.
*/
@SdkProtectedApi
public interface ProtocolMarshaller<MarshalledT> {
MarshalledT marshall(SdkPojo pojo);
}
| 2,156 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/OperationMetadataAttribute.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Key for additional metadata in {@link OperationInfo}. Used to register protocol specific metadata about
* an operation.
*
* @param <T> Type of metadata.
*/
@SdkProtectedApi
public final class OperationMetadataAttribute<T> extends AttributeMap.Key<T> {
public OperationMetadataAttribute(Class<T> valueType) {
super(valueType);
}
}
| 2,157 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/StringToValueConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.math.BigDecimal;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* Converter implementations that transform a String to a specified type.
*/
@SdkProtectedApi
public final class StringToValueConverter {
/**
* Interface to convert a String into another type.
*
* @param <T> Type to convert to.
*/
@FunctionalInterface
public interface StringToValue<T> {
/**
* Converts the value to a string.
*
* @param s Value to convert from.
* @param sdkField {@link SdkField} containing metadata about the member being unmarshalled.
* @return Unmarshalled value.
*/
T convert(String s, SdkField<T> sdkField);
}
/**
* Simple interface to convert a String to another type. Useful for implementations that don't need the {@link SdkField}.
*
* @param <T> Type to convert to.
*/
@FunctionalInterface
public interface SimpleStringToValue<T> extends StringToValue<T> {
@Override
default T convert(String s, SdkField<T> sdkField) {
return convert(s);
}
/**
* Converts the value to a string.
*
* @param s Value to convert from.
* @return Unmarshalled value.
*/
T convert(String s);
}
/**
* Identity converter.
*/
public static final SimpleStringToValue<String> TO_STRING = val -> val;
public static final SimpleStringToValue<Integer> TO_INTEGER = Integer::parseInt;
public static final SimpleStringToValue<Long> TO_LONG = Long::parseLong;
public static final SimpleStringToValue<Short> TO_SHORT = Short::parseShort;
public static final SimpleStringToValue<Float> TO_FLOAT = Float::parseFloat;
public static final SimpleStringToValue<Double> TO_DOUBLE = Double::parseDouble;
public static final SimpleStringToValue<BigDecimal> TO_BIG_DECIMAL = BigDecimal::new;
public static final SimpleStringToValue<Boolean> TO_BOOLEAN = Boolean::parseBoolean;
public static final SimpleStringToValue<SdkBytes> TO_SDK_BYTES = StringToValueConverter::toSdkBytes;
private StringToValueConverter() {
}
private static SdkBytes toSdkBytes(String s) {
return SdkBytes.fromByteArray(BinaryUtils.fromBase64(s));
}
}
| 2,158 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/ProtocolUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.net.URI;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.http.SdkHttpUtils;
/**
* Utilities common to all protocols.
*/
@SdkProtectedApi
public final class ProtocolUtils {
private ProtocolUtils() {
}
/**
* Creates the basic {@link SdkHttpFullRequest} with information from the {@link OperationInfo} and the endpoint.
*
* @param operationInfo Metadata about operation, contains HTTP method and request URI.
* @param endpoint Endpoint of request.
* @return Mutable {@link SdkHttpFullRequest.Builder} with HTTP method, URI, and static query parameters set.
*/
public static SdkHttpFullRequest.Builder createSdkHttpRequest(OperationInfo operationInfo, URI endpoint) {
SdkHttpFullRequest.Builder request = SdkHttpFullRequest
.builder()
.method(operationInfo.httpMethod())
.uri(endpoint);
return request.encodedPath(SdkHttpUtils.appendUri(request.encodedPath(),
addStaticQueryParametersToRequest(request, operationInfo.requestUri())));
}
/**
* Identifies the static query parameters in Uri resource path for and adds it to
* request.
*
* Returns the updated uriResourcePath.
*/
@SdkTestInternalApi
static String addStaticQueryParametersToRequest(SdkHttpFullRequest.Builder request,
String uriResourcePath) {
if (request == null || uriResourcePath == null) {
return null;
}
String resourcePath = uriResourcePath;
int index = resourcePath.indexOf('?');
if (index != -1) {
String queryString = resourcePath.substring(index + 1);
resourcePath = resourcePath.substring(0, index);
for (String s : queryString.split("[;&]")) {
index = s.indexOf('=');
if (index != -1) {
request.putRawQueryParameter(s.substring(0, index), s.substring(index + 1));
} else {
request.putRawQueryParameter(s, (String) null);
}
}
}
return resourcePath;
}
}
| 2,159 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/OperationInfo.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Static information about an API operation used to marshall it correctly.
*/
@SdkProtectedApi
public final class OperationInfo {
private final String requestUri;
private final SdkHttpMethod httpMethod;
private final String operationIdentifier;
private final String apiVersion;
private final boolean hasExplicitPayloadMember;
private final boolean hasPayloadMembers;
private final boolean hasImplicitPayloadMembers;
private final boolean hasStreamingInput;
private final boolean hasEventStreamingInput;
private final boolean hasEvent;
private final AttributeMap additionalMetadata;
private OperationInfo(Builder builder) {
this.requestUri = builder.requestUri;
this.httpMethod = builder.httpMethod;
this.operationIdentifier = builder.operationIdentifier;
this.apiVersion = builder.apiVersion;
this.hasExplicitPayloadMember = builder.hasExplicitPayloadMember;
this.hasImplicitPayloadMembers = builder.hasImplicitPayloadMembers;
this.hasPayloadMembers = builder.hasPayloadMembers;
this.hasStreamingInput = builder.hasStreamingInput;
this.additionalMetadata = builder.additionalMetadata.build();
this.hasEventStreamingInput = builder.hasEventStreamingInput;
this.hasEvent = builder.hasEvent;
}
/**
* @return Request URI for operation (may contain placeholders for members bound to the uri).
*/
public String requestUri() {
return requestUri;
}
/**
* @return HTTP Method that should be used when sending the request.
*/
public SdkHttpMethod httpMethod() {
return httpMethod;
}
/**
* @return Identifier for the operation/API being invoked. This is used for RPC based protocols that
* need to identify which action is being taken. For Query/EC2 protocol this is sent as the 'Action' query
* parameter, for JSON RPC this is sent as the 'X-Amz-Target' header.
*/
public String operationIdentifier() {
return operationIdentifier;
}
/**
* @return Version of the service's API. For Query protocol this is sent as a 'Version' query parameter.
*/
public String apiVersion() {
return apiVersion;
}
/**
* @return True if the operation has a member that's explicitly marked as the payload. False otherwise. (Applicable only to
* RESTUL protocols).
*/
public boolean hasExplicitPayloadMember() {
return hasExplicitPayloadMember;
}
/**
* @return True if the operation has members bound to the payload. Some requests (especially GET and DELETE) may not
* have any members bound to the payload. (Applicable only to RESTFUL protocols).
*/
public boolean hasPayloadMembers() {
return hasPayloadMembers;
}
/**
* @return True if the operation has members that are not explicitly bound to a marshalling location, and thus are
* implicitly bound to the body.
*/
public boolean hasImplicitPayloadMembers() {
return hasImplicitPayloadMembers;
}
/**
* @return True if the operation has streaming input.
*/
public boolean hasStreamingInput() {
return hasStreamingInput;
}
/**
* @return True if the operation has event streaming input.
*/
public boolean hasEventStreamingInput() {
return hasEventStreamingInput;
}
/**
* @return True if the operation has event.
*/
public boolean hasEvent() {
return hasEvent;
}
/**
* Gets an unmodeled piece of metadata. Useful for protocol specific options.
*
* @param key Key the metadata was registered under.
* @param <T> Type of metadata being requested.
* @return The value of the additional metadata being requested or null if it's not present.
*/
public <T> T addtionalMetadata(OperationMetadataAttribute<T> key) {
return additionalMetadata.get(key);
}
/**
* @return Builder instance to construct a {@link OperationInfo}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for a {@link OperationInfo}.
*/
public static final class Builder {
private String requestUri;
private SdkHttpMethod httpMethod;
private String operationIdentifier;
private String apiVersion;
private boolean hasExplicitPayloadMember;
private boolean hasImplicitPayloadMembers;
private boolean hasPayloadMembers;
private boolean hasStreamingInput;
private boolean hasEventStreamingInput;
private boolean hasEvent;
private AttributeMap.Builder additionalMetadata = AttributeMap.builder();
private Builder() {
}
public Builder requestUri(String requestUri) {
this.requestUri = requestUri;
return this;
}
public Builder httpMethod(SdkHttpMethod httpMethod) {
this.httpMethod = httpMethod;
return this;
}
public Builder operationIdentifier(String operationIdentifier) {
this.operationIdentifier = operationIdentifier;
return this;
}
public Builder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
public Builder hasExplicitPayloadMember(boolean hasExplicitPayloadMember) {
this.hasExplicitPayloadMember = hasExplicitPayloadMember;
return this;
}
public Builder hasPayloadMembers(boolean hasPayloadMembers) {
this.hasPayloadMembers = hasPayloadMembers;
return this;
}
public Builder hasImplicitPayloadMembers(boolean hasImplicitPayloadMembers) {
this.hasImplicitPayloadMembers = hasImplicitPayloadMembers;
return this;
}
public Builder hasStreamingInput(boolean hasStreamingInput) {
this.hasStreamingInput = hasStreamingInput;
return this;
}
public Builder hasEventStreamingInput(boolean hasEventStreamingInput) {
this.hasEventStreamingInput = hasEventStreamingInput;
return this;
}
public Builder hasEvent(boolean hasEvent) {
this.hasEvent = hasEvent;
return this;
}
/**
* Adds additional unmodeled metadata to the {@link OperationInfo}. Useful for communicating protocol
* specific operation metadata.
*
* @param key Key to register metadata.
* @param value Value of metadata.
* @param <T> Type of metadata being registered.
* @return This builder for method chaining.
*/
public <T> Builder putAdditionalMetadata(OperationMetadataAttribute<T> key, T value) {
additionalMetadata.put(key, value);
return this;
}
/**
* @return An immutable {@link OperationInfo} object.
*/
public OperationInfo build() {
return new OperationInfo(this);
}
}
}
| 2,160 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/InstantToString.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.time.Instant;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.traits.TimestampFormatTrait;
import software.amazon.awssdk.protocols.core.ValueToStringConverter.ValueToString;
import software.amazon.awssdk.utils.DateUtils;
/**
* Implementation of {@link ValueToString} that converts and {@link Instant} to a string. * Respects the
* {@link TimestampFormatTrait} if present.
*/
@SdkProtectedApi
public final class InstantToString implements ValueToString<Instant> {
private final Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats;
private InstantToString(Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats) {
this.defaultFormats = defaultFormats;
}
@Override
public String convert(Instant val, SdkField<Instant> sdkField) {
if (val == null) {
return null;
}
TimestampFormatTrait.Format format =
sdkField.getOptionalTrait(TimestampFormatTrait.class)
.map(TimestampFormatTrait::format)
.orElseGet(() -> getDefaultTimestampFormat(sdkField.location(), defaultFormats));
switch (format) {
case ISO_8601:
return DateUtils.formatIso8601Date(val);
case RFC_822:
return DateUtils.formatRfc822Date(val);
case UNIX_TIMESTAMP:
return DateUtils.formatUnixTimestampInstant(val);
default:
throw SdkClientException.create("Unsupported timestamp format - " + format);
}
}
private TimestampFormatTrait.Format getDefaultTimestampFormat(
MarshallLocation location, Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats) {
TimestampFormatTrait.Format format = defaultFormats.get(location);
if (format == null) {
throw SdkClientException.create("No default timestamp marshaller found for location - " + location);
}
return format;
}
public static InstantToString create(Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats) {
return new InstantToString(defaultFormats);
}
}
| 2,161 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/PathMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.http.SdkHttpUtils;
@SdkProtectedApi
public abstract class PathMarshaller {
/**
* Marshaller for non greedy path labels. Value is URL encoded and then replaced in the request URI.
*/
public static final PathMarshaller NON_GREEDY = new NonGreedyPathMarshaller();
/**
* Marshaller for greedy path labels. Value is not URL encoded and replaced in the request URI.
*/
public static final PathMarshaller GREEDY = new GreedyPathMarshaller();
/**
* Marshaller for greedy path labels that allows leading slahes. Value is not URL encoded and
* replaced in the request URI.
*/
public static final PathMarshaller GREEDY_WITH_SLASHES = new GreedyLeadingSlashPathMarshaller();
private PathMarshaller() {
}
private static String trimLeadingSlash(String value) {
if (value.startsWith("/")) {
return value.replaceFirst("/", "");
}
return value;
}
/**
* @param resourcePath Current resource path with path param placeholder
* @param paramName Name of parameter (i.e. placeholder value {Foo})
* @param pathValue String value of path parameter.
* @return New URI with placeholder replaced with marshalled value.
*/
public abstract String marshall(String resourcePath, String paramName, String pathValue);
private static class NonGreedyPathMarshaller extends PathMarshaller {
@Override
public String marshall(String resourcePath, String paramName, String pathValue) {
Validate.notEmpty(pathValue, "%s cannot be empty.", paramName);
return StringUtils.replace(resourcePath, "{" + paramName + "}", SdkHttpUtils.urlEncode(pathValue));
}
}
private static class GreedyPathMarshaller extends PathMarshaller {
@Override
public String marshall(String resourcePath, String paramName, String pathValue) {
Validate.notEmpty(pathValue, "%s cannot be empty.", paramName);
return StringUtils.replace(resourcePath,
"{" + paramName + "+}",
SdkHttpUtils.urlEncodeIgnoreSlashes(trimLeadingSlash(pathValue)));
}
}
private static class GreedyLeadingSlashPathMarshaller extends PathMarshaller {
@Override
public String marshall(String resourcePath, String paramName, String pathValue) {
Validate.notEmpty(pathValue, "%s cannot be empty.", paramName);
return StringUtils.replace(resourcePath, "{" + paramName + "+}", SdkHttpUtils.urlEncodeIgnoreSlashes(pathValue));
}
}
}
| 2,162 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/ValueToStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.math.BigDecimal;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* Converts various types to Strings. Used for Query Param/Header/Path marshalling.
*/
@SdkProtectedApi
public final class ValueToStringConverter {
/**
* Interface to convert a type to a String.
*
* @param <T> Type to convert.
*/
@FunctionalInterface
public interface ValueToString<T> {
/**
* Converts the value to a string.
*
* @param t Value to convert.
* @param field {@link SdkField} containing metadata about the member being marshalled.
* @return String value.
*/
String convert(T t, SdkField<T> field);
}
/**
* Simple interface to convert a type to a String. Useful for implementations that don't need the {@link SdkField}.
*
* @param <T> Type to convert.
*/
@FunctionalInterface
public interface SimpleValueToString<T> extends ValueToString<T> {
@Override
default String convert(T t, SdkField<T> field) {
return convert(t);
}
/**
* Converts the value to a string.
*
* @param t Value to convert.
* @return String value.
*/
String convert(T t);
}
/**
* Identity converter.
*/
public static final SimpleValueToString<String> FROM_STRING = val -> val;
public static final SimpleValueToString<Integer> FROM_INTEGER = Object::toString;
public static final SimpleValueToString<Long> FROM_LONG = Object::toString;
public static final SimpleValueToString<Short> FROM_SHORT = Object::toString;
public static final SimpleValueToString<Float> FROM_FLOAT = Object::toString;
public static final SimpleValueToString<Double> FROM_DOUBLE = Object::toString;
public static final SimpleValueToString<BigDecimal> FROM_BIG_DECIMAL = Object::toString;
/**
* Marshalls boolean as a literal 'true' or 'false' string.
*/
public static final SimpleValueToString<Boolean> FROM_BOOLEAN = Object::toString;
/**
* Marshalls bytes as a Base64 string.
*/
public static final SimpleValueToString<SdkBytes> FROM_SDK_BYTES = b -> BinaryUtils.toBase64(b.asByteArray());
private ValueToStringConverter() {
}
}
| 2,163 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/StringToInstant.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.time.Instant;
import java.util.Map;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.traits.TimestampFormatTrait;
import software.amazon.awssdk.utils.DateUtils;
/**
* Implementation of {@link StringToValueConverter.StringToValue} that converts a string to an {@link Instant} type.
* Respects the {@link TimestampFormatTrait} if present.
*/
@SdkProtectedApi
public final class StringToInstant implements StringToValueConverter.StringToValue<Instant> {
/**
* Default formats for the given location.
*/
private final Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats;
private StringToInstant(Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats) {
this.defaultFormats = defaultFormats;
}
@Override
public Instant convert(String value, SdkField<Instant> field) {
if (value == null) {
return null;
}
TimestampFormatTrait.Format format = resolveTimestampFormat(field);
switch (format) {
case ISO_8601:
return DateUtils.parseIso8601Date(value);
case UNIX_TIMESTAMP:
return safeParseDate(DateUtils::parseUnixTimestampInstant).apply(value);
case UNIX_TIMESTAMP_MILLIS:
return safeParseDate(DateUtils::parseUnixTimestampMillisInstant).apply(value);
case RFC_822:
return DateUtils.parseRfc822Date(value);
default:
throw SdkClientException.create("Unrecognized timestamp format - " + format);
}
}
/**
* Wraps date unmarshalling function to handle the {@link NumberFormatException}.
* @param dateUnmarshaller Original date unmarshaller function.
* @return New date unmarshaller function with exception handling.
*/
private Function<String, Instant> safeParseDate(Function<String, Instant> dateUnmarshaller) {
return value -> {
try {
return dateUnmarshaller.apply(value);
} catch (NumberFormatException e) {
throw SdkClientException.builder()
.message("Unable to parse date : " + value)
.cause(e)
.build();
}
};
}
private TimestampFormatTrait.Format resolveTimestampFormat(SdkField<Instant> field) {
TimestampFormatTrait trait = field.getTrait(TimestampFormatTrait.class);
if (trait == null) {
TimestampFormatTrait.Format format = defaultFormats.get(field.location());
if (format == null) {
throw SdkClientException.create(
String.format("Timestamps are not supported for this location (%s)", field.location()));
}
return format;
} else {
return trait.format();
}
}
/**
* @param defaultFormats Default formats for each {@link MarshallLocation} as defined by the protocol.
* @return New {@link StringToValueConverter.StringToValue} for {@link Instant} types.
*/
public static StringToInstant create(Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats) {
return new StringToInstant(defaultFormats);
}
}
| 2,164 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/ExceptionMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkPojo;
/**
* Metadata needed to unmarshall a modeled exception.
*/
@SdkProtectedApi
public final class ExceptionMetadata {
private final String errorCode;
private final Supplier<SdkPojo> exceptionBuilderSupplier;
private final Integer httpStatusCode;
private ExceptionMetadata(Builder builder) {
this.errorCode = builder.errorCode;
this.exceptionBuilderSupplier = builder.exceptionBuilderSupplier;
this.httpStatusCode = builder.httpStatusCode;
}
/**
* Returns the error code for the modeled exception.
*/
public String errorCode() {
return errorCode;
}
/**
* Returns the Supplier to get the builder class for the exception.
*/
public Supplier<SdkPojo> exceptionBuilderSupplier() {
return exceptionBuilderSupplier;
}
/**
* Returns the http status code for the exception.
* For modeled exceptions, this value is populated from the c2j model.
*/
public Integer httpStatusCode() {
return httpStatusCode;
}
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link ExceptionMetadata}
*/
public static final class Builder {
private String errorCode;
private Supplier<SdkPojo> exceptionBuilderSupplier;
private Integer httpStatusCode;
private Builder() {
}
public Builder errorCode(String errorCode) {
this.errorCode = errorCode;
return this;
}
public Builder exceptionBuilderSupplier(Supplier<SdkPojo> exceptionBuilderSupplier) {
this.exceptionBuilderSupplier = exceptionBuilderSupplier;
return this;
}
public Builder httpStatusCode(Integer httpStatusCode) {
this.httpStatusCode = httpStatusCode;
return this;
}
public ExceptionMetadata build() {
return new ExceptionMetadata(this);
}
}
}
| 2,165 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/AbstractMarshallingRegistry.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.protocol.MarshallingType;
/**
* Base class for marshaller/unmarshaller registry implementations.
*/
@SdkProtectedApi
public abstract class AbstractMarshallingRegistry {
private final Map<MarshallLocation, Map<MarshallingType, Object>> registry;
private final Set<MarshallingType<?>> marshallingTypes;
private final Map<Class<?>, MarshallingType<?>> marshallingTypeCache;
protected AbstractMarshallingRegistry(Builder builder) {
this.registry = builder.registry;
this.marshallingTypes = builder.marshallingTypes;
this.marshallingTypeCache = new HashMap<>(marshallingTypes.size());
}
/**
* Get a registered marshaller/unmarshaller by location and type.
*
* @param marshallLocation Location of registered (un)marshaller.
* @param marshallingType Type of registered (un)marshaller.
* @return Registered marshaller/unmarshaller.
* @throws SdkClientException if no marshaller/unmarshaller is registered for the given location and type.
*/
protected Object get(MarshallLocation marshallLocation, MarshallingType<?> marshallingType) {
Map<MarshallingType, Object> byLocation = registry.get(marshallLocation);
if (byLocation == null) {
throw SdkClientException.create("No marshaller/unmarshaller registered for location " + marshallLocation.name());
}
Object registered = byLocation.get(marshallingType);
if (registered == null) {
throw SdkClientException.create(String.format("No marshaller/unmarshaller of type %s registered for location %s.",
marshallingType,
marshallLocation.name()));
}
return registered;
}
@SuppressWarnings("unchecked")
protected <T> MarshallingType<T> toMarshallingType(T val) {
if (val == null) {
return (MarshallingType<T>) MarshallingType.NULL;
} else if (val instanceof SdkPojo) {
// We don't want to cache every single POJO type so we make a special case of it here.
return (MarshallingType<T>) MarshallingType.SDK_POJO;
} else if (!marshallingTypeCache.containsKey(val.getClass())) {
return (MarshallingType<T>) populateMarshallingTypeCache(val.getClass());
}
return (MarshallingType<T>) marshallingTypeCache.get(val.getClass());
}
private MarshallingType<?> populateMarshallingTypeCache(Class<?> clzz) {
synchronized (marshallingTypeCache) {
if (!marshallingTypeCache.containsKey(clzz)) {
for (MarshallingType<?> marshallingType : marshallingTypes) {
if (marshallingType.getTargetClass().isAssignableFrom(clzz)) {
marshallingTypeCache.put(clzz, marshallingType);
return marshallingType;
}
}
throw SdkClientException.builder().message("MarshallingType not found for class " + clzz).build();
}
}
return marshallingTypeCache.get(clzz);
}
/**
* Builder for a {@link AbstractMarshallingRegistry}.
*/
public abstract static class Builder {
private final Map<MarshallLocation, Map<MarshallingType, Object>> registry = new EnumMap<>(MarshallLocation.class);
private final Set<MarshallingType<?>> marshallingTypes = new HashSet<>();
protected Builder() {
}
protected <T> Builder register(MarshallLocation marshallLocation,
MarshallingType<T> marshallingType,
Object marshaller) {
marshallingTypes.add(marshallingType);
if (!registry.containsKey(marshallLocation)) {
registry.put(marshallLocation, new HashMap<>());
}
registry.get(marshallLocation).put(marshallingType, marshaller);
return this;
}
}
}
| 2,166 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/JsonErrorCodeParserTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.json.internal.unmarshall.JsonErrorCodeParser;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.utils.StringInputStream;
public class JsonErrorCodeParserTest {
/**
* Value of error type present in headers for tests below
*/
private static final String HEADER_ERROR_TYPE = "headerErrorType";
/**
* Value of error type present in JSON content for tests below
*/
private static final String JSON_ERROR_TYPE = "jsonErrorType";
private static final String ERROR_FIELD_NAME = "testErrorCode";
private final JsonErrorCodeParser parser = new JsonErrorCodeParser(ERROR_FIELD_NAME);
private static JsonContent toJsonContent(String errorType) throws IOException {
JsonNode node = JsonNode.parser().parse(new StringInputStream(
String.format("{\"%s\": \"%s\"}", ERROR_FIELD_NAME, errorType)));
return new JsonContent(null, node);
}
private static SdkHttpFullResponse httpResponseWithoutHeaders() {
return ValidSdkObjects.sdkHttpFullResponse().build();
}
private static SdkHttpFullResponse httpResponseWithHeaders(String header, String value) {
return ValidSdkObjects.sdkHttpFullResponse().putHeader(header, value).build();
}
@Test
public void parseErrorType_ErrorTypeInHeadersTakesPrecedence_NoSuffix() throws IOException {
String actualErrorType = parser.parseErrorCode(
httpResponseWithHeaders(JsonErrorCodeParser.X_AMZN_ERROR_TYPE, HEADER_ERROR_TYPE),
toJsonContent(JSON_ERROR_TYPE));
assertEquals(HEADER_ERROR_TYPE, actualErrorType);
}
@Test
public void parseErrorType_ErrorTypeInHeadersTakesPrecedence_SuffixIgnored() throws IOException {
String actualErrorType = parser.parseErrorCode(
httpResponseWithHeaders(JsonErrorCodeParser.X_AMZN_ERROR_TYPE,
String.format("%s:%s", HEADER_ERROR_TYPE, "someSuffix")), toJsonContent(JSON_ERROR_TYPE));
assertEquals(HEADER_ERROR_TYPE, actualErrorType);
}
@Test
public void parseErrorType_ErrorTypeInHeaders_HonorCaseInsensitivity() throws IOException {
String actualErrorType = parser.parseErrorCode(
httpResponseWithHeaders("x-amzn-errortype",
String.format("%s:%s", HEADER_ERROR_TYPE, "someSuffix")), toJsonContent(JSON_ERROR_TYPE));
assertEquals(HEADER_ERROR_TYPE, actualErrorType);
}
@Test
public void parseErrorType_ErrorTypeInContent_NoPrefix() throws IOException {
String actualErrorType = parser.parseErrorCode(httpResponseWithoutHeaders(), toJsonContent(JSON_ERROR_TYPE));
assertEquals(JSON_ERROR_TYPE, actualErrorType);
}
@Test
public void parseErrorType_ErrorTypeInContent_PrefixIgnored() throws IOException {
String actualErrorType = parser.parseErrorCode(httpResponseWithoutHeaders(),
toJsonContent(String.format("%s#%s", "somePrefix", JSON_ERROR_TYPE)));
assertEquals(JSON_ERROR_TYPE, actualErrorType);
}
@Test
public void parseErrorType_NotPresentInHeadersAndNullContent_ReturnsNull() {
assertNull(parser.parseErrorCode(httpResponseWithoutHeaders(), null));
}
@Test
public void parseErrorType_NotPresentInHeadersAndEmptyContent_ReturnsNull() {
assertNull(parser.parseErrorCode(httpResponseWithoutHeaders(),
new JsonContent(null, JsonNode.emptyObjectNode())));
}
}
| 2,167 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/SdkJsonGeneratorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.time.Instant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.utils.BinaryUtils;
public class SdkJsonGeneratorTest {
/**
* Delta for comparing double values
*/
private static final double DELTA = .0001;
private StructuredJsonGenerator jsonGenerator;
@BeforeEach
public void setup() {
jsonGenerator = new SdkJsonGenerator(JsonFactory.builder().build(), "application/json");
}
@Test
public void simpleObject_AllPrimitiveTypes() throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("stringProp").writeValue("stringVal");
jsonGenerator.writeFieldName("integralProp").writeValue(42);
jsonGenerator.writeFieldName("booleanProp").writeValue(true);
jsonGenerator.writeFieldName("doubleProp").writeValue(123.456);
jsonGenerator.writeEndObject();
JsonNode node = toJsonNode();
assertTrue(node.isObject());
assertEquals("stringVal", node.asObject().get("stringProp").text());
assertEquals("42", node.asObject().get("integralProp").asNumber());
assertEquals(true, node.asObject().get("booleanProp").asBoolean());
assertEquals(123.456, Double.parseDouble(node.asObject().get("doubleProp").asNumber()), DELTA);
}
@Test
public void simpleObject_WithLongProperty_PreservesLongValue() throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("longProp").writeValue(Long.MAX_VALUE);
jsonGenerator.writeEndObject();
JsonNode node = toJsonNode();
assertEquals(Long.toString(Long.MAX_VALUE), node.asObject().get("longProp").asNumber());
}
@Test
public void simpleObject_WithBinaryData_WritesAsBase64() throws IOException {
byte[] data = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("binaryProp").writeValue(ByteBuffer.wrap(data));
jsonGenerator.writeEndObject();
JsonNode node = toJsonNode();
assertEquals(BinaryUtils.toBase64(data), node.asObject().get("binaryProp").text());
}
@Test
public void simpleObject_WithServiceDate() throws IOException {
Instant instant = Instant.ofEpochMilli(123456);
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("dateProp").writeValue(instant);
jsonGenerator.writeEndObject();
JsonNode node = toJsonNode();
assertEquals(123.456, Double.parseDouble(node.asObject().get("dateProp").asNumber()), DELTA);
}
@Test
public void stringArray() throws IOException {
jsonGenerator.writeStartArray();
jsonGenerator.writeValue("valOne");
jsonGenerator.writeValue("valTwo");
jsonGenerator.writeValue("valThree");
jsonGenerator.writeEndArray();
JsonNode node = toJsonNode();
assertTrue(node.isArray());
assertEquals("valOne", node.asArray().get(0).text());
assertEquals("valTwo", node.asArray().get(1).text());
assertEquals("valThree", node.asArray().get(2).text());
}
@Test
public void complexArray() throws IOException {
jsonGenerator.writeStartArray();
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("nestedProp").writeValue("nestedVal");
jsonGenerator.writeEndObject();
jsonGenerator.writeEndArray();
JsonNode node = toJsonNode();
assertEquals("nestedVal", node.asArray().get(0).asObject().get("nestedProp").text());
}
@Test
public void unclosedObject_AutoClosesOnClose() throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("stringProp").writeValue("stringVal");
JsonNode node = toJsonNode();
assertTrue(node.isObject());
}
@Test
public void unclosedArray_AutoClosesOnClose() throws IOException {
jsonGenerator.writeStartArray();
jsonGenerator.writeValue("valOne");
jsonGenerator.writeValue("valTwo");
jsonGenerator.writeValue("valThree");
JsonNode node = toJsonNode();
assertTrue(node.isArray());
assertEquals(3, node.asArray().size());
}
// See https://forums.aws.amazon.com/thread.jspa?threadID=158756
@Test
public void testNumericNoQuote() {
StructuredJsonGenerator jw = new SdkJsonGenerator(new JsonFactory(), null);
jw.writeStartObject();
jw.writeFieldName("foo").writeValue(Instant.now());
jw.writeEndObject();
String s = new String(jw.getBytes(), Charset.forName("UTF-8"));
// Something like: {"foo":1408378076.135}.
// Note prior to the changes, it was {"foo":1408414571}
// (with no decimal point nor places.)
System.out.println(s);
final String prefix = "{\"foo\":";
assertTrue(s.startsWith(prefix), s);
final int startPos = prefix.length();
// verify no starting quote for the value
assertFalse(s.startsWith("{\"foo\":\""), s);
assertTrue(s.endsWith("}"), s);
// Not: {"foo":"1408378076.135"}.
// verify no ending quote for the value
assertFalse(s.endsWith("\"}"), s);
final int endPos = s.indexOf("}");
final int dotPos = s.length() - 5;
assertTrue(s.charAt(dotPos) == '.', s);
// verify all numeric before '.'
char[] a = s.toCharArray();
for (int i = startPos; i < dotPos; i++) {
assertTrue(a[i] <= '9' && a[i] >= '0');
}
int j = 0;
// verify all numeric after '.'
for (int i = dotPos + 1; i < endPos; i++) {
assertTrue(a[i] <= '9' && a[i] >= '0');
j++;
}
// verify decimal precision of exactly 3
assertTrue(j == 3);
}
private JsonNode toJsonNode() throws IOException {
return JsonNode.parser().parse(new ByteArrayInputStream(jsonGenerator.getBytes()));
}
}
| 2,168 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/AwsJsonErrorMessageParserTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.json.internal.unmarshall.AwsJsonErrorMessageParser;
import software.amazon.awssdk.protocols.json.internal.unmarshall.ErrorMessageParser;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.utils.StringInputStream;
public class AwsJsonErrorMessageParserTest {
private static final String X_AMZN_ERROR_MESSAGE = "x-amzn-error-message";
private static final ErrorMessageParser parser = AwsJsonErrorMessageParser.DEFAULT_ERROR_MESSAGE_PARSER;
private static final String MESSAGE_CONTENT = "boom";
private SdkHttpFullResponse.Builder responseBuilder;
private JsonNodeParser jsonParser;
@BeforeEach
public void setup() {
jsonParser = JsonNode.parser();
responseBuilder = ValidSdkObjects.sdkHttpFullResponse();
}
@Test
public void testErrorMessageAt_message() {
JsonNode jsonNode = parseJson("message", MESSAGE_CONTENT);
String parsed = parser.parseErrorMessage(responseBuilder.build(), jsonNode);
assertEquals(MESSAGE_CONTENT, parsed);
}
private JsonNode parseJson(String fieldName, String value) {
return jsonParser.parse(new StringInputStream(String.format("{\"%s\": \"%s\"}", fieldName, value)));
}
private JsonNode parseJson(String json) {
return jsonParser.parse(new StringInputStream(json));
}
@Test
public void testErrorMessageAt_Message() {
JsonNode jsonNode = parseJson("Message", MESSAGE_CONTENT);
String parsed = parser.parseErrorMessage(responseBuilder.build(), jsonNode);
assertEquals(MESSAGE_CONTENT, parsed);
}
@Test
public void testErrorMessageAt_errorMessage() {
JsonNode jsonNode = parseJson("errorMessage", MESSAGE_CONTENT);
String parsed = parser.parseErrorMessage(responseBuilder.build(), jsonNode);
assertEquals(MESSAGE_CONTENT, parsed);
}
@Test
public void testNoErrorMessage_ReturnsNull() {
String parsed = parser.parseErrorMessage(responseBuilder.build(), parseJson("{}"));
assertNull(parsed);
}
@Test
public void testErrorMessageIsNumber_ReturnsStringValue() {
JsonNode jsonNode = parseJson("{\"message\": 1}");
String parsed = parser.parseErrorMessage(responseBuilder.build(), jsonNode);
assertEquals("1", parsed);
}
@Test
public void testErrorMessageIsObject_ReturnsNull() {
JsonNode jsonNode = parseJson("{\"message\": {\"foo\": \"bar\"}}");
String parsed = parser.parseErrorMessage(responseBuilder.build(), jsonNode);
assertNull(parsed);
}
@Test
public void testErrorMessageAtMultipleLocations_ReturnsLowerMessage() {
String randomStuff = UUID.randomUUID().toString();
String json = String.format("{"
+ " \"%s\": \"%s\","
+ " \"%s\": \"%s\","
+ " \"%s\": \"%s\""
+ "}", "message", MESSAGE_CONTENT,
"Message", randomStuff,
"errorMessage", randomStuff);
String parsed = parser.parseErrorMessage(responseBuilder.build(), parseJson(json));
assertEquals(MESSAGE_CONTENT, parsed);
}
@Test
public void errorMessageInHeader_ReturnsHeaderValue() {
responseBuilder.putHeader(X_AMZN_ERROR_MESSAGE, MESSAGE_CONTENT);
String parsed = parser.parseErrorMessage(responseBuilder.build(), parseJson("{}"));
assertEquals(MESSAGE_CONTENT, parsed);
}
@Test
public void errorMessageInHeader_ReturnsHeaderValue_CaseInsensitive() {
responseBuilder.putHeader("x-AMZN-error-message", MESSAGE_CONTENT);
String parsed = parser.parseErrorMessage(responseBuilder.build(), parseJson("{}"));
assertEquals(MESSAGE_CONTENT, parsed);
}
@Test
public void errorMessageInHeader_TakesPrecedenceOverMessageInBody() {
responseBuilder.putHeader(X_AMZN_ERROR_MESSAGE, MESSAGE_CONTENT);
JsonNode jsonNode = parseJson("message", "other message in body");
String parsed = parser.parseErrorMessage(responseBuilder.build(), jsonNode);
assertEquals(MESSAGE_CONTENT, parsed);
}
}
| 2,169 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/ValidSdkObjects.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import java.net.URI;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpMethod;
/**
* A collection of objects (or object builder) pre-populated with all required fields. This allows tests to focus on what data
* they care about, not necessarily what data is required.
*/
public final class ValidSdkObjects {
private ValidSdkObjects() {}
public static SdkHttpFullRequest.Builder sdkHttpFullRequest() {
return SdkHttpFullRequest.builder()
.uri(URI.create("http://test.com:80"))
.method(SdkHttpMethod.GET);
}
public static SdkHttpFullResponse.Builder sdkHttpFullResponse() {
return SdkHttpFullResponse.builder()
.statusCode(200);
}
}
| 2,170 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/FaultStatusCodeMappingTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.core.ExceptionMetadata;
import software.amazon.awssdk.protocols.json.internal.unmarshall.AwsJsonProtocolErrorUnmarshaller;
import software.amazon.awssdk.protocols.json.internal.unmarshall.JsonProtocolUnmarshaller;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
public class FaultStatusCodeMappingTest {
@ParameterizedTest
@MethodSource("unmarshal_faultValue_testCases")
public void unmarshal_faultValue_useCorrectly(TestCase tc) {
AwsJsonProtocolErrorUnmarshaller unmarshaller = makeUnmarshaller(
Arrays.asList(ExceptionMetadata.builder()
.errorCode("ServiceException")
.httpStatusCode(tc.metadataStatusCode)
.exceptionBuilderSupplier(AwsServiceException::builder)
.build()), false);
SdkHttpFullResponse.Builder responseBuilder =
SdkHttpFullResponse
.builder()
.content(errorContent("ServiceException"))
.putHeader("x-amzn-query-error", "actualErrorCode;Sender");
if (tc.httpStatusCode != null) {
responseBuilder.statusCode(tc.httpStatusCode);
}
AwsServiceException exception = unmarshaller.handle(responseBuilder.build(), new ExecutionAttributes());
assertThat(exception.statusCode()).isEqualTo(tc.expectedStatusCode);
assertThat(exception.awsErrorDetails().errorCode()).isEqualTo("ServiceException");
}
@ParameterizedTest
@MethodSource("x_amzn_query_error_testCases")
public void unmarshal_faultValue_useCorrectly_awsQueryCompatible(QueryErrorTestCase tc) {
AwsJsonProtocolErrorUnmarshaller unmarshaller = makeUnmarshaller(
Arrays.asList(ExceptionMetadata.builder()
.errorCode("ServiceException")
.exceptionBuilderSupplier(AwsServiceException::builder)
.build()), tc.hasAwsQueryCompatible);
SdkHttpFullResponse.Builder responseBuilder =
SdkHttpFullResponse
.builder()
.content(errorContent("ServiceException"))
.putHeader("x-amzn-query-error", tc.queryErrorHeader);
AwsServiceException exception = unmarshaller.handle(responseBuilder.build(), new ExecutionAttributes());
assertThat(exception.awsErrorDetails().errorCode()).isEqualTo(tc.expectedErrorCode);
}
public static List<TestCase> unmarshal_faultValue_testCases() {
return Arrays.asList(
new TestCase(null, null, 500),
new TestCase(null, 1, 1),
new TestCase(2, null, 2),
new TestCase(2, 1, 2)
);
}
public static List<QueryErrorTestCase> x_amzn_query_error_testCases() {
return Arrays.asList(
new QueryErrorTestCase(true, "customErrorCode;Sender", "customErrorCode"),
new QueryErrorTestCase(true, "customError CodeSender", "ServiceException"),
new QueryErrorTestCase(true, "customError", "ServiceException"),
new QueryErrorTestCase(true, ";Sender", "ServiceException"),
new QueryErrorTestCase(true, null, "ServiceException"),
new QueryErrorTestCase(true, "", "ServiceException"),
new QueryErrorTestCase(false, "customErrorCode;Sender", "ServiceException")
);
}
private static AwsJsonProtocolErrorUnmarshaller makeUnmarshaller(List<ExceptionMetadata> exceptionMetadata,
boolean hasAwsQueryCompatible) {
return AwsJsonProtocolErrorUnmarshaller.builder()
.exceptions(exceptionMetadata)
.jsonProtocolUnmarshaller(JsonProtocolUnmarshaller.builder()
.defaultTimestampFormats(Collections.emptyMap())
.build())
.jsonFactory(new JsonFactory())
.errorMessageParser((resp, content) -> "Some server error")
.errorCodeParser((resp, content) ->
content.getJsonNode().asObject().get("errorCode").asString())
.hasAwsQueryCompatible(hasAwsQueryCompatible)
.build();
}
private static AbortableInputStream errorContent(String code) {
String json = String.format("{\"errorCode\":\"%s\"}", code);
return contentAsStream(json);
}
private static AbortableInputStream contentAsStream(String content) {
return AbortableInputStream.create(SdkBytes.fromUtf8String(content).asInputStream());
}
private static class TestCase {
private final Integer httpStatusCode;
private final Integer metadataStatusCode;
private final int expectedStatusCode;
public TestCase(Integer httpStatusCode, Integer metadataStatusCode, int expectedStatusCode) {
this.httpStatusCode = httpStatusCode;
this.metadataStatusCode = metadataStatusCode;
this.expectedStatusCode = expectedStatusCode;
}
}
private static class QueryErrorTestCase {
private final boolean hasAwsQueryCompatible;
private final String queryErrorHeader;
private final String expectedErrorCode;
public QueryErrorTestCase(boolean hasAwsQueryCompatible, String queryErrorHeader, String expectedErrorCode) {
this.hasAwsQueryCompatible = hasAwsQueryCompatible;
this.queryErrorHeader = queryErrorHeader;
this.expectedErrorCode = expectedErrorCode;
}
}
}
| 2,171 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/internal/dom/DocumentUnmarshallerTest.java | package software.amazon.awssdk.protocols.json.internal.dom;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkNumber;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.protocols.json.internal.unmarshall.document.DocumentUnmarshaller;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.EmbeddedObjectJsonNode;
public class DocumentUnmarshallerTest {
@Test
public void testDocumentFromNumberNode() throws ParseException {
JsonNode node = JsonNode.parser().parse("100");
assertThat(Document.fromNumber(SdkNumber.fromInteger(100)).asNumber().intValue())
.isEqualTo(node.visit(new DocumentUnmarshaller()).asNumber().intValue());
}
@Test
public void testDocumentFromBoolean() {
JsonNode node = JsonNode.parser().parse("true");
assertThat(Document.fromBoolean(true)).isEqualTo(node.visit(new DocumentUnmarshaller()));
}
@Test
public void testDocumentFromString() {
JsonNode node = JsonNode.parser().parse("\"100.00\"");
assertThat(Document.fromString("100.00")).isEqualTo(node.visit(new DocumentUnmarshaller()));
}
@Test
public void testDocumentFromNull() {
JsonNode node = JsonNode.parser().parse("null");
assertThat(Document.fromNull()).isEqualTo(node.visit(new DocumentUnmarshaller()));
}
@Test
public void testExceptionIsThrownFromEmbededObjectType() {
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(() -> new EmbeddedObjectJsonNode(new Object()).visit(new DocumentUnmarshaller()));
}
@Test
public void testDocumentFromObjectNode(){
JsonNode node = JsonNode.parser().parse("{\"firstKey\": \"firstValue\", \"secondKey\": \"secondValue\"}");
Document documentMap = node.visit(new DocumentUnmarshaller());
Map<String, Document> expectedMap = new LinkedHashMap<>();
expectedMap.put("firstKey", Document.fromString("firstValue"));
expectedMap.put("secondKey", Document.fromString("secondValue"));
final Document expectedDocumentMap = Document.fromMap(expectedMap);
assertThat(documentMap).isEqualTo(expectedDocumentMap);
}
@Test
public void testDocumentFromArrayNode(){
JsonNode node = JsonNode.parser().parse("[\"One\", 10, true, null]");
List<Document> documentList = new ArrayList<>();
documentList.add(Document.fromString("One"));
documentList.add(Document.fromNumber(SdkNumber.fromBigDecimal(BigDecimal.TEN)));
documentList.add(Document.fromBoolean(true));
documentList.add(Document.fromNull());
final Document document = Document.fromList(documentList);
final Document actualDocument = node.visit(new DocumentUnmarshaller());
assertThat(actualDocument).isEqualTo(document);
}
}
| 2,172 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/ErrorCodeParser.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.http.SdkHttpFullResponse;
/**
* Error code parser to parse error code from the response returned by AWS services.
*/
@SdkProtectedApi
public interface ErrorCodeParser {
String parseErrorCode(SdkHttpFullResponse response, JsonContent jsonContent);
}
| 2,173 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/StructuredJsonGenerator.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.time.Instant;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Interface for generating a JSON
*/
@SdkProtectedApi
public interface StructuredJsonGenerator {
/**
* No-op implementation that ignores all calls and returns empty bytes from getBytes.
*/
StructuredJsonGenerator NO_OP = new StructuredJsonGenerator() {
@Override
public StructuredJsonGenerator writeStartArray() {
return this;
}
@Override
public StructuredJsonGenerator writeEndArray() {
return this;
}
@Override
public StructuredJsonGenerator writeNull() {
return this;
}
@Override
public StructuredJsonGenerator writeStartObject() {
return this;
}
@Override
public StructuredJsonGenerator writeEndObject() {
return this;
}
@Override
public StructuredJsonGenerator writeFieldName(String fieldName) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(String val) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(boolean bool) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(long val) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(double val) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(float val) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(short val) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(int val) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(ByteBuffer bytes) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(Instant instant) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(BigDecimal value) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(BigInteger value) {
return this;
}
@Override
public StructuredJsonGenerator writeNumber(String number) {
return this;
}
@Override
public byte[] getBytes() {
return null;
}
@Override
public String getContentType() {
return null;
}
};
StructuredJsonGenerator writeStartArray();
StructuredJsonGenerator writeEndArray();
StructuredJsonGenerator writeNull();
StructuredJsonGenerator writeStartObject();
StructuredJsonGenerator writeEndObject();
StructuredJsonGenerator writeFieldName(String fieldName);
StructuredJsonGenerator writeValue(String val);
StructuredJsonGenerator writeValue(boolean bool);
StructuredJsonGenerator writeValue(long val);
StructuredJsonGenerator writeValue(double val);
StructuredJsonGenerator writeValue(float val);
StructuredJsonGenerator writeValue(short val);
StructuredJsonGenerator writeValue(int val);
StructuredJsonGenerator writeValue(ByteBuffer bytes);
StructuredJsonGenerator writeValue(Instant instant);
StructuredJsonGenerator writeNumber(String number);
StructuredJsonGenerator writeValue(BigDecimal value);
StructuredJsonGenerator writeValue(BigInteger value);
byte[] getBytes();
/**
* New clients use {@link SdkJsonProtocolFactory#getContentType()}.
*/
@Deprecated
String getContentType();
}
| 2,174 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/JsonContentTypeResolver.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Interface to compute the content type to send in requests for JSON based protocols.
*/
@SdkProtectedApi
public interface JsonContentTypeResolver {
/**
* Computes content type to send in requests.
*
* @param protocolMetadata Metadata about the protocol.
* @return Correct content type to send in request based on metadata about the client.
*/
String resolveContentType(AwsJsonProtocolMetadata protocolMetadata);
}
| 2,175 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/AwsJsonProtocol.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Supported protocols for the new marshalling style. Currently only includes JSON based services.
*/
@SdkProtectedApi
public enum AwsJsonProtocol {
/**
* RPC protocol that sends all data in the payload as JSON and sends the X-Amz-Target header to indicate the
* operation to invoke.
*/
AWS_JSON,
/**
* Protocol that supports RESTful bindings. Members can be bound to the headers, query params, path, or payload. Supports
* binary and streaming data. Operation is identified by HTTP verb and resource path combination.
*/
REST_JSON,
}
| 2,176 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/StructuredJsonFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
/**
* Common interface for creating generators (writers) and protocol handlers for JSON like protocols.
*/
@SdkProtectedApi
public interface StructuredJsonFactory {
/**
* Returns the {@link StructuredJsonGenerator} to be used for marshalling the request.
*
* @param contentType Content type to send for requests.
*/
StructuredJsonGenerator createWriter(String contentType);
JsonFactory getJsonFactory();
ErrorCodeParser getErrorCodeParser(String customErrorCodeFieldName);
}
| 2,177 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/SdkJsonGenerator.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.time.Instant;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.thirdparty.jackson.core.JsonGenerator;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.DateUtils;
/**
* Thin wrapper around Jackson's JSON generator.
*/
@SdkProtectedApi
public class SdkJsonGenerator implements StructuredJsonGenerator {
/**
* Default buffer size for the BAOS. Chosen somewhat arbitrarily. Should be large enough to
* prevent frequent resizings but small enough to avoid wasted allocations for small requests.
*/
private static final int DEFAULT_BUFFER_SIZE = 1024;
private final ByteArrayOutputStream baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
private final JsonGenerator generator;
private final String contentType;
public SdkJsonGenerator(JsonFactory factory, String contentType) {
try {
/**
* A {@link JsonGenerator} created is by default enabled with
* UTF-8 encoding
*/
this.generator = factory.createGenerator(baos);
this.contentType = contentType;
} catch (IOException e) {
throw new JsonGenerationException(e);
}
}
@Override
public StructuredJsonGenerator writeStartArray() {
try {
generator.writeStartArray();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeEndArray() {
try {
generator.writeEndArray();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeNull() {
try {
generator.writeNull();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeStartObject() {
try {
generator.writeStartObject();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeEndObject() {
try {
generator.writeEndObject();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeFieldName(String fieldName) {
try {
generator.writeFieldName(fieldName);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(String val) {
try {
generator.writeString(val);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(boolean bool) {
try {
generator.writeBoolean(bool);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(long val) {
try {
generator.writeNumber(val);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(double val) {
try {
generator.writeNumber(val);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(float val) {
try {
generator.writeNumber(val);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(short val) {
try {
generator.writeNumber(val);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(int val) {
try {
generator.writeNumber(val);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(ByteBuffer bytes) {
try {
generator.writeBinary(BinaryUtils.copyBytesFrom(bytes));
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
//TODO: This date formatting is coupled to AWS's format. Should generalize it
public StructuredJsonGenerator writeValue(Instant instant) {
try {
generator.writeNumber(DateUtils.formatUnixTimestampInstant(instant));
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(BigDecimal value) {
try {
/**
* Note that this is not how the backend represents BigDecimal types. On the wire
* it's normally a JSON number but this causes problems with certain JSON implementations
* that parse JSON numbers as floating points automatically. (See API-433)
*/
generator.writeString(value.toString());
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(BigInteger value) {
try {
generator.writeNumber(value);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeNumber(String number) {
try {
generator.writeNumber(number);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
/**
* Closes the generator and flushes to write. Must be called when finished writing JSON
* content.
*/
private void close() {
try {
generator.close();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
}
/**
* Get the JSON content as a UTF-8 encoded byte array. It is recommended to hold onto the array
* reference rather then making repeated calls to this method as a new array will be created
* each time.
*
* @return Array of UTF-8 encoded bytes that make up the generated JSON.
*/
@Override
public byte[] getBytes() {
close();
return baos.toByteArray();
}
@Override
public String getContentType() {
return contentType;
}
protected JsonGenerator getGenerator() {
return generator;
}
/**
* Indicates an issue writing JSON content.
*/
public static class JsonGenerationException extends SdkClientException {
public JsonGenerationException(Throwable t) {
super(SdkClientException.builder().cause(t));
}
}
}
| 2,178 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/JsonOperationMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.protocols.json.internal.unmarshall.JsonResponseHandler;
/**
* Contains various information needed to create a {@link JsonResponseHandler}
* for the client.
*/
@SdkProtectedApi
public final class JsonOperationMetadata {
private final boolean hasStreamingSuccessResponse;
private final boolean isPayloadJson;
private JsonOperationMetadata(Builder builder) {
this.hasStreamingSuccessResponse = builder.hasStreamingSuccessResponse;
this.isPayloadJson = builder.isPayloadJson;
}
public boolean hasStreamingSuccessResponse() {
return hasStreamingSuccessResponse;
}
public boolean isPayloadJson() {
return isPayloadJson;
}
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link JsonOperationMetadata}.
*/
public static final class Builder {
private boolean hasStreamingSuccessResponse;
private boolean isPayloadJson;
private Builder() {
}
/**
* True is payload contains JSON content, false if it doesn't (i.e. it contains binary content or no content).
*
* @return This builder for method chaining.
*/
public Builder isPayloadJson(boolean payloadJson) {
isPayloadJson = payloadJson;
return this;
}
/**
* True if the success response (2xx response) contains a payload that should be treated as streaming. False otherwise.
*
* @return This builder for method chaining.
*/
public Builder hasStreamingSuccessResponse(boolean hasStreamingSuccessResponse) {
this.hasStreamingSuccessResponse = hasStreamingSuccessResponse;
return this;
}
public JsonOperationMetadata build() {
return new JsonOperationMetadata(this);
}
}
}
| 2,179 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/BaseAwsJsonProtocolFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import static java.util.Collections.unmodifiableList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.http.MetricCollectingHttpResponseHandler;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.traits.TimestampFormatTrait;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.core.ExceptionMetadata;
import software.amazon.awssdk.protocols.core.OperationInfo;
import software.amazon.awssdk.protocols.core.ProtocolMarshaller;
import software.amazon.awssdk.protocols.json.internal.AwsStructuredPlainJsonFactory;
import software.amazon.awssdk.protocols.json.internal.marshall.JsonProtocolMarshallerBuilder;
import software.amazon.awssdk.protocols.json.internal.unmarshall.AwsJsonErrorMessageParser;
import software.amazon.awssdk.protocols.json.internal.unmarshall.AwsJsonProtocolErrorUnmarshaller;
import software.amazon.awssdk.protocols.json.internal.unmarshall.AwsJsonResponseHandler;
import software.amazon.awssdk.protocols.json.internal.unmarshall.JsonProtocolUnmarshaller;
import software.amazon.awssdk.protocols.json.internal.unmarshall.JsonResponseHandler;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
@SdkProtectedApi
public abstract class BaseAwsJsonProtocolFactory {
/**
* Content type resolver implementation for plain text AWS_JSON services.
*/
protected static final JsonContentTypeResolver AWS_JSON = new DefaultJsonContentTypeResolver("application/x-amz-json-");
private final AwsJsonProtocolMetadata protocolMetadata;
private final List<ExceptionMetadata> modeledExceptions;
private final Supplier<SdkPojo> defaultServiceExceptionSupplier;
private final String customErrorCodeFieldName;
private final boolean hasAwsQueryCompatible;
private final SdkClientConfiguration clientConfiguration;
private final JsonProtocolUnmarshaller protocolUnmarshaller;
protected BaseAwsJsonProtocolFactory(Builder<?> builder) {
this.protocolMetadata = builder.protocolMetadata.build();
this.modeledExceptions = unmodifiableList(builder.modeledExceptions);
this.defaultServiceExceptionSupplier = builder.defaultServiceExceptionSupplier;
this.customErrorCodeFieldName = builder.customErrorCodeFieldName;
this.hasAwsQueryCompatible = builder.hasAwsQueryCompatible;
this.clientConfiguration = builder.clientConfiguration;
this.protocolUnmarshaller = JsonProtocolUnmarshaller
.builder()
.parser(JsonNodeParser.builder()
.jsonFactory(getSdkFactory().getJsonFactory())
.build())
.defaultTimestampFormats(getDefaultTimestampFormats())
.build();
}
/**
* Creates a new response handler with the given {@link JsonOperationMetadata} and a supplier of the POJO response
* type.
*
* @param operationMetadata Metadata about operation being unmarshalled.
* @param pojoSupplier {@link Supplier} of the POJO response type.
* @param <T> Type being unmarshalled.
* @return HttpResponseHandler that will handle the HTTP response and unmarshall into a POJO.
*/
public final <T extends SdkPojo> HttpResponseHandler<T> createResponseHandler(JsonOperationMetadata operationMetadata,
Supplier<SdkPojo> pojoSupplier) {
return createResponseHandler(operationMetadata, r -> pojoSupplier.get());
}
/**
* Creates a new response handler with the given {@link JsonOperationMetadata} and a supplier of the POJO response
* type.
*
* @param operationMetadata Metadata about operation being unmarshalled.
* @param pojoSupplier {@link Supplier} of the POJO response type. Has access to the HTTP response, primarily for polymorphic
* deserialization as seen in event stream (i.e. unmarshalled event depends on ':event-type' header).
* @param <T> Type being unmarshalled.
* @return HttpResponseHandler that will handle the HTTP response and unmarshall into a POJO.
*/
public final <T extends SdkPojo> HttpResponseHandler<T> createResponseHandler(
JsonOperationMetadata operationMetadata,
Function<SdkHttpFullResponse, SdkPojo> pojoSupplier) {
return timeUnmarshalling(
new AwsJsonResponseHandler<>(
new JsonResponseHandler<>(protocolUnmarshaller,
pojoSupplier,
operationMetadata.hasStreamingSuccessResponse(),
operationMetadata.isPayloadJson())));
}
/**
* Creates a response handler for handling a error response (non 2xx response).
*/
public final HttpResponseHandler<AwsServiceException> createErrorResponseHandler(
JsonOperationMetadata errorResponseMetadata) {
return timeUnmarshalling(AwsJsonProtocolErrorUnmarshaller
.builder()
.jsonProtocolUnmarshaller(protocolUnmarshaller)
.exceptions(modeledExceptions)
.errorCodeParser(getSdkFactory().getErrorCodeParser(customErrorCodeFieldName))
.hasAwsQueryCompatible(hasAwsQueryCompatible)
.errorMessageParser(AwsJsonErrorMessageParser.DEFAULT_ERROR_MESSAGE_PARSER)
.jsonFactory(getSdkFactory().getJsonFactory())
.defaultExceptionSupplier(defaultServiceExceptionSupplier)
.build());
}
private <T> MetricCollectingHttpResponseHandler<T> timeUnmarshalling(HttpResponseHandler<T> delegate) {
return MetricCollectingHttpResponseHandler.create(CoreMetric.UNMARSHALLING_DURATION, delegate);
}
private StructuredJsonGenerator createGenerator(OperationInfo operationInfo) {
if (operationInfo.hasPayloadMembers() || protocolMetadata.protocol() == AwsJsonProtocol.AWS_JSON) {
return createGenerator();
} else {
return StructuredJsonGenerator.NO_OP;
}
}
@SdkTestInternalApi
private StructuredJsonGenerator createGenerator() {
return getSdkFactory().createWriter(getContentType());
}
@SdkTestInternalApi
public final String getContentType() {
return protocolMetadata.contentType() != null ? protocolMetadata.contentType()
: getContentTypeResolver().resolveContentType(protocolMetadata);
}
/**
* @return Content type resolver implementation to use.
*/
protected JsonContentTypeResolver getContentTypeResolver() {
return AWS_JSON;
}
/**
* @return Instance of {@link StructuredJsonFactory} to use in creating handlers.
*/
protected StructuredJsonFactory getSdkFactory() {
return AwsStructuredPlainJsonFactory.SDK_JSON_FACTORY;
}
/**
* @return The default timestamp format for unmarshalling for each location in the response. This
* can be overridden by subclasses to customize behavior.
*/
protected Map<MarshallLocation, TimestampFormatTrait.Format> getDefaultTimestampFormats() {
Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class);
formats.put(MarshallLocation.HEADER, TimestampFormatTrait.Format.RFC_822);
formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.UNIX_TIMESTAMP);
return Collections.unmodifiableMap(formats);
}
public final ProtocolMarshaller<SdkHttpFullRequest> createProtocolMarshaller(OperationInfo operationInfo) {
return JsonProtocolMarshallerBuilder.create()
.endpoint(clientConfiguration.option(SdkClientOption.ENDPOINT))
.jsonGenerator(createGenerator(operationInfo))
.contentType(getContentType())
.operationInfo(operationInfo)
.sendExplicitNullForPayload(false)
.protocolMetadata(protocolMetadata)
.build();
}
/**
* Builder for {@link AwsJsonProtocolFactory}.
*/
public abstract static class Builder<SubclassT extends Builder> {
private final AwsJsonProtocolMetadata.Builder protocolMetadata = AwsJsonProtocolMetadata.builder();
private final List<ExceptionMetadata> modeledExceptions = new ArrayList<>();
private Supplier<SdkPojo> defaultServiceExceptionSupplier;
private String customErrorCodeFieldName;
private SdkClientConfiguration clientConfiguration;
private boolean hasAwsQueryCompatible;
protected Builder() {
}
/**
* Registers a new modeled exception by the error code.
*
* @param errorMetadata Metadata to unmarshall the modeled exception.
* @return This builder for method chaining.
*/
public final SubclassT registerModeledException(ExceptionMetadata errorMetadata) {
modeledExceptions.add(errorMetadata);
return getSubclass();
}
/**
* A supplier for the services base exception builder. This is used when we can't identify any modeled
* exception to unmarshall into.
*
* @param exceptionBuilderSupplier Suppplier of the base service exceptions Builder.
* @return This builder for method chaining.
*/
public final SubclassT defaultServiceExceptionSupplier(Supplier<SdkPojo> exceptionBuilderSupplier) {
this.defaultServiceExceptionSupplier = exceptionBuilderSupplier;
return getSubclass();
}
/**
* @param protocol Protocol of the client (i.e. REST or RPC).
* @return This builder for method chaining.
*/
public final SubclassT protocol(AwsJsonProtocol protocol) {
protocolMetadata.protocol(protocol);
return getSubclass();
}
/**
* Protocol version of the client (right now supports JSON 1.0 and JSON 1.1). Used to determine content type.
*
* @param protocolVersion JSON protocol version.
* @return This builder for method chaining.
*/
public final SubclassT protocolVersion(String protocolVersion) {
protocolMetadata.protocolVersion(protocolVersion);
return getSubclass();
}
/**
* ContentType of the client (By default it is used from {@link #AWS_JSON} ).
* Used to determine content type.
*
* @param contentType JSON protocol contentType.
* @return This builder for method chaining.
*/
public final SubclassT contentType(String contentType) {
protocolMetadata.contentType(contentType);
return getSubclass();
}
/**
* Custom field name containing the error code that identifies the exception. Currently only used by Glacier
* which uses the "code" field instead of the traditional "__type".
*
* @param customErrorCodeFieldName Custom field name to look for error code.
* @return This builder for method chaining.
*/
public final SubclassT customErrorCodeFieldName(String customErrorCodeFieldName) {
this.customErrorCodeFieldName = customErrorCodeFieldName;
return getSubclass();
}
/**
* Sets the {@link SdkClientConfiguration} which contains the service endpoint.
*
* @param clientConfiguration Configuration of the client.
* @return This builder for method chaining.
*/
public final SubclassT clientConfiguration(SdkClientConfiguration clientConfiguration) {
this.clientConfiguration = clientConfiguration;
return getSubclass();
}
/**
* Provides a check on whether AwsQueryCompatible trait is found in Metadata.
* If true, custom error codes can be provided
*
* @param hasAwsQueryCompatible boolean of whether the AwsQueryCompatible trait is found
* @return This builder for method chaining.
*/
public final SubclassT hasAwsQueryCompatible(boolean hasAwsQueryCompatible) {
this.hasAwsQueryCompatible = hasAwsQueryCompatible;
return getSubclass();
}
@SuppressWarnings("unchecked")
private SubclassT getSubclass() {
return (SubclassT) this;
}
}
}
| 2,180 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/AwsJsonProtocolFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.ThreadSafe;
/**
* Factory to generate the various JSON protocol handlers and generators to be used for
* communicating with the service.
*/
@ThreadSafe
@SdkProtectedApi
public final class AwsJsonProtocolFactory extends BaseAwsJsonProtocolFactory {
protected AwsJsonProtocolFactory(Builder builder) {
super(builder);
}
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link AwsJsonProtocolFactory}.
*/
public static final class Builder extends BaseAwsJsonProtocolFactory.Builder<Builder> {
private Builder() {
}
public AwsJsonProtocolFactory build() {
return new AwsJsonProtocolFactory(this);
}
}
}
| 2,181 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/AwsJsonProtocolMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Provides additional metadata about AWS Json protocol.
*/
@SdkProtectedApi
public final class AwsJsonProtocolMetadata {
private final AwsJsonProtocol protocol;
private final String protocolVersion;
private final String contentType;
private AwsJsonProtocolMetadata(Builder builder) {
this.protocol = builder.protocol;
this.protocolVersion = builder.protocolVersion;
this.contentType = builder.contentType;
}
/**
* @return the protocol
*/
public AwsJsonProtocol protocol() {
return protocol;
}
/**
* @return the protocol version
*/
public String protocolVersion() {
return protocolVersion;
}
public static Builder builder() {
return new AwsJsonProtocolMetadata.Builder();
}
/**
*
* @return the content Type.
*/
public String contentType() {
return contentType;
}
public static final class Builder {
private AwsJsonProtocol protocol;
private String protocolVersion;
private String contentType;
private Builder() {
}
public Builder protocol(AwsJsonProtocol protocol) {
this.protocol = protocol;
return this;
}
public Builder protocolVersion(String protocolVersion) {
this.protocolVersion = protocolVersion;
return this;
}
public Builder contentType(String contentType) {
this.contentType = contentType;
return this;
}
public AwsJsonProtocolMetadata build() {
return new AwsJsonProtocolMetadata(this);
}
}
}
| 2,182 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/DefaultJsonContentTypeResolver.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Prefers an explicit content type if provided. Otherwise computes the correct content type based
* on the wire format used and the version of the protocol.
*/
@SdkProtectedApi
public class DefaultJsonContentTypeResolver implements JsonContentTypeResolver {
private static final String REST_JSON_CONTENT_TYPE = "application/json";
private final String prefix;
public DefaultJsonContentTypeResolver(String prefix) {
this.prefix = prefix;
}
@Override
public String resolveContentType(AwsJsonProtocolMetadata protocolMetadata) {
if (AwsJsonProtocol.REST_JSON.equals(protocolMetadata.protocol())) {
return REST_JSON_CONTENT_TYPE;
}
return prefix + protocolMetadata.protocolVersion();
}
}
| 2,183 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/JsonContent.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.utils.IoUtils;
/**
* Simple struct like class to hold both the raw json string content and it's parsed JsonNode
*/
@SdkProtectedApi
//TODO Do we need this? It isn't well encapsulated because of storing non-copied arrays.
public class JsonContent {
private static final Logger LOG = LoggerFactory.getLogger(JsonContent.class);
private final byte[] rawContent;
private final JsonNode jsonNode;
JsonContent(byte[] rawJsonContent, JsonNode jsonNode) {
this.rawContent = rawJsonContent;
this.jsonNode = jsonNode;
}
private JsonContent(byte[] rawJsonContent, JsonFactory jsonFactory) {
this.rawContent = rawJsonContent;
this.jsonNode = parseJsonContent(rawJsonContent, jsonFactory);
}
/**
* Static factory method to create a JsonContent object from the contents of the HttpResponse
* provided
*/
public static JsonContent createJsonContent(SdkHttpFullResponse httpResponse,
JsonFactory jsonFactory) {
byte[] rawJsonContent = httpResponse.content().map(c -> {
try {
return IoUtils.toByteArray(c);
} catch (IOException e) {
LOG.debug("Unable to read HTTP response content", e);
}
return null;
}).orElse(null);
return new JsonContent(rawJsonContent, jsonFactory);
}
private static JsonNode parseJsonContent(byte[] rawJsonContent, JsonFactory jsonFactory) {
if (rawJsonContent == null || rawJsonContent.length == 0) {
return JsonNode.emptyObjectNode();
}
try {
JsonNodeParser parser = JsonNodeParser.builder().jsonFactory(jsonFactory).build();
return parser.parse(rawJsonContent);
} catch (Exception e) {
LOG.debug("Unable to parse HTTP response content", e);
return JsonNode.emptyObjectNode();
}
}
public byte[] getRawContent() {
return rawContent;
}
public JsonNode getJsonNode() {
return jsonNode;
}
}
| 2,184 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/BaseAwsStructuredJsonFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.protocols.json.internal.unmarshall.JsonErrorCodeParser;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
/**
* Generic implementation of a structured JSON factory that is pluggable for different variants of
* JSON.
*/
@SdkProtectedApi
public abstract class BaseAwsStructuredJsonFactory implements StructuredJsonFactory {
private final JsonFactory jsonFactory;
protected BaseAwsStructuredJsonFactory(JsonFactory jsonFactory) {
this.jsonFactory = jsonFactory;
}
@Override
public StructuredJsonGenerator createWriter(String contentType) {
return createWriter(jsonFactory, contentType);
}
protected abstract StructuredJsonGenerator createWriter(JsonFactory jsonFactory,
String contentType);
@Override
public ErrorCodeParser getErrorCodeParser(String customErrorCodeFieldName) {
return new JsonErrorCodeParser(customErrorCodeFieldName);
}
}
| 2,185 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/MarshallerUtil.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.protocol.MarshallLocation;
@SdkInternalApi
public final class MarshallerUtil {
private MarshallerUtil() {
}
/**
* @return true if the location is in the URI, false otherwise.
*/
public static boolean isInUri(MarshallLocation location) {
switch (location) {
case PATH:
case QUERY_PARAM:
return true;
default:
return false;
}
}
}
| 2,186 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/AwsStructuredPlainJsonFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.json.BaseAwsStructuredJsonFactory;
import software.amazon.awssdk.protocols.json.SdkJsonGenerator;
import software.amazon.awssdk.protocols.json.StructuredJsonGenerator;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
/**
* Creates generators and protocol handlers for plain text JSON wire format.
*/
@SdkInternalApi
public final class AwsStructuredPlainJsonFactory {
/**
* Recommended to share JsonFactory instances per http://wiki.fasterxml
* .com/JacksonBestPracticesPerformance
*/
private static final JsonFactory JSON_FACTORY = new JsonFactory();
public static final BaseAwsStructuredJsonFactory SDK_JSON_FACTORY = new BaseAwsStructuredJsonFactory(JSON_FACTORY) {
@Override
protected StructuredJsonGenerator createWriter(JsonFactory jsonFactory,
String contentType) {
return new SdkJsonGenerator(jsonFactory, contentType);
}
@Override
public JsonFactory getJsonFactory() {
return JsonNodeParser.DEFAULT_JSON_FACTORY;
}
};
protected AwsStructuredPlainJsonFactory() {
}
}
| 2,187 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/JsonErrorCodeParser.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.json.ErrorCodeParser;
import software.amazon.awssdk.protocols.json.JsonContent;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
@SdkInternalApi
public class JsonErrorCodeParser implements ErrorCodeParser {
/**
* Services using AWS JSON 1.1 protocol with HTTP binding send the error code information in the
* response headers, instead of the content. Package private for tests.
*/
public static final String X_AMZN_ERROR_TYPE = "x-amzn-ErrorType";
static final String ERROR_CODE_HEADER = ":error-code";
static final String EXCEPTION_TYPE_HEADER = ":exception-type";
private static final Logger log = LoggerFactory.getLogger(JsonErrorCodeParser.class);
/**
* List of header keys that represent the error code sent by service.
* Response should only contain one of these headers
*/
private final List<String> errorCodeHeaders;
private final String errorCodeFieldName;
public JsonErrorCodeParser(String errorCodeFieldName) {
this.errorCodeFieldName = errorCodeFieldName == null ? "__type" : errorCodeFieldName;
this.errorCodeHeaders = Arrays.asList(X_AMZN_ERROR_TYPE, ERROR_CODE_HEADER, EXCEPTION_TYPE_HEADER);
}
/**
* Parse the error code from the response.
*
* @return Error Code of exceptional response or null if it can't be determined
*/
@Override
public String parseErrorCode(SdkHttpFullResponse response, JsonContent jsonContent) {
String errorCodeFromHeader = parseErrorCodeFromHeader(response);
if (errorCodeFromHeader != null) {
return errorCodeFromHeader;
} else if (jsonContent != null) {
return parseErrorCodeFromContents(jsonContent.getJsonNode());
} else {
return null;
}
}
/**
* Attempt to parse the error code from the response headers. Returns null if information is not
* present in the header.
*/
private String parseErrorCodeFromHeader(SdkHttpFullResponse response) {
for (String errorCodeHeader : errorCodeHeaders) {
Optional<String> errorCode = response.firstMatchingHeader(errorCodeHeader);
if (errorCode.isPresent()) {
if (X_AMZN_ERROR_TYPE.equals(errorCodeHeader)) {
return parseErrorCodeFromXAmzErrorType(errorCode.get());
}
return errorCode.get();
}
}
return null;
}
private String parseErrorCodeFromXAmzErrorType(String headerValue) {
if (headerValue != null) {
int separator = headerValue.indexOf(':');
if (separator != -1) {
headerValue = headerValue.substring(0, separator);
}
}
return headerValue;
}
/**
* Attempt to parse the error code from the response content. Returns null if information is not
* present in the content. Codes are expected to be in the form <b>"typeName"</b> or
* <b>"prefix#typeName"</b> Examples : "AccessDeniedException",
* "software.amazon.awssdk.dynamodb.v20111205#ProvisionedThroughputExceededException"
*/
private String parseErrorCodeFromContents(JsonNode jsonContents) {
if (jsonContents == null) {
return null;
}
JsonNode errorCodeField = jsonContents.field(errorCodeFieldName).orElse(null);
if (errorCodeField == null) {
return null;
}
String code = errorCodeField.text();
int separator = code.lastIndexOf('#');
return code.substring(separator + 1);
}
}
| 2,188 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/AwsJsonResponseHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID;
import java.util.HashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.AwsResponse;
import software.amazon.awssdk.awscore.AwsResponseMetadata;
import software.amazon.awssdk.awscore.DefaultAwsResponseMetadata;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpResponse;
@SdkInternalApi
public final class AwsJsonResponseHandler<T> implements HttpResponseHandler<T> {
private final HttpResponseHandler<T> responseHandler;
public AwsJsonResponseHandler(HttpResponseHandler<T> responseHandler) {
this.responseHandler = responseHandler;
}
@Override
@SuppressWarnings("unchecked")
public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception {
T result = responseHandler.handle(response, executionAttributes);
// As T is not bounded to AwsResponse, we need to do explicitly cast here.
if (result instanceof AwsResponse) {
AwsResponseMetadata responseMetadata = generateResponseMetadata(response);
return (T) ((AwsResponse) result).toBuilder().responseMetadata(responseMetadata).build();
}
return result;
}
/**
* Create the default {@link AwsResponseMetadata}.
*/
private AwsResponseMetadata generateResponseMetadata(SdkHttpResponse response) {
Map<String, String> metadata = new HashMap<>();
metadata.put(AWS_REQUEST_ID, response.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADERS).orElse(null));
response.forEachHeader((key, value) -> metadata.put(key, value.get(0)));
return DefaultAwsResponseMetadata.create(metadata);
}
}
| 2,189 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/SdkJsonErrorMessageParser.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
@SdkInternalApi
public class SdkJsonErrorMessageParser implements ErrorMessageParser {
private static final List<String> DEFAULT_ERROR_MESSAGE_LOCATIONS = Arrays
.asList("message", "Message", "errorMessage");
/**
* Standard JSON Error Message Parser that checks for JSON fields in this order: 'message',
* 'Message', 'errorMessage'
*/
public static final SdkJsonErrorMessageParser DEFAULT_ERROR_MESSAGE_PARSER = new SdkJsonErrorMessageParser(
DEFAULT_ERROR_MESSAGE_LOCATIONS);
private final List<String> errorMessageJsonLocations;
/**
* @param errorMessageJsonLocations JSON field locations where the parser will attempt to
* extract the error message from.
*/
private SdkJsonErrorMessageParser(List<String> errorMessageJsonLocations) {
this.errorMessageJsonLocations = new LinkedList<>(errorMessageJsonLocations);
}
/**
* Parse the error message from the response.
*
* @return Error Code of exceptional response or null if it can't be determined
*/
@Override
public String parseErrorMessage(SdkHttpFullResponse httpResponse, JsonNode jsonNode) {
for (String field : errorMessageJsonLocations) {
String value = jsonNode.field(field).map(JsonNode::text).orElse(null);
if (value != null) {
return value;
}
}
return null;
}
}
| 2,190 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/JsonUnmarshallerRegistry.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.protocols.core.AbstractMarshallingRegistry;
/**
* Registry of {@link JsonUnmarshaller} implementations by location and type.
*/
@SdkInternalApi
final class JsonUnmarshallerRegistry extends AbstractMarshallingRegistry {
private JsonUnmarshallerRegistry(Builder builder) {
super(builder);
}
@SuppressWarnings("unchecked")
public <T> JsonUnmarshaller<Object> getUnmarshaller(MarshallLocation marshallLocation, MarshallingType<T> marshallingType) {
return (JsonUnmarshaller<Object>) get(marshallLocation, marshallingType);
}
/**
* @return Builder instance to construct a {@link JsonUnmarshallerRegistry}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for a {@link JsonUnmarshallerRegistry}.
*/
public static final class Builder extends AbstractMarshallingRegistry.Builder {
private Builder() {
}
public <T> Builder payloadUnmarshaller(MarshallingType<T> marshallingType,
JsonUnmarshaller<T> marshaller) {
register(MarshallLocation.PAYLOAD, marshallingType, marshaller);
return this;
}
public <T> Builder headerUnmarshaller(MarshallingType<T> marshallingType,
JsonUnmarshaller<T> marshaller) {
register(MarshallLocation.HEADER, marshallingType, marshaller);
return this;
}
public <T> Builder statusCodeUnmarshaller(MarshallingType<T> marshallingType,
JsonUnmarshaller<T> marshaller) {
register(MarshallLocation.STATUS_CODE, marshallingType, marshaller);
return this;
}
/**
* @return An immutable {@link JsonUnmarshallerRegistry} object.
*/
public JsonUnmarshallerRegistry build() {
return new JsonUnmarshallerRegistry(this);
}
}
}
| 2,191 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/JsonUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
/**
* Interface for unmarshalling a field from a JSON based service.
*
* @param <T> Type to unmarshall into.
*/
@SdkInternalApi
public interface JsonUnmarshaller<T> {
/**
* @param context Context containing dependencies and unmarshaller registry.
* @param jsonContent Parsed JSON content of body. May be null for REST JSON based services that don't have payload members.
* @param field {@link SdkField} of member being unmarshalled.
* @return Unmarshalled value.
*/
T unmarshall(JsonUnmarshallerContext context,
JsonNode jsonContent,
SdkField<T> field);
}
| 2,192 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/JsonResponseHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import static software.amazon.awssdk.utils.Validate.paramNotNull;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.SdkStandardLogger;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.utils.FunctionalUtils;
import software.amazon.awssdk.utils.IoUtils;
/**
* Default implementation of HttpResponseHandler that handles a successful response from a
* service and unmarshalls the result using a JSON unmarshaller.
*
* @param <T> Indicates the type being unmarshalled by this response handler.
*/
@SdkInternalApi
public final class JsonResponseHandler<T extends SdkPojo> implements HttpResponseHandler<T> {
private final Function<SdkHttpFullResponse, SdkPojo> pojoSupplier;
private final boolean needsConnectionLeftOpen;
private final boolean isPayloadJson;
/**
* The JSON unmarshaller to use when handling the response
*/
private JsonProtocolUnmarshaller unmarshaller;
/**
* Constructs a new response handler that will use the specified JSON unmarshaller to unmarshall
* the service response and uses the specified response element path to find the root of the
* business data in the service's response.
*
* @param unmarshaller The JSON unmarshaller to use on the response.
*/
public JsonResponseHandler(JsonProtocolUnmarshaller unmarshaller,
Function<SdkHttpFullResponse, SdkPojo> pojoSupplier,
boolean needsConnectionLeftOpen,
boolean isPayloadJson) {
this.unmarshaller = paramNotNull(unmarshaller, "unmarshaller");
this.pojoSupplier = pojoSupplier;
this.needsConnectionLeftOpen = needsConnectionLeftOpen;
this.isPayloadJson = isPayloadJson;
}
/**
* @see HttpResponseHandler#handle(SdkHttpFullResponse, ExecutionAttributes)
*/
@Override
public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception {
SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Parsing service response JSON.");
try {
T result = unmarshaller.unmarshall(pojoSupplier.apply(response), response);
// Make sure we read all the data to get an accurate CRC32 calculation.
// See https://github.com/aws/aws-sdk-java/issues/1018
if (shouldParsePayloadAsJson() && response.content().isPresent()) {
IoUtils.drainInputStream(response.content().get());
}
SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Done parsing service response.");
return result;
} finally {
if (!needsConnectionLeftOpen) {
response.content().ifPresent(i -> FunctionalUtils.invokeSafely(i::close));
}
}
}
@Override
public boolean needsConnectionLeftOpen() {
return needsConnectionLeftOpen;
}
/**
* @return True if the payload will be parsed as JSON, false otherwise.
*/
private boolean shouldParsePayloadAsJson() {
return !needsConnectionLeftOpen && isPayloadJson;
}
}
| 2,193 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/HeaderUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.traits.JsonValueTrait;
import software.amazon.awssdk.protocols.core.StringToValueConverter;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* Header unmarshallers for all the simple types we support.
*/
@SdkInternalApi
final class HeaderUnmarshaller {
public static final JsonUnmarshaller<String> STRING =
new SimpleHeaderUnmarshaller<>(HeaderUnmarshaller::unmarshallStringHeader);
public static final JsonUnmarshaller<Integer> INTEGER = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_INTEGER);
public static final JsonUnmarshaller<Long> LONG = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_LONG);
public static final JsonUnmarshaller<Short> SHORT = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_SHORT);
public static final JsonUnmarshaller<Double> DOUBLE = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_DOUBLE);
public static final JsonUnmarshaller<Boolean> BOOLEAN = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_BOOLEAN);
public static final JsonUnmarshaller<Float> FLOAT = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_FLOAT);
// Only supports string value type
public static final JsonUnmarshaller<List<?>> LIST =
(context, jsonContent, field) -> context.response().matchingHeaders(field.locationName());
private HeaderUnmarshaller() {
}
/**
* Unmarshalls a string header, taking into account whether it's a Base 64 encoded JSON value.
* <p>
* <em>Note:</em> This code does no attempt to validate whether the unmarshalled string does, in fact, represent valid
* JSON values. The string value is returned as-is, and it's up to the user to validate the results.
*
* @param value Value to unmarshall
* @param field {@link SdkField} containing metadata about member being unmarshalled.
* @return Unmarshalled value.
*/
private static String unmarshallStringHeader(String value,
SdkField<String> field) {
return field.containsTrait(JsonValueTrait.class) ?
new String(BinaryUtils.fromBase64(value), StandardCharsets.UTF_8) : value;
}
public static JsonUnmarshaller<Instant> createInstantHeaderUnmarshaller(
StringToValueConverter.StringToValue<Instant> instantStringToValue) {
return new SimpleHeaderUnmarshaller<>(instantStringToValue);
}
/**
* Simple unmarshaller implementation that calls a {@link StringToValueConverter} with the header value if it's present.
*
* @param <T> Type to unmarshall into.
*/
private static class SimpleHeaderUnmarshaller<T> implements JsonUnmarshaller<T> {
private final StringToValueConverter.StringToValue<T> stringToValue;
private SimpleHeaderUnmarshaller(StringToValueConverter.StringToValue<T> stringToValue) {
this.stringToValue = stringToValue;
}
@Override
public T unmarshall(JsonUnmarshallerContext context,
JsonNode jsonContent,
SdkField<T> field) {
return context.response().firstMatchingHeader(field.locationName())
.map(s -> stringToValue.convert(s, field))
.orElse(null);
}
}
}
| 2,194 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/JsonProtocolUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import static software.amazon.awssdk.protocols.core.StringToValueConverter.TO_SDK_BYTES;
import java.io.IOException;
import java.time.Instant;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.core.traits.ListTrait;
import software.amazon.awssdk.core.traits.MapTrait;
import software.amazon.awssdk.core.traits.PayloadTrait;
import software.amazon.awssdk.core.traits.TimestampFormatTrait;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.core.StringToInstant;
import software.amazon.awssdk.protocols.core.StringToValueConverter;
import software.amazon.awssdk.protocols.json.internal.MarshallerUtil;
import software.amazon.awssdk.protocols.json.internal.unmarshall.document.DocumentUnmarshaller;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.utils.builder.Buildable;
/**
* Unmarshaller implementation for both JSON RPC and REST JSON services. This class is thread-safe and it is
* recommended to reuse a single instance for best performance.
*/
@SdkInternalApi
@ThreadSafe
public final class JsonProtocolUnmarshaller {
public final StringToValueConverter.StringToValue<Instant> instantStringToValue;
private final JsonUnmarshallerRegistry registry;
private final JsonNodeParser parser;
private JsonProtocolUnmarshaller(Builder builder) {
this.parser = builder.parser;
this.instantStringToValue = StringToInstant.create(builder.defaultTimestampFormats.isEmpty() ?
new EnumMap<>(MarshallLocation.class) :
new EnumMap<>(builder.defaultTimestampFormats));
this.registry = createUnmarshallerRegistry(instantStringToValue);
}
private static JsonUnmarshallerRegistry createUnmarshallerRegistry(
StringToValueConverter.StringToValue<Instant> instantStringToValue) {
return JsonUnmarshallerRegistry
.builder()
.statusCodeUnmarshaller(MarshallingType.INTEGER, (context, json, f) -> context.response().statusCode())
.headerUnmarshaller(MarshallingType.STRING, HeaderUnmarshaller.STRING)
.headerUnmarshaller(MarshallingType.INTEGER, HeaderUnmarshaller.INTEGER)
.headerUnmarshaller(MarshallingType.LONG, HeaderUnmarshaller.LONG)
.headerUnmarshaller(MarshallingType.SHORT, HeaderUnmarshaller.SHORT)
.headerUnmarshaller(MarshallingType.DOUBLE, HeaderUnmarshaller.DOUBLE)
.headerUnmarshaller(MarshallingType.BOOLEAN, HeaderUnmarshaller.BOOLEAN)
.headerUnmarshaller(MarshallingType.INSTANT, HeaderUnmarshaller.createInstantHeaderUnmarshaller(instantStringToValue))
.headerUnmarshaller(MarshallingType.FLOAT, HeaderUnmarshaller.FLOAT)
.headerUnmarshaller(MarshallingType.LIST, HeaderUnmarshaller.LIST)
.payloadUnmarshaller(MarshallingType.STRING, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_STRING))
.payloadUnmarshaller(MarshallingType.INTEGER, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_INTEGER))
.payloadUnmarshaller(MarshallingType.LONG, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_LONG))
.payloadUnmarshaller(MarshallingType.SHORT, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_SHORT))
.payloadUnmarshaller(MarshallingType.FLOAT, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_FLOAT))
.payloadUnmarshaller(MarshallingType.DOUBLE, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_DOUBLE))
.payloadUnmarshaller(MarshallingType.BIG_DECIMAL, new SimpleTypeJsonUnmarshaller<>(
StringToValueConverter.TO_BIG_DECIMAL))
.payloadUnmarshaller(MarshallingType.BOOLEAN, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_BOOLEAN))
.payloadUnmarshaller(MarshallingType.SDK_BYTES, JsonProtocolUnmarshaller::unmarshallSdkBytes)
.payloadUnmarshaller(MarshallingType.INSTANT, new SimpleTypeJsonUnmarshaller<>(instantStringToValue))
.payloadUnmarshaller(MarshallingType.SDK_POJO, JsonProtocolUnmarshaller::unmarshallStructured)
.payloadUnmarshaller(MarshallingType.LIST, JsonProtocolUnmarshaller::unmarshallList)
.payloadUnmarshaller(MarshallingType.MAP, JsonProtocolUnmarshaller::unmarshallMap)
.payloadUnmarshaller(MarshallingType.DOCUMENT, JsonProtocolUnmarshaller::unmarshallDocument)
.build();
}
private static SdkBytes unmarshallSdkBytes(JsonUnmarshallerContext context,
JsonNode jsonContent,
SdkField<SdkBytes> field) {
if (jsonContent == null || jsonContent.isNull()) {
return null;
}
// Binary protocols like CBOR may already have the raw bytes extracted.
if (jsonContent.isEmbeddedObject()) {
return SdkBytes.fromByteArray((byte[]) jsonContent.asEmbeddedObject());
} else {
// Otherwise decode the JSON string as Base64
return TO_SDK_BYTES.convert(jsonContent.text(), field);
}
}
private static SdkPojo unmarshallStructured(JsonUnmarshallerContext context, JsonNode jsonContent, SdkField<SdkPojo> f) {
if (jsonContent == null || jsonContent.isNull()) {
return null;
} else {
return unmarshallStructured(f.constructor().get(), jsonContent, context);
}
}
private static Document unmarshallDocument(JsonUnmarshallerContext context,
JsonNode jsonContent,
SdkField<Document> field) {
if (jsonContent == null) {
return null;
}
return jsonContent.isNull() ? Document.fromNull() : getDocumentFromJsonContent(jsonContent);
}
private static Document getDocumentFromJsonContent(JsonNode jsonContent) {
return jsonContent.visit(new DocumentUnmarshaller());
}
private static Map<String, ?> unmarshallMap(JsonUnmarshallerContext context,
JsonNode jsonContent,
SdkField<Map<String, ?>> field) {
if (jsonContent == null || jsonContent.isNull()) {
return null;
}
SdkField<Object> valueInfo = field.getTrait(MapTrait.class).valueFieldInfo();
Map<String, Object> map = new HashMap<>();
jsonContent.asObject().forEach((fieldName, value) -> {
JsonUnmarshaller<Object> unmarshaller = context.getUnmarshaller(valueInfo.location(), valueInfo.marshallingType());
map.put(fieldName, unmarshaller.unmarshall(context, value, valueInfo));
});
return map;
}
private static List<?> unmarshallList(JsonUnmarshallerContext context, JsonNode jsonContent, SdkField<List<?>> field) {
if (jsonContent == null || jsonContent.isNull()) {
return null;
}
return jsonContent.asArray()
.stream()
.map(item -> {
SdkField<Object> memberInfo = field.getTrait(ListTrait.class).memberFieldInfo();
JsonUnmarshaller<Object> unmarshaller = context.getUnmarshaller(memberInfo.location(),
memberInfo.marshallingType());
return unmarshaller.unmarshall(context, item, memberInfo);
})
.collect(Collectors.toList());
}
private static class SimpleTypeJsonUnmarshaller<T> implements JsonUnmarshaller<T> {
private final StringToValueConverter.StringToValue<T> stringToValue;
private SimpleTypeJsonUnmarshaller(StringToValueConverter.StringToValue<T> stringToValue) {
this.stringToValue = stringToValue;
}
@Override
public T unmarshall(JsonUnmarshallerContext context,
JsonNode jsonContent,
SdkField<T> field) {
return jsonContent != null && !jsonContent.isNull() ? stringToValue.convert(jsonContent.text(), field) : null;
}
}
public <TypeT extends SdkPojo> TypeT unmarshall(SdkPojo sdkPojo,
SdkHttpFullResponse response) throws IOException {
JsonNode jsonNode = hasJsonPayload(sdkPojo, response) ? parser.parse(response.content().get()) : null;
return unmarshall(sdkPojo, response, jsonNode);
}
private boolean hasJsonPayload(SdkPojo sdkPojo, SdkHttpFullResponse response) {
return sdkPojo.sdkFields()
.stream()
.anyMatch(f -> isPayloadMemberOnUnmarshall(f) && !isExplicitBlobPayloadMember(f)
&& !isExplicitStringPayloadMember(f))
&& response.content().isPresent();
}
private boolean isExplicitBlobPayloadMember(SdkField<?> f) {
return isExplicitPayloadMember(f) && f.marshallingType() == MarshallingType.SDK_BYTES;
}
private boolean isExplicitStringPayloadMember(SdkField<?> f) {
return isExplicitPayloadMember(f) && f.marshallingType() == MarshallingType.STRING;
}
private static boolean isExplicitPayloadMember(SdkField<?> f) {
return f.containsTrait(PayloadTrait.class);
}
private boolean isPayloadMemberOnUnmarshall(SdkField<?> f) {
return f.location() == MarshallLocation.PAYLOAD || MarshallerUtil.isInUri(f.location());
}
public <TypeT extends SdkPojo> TypeT unmarshall(SdkPojo sdkPojo,
SdkHttpFullResponse response,
JsonNode jsonContent) {
JsonUnmarshallerContext context = JsonUnmarshallerContext.builder()
.unmarshallerRegistry(registry)
.response(response)
.build();
return unmarshallStructured(sdkPojo, jsonContent, context);
}
@SuppressWarnings("unchecked")
private static <TypeT extends SdkPojo> TypeT unmarshallStructured(SdkPojo sdkPojo,
JsonNode jsonContent,
JsonUnmarshallerContext context) {
for (SdkField<?> field : sdkPojo.sdkFields()) {
if (isExplicitPayloadMember(field) && field.marshallingType() == MarshallingType.SDK_BYTES) {
Optional<AbortableInputStream> responseContent = context.response().content();
if (responseContent.isPresent()) {
field.set(sdkPojo, SdkBytes.fromInputStream(responseContent.get()));
} else {
field.set(sdkPojo, SdkBytes.fromByteArrayUnsafe(new byte[0]));
}
} else if (isExplicitPayloadMember(field) && field.marshallingType() == MarshallingType.STRING) {
Optional<AbortableInputStream> responseContent = context.response().content();
if (responseContent.isPresent()) {
field.set(sdkPojo, SdkBytes.fromInputStream(responseContent.get()).asUtf8String());
} else {
field.set(sdkPojo, "");
}
} else {
JsonNode jsonFieldContent = getJsonNode(jsonContent, field);
JsonUnmarshaller<Object> unmarshaller = context.getUnmarshaller(field.location(), field.marshallingType());
field.set(sdkPojo, unmarshaller.unmarshall(context, jsonFieldContent, (SdkField<Object>) field));
}
}
return (TypeT) ((Buildable) sdkPojo).build();
}
private static JsonNode getJsonNode(JsonNode jsonContent, SdkField<?> field) {
if (jsonContent == null) {
return null;
}
return isFieldExplicitlyTransferredAsJson(field) ? jsonContent : jsonContent.field(field.locationName()).orElse(null);
}
private static boolean isFieldExplicitlyTransferredAsJson(SdkField<?> field) {
return isExplicitPayloadMember(field) && !MarshallingType.DOCUMENT.equals(field.marshallingType());
}
/**
* @return New instance of {@link Builder}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link JsonProtocolUnmarshaller}.
*/
public static final class Builder {
private JsonNodeParser parser;
private Map<MarshallLocation, TimestampFormatTrait.Format> defaultTimestampFormats;
private Builder() {
}
/**
* @param parser JSON parser to use.
* @return This builder for method chaining.
*/
public Builder parser(JsonNodeParser parser) {
this.parser = parser;
return this;
}
/**
* @param formats The default timestamp formats for each location in the HTTP response.
* @return This builder for method chaining.
*/
public Builder defaultTimestampFormats(Map<MarshallLocation, TimestampFormatTrait.Format> formats) {
this.defaultTimestampFormats = formats;
return this;
}
/**
* @return New instance of {@link JsonProtocolUnmarshaller}.
*/
public JsonProtocolUnmarshaller build() {
return new JsonProtocolUnmarshaller(this);
}
}
}
| 2,195 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/ErrorMessageParser.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
@SdkInternalApi
public interface ErrorMessageParser {
String parseErrorMessage(SdkHttpFullResponse httpResponse, JsonNode jsonNode);
}
| 2,196 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/AwsJsonErrorMessageParser.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
@SdkInternalApi
public final class AwsJsonErrorMessageParser implements ErrorMessageParser {
public static final ErrorMessageParser DEFAULT_ERROR_MESSAGE_PARSER =
new AwsJsonErrorMessageParser(SdkJsonErrorMessageParser.DEFAULT_ERROR_MESSAGE_PARSER);
/**
* x-amzn-error-message may be returned by RESTFUL services that do not send a response
* payload (like in a HEAD request).
*/
private static final String X_AMZN_ERROR_MESSAGE = "x-amzn-error-message";
/**
* Error message header returned by event stream errors
*/
private static final String EVENT_ERROR_MESSAGE = ":error-message";
private SdkJsonErrorMessageParser errorMessageParser;
/**
* @param errorMessageJsonLocations JSON field locations where the parser will attempt to
* extract the error message from.
*/
public AwsJsonErrorMessageParser(SdkJsonErrorMessageParser errorMessageJsonLocations) {
this.errorMessageParser = errorMessageJsonLocations;
}
/**
* Parse the error message from the response.
*
* @return Error Code of exceptional response or null if it can't be determined
*/
@Override
public String parseErrorMessage(SdkHttpFullResponse httpResponse, JsonNode jsonNode) {
String headerMessage = httpResponse.firstMatchingHeader(X_AMZN_ERROR_MESSAGE).orElse(null);
if (headerMessage != null) {
return headerMessage;
}
String eventHeaderMessage = httpResponse.firstMatchingHeader(EVENT_ERROR_MESSAGE).orElse(null);
if (eventHeaderMessage != null) {
return eventHeaderMessage;
}
return errorMessageParser.parseErrorMessage(httpResponse, jsonNode);
}
}
| 2,197 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/JsonUnmarshallerContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.json.internal.MarshallerUtil;
/**
* Dependencies needed by implementations of {@link JsonUnmarshaller}.
*/
@SdkInternalApi
public final class JsonUnmarshallerContext {
private final SdkHttpFullResponse response;
private final JsonUnmarshallerRegistry unmarshallerRegistry;
private JsonUnmarshallerContext(Builder builder) {
this.response = builder.response;
this.unmarshallerRegistry = builder.unmarshallerRegistry;
}
/**
* @return The {@link SdkHttpFullResponse} of the API call.
*/
public SdkHttpFullResponse response() {
return response;
}
/**
* Lookup the marshaller for the given location andtype.
*
* @param location {@link MarshallLocation} of member.
* @param marshallingType {@link MarshallingType} of member.
* @return Unmarshaller implementation.
* @throws SdkClientException if no unmarshaller is found.
*/
public JsonUnmarshaller<Object> getUnmarshaller(MarshallLocation location, MarshallingType<?> marshallingType) {
// A member being in the URI on a response is nonsensical; when a member is declared to be somewhere in the URI,
// it should be found in the payload on response
if (MarshallerUtil.isInUri(location)) {
location = MarshallLocation.PAYLOAD;
}
return unmarshallerRegistry.getUnmarshaller(location, marshallingType);
}
/**
* @return Builder instance to construct a {@link JsonUnmarshallerContext}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for a {@link JsonUnmarshallerContext}.
*/
public static final class Builder {
private SdkHttpFullResponse response;
private JsonUnmarshallerRegistry unmarshallerRegistry;
private Builder() {
}
public Builder response(SdkHttpFullResponse response) {
this.response = response;
return this;
}
public Builder unmarshallerRegistry(JsonUnmarshallerRegistry unmarshallerRegistry) {
this.unmarshallerRegistry = unmarshallerRegistry;
return this;
}
/**
* @return An immutable {@link JsonUnmarshallerContext} object.
*/
public JsonUnmarshallerContext build() {
return new JsonUnmarshallerContext(this);
}
}
}
| 2,198 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/AwsJsonProtocolErrorUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.core.ExceptionMetadata;
import software.amazon.awssdk.protocols.json.ErrorCodeParser;
import software.amazon.awssdk.protocols.json.JsonContent;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.utils.StringUtils;
/**
* Unmarshaller for AWS specific error responses. All errors are unmarshalled into a subtype of
* {@link AwsServiceException} (more specifically a subtype generated for each AWS service).
*/
@SdkInternalApi
public final class AwsJsonProtocolErrorUnmarshaller implements HttpResponseHandler<AwsServiceException> {
private static final String QUERY_COMPATIBLE_ERRORCODE_DELIMITER = ";";
private static final String X_AMZN_QUERY_ERROR = "x-amzn-query-error";
private final JsonProtocolUnmarshaller jsonProtocolUnmarshaller;
private final List<ExceptionMetadata> exceptions;
private final ErrorMessageParser errorMessageParser;
private final JsonFactory jsonFactory;
private final Supplier<SdkPojo> defaultExceptionSupplier;
private final ErrorCodeParser errorCodeParser;
private final boolean hasAwsQueryCompatible;
private AwsJsonProtocolErrorUnmarshaller(Builder builder) {
this.jsonProtocolUnmarshaller = builder.jsonProtocolUnmarshaller;
this.errorCodeParser = builder.errorCodeParser;
this.errorMessageParser = builder.errorMessageParser;
this.jsonFactory = builder.jsonFactory;
this.defaultExceptionSupplier = builder.defaultExceptionSupplier;
this.exceptions = builder.exceptions;
this.hasAwsQueryCompatible = builder.hasAwsQueryCompatible;
}
@Override
public AwsServiceException handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) {
return unmarshall(response, executionAttributes);
}
private AwsServiceException unmarshall(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) {
JsonContent jsonContent = JsonContent.createJsonContent(response, jsonFactory);
String errorCode = errorCodeParser.parseErrorCode(response, jsonContent);
Optional<ExceptionMetadata> modeledExceptionMetadata = exceptions.stream()
.filter(e -> e.errorCode().equals(errorCode))
.findAny();
SdkPojo sdkPojo = modeledExceptionMetadata.map(ExceptionMetadata::exceptionBuilderSupplier)
.orElse(defaultExceptionSupplier)
.get();
AwsServiceException.Builder exception = ((AwsServiceException) jsonProtocolUnmarshaller
.unmarshall(sdkPojo, response, jsonContent.getJsonNode())).toBuilder();
String errorMessage = errorMessageParser.parseErrorMessage(response, jsonContent.getJsonNode());
exception.awsErrorDetails(extractAwsErrorDetails(response, executionAttributes, jsonContent,
getEffectiveErrorCode(response, errorCode), errorMessage));
exception.clockSkew(getClockSkew(executionAttributes));
// Status code and request id are sdk level fields
exception.message(errorMessageForException(errorMessage, errorCode, response.statusCode()));
exception.statusCode(statusCode(response, modeledExceptionMetadata));
exception.requestId(response.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADERS).orElse(null));
exception.extendedRequestId(response.firstMatchingHeader(X_AMZ_ID_2_HEADER).orElse(null));
return exception.build();
}
private String getEffectiveErrorCode(SdkHttpFullResponse response, String errorCode) {
if (this.hasAwsQueryCompatible) {
String compatibleErrorCode = queryCompatibleErrorCodeFromResponse(response);
if (!StringUtils.isEmpty(compatibleErrorCode)) {
return compatibleErrorCode;
}
}
return errorCode;
}
private String queryCompatibleErrorCodeFromResponse(SdkHttpFullResponse response) {
Optional<String> headerValue = response.firstMatchingHeader(X_AMZN_QUERY_ERROR);
return headerValue.map(this::parseQueryErrorCodeFromDelimiter).orElse(null);
}
private String parseQueryErrorCodeFromDelimiter(String queryHeaderValue) {
int delimiter = queryHeaderValue.indexOf(QUERY_COMPATIBLE_ERRORCODE_DELIMITER);
if (delimiter > 0) {
return queryHeaderValue.substring(0, delimiter);
}
return null;
}
private String errorMessageForException(String errorMessage, String errorCode, int statusCode) {
if (StringUtils.isNotBlank(errorMessage)) {
return errorMessage;
}
if (StringUtils.isNotBlank(errorCode)) {
return "Service returned error code " + errorCode;
}
return "Service returned HTTP status code " + statusCode;
}
private Duration getClockSkew(ExecutionAttributes executionAttributes) {
Integer timeOffset = executionAttributes.getAttribute(SdkExecutionAttribute.TIME_OFFSET);
return timeOffset == null ? null : Duration.ofSeconds(timeOffset);
}
private int statusCode(SdkHttpFullResponse response, Optional<ExceptionMetadata> modeledExceptionMetadata) {
if (response.statusCode() != 0) {
return response.statusCode();
}
return modeledExceptionMetadata.filter(m -> m.httpStatusCode() != null)
.map(ExceptionMetadata::httpStatusCode)
.orElse(500);
}
/**
* Build the {@link AwsErrorDetails} from the metadata in the response.
*
* @param response HTTP response.
* @param executionAttributes Execution attributes.
* @param jsonContent Parsed JSON content.
* @param errorCode Parsed error code/type.
* @param errorMessage Parsed error message.
* @return AwsErrorDetails
*/
private AwsErrorDetails extractAwsErrorDetails(SdkHttpFullResponse response,
ExecutionAttributes executionAttributes,
JsonContent jsonContent,
String errorCode,
String errorMessage) {
AwsErrorDetails.Builder errorDetails =
AwsErrorDetails.builder()
.errorCode(errorCode)
.serviceName(executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME))
.sdkHttpResponse(response);
if (jsonContent.getRawContent() != null) {
errorDetails.rawResponse(SdkBytes.fromByteArray(jsonContent.getRawContent()));
}
errorDetails.errorMessage(errorMessage);
return errorDetails.build();
}
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link AwsJsonProtocolErrorUnmarshaller}.
*/
public static final class Builder {
private JsonProtocolUnmarshaller jsonProtocolUnmarshaller;
private List<ExceptionMetadata> exceptions;
private ErrorMessageParser errorMessageParser;
private JsonFactory jsonFactory;
private Supplier<SdkPojo> defaultExceptionSupplier;
private ErrorCodeParser errorCodeParser;
private boolean hasAwsQueryCompatible;
private Builder() {
}
/**
* Underlying response unmarshaller. Exceptions for the JSON protocol are follow the same unmarshalling logic
* as success responses but with an additional "error type" that allows for polymorphic deserialization.
*
* @return This builder for method chaining.
*/
public Builder jsonProtocolUnmarshaller(JsonProtocolUnmarshaller jsonProtocolUnmarshaller) {
this.jsonProtocolUnmarshaller = jsonProtocolUnmarshaller;
return this;
}
/**
* List of {@link ExceptionMetadata} to represent the modeled exceptions for the service.
* For AWS services the error type is a string representing the type of the modeled exception.
*
* @return This builder for method chaining.
*/
public Builder exceptions(List<ExceptionMetadata> exceptions) {
this.exceptions = exceptions;
return this;
}
/**
* Implementation that can extract an error message from the JSON response. Implementations may look for a
* specific field in the JSON document or a specific header for example.
*
* @return This builder for method chaining.
*/
public Builder errorMessageParser(ErrorMessageParser errorMessageParser) {
this.errorMessageParser = errorMessageParser;
return this;
}
/**
* JSON Factory to create a JSON parser.
*
* @return This builder for method chaining.
*/
public Builder jsonFactory(JsonFactory jsonFactory) {
this.jsonFactory = jsonFactory;
return this;
}
/**
* Default exception type if "error code" does not match any known modeled exception. This is the generated
* base exception for the service (i.e. DynamoDbException).
*
* @return This builder for method chaining.
*/
public Builder defaultExceptionSupplier(Supplier<SdkPojo> defaultExceptionSupplier) {
this.defaultExceptionSupplier = defaultExceptionSupplier;
return this;
}
/**
* Implementation of {@link ErrorCodeParser} that can extract an error code or type from the JSON response.
* Implementations may look for a specific field in the JSON document or a specific header for example.
*
* @return This builder for method chaining.
*/
public Builder errorCodeParser(ErrorCodeParser errorCodeParser) {
this.errorCodeParser = errorCodeParser;
return this;
}
public AwsJsonProtocolErrorUnmarshaller build() {
return new AwsJsonProtocolErrorUnmarshaller(this);
}
/**
* Provides a check on whether AwsQueryCompatible trait is found in Metadata.
* If true, error code will be derived from custom header. Otherwise, error code will be retrieved from its
* original source
*
* @param hasAwsQueryCompatible boolean of whether the AwsQueryCompatible trait is found
* @return This builder for method chaining.
*/
public Builder hasAwsQueryCompatible(boolean hasAwsQueryCompatible) {
this.hasAwsQueryCompatible = hasAwsQueryCompatible;
return this;
}
}
}
| 2,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.