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/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws/test/DependencyFactory.java |
package software.amazonaws.test;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.s3.S3Client;
/**
* The module containing all dependencies required by the {@link Handler}.
*/
public class DependencyFactory {
private DependencyFactory() {}
/**
* @return an instance of S3Client
*/
public static S3Client s3Client() {
return S3Client.builder()
.httpClientBuilder(ApacheHttpClient.builder())
.build();
}
}
| 2,900 |
0 | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/src/main/java/software/amazonaws/test/App.java | package software.amazonaws.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class App {
private static final Logger logger = LoggerFactory.getLogger(App.class);
public static void main(String... args) {
logger.info("Application starts");
Handler handler = new Handler();
handler.sendRequest();
logger.info("Application ends");
}
}
| 2,901 |
0 | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/test/java/software/amazonaws | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/test/java/software/amazonaws/test/HandlerTest.java | package software.amazonaws.test;
import org.junit.jupiter.api.Test;
public class HandlerTest {
//TODO add tests here
}
| 2,902 |
0 | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/main/java/software/amazonaws | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/main/java/software/amazonaws/test/Handler.java | package software.amazonaws.test;
import software.amazon.awssdk.services.s3.S3Client;
public class Handler {
private final S3Client s3Client;
public Handler() {
s3Client = DependencyFactory.s3Client();
}
public void sendRequest() {
// TODO: invoking the api calls using s3Client.
}
}
| 2,903 |
0 | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/main/java/software/amazonaws | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/main/java/software/amazonaws/test/DependencyFactory.java |
package software.amazonaws.test;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.s3.S3Client;
/**
* The module containing all dependencies required by the {@link Handler}.
*/
public class DependencyFactory {
private DependencyFactory() {}
/**
* @return an instance of S3Client
*/
public static S3Client s3Client() {
return S3Client.builder()
.httpClientBuilder(ApacheHttpClient.builder())
.build();
}
}
| 2,904 |
0 | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/main/java/software/amazonaws | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclientwithoutnativeimage/reference/src/main/java/software/amazonaws/test/App.java | package software.amazonaws.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class App {
private static final Logger logger = LoggerFactory.getLogger(App.class);
public static void main(String... args) {
logger.info("Application starts");
Handler handler = new Handler();
handler.sendRequest();
logger.info("Application ends");
}
}
| 2,905 |
0 | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/test | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/test/java/HandlerTest.java | #set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package};
import org.junit.jupiter.api.Test;
public class HandlerTest {
//TODO add tests here
}
| 2,906 |
0 | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/main | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/main/java/Handler.java | #parse ( "global.vm")
package ${package};
import software.amazon.awssdk.services.${servicePackage}.${serviceClientClassName};
public class Handler {
private final ${serviceClientClassName} ${serviceClientVariable}Client;
public Handler() {
${serviceClientVariable}Client = DependencyFactory.${serviceClientVariable}Client();
}
public void sendRequest() {
// TODO: invoking the api calls using ${serviceClientVariable}Client.
}
}
| 2,907 |
0 | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/main | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/main/java/DependencyFactory.java | #parse ( "global.vm")
package ${package};
import software.amazon.awssdk.http.${httpClientPackageName};
import software.amazon.awssdk.services.${servicePackage}.${serviceClientClassName};
/**
* The module containing all dependencies required by the {@link Handler}.
*/
public class DependencyFactory {
private DependencyFactory() {}
/**
* @return an instance of ${serviceClientClassName}
*/
public static ${serviceClientClassName} ${serviceClientVariable}Client() {
return ${serviceClientClassName}.builder()
.httpClientBuilder(${httpClientClassName}.builder())
.build();
}
}
| 2,908 |
0 | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/main | Create_ds/aws-sdk-java-v2/archetypes/archetype-app-quickstart/src/main/resources/archetype-resources/src/main/java/App.java | #parse ( "global.vm")
package ${package};
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class App {
private static final Logger logger = LoggerFactory.getLogger(App.class);
public static void main(String... args) {
logger.info("Application starts");
Handler handler = new Handler();
handler.sendRequest();
logger.info("Application ends");
}
}
| 2,909 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/CloudWatchMetricPublisherTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.http.HttpMetric;
import software.amazon.awssdk.metrics.MetricCategory;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.metrics.MetricLevel;
import software.amazon.awssdk.metrics.SdkMetric;
import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform.MetricCollectionAggregator;
import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
import software.amazon.awssdk.services.cloudwatch.model.MetricDatum;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataResponse;
public class CloudWatchMetricPublisherTest {
private CloudWatchAsyncClient cloudWatch;
private CloudWatchMetricPublisher.Builder publisherBuilder;
@Before
public void setup() {
cloudWatch = Mockito.mock(CloudWatchAsyncClient.class);
publisherBuilder = CloudWatchMetricPublisher.builder()
.cloudWatchClient(cloudWatch)
.uploadFrequency(Duration.ofMinutes(60));
Mockito.when(cloudWatch.putMetricData(any(PutMetricDataRequest.class)))
.thenReturn(CompletableFuture.completedFuture(PutMetricDataResponse.builder().build()));
}
@Test
public void noMetricsNoCalls() {
try (CloudWatchMetricPublisher publisher = publisherBuilder.build()) {
publisher.publish(MetricCollector.create("test").collect());
}
assertNoPutMetricCalls();
}
@Test
public void interruptedShutdownStillTerminates() {
CloudWatchMetricPublisher publisher = publisherBuilder.build();
Thread.currentThread().interrupt();
publisher.close();
assertThat(publisher.isShutdown()).isTrue();
Thread.interrupted(); // Clear interrupt flag
}
@Test
public void closeDoesNotCloseConfiguredClient() {
CloudWatchMetricPublisher.builder().cloudWatchClient(cloudWatch).build().close();
Mockito.verify(cloudWatch, never()).close();
}
@Test(timeout = 10_000)
public void closeWaitsForUploadToComplete() throws InterruptedException {
CountDownLatch cloudwatchPutCalledLatch = new CountDownLatch(1);
CompletableFuture<PutMetricDataResponse> result = new CompletableFuture<>();
CloudWatchAsyncClient cloudWatch = Mockito.mock(CloudWatchAsyncClient.class);
try (CloudWatchMetricPublisher publisher = CloudWatchMetricPublisher.builder()
.cloudWatchClient(cloudWatch)
.uploadFrequency(Duration.ofMinutes(60))
.build()) {
MetricCollector collector = newCollector();
collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5);
publisher.publish(new FixedTimeMetricCollection(collector.collect()));
Mockito.when(cloudWatch.putMetricData(any(PutMetricDataRequest.class))).thenAnswer(x -> {
cloudwatchPutCalledLatch.countDown();
return result;
});
publisher.publish(MetricCollector.create("test").collect());
Thread closeThread = new Thread(publisher::close);
assertThat(publisher.isShutdown()).isFalse();
closeThread.start();
// Wait until cloudwatch is called
cloudwatchPutCalledLatch.await();
// Wait to make sure the close thread seems to be waiting for the cloudwatch call to complete
Thread.sleep(1_000);
assertThat(closeThread.isAlive()).isTrue();
// Complete the cloudwatch call
result.complete(null);
// Make sure the close thread finishes
closeThread.join(5_000);
assertThat(closeThread.isAlive()).isFalse();
}
}
@Test
public void defaultNamespaceIsCorrect() {
try (CloudWatchMetricPublisher publisher = CloudWatchMetricPublisher.builder()
.cloudWatchClient(cloudWatch)
.build()) {
MetricCollector collector = newCollector();
collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5);
publisher.publish(new FixedTimeMetricCollection(collector.collect()));
}
PutMetricDataRequest call = getPutMetricCall();
assertThat(call.namespace()).isEqualTo("AwsSdk/JavaSdk2");
}
@Test
public void defaultDimensionsIsCorrect() {
try (CloudWatchMetricPublisher publisher = CloudWatchMetricPublisher.builder()
.cloudWatchClient(cloudWatch)
.build()) {
MetricCollector collector = newCollector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(CoreMetric.OPERATION_NAME, "OperationName");
collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5);
publisher.publish(new FixedTimeMetricCollection(collector.collect()));
}
PutMetricDataRequest call = getPutMetricCall();
assertThat(call.metricData().get(0).dimensions())
.containsExactlyInAnyOrder(Dimension.builder()
.name(CoreMetric.SERVICE_ID.name())
.value("ServiceId")
.build(),
Dimension.builder()
.name(CoreMetric.OPERATION_NAME.name())
.value("OperationName")
.build());
}
@Test
public void namespaceSettingIsHonored() {
try (CloudWatchMetricPublisher publisher = publisherBuilder.namespace("namespace").build()) {
MetricCollector collector = newCollector();
collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5);
publisher.publish(new FixedTimeMetricCollection(collector.collect()));
}
assertThat(getPutMetricCall().namespace()).isEqualTo("namespace");
}
@Test
public void dimensionsSettingIsHonored() {
try (CloudWatchMetricPublisher publisher = publisherBuilder.dimensions(CoreMetric.SERVICE_ID).build()) {
MetricCollector collector = newCollector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(CoreMetric.OPERATION_NAME, "OperationName");
collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5);
publisher.publish(new FixedTimeMetricCollection(collector.collect()));
}
PutMetricDataRequest call = getPutMetricCall();
assertThat(call.metricData().get(0).dimensions()).containsExactly(Dimension.builder()
.name(CoreMetric.SERVICE_ID.name())
.value("ServiceId")
.build());
}
@Test
public void metricCategoriesSettingIsHonored() {
try (CloudWatchMetricPublisher publisher = publisherBuilder.metricCategories(MetricCategory.HTTP_CLIENT).build()) {
MetricCollector collector = newCollector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(CoreMetric.API_CALL_SUCCESSFUL, true);
collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5);
publisher.publish(new FixedTimeMetricCollection(collector.collect()));
}
PutMetricDataRequest call = getPutMetricCall();
MetricDatum metric = call.metricData().get(0);
assertThat(call.metricData()).hasSize(1);
assertThat(metric.dimensions()).containsExactly(Dimension.builder()
.name(CoreMetric.SERVICE_ID.name())
.value("ServiceId")
.build());
assertThat(metric.metricName()).isEqualTo(HttpMetric.AVAILABLE_CONCURRENCY.name());
}
@Test
public void metricLevelSettingIsHonored() {
try (CloudWatchMetricPublisher publisher = publisherBuilder.metricLevel(MetricLevel.INFO).build()) {
MetricCollector collector = newCollector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(CoreMetric.API_CALL_SUCCESSFUL, true);
collector.reportMetric(HttpMetric.HTTP_STATUS_CODE, 404);
publisher.publish(new FixedTimeMetricCollection(collector.collect()));
}
PutMetricDataRequest call = getPutMetricCall();
MetricDatum metric = call.metricData().get(0);
assertThat(call.metricData()).hasSize(1);
assertThat(metric.dimensions()).containsExactly(Dimension.builder()
.name(CoreMetric.SERVICE_ID.name())
.value("ServiceId")
.build());
assertThat(metric.metricName()).isEqualTo(CoreMetric.API_CALL_SUCCESSFUL.name());
}
@Test
public void maximumCallsPerPublishSettingIsHonored() {
try (CloudWatchMetricPublisher publisher = publisherBuilder.maximumCallsPerUpload(1)
.detailedMetrics(HttpMetric.AVAILABLE_CONCURRENCY)
.build()) {
for (int i = 0; i < MetricCollectionAggregator.MAX_VALUES_PER_REQUEST + 1; ++i) {
MetricCollector collector = newCollector();
collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, i);
publisher.publish(new FixedTimeMetricCollection(collector.collect()));
}
}
assertThat(getPutMetricCalls()).hasSize(1);
}
@Test
public void detailedMetricsSettingIsHonored() {
try (CloudWatchMetricPublisher publisher = publisherBuilder.detailedMetrics(HttpMetric.AVAILABLE_CONCURRENCY).build()) {
for (int i = 0; i < 10; ++i) {
MetricCollector collector = newCollector();
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 10);
collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, i);
publisher.publish(new FixedTimeMetricCollection(collector.collect()));
}
}
PutMetricDataRequest call = getPutMetricCall();
MetricDatum concurrencyMetric = getDatum(call, HttpMetric.MAX_CONCURRENCY);
MetricDatum availableConcurrency = getDatum(call, HttpMetric.AVAILABLE_CONCURRENCY);
assertThat(concurrencyMetric.values()).isEmpty();
assertThat(concurrencyMetric.counts()).isEmpty();
assertThat(concurrencyMetric.statisticValues()).isNotNull();
assertThat(availableConcurrency.values()).isNotEmpty();
assertThat(availableConcurrency.counts()).isNotEmpty();
assertThat(availableConcurrency.statisticValues()).isNull();
}
private MetricDatum getDatum(PutMetricDataRequest call, SdkMetric<?> metric) {
return call.metricData().stream().filter(m -> m.metricName().equals(metric.name())).findAny().get();
}
private PutMetricDataRequest getPutMetricCall() {
List<PutMetricDataRequest> calls = getPutMetricCalls();
assertThat(calls).hasSize(1);
return calls.get(0);
}
private List<PutMetricDataRequest> getPutMetricCalls() {
ArgumentCaptor<PutMetricDataRequest> captor = ArgumentCaptor.forClass(PutMetricDataRequest.class);
Mockito.verify(cloudWatch).putMetricData(captor.capture());
return captor.getAllValues();
}
private void assertNoPutMetricCalls() {
Mockito.verify(cloudWatch, never()).putMetricData(any(PutMetricDataRequest.class));
}
private MetricCollector newCollector() {
return MetricCollector.create("test");
}
} | 2,910 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/FixedTimeMetricCollection.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch;
import java.time.Instant;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricRecord;
import software.amazon.awssdk.metrics.SdkMetric;
/**
* An implementation of {@link MetricCollection} that sets a static time for the {@link #creationTime()}. This makes it easier
* to test aggregation behavior, because the times can be fixed instead of regenerated each time the {@code MetricCollection} is
* created.
*/
public class FixedTimeMetricCollection implements MetricCollection {
private final MetricCollection delegate;
private final Instant creationTime;
public FixedTimeMetricCollection(MetricCollection delegate) {
this(delegate, Instant.EPOCH);
}
public FixedTimeMetricCollection(MetricCollection delegate,
Instant creationTime) {
this.delegate = delegate;
this.creationTime = creationTime;
}
@Override
public String name() {
return delegate.name();
}
@Override
public <T> List<T> metricValues(SdkMetric<T> metric) {
return delegate.metricValues(metric);
}
@Override
public List<MetricCollection> children() {
return delegate.children()
.stream()
.map(c -> new FixedTimeMetricCollection(c, creationTime))
.collect(Collectors.toList());
}
@Override
public Instant creationTime() {
return creationTime;
}
@Override
public Iterator<MetricRecord<?>> iterator() {
return delegate.iterator();
}
}
| 2,911 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/MetricUploaderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataResponse;
public class MetricUploaderTest {
private List<CompletableFuture<PutMetricDataResponse>> putMetricDataResponseFutures = new ArrayList<>();
private CloudWatchAsyncClient client;
private MetricUploader uploader;
@BeforeEach
public void setUp() {
client = Mockito.mock(CloudWatchAsyncClient.class);
uploader = new MetricUploader(client);
Mockito.when(client.putMetricData(any(PutMetricDataRequest.class))).thenAnswer(p -> {
CompletableFuture<PutMetricDataResponse> result = new CompletableFuture<>();
putMetricDataResponseFutures.add(result);
return result;
});
}
@Test
public void uploadSuccessIsPropagated() {
CompletableFuture<Void> uploadFuture = uploader.upload(Arrays.asList(PutMetricDataRequest.builder().build(),
PutMetricDataRequest.builder().build()));
assertThat(putMetricDataResponseFutures).hasSize(2);
assertThat(uploadFuture).isNotCompleted();
putMetricDataResponseFutures.get(0).complete(PutMetricDataResponse.builder().build());
assertThat(uploadFuture).isNotCompleted();
putMetricDataResponseFutures.get(1).complete(PutMetricDataResponse.builder().build());
assertThat(uploadFuture).isCompleted();
}
@Test
public void uploadFailureIsPropagated() {
CompletableFuture<Void> uploadFuture = uploader.upload(Arrays.asList(PutMetricDataRequest.builder().build(),
PutMetricDataRequest.builder().build()));
assertThat(putMetricDataResponseFutures).hasSize(2);
assertThat(uploadFuture).isNotCompleted();
putMetricDataResponseFutures.get(0).completeExceptionally(new Throwable());
putMetricDataResponseFutures.get(1).complete(PutMetricDataResponse.builder().build());
assertThat(uploadFuture).isCompletedExceptionally();
}
@Test
public void closeFalseDoesNotCloseClient() {
uploader.close(false);
Mockito.verify(client, never()).close();
}
@Test
public void closeTrueClosesClient() {
uploader.close(true);
Mockito.verify(client, times(1)).close();
}
} | 2,912 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/task/UploadMetricsTasksTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal.task;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.MetricUploader;
import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform.MetricCollectionAggregator;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest;
public class UploadMetricsTasksTest {
private MetricCollectionAggregator aggregator;
private MetricUploader uploader;
private UploadMetricsTasks task;
@BeforeEach
public void setUp() {
aggregator = Mockito.mock(MetricCollectionAggregator.class);
uploader = Mockito.mock(MetricUploader.class);
task = new UploadMetricsTasks(aggregator, uploader, 2);
}
@Test
public void extraTasksAboveMaximumAreDropped() {
List<PutMetricDataRequest> requests = Arrays.asList(PutMetricDataRequest.builder().build(),
PutMetricDataRequest.builder().build(),
PutMetricDataRequest.builder().build());
Mockito.when(aggregator.getRequests()).thenReturn(requests);
task.call();
ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
Mockito.verify(uploader).upload(captor.capture());
List<PutMetricDataRequest> uploadedRequests = captor.getValue();
assertThat(uploadedRequests).hasSize(2);
assertThat(uploadedRequests).containsOnlyElementsOf(requests);
}
} | 2,913 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/test/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/MetricCollectionAggregatorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal.transform;
import static java.time.temporal.ChronoUnit.HOURS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.fail;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.http.HttpMetric;
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;
import software.amazon.awssdk.metrics.publishers.cloudwatch.FixedTimeMetricCollection;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest;
import software.amazon.awssdk.services.cloudwatch.model.StatisticSet;
public class MetricCollectionAggregatorTest {
private static final String DEFAULT_NAMESPACE = "namespace";
private static final Set<SdkMetric<String>> DEFAULT_DIMENSIONS = Stream.of(CoreMetric.SERVICE_ID, CoreMetric.OPERATION_NAME)
.collect(Collectors.toSet());
private static final MetricLevel DEFAULT_METRIC_LEVEL = MetricLevel.INFO;
private static final Set<MetricCategory> DEFAULT_CATEGORIES = Collections.singleton(MetricCategory.HTTP_CLIENT);
private static final Set<SdkMetric<?>> DEFAULT_DETAILED_METRICS = Collections.emptySet();
@Test
public void maximumRequestsIsHonored() {
List<PutMetricDataRequest> requests;
requests = aggregatorWithUniqueMetricsAdded(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST).getRequests();
assertThat(requests).hasOnlyOneElementSatisfying(request -> {
assertThat(request.metricData()).hasSize(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST);
});
requests = aggregatorWithUniqueMetricsAdded(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST + 1).getRequests();
assertThat(requests).hasSize(2);
assertThat(requests.get(0).metricData()).hasSize(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST);
assertThat(requests.get(1).metricData()).hasSize(1);
}
@Test
public void maximumMetricValuesIsHonored() {
List<PutMetricDataRequest> requests;
requests = aggregatorWithUniqueValuesAdded(HttpMetric.MAX_CONCURRENCY,
MetricCollectionAggregator.MAX_VALUES_PER_REQUEST).getRequests();
assertThat(requests).hasSize(1);
validateValuesCount(requests.get(0), MetricCollectionAggregator.MAX_VALUES_PER_REQUEST);
requests = aggregatorWithUniqueValuesAdded(HttpMetric.MAX_CONCURRENCY,
MetricCollectionAggregator.MAX_VALUES_PER_REQUEST + 1).getRequests();
assertThat(requests).hasSize(2);
validateValuesCount(requests.get(0), MetricCollectionAggregator.MAX_VALUES_PER_REQUEST);
validateValuesCount(requests.get(1), 1);
}
private void validateValuesCount(PutMetricDataRequest request, int valuesExpected) {
assertThat(request.metricData().stream().flatMap(m -> m.values().stream()))
.hasSize(valuesExpected);
}
@Test
public void smallValuesAreNormalizedToZeroWithSummaryMetrics() {
// Really small values (close to 0) result in CloudWatch failing with an "unsupported value" error. Make sure that we
// floor those values to 0 to prevent that error.
MetricCollectionAggregator aggregator = defaultAggregator();
MetricCollector collector = collector();
SdkMetric<Double> metric = someMetric(Double.class);
collector.reportMetric(metric, -1E-10);
collector.reportMetric(metric, 1E-10);
aggregator.addCollection(collectToFixedTime(collector));
assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> {
assertThat(request.metricData()).hasOnlyOneElementSatisfying(metricData -> {
StatisticSet stats = metricData.statisticValues();
assertThat(stats.minimum()).isEqualTo(0.0);
assertThat(stats.maximum()).isEqualTo(0.0);
assertThat(stats.sum()).isEqualTo(0.0);
assertThat(stats.sampleCount()).isEqualTo(2.0);
});
});
}
@Test
public void smallValuesAreNormalizedToZeroWithDetailedMetrics() {
// Really small values (close to 0) result in CloudWatch failing with an "unsupported value" error. Make sure that we
// floor those values to 0 to prevent that error.
SdkMetric<Double> metric = someMetric(Double.class);
MetricCollectionAggregator aggregator = aggregatorWithCustomDetailedMetrics(metric);
MetricCollector collector = collector();
collector.reportMetric(metric, -1E-10);
collector.reportMetric(metric, 1E-10);
aggregator.addCollection(collectToFixedTime(collector));
assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> {
assertThat(request.metricData()).hasOnlyOneElementSatisfying(metricData -> {
assertThat(metricData.values()).hasOnlyOneElementSatisfying(metricValue -> {
assertThat(metricValue).isEqualTo(0.0);
});
assertThat(metricData.counts()).hasOnlyOneElementSatisfying(metricCount -> {
assertThat(metricCount).isEqualTo(2.0);
});
});
});
}
@Test
public void dimensionOrderInCollectionDoesNotMatter() {
MetricCollectionAggregator aggregator = defaultAggregator();
MetricCollector collector = collector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(CoreMetric.OPERATION_NAME, "OperationName");
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 1);
aggregator.addCollection(collectToFixedTime(collector));
collector = collector();
collector.reportMetric(CoreMetric.OPERATION_NAME, "OperationName");
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 2);
aggregator.addCollection(collectToFixedTime(collector));
assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> {
assertThat(request.metricData()).hasSize(1);
});
}
@Test
public void metricsAreAggregatedByDimensionMetricAndTime() {
MetricCollectionAggregator aggregator = defaultAggregator();
MetricCollector collector = collector();
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 1);
aggregator.addCollection(collectToFixedTimeBucket(collector, 0));
collector = collector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 2);
aggregator.addCollection(collectToFixedTimeBucket(collector, 0));
collector = collector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(CoreMetric.OPERATION_NAME, "OperationName");
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 3);
collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 4);
aggregator.addCollection(collectToFixedTimeBucket(collector, 0));
collector = collector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(CoreMetric.OPERATION_NAME, "OperationName");
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 5);
aggregator.addCollection(collectToFixedTimeBucket(collector, 1));
assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> {
assertThat(request.namespace()).isEqualTo(DEFAULT_NAMESPACE);
assertThat(request.metricData()).hasSize(5).allSatisfy(data -> {
assertThat(data.values()).isEmpty();
assertThat(data.counts()).isEmpty();
if (data.dimensions().isEmpty()) {
assertThat(data.metricName()).isEqualTo(HttpMetric.MAX_CONCURRENCY.name());
assertThat(data.statisticValues().sampleCount()).isEqualTo(1);
assertThat(data.statisticValues().sum()).isEqualTo(1);
} else if (data.dimensions().size() == 1) {
assertThat(data.metricName()).isEqualTo(HttpMetric.MAX_CONCURRENCY.name());
assertThat(data.statisticValues().sampleCount()).isEqualTo(1);
assertThat(data.statisticValues().sum()).isEqualTo(2);
} else {
assertThat(data.dimensions().size()).isEqualTo(2);
if (data.timestamp().equals(Instant.EPOCH)) {
// Time bucket 0
if (data.metricName().equals(HttpMetric.MAX_CONCURRENCY.name())) {
assertThat(data.statisticValues().sampleCount()).isEqualTo(1);
assertThat(data.statisticValues().sum()).isEqualTo(3);
} else {
assertThat(data.metricName()).isEqualTo(HttpMetric.AVAILABLE_CONCURRENCY.name());
assertThat(data.statisticValues().sampleCount()).isEqualTo(1);
assertThat(data.statisticValues().sum()).isEqualTo(4);
}
} else {
// Time bucket 1
assertThat(data.metricName()).isEqualTo(HttpMetric.MAX_CONCURRENCY.name());
assertThat(data.statisticValues().sampleCount()).isEqualTo(1);
assertThat(data.statisticValues().sum()).isEqualTo(5);
}
}
});
});
}
@Test
public void metricSummariesAreCorrectWithValuesInSameCollector() {
MetricCollectionAggregator aggregator = defaultAggregator();
MetricCollector collector = collector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 2);
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 1);
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 4);
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 4);
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 3);
aggregator.addCollection(collectToFixedTime(collector));
assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> {
assertThat(request.namespace()).isEqualTo(DEFAULT_NAMESPACE);
assertThat(request.metricData()).hasOnlyOneElementSatisfying(metricData -> {
assertThat(metricData.dimensions()).hasOnlyOneElementSatisfying(dimension -> {
assertThat(dimension.name()).isEqualTo(CoreMetric.SERVICE_ID.name());
assertThat(dimension.value()).isEqualTo("ServiceId");
});
assertThat(metricData.values()).isEmpty();
assertThat(metricData.counts()).isEmpty();
assertThat(metricData.statisticValues()).isEqualTo(StatisticSet.builder()
.minimum(1.0)
.maximum(4.0)
.sum(14.0)
.sampleCount(5.0)
.build());
});
});
}
@Test
public void metricSummariesAreCorrectWithValuesInDifferentCollector() {
MetricCollectionAggregator aggregator = defaultAggregator();
MetricCollector collector = collector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 2);
aggregator.addCollection(collectToFixedTime(collector));
collector = collector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 1);
aggregator.addCollection(collectToFixedTime(collector));
collector = collector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 4);
aggregator.addCollection(collectToFixedTime(collector));
collector = collector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 4);
aggregator.addCollection(collectToFixedTime(collector));
collector = collector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 3);
aggregator.addCollection(collectToFixedTime(collector));
assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> {
assertThat(request.namespace()).isEqualTo(DEFAULT_NAMESPACE);
assertThat(request.metricData()).hasOnlyOneElementSatisfying(metricData -> {
assertThat(metricData.dimensions()).hasOnlyOneElementSatisfying(dimension -> {
assertThat(dimension.name()).isEqualTo(CoreMetric.SERVICE_ID.name());
assertThat(dimension.value()).isEqualTo("ServiceId");
});
assertThat(metricData.values()).isEmpty();
assertThat(metricData.counts()).isEmpty();
assertThat(metricData.statisticValues()).isEqualTo(StatisticSet.builder()
.minimum(1.0)
.maximum(4.0)
.sum(14.0)
.sampleCount(5.0)
.build());
});
});
}
@Test
public void detailedMetricsAreCorrect() {
MetricCollectionAggregator aggregator = aggregatorWithCustomDetailedMetrics(HttpMetric.MAX_CONCURRENCY);
MetricCollector collector = collector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 2);
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 1);
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 4);
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 4);
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 3);
aggregator.addCollection(collectToFixedTime(collector));
assertThat(aggregator.getRequests()).hasOnlyOneElementSatisfying(request -> {
assertThat(request.namespace()).isEqualTo(DEFAULT_NAMESPACE);
assertThat(request.metricData()).hasOnlyOneElementSatisfying(metricData -> {
assertThat(metricData.dimensions()).hasOnlyOneElementSatisfying(dimension -> {
assertThat(dimension.name()).isEqualTo(CoreMetric.SERVICE_ID.name());
assertThat(dimension.value()).isEqualTo("ServiceId");
});
assertThat(metricData.values()).hasSize(4);
assertThat(metricData.statisticValues()).isNull();
for (int i = 0; i < metricData.values().size(); i++) {
Double value = metricData.values().get(i);
Double count = metricData.counts().get(i);
switch (value.toString()) {
case "1.0":
case "2.0":
case "3.0":
assertThat(count).isEqualTo(1.0);
break;
case "4.0":
assertThat(count).isEqualTo(2.0);
break;
default:
fail();
}
}
});
});
}
@Test
public void metricsFromOtherCategoriesAreIgnored() {
MetricCollectionAggregator aggregator = defaultAggregator();
MetricCollector collector = collector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(HttpMetric.HTTP_STATUS_CODE, 404);
aggregator.addCollection(collectToFixedTime(collector));
assertThat(aggregator.getRequests()).isEmpty();
}
@Test
public void getRequestsResetsState() {
MetricCollectionAggregator aggregator = defaultAggregator();
MetricCollector collector = collector();
collector.reportMetric(CoreMetric.SERVICE_ID, "ServiceId");
collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 1);
aggregator.addCollection(collectToFixedTime(collector));
assertThat(aggregator.getRequests()).hasSize(1);
assertThat(aggregator.getRequests()).isEmpty();
}
@Test
public void numberTypesAreTransformedCorrectly() {
SdkMetric<CustomNumber> metric = someMetric(CustomNumber.class);
assertThat(transformMetricValueUsingAggregator(metric, new CustomNumber(-1000.5))).isEqualTo(-1000.5);
assertThat(transformMetricValueUsingAggregator(metric, new CustomNumber(0))).isEqualTo(0);
assertThat(transformMetricValueUsingAggregator(metric, new CustomNumber(1000.5))).isEqualTo(1000.5);
}
@Test
public void durationsAreTransformedCorrectly() {
SdkMetric<Duration> metric = someMetric(Duration.class);
assertThat(transformMetricValueUsingAggregator(metric, Duration.ofSeconds(-10))).isEqualTo(-10_000);
assertThat(transformMetricValueUsingAggregator(metric, Duration.ofSeconds(0))).isEqualTo(0);
assertThat(transformMetricValueUsingAggregator(metric, Duration.ofSeconds(10))).isEqualTo(10_000);
}
@Test
public void booleansAreTransformedCorrectly() {
SdkMetric<Boolean> metric = someMetric(Boolean.class);
assertThat(transformMetricValueUsingAggregator(metric, false)).isEqualTo(0.0);
assertThat(transformMetricValueUsingAggregator(metric, true)).isEqualTo(1.0);
}
private <T> Double transformMetricValueUsingAggregator(SdkMetric<T> metric, T input) {
MetricCollectionAggregator aggregator = aggregatorWithCustomDetailedMetrics(metric);
MetricCollector collector = collector();
collector.reportMetric(metric, input);
aggregator.addCollection(collectToFixedTime(collector));
return aggregator.getRequests().get(0).metricData().get(0).values().get(0);
}
private MetricCollectionAggregator aggregatorWithUniqueValuesAdded(SdkMetric<Integer> metric, int numValues) {
MetricCollectionAggregator aggregator = aggregatorWithCustomDetailedMetrics(metric);
for (int i = 0; i < numValues; i++) {
MetricCollector collector = collector();
collector.reportMetric(metric, i);
aggregator.addCollection(collectToFixedTime(collector));
}
return aggregator;
}
private MetricCollectionAggregator aggregatorWithUniqueMetricsAdded(int numMetrics) {
MetricCollectionAggregator aggregator = defaultAggregator();
MetricCollector collector = collector();
for (int i = 0; i < numMetrics; i++) {
collector.reportMetric(someMetric(), 0);
}
aggregator.addCollection(collectToFixedTime(collector));
return aggregator;
}
private MetricCollectionAggregator defaultAggregator() {
return new MetricCollectionAggregator(DEFAULT_NAMESPACE,
DEFAULT_DIMENSIONS,
DEFAULT_CATEGORIES,
DEFAULT_METRIC_LEVEL,
DEFAULT_DETAILED_METRICS);
}
private MetricCollectionAggregator aggregatorWithCustomDetailedMetrics(SdkMetric<?>... detailedMetrics) {
return new MetricCollectionAggregator(DEFAULT_NAMESPACE,
DEFAULT_DIMENSIONS,
DEFAULT_CATEGORIES,
DEFAULT_METRIC_LEVEL,
Stream.of(detailedMetrics).collect(Collectors.toSet()));
}
private MetricCollector collector() {
return MetricCollector.create("test");
}
private SdkMetric<Integer> someMetric() {
return someMetric(Integer.class);
}
private <T> SdkMetric<T> someMetric(Class<T> clazz) {
return SdkMetric.create(getClass().getSimpleName() + UUID.randomUUID().toString(),
clazz,
MetricLevel.INFO,
MetricCategory.HTTP_CLIENT);
}
private MetricCollection collectToFixedTime(MetricCollector collector) {
return new FixedTimeMetricCollection(collector.collect());
}
private MetricCollection collectToFixedTimeBucket(MetricCollector collector, int timeBucket) {
// Make sure collectors in different "time buckets" are in a different minute than other collectors. We also offset the
// hour by a few seconds, to make sure the metric collection aggregator is actually ignoring the "seconds" portion of
// the collection time.
Instant metricTime = Instant.EPOCH.plus(timeBucket, HOURS)
.plusSeconds(Math.max(59, timeBucket));
return new FixedTimeMetricCollection(collector.collect(), metricTime);
}
private static class CustomNumber extends Number {
private final double value;
public CustomNumber(double value) {
this.value = value;
}
@Override
public int intValue() {
throw new UnsupportedOperationException();
}
@Override
public long longValue() {
throw new UnsupportedOperationException();
}
@Override
public float floatValue() {
throw new UnsupportedOperationException();
}
@Override
public double doubleValue() {
return value;
}
}
} | 2,914 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/CloudWatchMetricPublisher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch;
import static software.amazon.awssdk.metrics.publishers.cloudwatch.internal.CloudWatchMetricLogger.METRIC_LOGGER;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.metrics.CoreMetric;
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.MetricPublisher;
import software.amazon.awssdk.metrics.SdkMetric;
import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.MetricUploader;
import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.task.AggregateMetricsTask;
import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.task.UploadMetricsTasks;
import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform.MetricCollectionAggregator;
import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
import software.amazon.awssdk.services.cloudwatch.model.MetricDatum;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest;
import software.amazon.awssdk.services.cloudwatch.model.StatisticSet;
import software.amazon.awssdk.utils.ThreadFactoryBuilder;
/**
* An implementation of {@link MetricPublisher} that aggregates and uploads metrics to Amazon CloudWatch on a periodic basis.
*
* <p>This simplifies the process of uploading custom metrics to CloudWatch, and can also be configured on the AWS
* SDK clients directly to upload AWS SDK-specific metrics (e.g. request latencies, failure rates) to CloudWatch.
*
* <p><b>Overview</b>
*
* <p>This publisher aggregates metric data in memory, and periodically uploads it to CloudWatch in a background thread. This
* minimizes the work necessary to upload metrics, allowing the caller to focus on collecting the data.
*
* <p>The default settings of the metrics publisher are meant to minimize memory usage and CloudWatch cost, while still
* providing a useful amount of insight into the metric data. Care should be taken when overriding the default values on the
* publisher, because they can result in an associated increased in memory usage and CloudWatch cost.
*
* <p>By default, all metrics are uploaded using summary statistics. This means that only count, maximum, minimum, sum and
* average data is available in CloudWatch. Metric details (e.g. p90, p99) can be enabled on a per-metric basis using
* {@link Builder#detailedMetrics(Collection)}.
*
* <p>See {@link Builder} for the configuration values that are available for the publisher, and how they can be used to
* increase the functionality or decrease the cost the publisher.
*
* <p><b>Logging</b>
*
* The CloudWatchMetricPublisher logs all aggregation and upload-related logs to the
* {@code software.amazon.awssdk.metrics.publishers.cloudwatch} namespace. To determine how many metrics are being uploaded
* successfully without checking the CloudWatch console, you can check for a "success" message at the DEBUG level. At the TRACE
* level, you can see exactly which metrics are being uploaded.
*
* <p><b>Configuring AWS SDK clients to upload client metrics</b>
*
* <p>
* Create a {@link CloudWatchMetricPublisher}, and configure it via
* {@link ClientOverrideConfiguration.Builder#addMetricPublisher(MetricPublisher)}
*
* <pre>
* CloudWatchMetricPublisher cloudWatchMetricPublisher = CloudWatchMetricPublisher.create();
* S3Client s3 = S3Client.builder()
* .overrideConfiguration(o -> o.addMetricPublisher(cloudWatchMetricPublisher))
* .build();
* </pre>
* <p><b>Uploading your own custom metrics</b>
*
* <i>Step 1: Define which metrics you wish to collect</i>
*
* <p>Metrics are described using the {@link SdkMetric#create} method. When you describe your metric, you specify
* the name that will appear in CloudWatch and the Java data-type of the metric. The metric should be described once for your
* entire application.
*
* <p>Supported types: (1) {@link Number} types (e.g. {@link Integer}, {@link Double}, etc.), (2) {@link Duration}.
*
* <pre>
* // In this and the following examples, we want to collect metrics about calls to a method we have defined: "myMethod"
* public static final class MyMethodMetrics {
* // The number of times "myMethod" has been called.
* private static final SdkMetric<Integer> MY_METHOD_CALL_COUNT =
* SdkMetric.create("MyMethodCallCount", Integer.class, MetricLevel.INFO, MetricCategory.CUSTOM);
*
* // The amount of time that "myMethod" took to execute.
* private static final SdkMetric<Duration> MY_METHOD_LATENCY =
* SdkMetric.create("MyMethodLatency", Duration.class, MetricLevel.INFO, MetricCategory.CUSTOM);
* }
* </pre>
*
* <p><i>Step 2: Create a {@code CloudWatchMetricPublisher}</i>
*
* <p>A {@code CloudWatchMetricPublisher} should be created once for your entire application, and be reused wherever it is
* needed. {@code CloudWatchMetricPublisher}s are thread-safe, so there should be no need to create multiple instances. Most
* people create and manage the publisher in their inversion-of-control (IoC) container (e.g. Spring/Dagger/Guice).
*
* <p>Note: When your application is finished with the {@code CloudWatchMetricPublisher}, make sure to {@link #close()} it. Your
* inversion-of-control container may handle this for you on JVM shutdown.
*
* <p>See {@link CloudWatchMetricPublisher.Builder} for all available configuration options.
*
* <pre>
* // Create a CloudWatchMetricPublisher using a custom namespace.
* MetricPublisher metricPublisher = CloudWatchMetricPublisher.builder()
* .namespace("MyApplication")
* .build();
* </pre>
*
* <p><i>Step 3: Collect and Publish Metrics</i>
*
* <p>Create and use a {@link MetricCollector} to collect data about your configured metrics.
*
* <pre>
* // Call "myMethod" and collect metrics about the call.
* Instant methodCallStartTime = Instant.now();
* myMethod();
* Duration methodCallDuration = Duration.between(methodCallStartTime, Instant.now());
*
* // Write the metrics to the CloudWatchMetricPublisher.
* MetricCollector metricCollector = MetricCollector.create("MyMethodCall");
* metricCollector.reportMetric(MyCustomMetrics.MY_METHOD_CALL_COUNT, 1);
* metricCollector.reportMetric(MyCustomMetrics.MY_METHOD_LATENCY, methodCallDuration);
* MetricCollection metricCollection = metricCollector.collect();
*
* metricPublisher.publish(metricCollection);
* </pre>
*
* <p><b>Warning:</b> Make sure the {@link #close()} this publisher when it is done being used to release all resources it
* consumes. Failure to do so will result in possible thread or file descriptor leaks.
*/
@ThreadSafe
@Immutable
@SdkPublicApi
public final class CloudWatchMetricPublisher implements MetricPublisher {
/**
* The maximum queue size for the internal {@link #executor} that is used to aggregate metric data and upload it to
* CloudWatch. If this value is too high, memory is wasted. If this value is too low, metrics could be dropped.
*
* This value is not currently configurable, because it's unlikely that this is a value that customers should need to modify.
* If customers really need control over this value, we might consider letting them instead configure the
* {@link BlockingQueue} used on the executor. The value here depends on the type of {@code BlockingQueue} in use, and
* we should probably not indirectly couple people to the type of blocking queue we're using.
*/
private static final int MAXIMUM_TASK_QUEUE_SIZE = 128;
private static final String DEFAULT_NAMESPACE = "AwsSdk/JavaSdk2";
private static final int DEFAULT_MAXIMUM_CALLS_PER_UPLOAD = 10;
private static final Duration DEFAULT_UPLOAD_FREQUENCY = Duration.ofMinutes(1);
private static final Set<SdkMetric<String>> DEFAULT_DIMENSIONS = Stream.of(CoreMetric.SERVICE_ID,
CoreMetric.OPERATION_NAME)
.collect(Collectors.toSet());
private static final Set<MetricCategory> DEFAULT_METRIC_CATEGORIES = Collections.singleton(MetricCategory.ALL);
private static final MetricLevel DEFAULT_METRIC_LEVEL = MetricLevel.INFO;
private static final Set<SdkMetric<?>> DEFAULT_DETAILED_METRICS = Collections.emptySet();
/**
* Whether {@link #close()} should call {@link CloudWatchAsyncClient#close()}. This is false when
* {@link Builder#cloudWatchClient(CloudWatchAsyncClient)} was specified, meaning the customer has to close the client
* themselves.
*/
private final boolean closeClientWithPublisher;
/**
* The aggregator that takes {@link MetricCollection}s and converts them into {@link PutMetricDataRequest}s. This aggregator
* is *not* thread safe, so it should only ever be accessed from the {@link #executor}'s thread.
*/
private final MetricCollectionAggregator metricAggregator;
/**
* The uploader that takes {@link PutMetricDataRequest}s and sends them to a {@link CloudWatchAsyncClient}.
*/
private final MetricUploader metricUploader;
/**
* The executor that executes {@link AggregateMetricsTask}s and {@link UploadMetricsTasks}s.
*/
private final ExecutorService executor;
/**
* A scheduled executor that periodically schedules a {@link UploadMetricsTasks} on the {@link #executor} thread. Note: this
* executor should never execute the flush task itself, because that needs access to the {@link #metricAggregator}, and the
* {@code metricAggregator} should only ever be accessed from the {@link #executor} thread.
*/
private final ScheduledExecutorService scheduledExecutor;
/**
* The maximum number of {@link PutMetricDataRequest}s that should ever be executed as part of a single
* {@link UploadMetricsTasks}.
*/
private final int maximumCallsPerUpload;
private CloudWatchMetricPublisher(Builder builder) {
this.closeClientWithPublisher = resolveCloseClientWithPublisher(builder);
this.metricAggregator = new MetricCollectionAggregator(resolveNamespace(builder),
resolveDimensions(builder),
resolveMetricCategories(builder),
resolveMetricLevel(builder),
resolveDetailedMetrics(builder));
this.metricUploader = new MetricUploader(resolveClient(builder));
this.maximumCallsPerUpload = resolveMaximumCallsPerUpload(builder);
ThreadFactory threadFactory = new ThreadFactoryBuilder().threadNamePrefix("cloud-watch-metric-publisher").build();
this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(threadFactory);
// Do not increase above 1 thread: access to MetricCollectionAggregator is not thread safe.
this.executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(MAXIMUM_TASK_QUEUE_SIZE),
threadFactory);
long flushFrequencyInMillis = resolveUploadFrequency(builder).toMillis();
this.scheduledExecutor.scheduleAtFixedRate(this::flushMetricsQuietly,
flushFrequencyInMillis, flushFrequencyInMillis, TimeUnit.MILLISECONDS);
}
private Set<MetricCategory> resolveMetricCategories(Builder builder) {
return builder.metricCategories == null ? DEFAULT_METRIC_CATEGORIES : new HashSet<>(builder.metricCategories);
}
private MetricLevel resolveMetricLevel(Builder builder) {
return builder.metricLevel == null ? DEFAULT_METRIC_LEVEL : builder.metricLevel;
}
private Set<SdkMetric<?>> resolveDetailedMetrics(Builder builder) {
return builder.detailedMetrics == null ? DEFAULT_DETAILED_METRICS : new HashSet<>(builder.detailedMetrics);
}
private Set<SdkMetric<String>> resolveDimensions(Builder builder) {
return builder.dimensions == null ? DEFAULT_DIMENSIONS : new HashSet<>(builder.dimensions);
}
private boolean resolveCloseClientWithPublisher(Builder builder) {
return builder.client == null;
}
private CloudWatchAsyncClient resolveClient(Builder builder) {
return builder.client == null ? CloudWatchAsyncClient.create() : builder.client;
}
private Duration resolveUploadFrequency(Builder builder) {
return builder.uploadFrequency == null ? DEFAULT_UPLOAD_FREQUENCY : builder.uploadFrequency;
}
private String resolveNamespace(Builder builder) {
return builder.namespace == null ? DEFAULT_NAMESPACE : builder.namespace;
}
private int resolveMaximumCallsPerUpload(Builder builder) {
return builder.maximumCallsPerUpload == null ? DEFAULT_MAXIMUM_CALLS_PER_UPLOAD : builder.maximumCallsPerUpload;
}
@Override
public void publish(MetricCollection metricCollection) {
try {
executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection));
} catch (RejectedExecutionException e) {
METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not "
+ "accept them. This usually occurs because your publisher has been shut down or you have "
+ "generated too many requests for the publisher to handle in a timely fashion.", e);
}
}
/**
* Flush the metrics (via a {@link UploadMetricsTasks}). In the event that the {@link #executor} task queue is full, this
* this will retry automatically.
*
* This returns when the {@code UploadMetricsTask} has been submitted to the executor. The returned future is completed
* when the metrics upload to cloudwatch has started. The inner-most future is finally completed when the upload to cloudwatch
* has finished.
*/
private Future<CompletableFuture<?>> flushMetrics() throws InterruptedException {
while (!executor.isShutdown()) {
try {
return executor.submit(new UploadMetricsTasks(metricAggregator, metricUploader, maximumCallsPerUpload));
} catch (RejectedExecutionException e) {
Thread.sleep(100);
}
}
return CompletableFuture.completedFuture(CompletableFuture.completedFuture(null));
}
private void flushMetricsQuietly() {
try {
flushMetrics();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
METRIC_LOGGER.error(() -> "Interrupted during metric flushing.", e);
}
}
@Override
public void close() {
try {
scheduledExecutor.shutdownNow();
Future<CompletableFuture<?>> flushFuture = flushMetrics();
executor.shutdown();
flushFuture.get(60, TimeUnit.SECONDS) // Wait for flush to start
.get(60, TimeUnit.SECONDS); // Wait for flush to finish
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
throw new TimeoutException("Internal executor did not shut down in 60 seconds.");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
METRIC_LOGGER.error(() -> "Interrupted during graceful metric publisher shutdown.", e);
} catch (ExecutionException e) {
METRIC_LOGGER.error(() -> "Failed during graceful metric publisher shutdown.", e);
} catch (TimeoutException e) {
METRIC_LOGGER.error(() -> "Timed out during graceful metric publisher shutdown.", e);
} finally {
runQuietly(scheduledExecutor::shutdownNow, "shutting down scheduled executor");
runQuietly(executor::shutdownNow, "shutting down executor");
runQuietly(() -> metricUploader.close(closeClientWithPublisher), "closing metric uploader");
}
}
private void runQuietly(Runnable runnable, String taskName) {
try {
runnable.run();
} catch (Exception e) {
METRIC_LOGGER.warn(() -> "Failed while " + taskName + ".", e);
}
}
/**
* Create a new {@link Builder} that can be used to create {@link CloudWatchMetricPublisher}s.
*/
public static Builder builder() {
return new Builder();
}
/**
* Create a {@link CloudWatchMetricPublisher} using all default values.
*/
public static CloudWatchMetricPublisher create() {
return builder().build();
}
/**
* Returns {@code true} when the internal executors for this publisher are shut down.
*/
boolean isShutdown() {
return scheduledExecutor.isShutdown() && executor.isShutdown();
}
/**
* Builder class to construct {@link CloudWatchMetricPublisher} instances. See the individual properties for which
* configuration settings are available.
*/
public static final class Builder {
private CloudWatchAsyncClient client;
private Duration uploadFrequency;
private String namespace;
private Integer maximumCallsPerUpload;
private Collection<SdkMetric<String>> dimensions;
private Collection<MetricCategory> metricCategories;
private MetricLevel metricLevel;
private Collection<SdkMetric<?>> detailedMetrics;
private Builder() {
}
/**
* Configure the {@link PutMetricDataRequest#namespace()} used for all put-metric-data calls from this publisher.
*
* <p>If this is not specified, {@code AwsSdk/JavaSdk2} will be used.
*/
public Builder namespace(String namespace) {
this.namespace = namespace;
return this;
}
/**
* Configure the {@link CloudWatchAsyncClient} instance that should be used to communicate with CloudWatch.
*
* <p>If this is not specified, the {@code CloudWatchAsyncClient} will be created via
* {@link CloudWatchAsyncClient#create()} (and will be closed when {@link #close()} is invoked).
*
* <p>If you specify a {@code CloudWatchAsyncClient} via this method, it <i>will not</i> be closed when this publisher
* is closed. You will need to need to manage the lifecycle of the client yourself.
*/
public Builder cloudWatchClient(CloudWatchAsyncClient client) {
this.client = client;
return this;
}
/**
* Configure the frequency at which aggregated metrics are uploaded to CloudWatch and released from memory.
*
* <p>If this is not specified, metrics will be uploaded once per minute.
*
* <p>Smaller values will: (1) reduce the amount of memory used by the library (particularly when
* {@link #detailedMetrics(Collection)} are enabled), (2) increase the number of CloudWatch calls (and therefore
* increase CloudWatch usage cost).
*
* <p>Larger values will: (1) increase the amount of memory used by the library (particularly when
* {@code detailedMetrics} are enabled), (2) increase the time it takes for metric data to appear in
* CloudWatch, (3) reduce the number of CloudWatch calls (and therefore decrease CloudWatch usage cost).
*
* <p><b>Warning:</b> When {@code detailedMetrics} are enabled, all unique metric values are stored in memory until they
* can be published to CloudWatch. A high {@code uploadFrequency} with multiple {@code detailedMetrics} enabled can
* quickly consume heap memory while the values wait to be published to CloudWatch. In memory constrained environments, it
* is recommended to minimize the number of {@code detailedMetrics} configured on the publisher, or to upload metric data
* more frequently. As with all performance and resource concerns, profiling in a production-like environment is
* encouraged.
*/
public Builder uploadFrequency(Duration uploadFrequency) {
this.uploadFrequency = uploadFrequency;
return this;
}
/**
* Configure the maximum number of {@link CloudWatchAsyncClient#putMetricData(PutMetricDataRequest)} calls that an
* individual "upload" event can make to CloudWatch. Any metrics that would exceed this limit are dropped during the
* upload, logging a warning on the {@code software.amazon.awssdk.metrics.publishers.cloudwatch} namespace.
*
* <p>The SDK will always attempt to maximize the number of metrics per put-metric-data call, but uploads will be split
* into multiple put-metric-data calls if they include a lot of different metrics or if there are a lot of high-value-
* distribution {@link #detailedMetrics(Collection)} being monitored.
*
* <p>This value combined with the {@link #uploadFrequency(Duration)} effectively provide a "hard cap" on the number of
* put-metric-data calls, to prevent unbounded cost in the event that too many metrics are enabled by the user.
*
* <p>If this is not specified, put-metric-data calls will be capped at 10 per upload.
*/
public Builder maximumCallsPerUpload(Integer maximumCallsPerUpload) {
this.maximumCallsPerUpload = maximumCallsPerUpload;
return this;
}
/**
* Configure the {@link SdkMetric}s that are used to define the {@link Dimension}s metrics are aggregated under.
*
* <p>If this is not specified, {@link CoreMetric#SERVICE_ID} and {@link CoreMetric#OPERATION_NAME} are used, allowing
* you to compare metrics for different services and operations.
*
* <p><b>Warning:</b> Configuring the dimensions incorrectly can result in a large increase in the number of unique
* metrics and put-metric-data calls to cloudwatch, which have an associated monetary cost. Be sure you're choosing your
* metric dimensions wisely, and that you always evaluate the cost of modifying these values on your monthly usage costs.
*
* <p><b>Example useful settings:</b>
* <ul>
* <li>{@code CoreMetric.SERVICE_ID} and {@code CoreMetric.OPERATION_NAME} (default): Separate metrics by service and
* operation, so that you can compare latencies between AWS services and operations.</li>
* <li>{@code CoreMetric.SERVICE_ID}, {@code CoreMetric.OPERATION_NAME} and {@code CoreMetric.HOST_NAME}: Separate
* metrics by service, operation and host so that you can compare latencies across hosts in your fleet. Note: This should
* only be used when your fleet is relatively small. Large fleets result in a large number of unique metrics being
* generated.</li>
* <li>{@code CoreMetric.SERVICE_ID}, {@code CoreMetric.OPERATION_NAME} and {@code HttpMetric.HTTP_CLIENT_NAME}: Separate
* metrics by service, operation and HTTP client type so that you can compare latencies between different HTTP client
* implementations.</li>
* </ul>
*/
public Builder dimensions(Collection<SdkMetric<String>> dimensions) {
this.dimensions = new ArrayList<>(dimensions);
return this;
}
/**
* @see #dimensions(SdkMetric[])
*/
@SafeVarargs
public final Builder dimensions(SdkMetric<String>... dimensions) {
return dimensions(Arrays.asList(dimensions));
}
/**
* Configure the {@link MetricCategory}s that should be uploaded to CloudWatch.
*
* <p>If this is not specified, {@link MetricCategory#ALL} is used.
*
* <p>All {@link SdkMetric}s are associated with at least one {@code MetricCategory}. This setting determines which
* category of metrics uploaded to CloudWatch. Any metrics {@link #publish(MetricCollection)}ed that do not fall under
* these configured categories are ignored.
*
* <p>Note: If there are {@link #dimensions(Collection)} configured that do not fall under these {@code MetricCategory}
* values, the dimensions will NOT be ignored. In other words, the metric category configuration only affects which
* metrics are uploaded to CloudWatch, not which values can be used for {@code dimensions}.
*/
public Builder metricCategories(Collection<MetricCategory> metricCategories) {
this.metricCategories = new ArrayList<>(metricCategories);
return this;
}
/**
* @see #metricCategories(Collection)
*/
public Builder metricCategories(MetricCategory... metricCategories) {
return metricCategories(Arrays.asList(metricCategories));
}
/**
* Configure the {@link MetricLevel} that should be uploaded to CloudWatch.
*
* <p>If this is not specified, {@link MetricLevel#INFO} is used.
*
* <p>All {@link SdkMetric}s are associated with one {@code MetricLevel}. This setting determines which level of metrics
* uploaded to CloudWatch. Any metrics {@link #publish(MetricCollection)}ed that do not fall under these configured
* categories are ignored.
*
* <p>Note: If there are {@link #dimensions(Collection)} configured that do not fall under this {@code MetricLevel}
* values, the dimensions will NOT be ignored. In other words, the metric category configuration only affects which
* metrics are uploaded to CloudWatch, not which values can be used for {@code dimensions}.
*/
public Builder metricLevel(MetricLevel metricLevel) {
this.metricLevel = metricLevel;
return this;
}
/**
* Configure the set of metrics for which detailed values and counts are uploaded to CloudWatch, instead of summaries.
*
* <p>By default, all metrics published to this publisher are summarized using {@link StatisticSet}s. This saves memory,
* because it allows the publisher to store a fixed amount of information in memory, no matter how many different metric
* values are published. The drawback is that metrics other than count, sum, average, maximum and minimum are not made
* available in CloudWatch. The {@code detailedMetrics} setting instructs the publisher to store and publish itemized
* {@link MetricDatum#values()} and {@link MetricDatum#counts()}, which enables other metrics like p90 and p99 to be
* queried in CloudWatch.
*
* <p><b>Warning:</b> When {@code detailedMetrics} are enabled, all unique metric values are stored in memory until they
* can be published to CloudWatch. A high {@code uploadFrequency} with multiple {@code detailedMetrics} enabled can
* quickly consume heap memory while the values wait to be published to CloudWatch. In memory constrained environments, it
* is recommended to minimize the number of {@code detailedMetrics} configured on the publisher, or to upload metric data
* more frequently. As with all performance and resource concerns, profiling in a production-like environment is
* encouraged.
*
* <p>In addition to additional heap memory usage, detailed metrics can result in more requests being sent to CloudWatch,
* which can also introduce additional usage cost. The {@link #maximumCallsPerUpload(Integer)} acts as a safeguard against
* too many calls being made, but if you configure multiple {@code detailedMetrics}, you may need to increase the
* {@code maximumCallsPerUpload} limit.
*/
public Builder detailedMetrics(Collection<SdkMetric<?>> detailedMetrics) {
this.detailedMetrics = new ArrayList<>(detailedMetrics);
return this;
}
/**
* @see #detailedMetrics(Collection)
*/
public Builder detailedMetrics(SdkMetric<?>... detailedMetrics) {
return detailedMetrics(Arrays.asList(detailedMetrics));
}
/**
* Build a {@link CloudWatchMetricPublisher} using the configuration currently configured on this publisher.
*/
public CloudWatchMetricPublisher build() {
return new CloudWatchMetricPublisher(this);
}
}
}
| 2,915 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/MetricUploader.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal;
import static software.amazon.awssdk.metrics.publishers.cloudwatch.internal.CloudWatchMetricLogger.METRIC_LOGGER;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest;
/**
* Uploads {@link PutMetricDataRequest}s to a {@link CloudWatchAsyncClient}, logging whether it was successful or a failure to
* the {@link CloudWatchMetricLogger#METRIC_LOGGER}.
*/
@SdkInternalApi
public class MetricUploader {
private final CloudWatchAsyncClient cloudWatchClient;
public MetricUploader(CloudWatchAsyncClient cloudWatchClient) {
this.cloudWatchClient = cloudWatchClient;
}
/**
* Upload the provided list of requests to CloudWatch, completing the returned future when the uploads complete. Note: This
* will log a message if one of the provided requests fails.
*/
public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) {
CompletableFuture<?>[] publishResults = startCalls(requests);
return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> {
int numRequests = publishResults.length;
if (t != null) {
METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t);
} else {
METRIC_LOGGER.debug(() -> "Successfully published " + numRequests +
" AWS SDK client-side metric requests to CloudWatch.");
}
});
}
private CompletableFuture<?>[] startCalls(List<PutMetricDataRequest> requests) {
return requests.stream()
.peek(this::logRequest)
.map(cloudWatchClient::putMetricData)
.toArray(CompletableFuture[]::new);
}
private void logRequest(PutMetricDataRequest putMetricDataRequest) {
METRIC_LOGGER.trace(() -> "Sending request to CloudWatch: " + putMetricDataRequest);
}
public void close(boolean closeClient) {
if (closeClient) {
this.cloudWatchClient.close();
}
}
}
| 2,916 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/CloudWatchMetricLogger.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.Logger;
/**
* A holder for {@link #METRIC_LOGGER}.
*/
@SdkInternalApi
public class CloudWatchMetricLogger {
/**
* The logger via which all cloudwatch-metric-publisher logs are written. This allows customers to easily enable/disable logs
* written from this module.
*/
public static final Logger METRIC_LOGGER = Logger.loggerFor("software.amazon.awssdk.metrics.publishers.cloudwatch");
private CloudWatchMetricLogger() {
}
}
| 2,917 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/task/AggregateMetricsTask.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal.task;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.publishers.cloudwatch.CloudWatchMetricPublisher;
import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform.MetricCollectionAggregator;
/**
* A task that is executed on the {@link CloudWatchMetricPublisher}'s executor to add a {@link MetricCollection} to a
* {@link MetricCollectionAggregator}.
*/
@SdkInternalApi
public class AggregateMetricsTask implements Runnable {
private final MetricCollectionAggregator collectionAggregator;
private final MetricCollection metricCollection;
public AggregateMetricsTask(MetricCollectionAggregator collectionAggregator,
MetricCollection metricCollection) {
this.collectionAggregator = collectionAggregator;
this.metricCollection = metricCollection;
}
@Override
public void run() {
collectionAggregator.addCollection(metricCollection);
}
}
| 2,918 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/task/UploadMetricsTasks.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal.task;
import static software.amazon.awssdk.metrics.publishers.cloudwatch.internal.CloudWatchMetricLogger.METRIC_LOGGER;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.publishers.cloudwatch.CloudWatchMetricPublisher;
import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.MetricUploader;
import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform.MetricCollectionAggregator;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest;
import software.amazon.awssdk.utils.CompletableFutureUtils;
/**
* A task that is executed on the {@link CloudWatchMetricPublisher}'s executor to collect requests from a
* {@link MetricCollectionAggregator} and write them to a {@link MetricUploader}.
*/
@SdkInternalApi
public class UploadMetricsTasks implements Callable<CompletableFuture<?>> {
private final MetricCollectionAggregator collectionAggregator;
private final MetricUploader uploader;
private int maximumRequestsPerFlush;
public UploadMetricsTasks(MetricCollectionAggregator collectionAggregator,
MetricUploader uploader,
int maximumRequestsPerFlush) {
this.collectionAggregator = collectionAggregator;
this.uploader = uploader;
this.maximumRequestsPerFlush = maximumRequestsPerFlush;
}
@Override
public CompletableFuture<?> call() {
try {
List<PutMetricDataRequest> allRequests = collectionAggregator.getRequests();
List<PutMetricDataRequest> requests = allRequests;
if (requests.size() > maximumRequestsPerFlush) {
METRIC_LOGGER.warn(() -> "Maximum AWS SDK client-side metric call count exceeded: " + allRequests.size() +
" > " + maximumRequestsPerFlush + ". Some metric requests will be dropped. This occurs "
+ "when the caller has configured too many metrics or too unique of dimensions without "
+ "an associated increase in the maximum-calls-per-upload configured on the publisher.");
requests = requests.subList(0, maximumRequestsPerFlush);
}
return uploader.upload(requests);
} catch (Throwable t) {
return CompletableFutureUtils.failedFuture(t);
}
}
}
| 2,919 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/MetricValueNormalizer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal.transform;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
class MetricValueNormalizer {
/**
* Really small values (close to 0) result in CloudWatch failing with an "unsupported value" error. Make sure that we floor
* those values to 0 to prevent that error.
*/
private static final double ZERO_THRESHOLD = 0.0001;
private MetricValueNormalizer() {
}
/**
* Normalizes a metric value so that it won't upset CloudWatch when it is uploaded.
*/
public static double normalize(double value) {
if (value > ZERO_THRESHOLD) {
return value;
}
if (value < -ZERO_THRESHOLD) {
return value;
}
return 0;
}
} | 2,920 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/MetricAggregatorKey.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal.transform;
import java.util.List;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.SdkMetric;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
/**
* A pairing of {@link SdkMetric} and {@link Dimension}s that can be used as a key in a map. This uniquely identifies a specific
* {@link MetricAggregator}.
*/
@SdkInternalApi
class MetricAggregatorKey {
private final SdkMetric<?> metric;
private final List<Dimension> dimensions;
MetricAggregatorKey(SdkMetric<?> metric, List<Dimension> dimensions) {
this.metric = metric;
this.dimensions = dimensions;
}
public final SdkMetric<?> metric() {
return this.metric;
}
public final List<Dimension> dimensions() {
return this.dimensions;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MetricAggregatorKey that = (MetricAggregatorKey) o;
if (!metric.equals(that.metric)) {
return false;
}
return dimensions.equals(that.dimensions);
}
@Override
public int hashCode() {
int result = metric.hashCode();
result = 31 * result + dimensions.hashCode();
return result;
}
}
| 2,921 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/MetricAggregator.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal.transform;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.metrics.SdkMetric;
import software.amazon.awssdk.metrics.publishers.cloudwatch.CloudWatchMetricPublisher;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
import software.amazon.awssdk.services.cloudwatch.model.MetricDatum;
import software.amazon.awssdk.services.cloudwatch.model.StandardUnit;
/**
* Used by {@link MetricCollectionAggregator} to aggregate metrics in memory until they are ready to be added to a
* {@link MetricDatum}.
*
* <p>This is either a {@link SummaryMetricAggregator} or a {@link DetailedMetricAggregator}, depending on the configured
* {@link CloudWatchMetricPublisher.Builder#detailedMetrics(Collection)} setting.
*/
@SdkInternalApi
interface MetricAggregator {
/**
* The metric that this aggregator is aggregating. For example, this may be aggregating {@link CoreMetric#API_CALL_DURATION}
* metric values. There may be multiple aggregators for a single type of metric, when their {@link #dimensions()} differ.
*/
SdkMetric<?> metric();
/**
* The dimensions associated with the metric values that this aggregator is aggregating. For example, this may be aggregating
* "S3's putObject" metrics or "DynamoDb's listTables" metrics. The exact metric being aggregated is available via
* {@link #metric()}.
*/
List<Dimension> dimensions();
/**
* Get the unit of the {@link #metric()} when it is published to CloudWatch.
*/
StandardUnit unit();
/**
* Add the provided metric value to this aggregator.
*/
void addMetricValue(double value);
/**
* Execute the provided consumer if this {@code MetricAggregator} is a {@link SummaryMetricAggregator}.
*/
default void ifSummary(Consumer<SummaryMetricAggregator> summaryConsumer) {
if (this instanceof SummaryMetricAggregator) {
summaryConsumer.accept((SummaryMetricAggregator) this);
}
}
/**
* Execute the provided consumer if this {@code MetricAggregator} is a {@link DetailedMetricAggregator}.
*/
default void ifDetailed(Consumer<DetailedMetricAggregator> detailsConsumer) {
if (this instanceof DetailedMetricAggregator) {
detailsConsumer.accept((DetailedMetricAggregator) this);
}
}
}
| 2,922 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/SummaryMetricAggregator.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal.transform;
import java.util.List;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.SdkMetric;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
import software.amazon.awssdk.services.cloudwatch.model.MetricDatum;
import software.amazon.awssdk.services.cloudwatch.model.StandardUnit;
/**
* An implementation of {@link MetricAggregator} that stores summary statistics for a given metric/dimension pair until the
* summary can be added to a {@link MetricDatum}.
*/
@SdkInternalApi
class SummaryMetricAggregator implements MetricAggregator {
private final SdkMetric<?> metric;
private final List<Dimension> dimensions;
private final StandardUnit unit;
private double min = Double.MAX_VALUE;
private double max = Double.MIN_VALUE;
private double sum = 0;
private int count = 0;
SummaryMetricAggregator(MetricAggregatorKey key, StandardUnit unit) {
this.metric = key.metric();
this.dimensions = key.dimensions();
this.unit = unit;
}
@Override
public SdkMetric<?> metric() {
return metric;
}
@Override
public List<Dimension> dimensions() {
return dimensions;
}
@Override
public void addMetricValue(double value) {
min = Double.min(value, min);
max = Double.max(value, max);
sum += value;
++count;
}
@Override
public StandardUnit unit() {
return unit;
}
public double min() {
return min;
}
public double max() {
return max;
}
public double sum() {
return sum;
}
public int count() {
return count;
}
}
| 2,923 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/DetailedMetricAggregator.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal.transform;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.SdkMetric;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
import software.amazon.awssdk.services.cloudwatch.model.MetricDatum;
import software.amazon.awssdk.services.cloudwatch.model.StandardUnit;
/**
* An implementation of {@link MetricAggregator} that stores all values and counts for a given metric/dimension pair
* until they can be added to a {@link MetricDatum}.
*/
@SdkInternalApi
class DetailedMetricAggregator implements MetricAggregator {
private final SdkMetric<?> metric;
private final List<Dimension> dimensions;
private final StandardUnit unit;
private final Map<Double, DetailedMetrics> metricDetails = new HashMap<>();
DetailedMetricAggregator(MetricAggregatorKey key, StandardUnit unit) {
this.metric = key.metric();
this.dimensions = key.dimensions();
this.unit = unit;
}
@Override
public SdkMetric<?> metric() {
return metric;
}
@Override
public List<Dimension> dimensions() {
return dimensions;
}
@Override
public void addMetricValue(double value) {
metricDetails.computeIfAbsent(value, v -> new DetailedMetrics(value)).metricCount++;
}
@Override
public StandardUnit unit() {
return unit;
}
public Collection<DetailedMetrics> detailedMetrics() {
return Collections.unmodifiableCollection(metricDetails.values());
}
public static class DetailedMetrics {
private final double metricValue;
private int metricCount = 0;
private DetailedMetrics(double metricValue) {
this.metricValue = metricValue;
}
public double metricValue() {
return metricValue;
}
public int metricCount() {
return metricCount;
}
}
}
| 2,924 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/MetricCollectionAggregator.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal.transform;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.ApiName;
import software.amazon.awssdk.metrics.MetricCategory;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricLevel;
import software.amazon.awssdk.metrics.SdkMetric;
import software.amazon.awssdk.metrics.publishers.cloudwatch.internal.transform.DetailedMetricAggregator.DetailedMetrics;
import software.amazon.awssdk.services.cloudwatch.model.MetricDatum;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest;
import software.amazon.awssdk.services.cloudwatch.model.StatisticSet;
/**
* Aggregates {@link MetricCollection}s by: (1) the minute in which they occurred, and (2) the dimensions in the collection
* associated with that metric. Allows retrieving the aggregated values as a list of {@link PutMetricDataRequest}s.
*
* <p>It would be too expensive to upload every {@code MetricCollection} as a unique {@code PutMetricDataRequest}, so this
* class aggregates the data so that multiple {@code MetricCollection}s can be placed in the same {@code PutMetricDataRequest}.
*
* <p><b>Warning:</b> This class is *not* thread-safe.
*/
@SdkInternalApi
@NotThreadSafe
public class MetricCollectionAggregator {
/**
* The maximum number of {@link MetricDatum}s allowed in {@link PutMetricDataRequest#metricData()}. This limit is imposed by
* CloudWatch.
*/
public static final int MAX_METRIC_DATA_PER_REQUEST = 20;
/**
* The maximum number of unique {@link MetricDatum#values()} allowed in a single {@link PutMetricDataRequest}. This limit is
* not imposed directly by CloudWatch, but they do impose a 40KB limit for a single request. This value was determined by
* trial-and-error to roughly equate to a 40KB limit when we are also at the {@link #MAX_METRIC_DATA_PER_REQUEST}.
*/
public static final int MAX_VALUES_PER_REQUEST = 300;
/**
* The API name to include in the user agent for all {@link PutMetricDataRequest}s generated by this aggregator.
*/
private static final ApiName API_NAME = ApiName.builder().name("hll").version("cw-mp").build();
/**
* The {@link PutMetricDataRequest#namespace()} that should be used for all {@link PutMetricDataRequest}s returned from
* {@link #getRequests()}.
*/
private final String namespace;
/**
* The {@link TimeBucketedMetrics} that actually performs the data aggregation whenever
* {@link #addCollection(MetricCollection)} is called.
*/
private final TimeBucketedMetrics timeBucketedMetrics;
public MetricCollectionAggregator(String namespace,
Set<SdkMetric<String>> dimensions,
Set<MetricCategory> metricCategories,
MetricLevel metricLevel,
Set<SdkMetric<?>> detailedMetrics) {
this.namespace = namespace;
this.timeBucketedMetrics = new TimeBucketedMetrics(dimensions, metricCategories, metricLevel, detailedMetrics);
}
/**
* Add a collection to this aggregator.
*/
public void addCollection(MetricCollection collection) {
timeBucketedMetrics.addMetrics(collection);
}
/**
* Get all {@link PutMetricDataRequest}s that can be generated from the data that was added via
* {@link #addCollection(MetricCollection)}. This method resets the state of this {@code MetricCollectionAggregator}.
*/
public List<PutMetricDataRequest> getRequests() {
List<PutMetricDataRequest> requests = new ArrayList<>();
List<MetricDatum> requestMetricDatums = new ArrayList<>();
ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter();
Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics();
for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) {
Instant timeBucket = entry.getKey();
for (MetricAggregator metric : entry.getValue()) {
if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) {
requests.add(newPutRequest(requestMetricDatums));
requestMetricDatums.clear();
}
metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator)));
metric.ifDetailed(detailedAggregator -> {
int startIndex = 0;
Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics();
while (startIndex < detailedMetrics.size()) {
if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) {
requests.add(newPutRequest(requestMetricDatums));
requestMetricDatums.clear();
valuesInRequestCounter.reset();
}
MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator,
startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get());
int valuesAdded = data.values().size();
startIndex += valuesAdded;
valuesInRequestCounter.add(valuesAdded);
requestMetricDatums.add(data);
}
});
}
}
if (!requestMetricDatums.isEmpty()) {
requests.add(newPutRequest(requestMetricDatums));
}
timeBucketedMetrics.reset();
return requests;
}
private MetricDatum detailedMetricDatum(Instant timeBucket,
DetailedMetricAggregator metric,
int metricStartIndex,
int maxElements) {
List<Double> values = new ArrayList<>();
List<Double> counts = new ArrayList<>();
Stream<DetailedMetrics> boundedMetrics = metric.detailedMetrics()
.stream()
.skip(metricStartIndex)
.limit(maxElements);
boundedMetrics.forEach(detailedMetrics -> {
values.add(MetricValueNormalizer.normalize(detailedMetrics.metricValue()));
counts.add((double) detailedMetrics.metricCount());
});
return MetricDatum.builder()
.timestamp(timeBucket)
.metricName(metric.metric().name())
.dimensions(metric.dimensions())
.unit(metric.unit())
.values(values)
.counts(counts)
.build();
}
private MetricDatum summaryMetricDatum(Instant timeBucket,
SummaryMetricAggregator metric) {
StatisticSet stats = StatisticSet.builder()
.minimum(MetricValueNormalizer.normalize(metric.min()))
.maximum(MetricValueNormalizer.normalize(metric.max()))
.sum(MetricValueNormalizer.normalize(metric.sum()))
.sampleCount((double) metric.count())
.build();
return MetricDatum.builder()
.timestamp(timeBucket)
.metricName(metric.metric().name())
.dimensions(metric.dimensions())
.unit(metric.unit())
.statisticValues(stats)
.build();
}
private PutMetricDataRequest newPutRequest(List<MetricDatum> metricData) {
return PutMetricDataRequest.builder()
.overrideConfiguration(r -> r.addApiName(API_NAME))
.namespace(namespace)
.metricData(metricData)
.build();
}
private static class ValuesInRequestCounter {
private int valuesInRequest;
private void add(int i) {
valuesInRequest += i;
}
private int get() {
return valuesInRequest;
}
private void reset() {
valuesInRequest = 0;
}
}
}
| 2,925 |
0 | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal | Create_ds/aws-sdk-java-v2/metric-publishers/cloudwatch-metric-publisher/src/main/java/software/amazon/awssdk/metrics/publishers/cloudwatch/internal/transform/TimeBucketedMetrics.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.publishers.cloudwatch.internal.transform;
import static java.time.temporal.ChronoUnit.MINUTES;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.metrics.MetricCategory;
import software.amazon.awssdk.metrics.MetricCollection;
import software.amazon.awssdk.metrics.MetricLevel;
import software.amazon.awssdk.metrics.MetricRecord;
import software.amazon.awssdk.metrics.SdkMetric;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
import software.amazon.awssdk.services.cloudwatch.model.StandardUnit;
/**
* "Buckets" metrics by the minute in which they were collected. This allows all metric data for a given 1-minute period to be
* aggregated under a specific {@link MetricAggregator}.
*/
@SdkInternalApi
class TimeBucketedMetrics {
/**
* A map from "the minute during which a metric value happened" to "the dimension and metric associated with the metric
* values" to "the aggregator for the metric values that occurred within that minute and for that dimension/metric".
*/
private final Map<Instant, Map<MetricAggregatorKey, MetricAggregator>> timeBucketedMetrics = new HashMap<>();
/**
* The dimensions that should be used for aggregating metrics that occur within a given minute. These are optional values.
* The dimensions will be used if a {@link MetricCollection} includes them, but if it does not, it will be aggregated with
* whatever dimensions (if any) are available.
*/
private final Set<SdkMetric<String>> dimensions;
/**
* The set of metrics for which {@link DetailedMetricAggregator}s should be used for aggregation. All other metrics will use
* a {@link SummaryMetricAggregator}.
*/
private final Set<SdkMetric<?>> detailedMetrics;
/**
* The metric categories for which we should aggregate values. Any categories outside of this set will have their values
* ignored/dropped.
*/
private final Set<MetricCategory> metricCategories;
/**
* The metric levels for which we should aggregate values. Any categories at a more "verbose" level than this one will have
* their values ignored/dropped.
*/
private final MetricLevel metricLevel;
/**
* True, when the {@link #metricCategories} contains {@link MetricCategory#ALL}.
*/
private final boolean metricCategoriesContainsAll;
TimeBucketedMetrics(Set<SdkMetric<String>> dimensions,
Set<MetricCategory> metricCategories,
MetricLevel metricLevel,
Set<SdkMetric<?>> detailedMetrics) {
this.dimensions = dimensions;
this.detailedMetrics = detailedMetrics;
this.metricCategories = metricCategories;
this.metricLevel = metricLevel;
this.metricCategoriesContainsAll = metricCategories.contains(MetricCategory.ALL);
}
/**
* Add the provided collection to the proper bucket, based on the metric collection's time.
*/
public void addMetrics(MetricCollection metrics) {
Instant bucket = getBucket(metrics);
addMetricsToBucket(metrics, bucket);
}
/**
* Reset this bucket, clearing all stored values.
*/
public void reset() {
timeBucketedMetrics.clear();
}
/**
* Retrieve all values in this collection. The map key is the minute in which the metric values were collected, and the
* map value are all of the metrics that were aggregated during that minute.
*/
public Map<Instant, Collection<MetricAggregator>> timeBucketedMetrics() {
return timeBucketedMetrics.entrySet()
.stream()
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().values()));
}
private Instant getBucket(MetricCollection metrics) {
return metrics.creationTime().truncatedTo(MINUTES);
}
private void addMetricsToBucket(MetricCollection metrics, Instant bucketId) {
aggregateMetrics(metrics, timeBucketedMetrics.computeIfAbsent(bucketId, i -> new HashMap<>()));
}
private void aggregateMetrics(MetricCollection metrics, Map<MetricAggregatorKey, MetricAggregator> bucket) {
List<Dimension> dimensions = dimensions(metrics);
extractAllMetrics(metrics).forEach(metricRecord -> {
MetricAggregatorKey aggregatorKey = new MetricAggregatorKey(metricRecord.metric(), dimensions);
valueFor(metricRecord).ifPresent(metricValue -> {
bucket.computeIfAbsent(aggregatorKey, m -> newAggregator(aggregatorKey))
.addMetricValue(MetricValueNormalizer.normalize(metricValue));
});
});
}
private List<Dimension> dimensions(MetricCollection metricCollection) {
List<Dimension> result = new ArrayList<>();
for (MetricRecord<?> metricRecord : metricCollection) {
if (dimensions.contains(metricRecord.metric())) {
result.add(Dimension.builder()
.name(metricRecord.metric().name())
.value((String) metricRecord.value())
.build());
}
}
// Sort the dimensions to make sure that the order in the input metric collection doesn't affect the result.
// We use descending order just so that "ServiceName" is before "OperationName" when we use the default dimensions.
result.sort(Comparator.comparing(Dimension::name).reversed());
return result;
}
private List<MetricRecord<?>> extractAllMetrics(MetricCollection metrics) {
List<MetricRecord<?>> result = new ArrayList<>();
extractAllMetrics(metrics, result);
return result;
}
private void extractAllMetrics(MetricCollection metrics, List<MetricRecord<?>> extractedMetrics) {
for (MetricRecord<?> metric : metrics) {
extractedMetrics.add(metric);
}
metrics.children().forEach(child -> extractAllMetrics(child, extractedMetrics));
}
private MetricAggregator newAggregator(MetricAggregatorKey aggregatorKey) {
SdkMetric<?> metric = aggregatorKey.metric();
StandardUnit metricUnit = unitFor(metric);
if (detailedMetrics.contains(metric)) {
return new DetailedMetricAggregator(aggregatorKey, metricUnit);
} else {
return new SummaryMetricAggregator(aggregatorKey, metricUnit);
}
}
private StandardUnit unitFor(SdkMetric<?> metric) {
Class<?> metricType = metric.valueClass();
if (Duration.class.isAssignableFrom(metricType)) {
return StandardUnit.MILLISECONDS;
}
return StandardUnit.NONE;
}
private Optional<Double> valueFor(MetricRecord<?> metricRecord) {
if (!shouldReport(metricRecord)) {
return Optional.empty();
}
Class<?> metricType = metricRecord.metric().valueClass();
if (Duration.class.isAssignableFrom(metricType)) {
Duration durationMetricValue = (Duration) metricRecord.value();
long millis = durationMetricValue.toMillis();
return Optional.of((double) millis);
} else if (Number.class.isAssignableFrom(metricType)) {
Number numberMetricValue = (Number) metricRecord.value();
return Optional.of(numberMetricValue.doubleValue());
} else if (Boolean.class.isAssignableFrom(metricType)) {
Boolean booleanMetricValue = (Boolean) metricRecord.value();
return Optional.of(booleanMetricValue ? 1.0 : 0.0);
}
return Optional.empty();
}
private boolean shouldReport(MetricRecord<?> metricRecord) {
return isSupportedCategory(metricRecord) && isSupportedLevel(metricRecord);
}
private boolean isSupportedCategory(MetricRecord<?> metricRecord) {
return metricCategoriesContainsAll ||
metricRecord.metric()
.categories()
.stream()
.anyMatch(metricCategories::contains);
}
private boolean isSupportedLevel(MetricRecord<?> metricRecord) {
return metricLevel.includesLevel(metricRecord.metric().level());
}
}
| 2,926 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/Md5UtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.internal.Base16;
public class Md5UtilsTest {
@Test
public void testBytes() {
byte[] md5 = Md5Utils.computeMD5Hash("Testing MD5".getBytes(StandardCharsets.UTF_8));
assertEquals("0b4f503b8eb7714ce12402406895cf68", StringUtils.lowerCase(Base16.encodeAsString(md5)));
String b64 = Md5Utils.md5AsBase64("Testing MD5".getBytes(StandardCharsets.UTF_8));
assertEquals("C09QO463cUzhJAJAaJXPaA==", b64);
}
@Test
public void testStream() throws IOException {
byte[] md5 = Md5Utils.computeMD5Hash(new ByteArrayInputStream("Testing MD5".getBytes(StandardCharsets.UTF_8)));
assertEquals("0b4f503b8eb7714ce12402406895cf68", StringUtils.lowerCase(Base16.encodeAsString(md5)));
String b64 = Md5Utils.md5AsBase64(new ByteArrayInputStream("Testing MD5".getBytes(StandardCharsets.UTF_8)));
assertEquals("C09QO463cUzhJAJAaJXPaA==", b64);
}
@Test
public void testFile() throws Exception {
File f = File.createTempFile("Md5UtilsTest-", "txt");
f.deleteOnExit();
FileUtils.writeStringToFile(f, "Testing MD5");
byte[] md5 = Md5Utils.computeMD5Hash(f);
assertEquals("0b4f503b8eb7714ce12402406895cf68", StringUtils.lowerCase(Base16.encodeAsString(md5)));
String b64 = Md5Utils.md5AsBase64(f);
assertEquals("C09QO463cUzhJAJAaJXPaA==", b64);
}
}
| 2,927 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/IoUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.in;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import org.junit.jupiter.api.Test;
public class IoUtilsTest {
private final Random random = new Random();
@Test
public void testEmptyByteArray() throws Exception {
String s = IoUtils.toUtf8String(new ByteArrayInputStream(new byte[0]));
assertEquals("", s);
}
@Test
public void testZeroByteStream() throws Exception {
String s = IoUtils.toUtf8String(new InputStream() {
@Override
public int read() throws IOException {
return -1;
}
});
assertEquals("", s);
}
@Test
public void test() throws Exception {
String s = IoUtils.toUtf8String(new ByteArrayInputStream("Testing".getBytes(StandardCharsets.UTF_8)));
assertEquals("Testing", s);
}
@Test
public void drainInputStream_AlreadyEos_DoesNotThrowException() throws IOException {
final InputStream inputStream = randomInputStream();
while (inputStream.read() != -1) {
}
IoUtils.drainInputStream(inputStream);
}
@Test
public void drainInputStream_RemainingBytesInStream_ReadsAllRemainingData() throws IOException {
final InputStream inputStream = randomInputStream();
IoUtils.drainInputStream(inputStream);
assertEquals(-1, inputStream.read());
}
@Test
public void applyMaxReadLimit_shouldHonor() throws IOException {
int length = 1 << 18;
InputStream inputStream = randomInputStream(length);
InputStream bufferedInputStream = new BufferedInputStream(inputStream);
IoUtils.markStreamWithMaxReadLimit(bufferedInputStream, length + 1);
IoUtils.drainInputStream(bufferedInputStream);
assertThat(bufferedInputStream.available()).isEqualTo(0);
bufferedInputStream.reset();
assertThat(bufferedInputStream.available()).isEqualTo(length);
}
private InputStream randomInputStream() {
byte[] data = new byte[100];
random.nextBytes(data);
return new ByteArrayInputStream(data);
}
private InputStream randomInputStream(int length) {
byte[] data = new byte[length];
random.nextBytes(data);
return new ByteArrayInputStream(data);
}
}
| 2,928 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/Base16CodecTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.internal.Base16;
import software.amazon.awssdk.utils.internal.Base16Lower;
/**
* @author hchar
*/
public class Base16CodecTest {
@Test
public void testVectorsPerRfc4648()
throws Exception {
String[] testVectors = {"", "f", "fo", "foo", "foob", "fooba", "foobar"};
String[] expected = {"", "66", "666F", "666F6F", "666F6F62", "666F6F6261", "666F6F626172"};
for (int i = 0; i < testVectors.length; i++) {
String data = testVectors[i];
byte[] source = data.getBytes("UTF-8");
String b16encoded = Base16.encodeAsString(data.getBytes("UTF-8"));
assertEquals(expected[i], b16encoded);
byte[] b16 = b16encoded.getBytes("UTF-8");
byte[] decoded = Base16.decode(b16);
assertTrue(Arrays.equals(source, decoded));
decoded = Base16Lower.decode(b16);
assertTrue(Arrays.equals(source, decoded));
}
}
@Test
public void testCodecConsistency()
throws Exception {
byte[] decoded = null;
for (int h = 0; h < 1000; h++) {
byte[] digest = MessageDigest.getInstance("SHA-1").digest(
UUID.randomUUID().toString().getBytes("UTF-8")
);
String b16Encoded = Base16.encodeAsString(digest);
{
decoded = Base16.decode(b16Encoded);
assertTrue(Arrays.equals(decoded, digest));
decoded = Base16Lower.decode(b16Encoded);
assertTrue(Arrays.equals(decoded, digest));
}
{ // test decoding case insensitivity
decoded = Base16.decode(b16Encoded.toLowerCase());
assertTrue(Arrays.equals(decoded, digest));
decoded = Base16Lower.decode(b16Encoded.toLowerCase());
assertTrue(Arrays.equals(decoded, digest));
}
}
}
}
| 2,929 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/SystemSettingTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Java6Assertions.assertThat;
import org.junit.jupiter.api.Test;
public class SystemSettingTest {
@Test
public void getNonDefaultStringValue_doesNotReturnDefaultValue() {
TestSystemSetting setting = new TestSystemSetting("prop", "env", "default");
assertThat(setting.getNonDefaultStringValue().isPresent()).isFalse();
}
private static class TestSystemSetting implements SystemSetting {
private final String property;
private final String environmentVariable;
private final String defaultValue;
public TestSystemSetting(String property, String environmentVariable, String defaultValue) {
this.property = property;
this.environmentVariable = environmentVariable;
this.defaultValue = defaultValue;
}
@Override
public String property() {
return property;
}
@Override
public String environmentVariable() {
return environmentVariable;
}
@Override
public String defaultValue() {
return defaultValue;
}
}
}
| 2,930 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/HostnameValidatorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class HostnameValidatorTest {
private static final String LONG_STRING_64 = "1234567890123456789012345678901234567890123456789012345678901234";
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void validHostComponent_shouldWork() {
HostnameValidator.validateHostnameCompliant("1", "id", "test");
HostnameValidator.validateHostnameCompliant(LONG_STRING_64.substring(0, LONG_STRING_64.length() - 1), "id", "test");
}
@Test
public void nullHostComponent_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("id");
exception.expectMessage("missing");
HostnameValidator.validateHostnameCompliant(null, "id", "test");
}
@Test
public void emptyHostComponent_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("id");
exception.expectMessage("empty");
HostnameValidator.validateHostnameCompliant("", "id", "test");
}
@Test
public void blankHostComponent_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("id");
exception.expectMessage("blank");
HostnameValidator.validateHostnameCompliant(" ", "id", "test");
}
@Test
public void hostComponentWithSlash_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("id");
exception.expectMessage("\"[A-Za-z0-9\\-]+\"");
HostnameValidator.validateHostnameCompliant("foo%2bar", "id", "test");
}
@Test
public void hostComponentWithEncodedString_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("id");
exception.expectMessage("63");
HostnameValidator.validateHostnameCompliant(LONG_STRING_64, "id", "test");
}
@Test
public void hostComponentTooLong_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("id");
exception.expectMessage("63");
HostnameValidator.validateHostnameCompliant(LONG_STRING_64, "id", "test");
}
}
| 2,931 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/SdkHttpUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.entry;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.http.SdkHttpUtils;
public class SdkHttpUtilsTest {
@Test
public void urlValuesEncodeCorrectly() {
String nonEncodedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
String encodedCharactersInput = "\t\n\r !\"#$%&'()*+,/:;<=>?@[\\]^`{|}";
String encodedCharactersOutput = "%09%0A%0D%20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E%60%7B%7C%7D";
assertThat(SdkHttpUtils.urlEncode(null)).isEqualTo(null);
assertThat(SdkHttpUtils.urlEncode("")).isEqualTo("");
assertThat(SdkHttpUtils.urlEncode(nonEncodedCharacters)).isEqualTo(nonEncodedCharacters);
assertThat(SdkHttpUtils.urlEncode(encodedCharactersInput)).isEqualTo(encodedCharactersOutput);
}
@Test
public void encodeUrlIgnoreSlashesEncodesCorrectly() {
String nonEncodedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~/";
String encodedCharactersInput = "\t\n\r !\"#$%&'()*+,:;<=>?@[\\]^`{|}";
String encodedCharactersOutput = "%09%0A%0D%20%21%22%23%24%25%26%27%28%29%2A%2B%2C%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E%60%7B%7C%7D";
assertThat(SdkHttpUtils.urlEncodeIgnoreSlashes(null)).isEqualTo(null);
assertThat(SdkHttpUtils.urlEncodeIgnoreSlashes("")).isEqualTo("");
assertThat(SdkHttpUtils.urlEncodeIgnoreSlashes(nonEncodedCharacters)).isEqualTo(nonEncodedCharacters);
assertThat(SdkHttpUtils.urlEncodeIgnoreSlashes(encodedCharactersInput)).isEqualTo(encodedCharactersOutput);
}
@Test
public void formDataValuesEncodeCorrectly() {
String nonEncodedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.*";
String encodedCharactersInput = "\t\n\r !\"#$%&'()+,/:;<=>?@[\\]^`{|}~";
String encodedCharactersOutput = "%09%0A%0D+%21%22%23%24%25%26%27%28%29%2B%2C%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E%60%7B%7C%7D%7E";
assertThat(SdkHttpUtils.formDataEncode(null)).isEqualTo(null);
assertThat(SdkHttpUtils.formDataEncode("")).isEqualTo("");
assertThat(SdkHttpUtils.formDataEncode(nonEncodedCharacters)).isEqualTo(nonEncodedCharacters);
assertThat(SdkHttpUtils.formDataEncode(encodedCharactersInput)).isEqualTo(encodedCharactersOutput);
}
@Test
public void encodeFlattenBehavesCorrectly() {
HashMap<String, List<String>> values = new LinkedHashMap<>();
values.put("SingleValue", singletonList("Value"));
values.put("SpaceValue", singletonList(" "));
values.put("EncodedValue", singletonList("/"));
values.put("NoValue", null);
values.put("NullValue", singletonList(null));
values.put("BlankValue", singletonList(""));
values.put("MultiValue", asList("Value1", "Value2"));
String expectedQueryString = "SingleValue=Value&SpaceValue=%20&EncodedValue=%2F&NullValue&BlankValue=&MultiValue=Value1&MultiValue=Value2";
String expectedFormDataString = "SingleValue=Value&SpaceValue=+&EncodedValue=%2F&NullValue&BlankValue=&MultiValue=Value1&MultiValue=Value2";
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.encodeAndFlattenQueryParameters(null));
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.encodeAndFlattenFormData(null));
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.encodeFormData(null));
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.encodeQueryParameters(null));
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.flattenQueryParameters(null));
assertThat(SdkHttpUtils.encodeAndFlattenQueryParameters(values)).hasValue(expectedQueryString);
assertThat(SdkHttpUtils.encodeAndFlattenFormData(values)).hasValue(expectedFormDataString);
assertThat(SdkHttpUtils.encodeAndFlattenQueryParameters(Collections.emptyMap())).isNotPresent();
assertThat(SdkHttpUtils.encodeAndFlattenQueryParameters(Collections.emptyMap())).isNotPresent();
}
@Test
public void urisAppendCorrectly() {
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.appendUri(null, ""));
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.appendUri(null, null));
assertThat(SdkHttpUtils.appendUri("", null)).isEqualTo("");
assertThat(SdkHttpUtils.appendUri("", "")).isEqualTo("");
assertThat(SdkHttpUtils.appendUri("", "bar")).isEqualTo("/bar");
assertThat(SdkHttpUtils.appendUri("", "/bar")).isEqualTo("/bar");
assertThat(SdkHttpUtils.appendUri("", "bar/")).isEqualTo("/bar/");
assertThat(SdkHttpUtils.appendUri("", "/bar/")).isEqualTo("/bar/");
assertThat(SdkHttpUtils.appendUri("foo.com", null)).isEqualTo("foo.com");
assertThat(SdkHttpUtils.appendUri("foo.com", "")).isEqualTo("foo.com");
assertThat(SdkHttpUtils.appendUri("foo.com/", "")).isEqualTo("foo.com/");
assertThat(SdkHttpUtils.appendUri("foo.com", "bar")).isEqualTo("foo.com/bar");
assertThat(SdkHttpUtils.appendUri("foo.com/", "bar")).isEqualTo("foo.com/bar");
assertThat(SdkHttpUtils.appendUri("foo.com", "/bar")).isEqualTo("foo.com/bar");
assertThat(SdkHttpUtils.appendUri("foo.com/", "/bar")).isEqualTo("foo.com/bar");
assertThat(SdkHttpUtils.appendUri("foo.com/", "/bar/")).isEqualTo("foo.com/bar/");
assertThat(SdkHttpUtils.appendUri("foo.com/", "//bar/")).isEqualTo("foo.com//bar/");
}
@Test
public void standardPortsAreCorrect() {
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.standardPort(null));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> SdkHttpUtils.standardPort("foo"));
assertThat(SdkHttpUtils.standardPort("http")).isEqualTo(80);
assertThat(SdkHttpUtils.standardPort("https")).isEqualTo(443);
assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.isUsingStandardPort(null, 80));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> SdkHttpUtils.isUsingStandardPort("foo", 80));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> SdkHttpUtils.isUsingStandardPort("foo", null));
assertThat(SdkHttpUtils.isUsingStandardPort("http", null)).isTrue();
assertThat(SdkHttpUtils.isUsingStandardPort("https", null)).isTrue();
assertThat(SdkHttpUtils.isUsingStandardPort("http", -1)).isTrue();
assertThat(SdkHttpUtils.isUsingStandardPort("https", -1)).isTrue();
assertThat(SdkHttpUtils.isUsingStandardPort("http", 80)).isTrue();
assertThat(SdkHttpUtils.isUsingStandardPort("http", 8080)).isFalse();
assertThat(SdkHttpUtils.isUsingStandardPort("https", 443)).isTrue();
assertThat(SdkHttpUtils.isUsingStandardPort("https", 8443)).isFalse();
}
@Test
public void headerRetrievalWorksCorrectly() {
Map<String, List<String>> headers = new HashMap<>();
headers.put("FOO", asList("bar", "baz"));
headers.put("foo", singletonList(null));
headers.put("other", singletonList("foo"));
headers.put("Foo", singletonList("baz2"));
assertThat(SdkHttpUtils.allMatchingHeaders(headers, "foo")).containsExactly("bar", "baz", null, "baz2");
assertThat(SdkHttpUtils.firstMatchingHeader(headers, "foo")).hasValue("bar");
assertThat(SdkHttpUtils.firstMatchingHeader(headers, "other")).hasValue("foo");
assertThat(SdkHttpUtils.firstMatchingHeader(headers, null)).isNotPresent();
assertThat(SdkHttpUtils.firstMatchingHeader(headers, "nothing")).isNotPresent();
}
@Test
public void headersFromCollectionWorksCorrectly() {
Map<String, List<String>> headers = new HashMap<>();
headers.put("FOO", asList("bar", "baz"));
headers.put("foo", singletonList(null));
headers.put("other", singletonList("foo"));
headers.put("Foo", singletonList("baz2"));
assertThat(SdkHttpUtils.allMatchingHeadersFromCollection(headers, asList("nothing"))).isEmpty();
assertThat(SdkHttpUtils.allMatchingHeadersFromCollection(headers, asList("foo")))
.containsExactlyInAnyOrder("bar", "baz", null, "baz2");
assertThat(SdkHttpUtils.allMatchingHeadersFromCollection(headers, asList("nothing", "foo")))
.containsExactlyInAnyOrder("bar", "baz", null, "baz2");
assertThat(SdkHttpUtils.allMatchingHeadersFromCollection(headers, asList("foo", "nothing")))
.containsExactlyInAnyOrder("bar", "baz", null, "baz2");
assertThat(SdkHttpUtils.allMatchingHeadersFromCollection(headers, asList("foo", "other")))
.containsExactlyInAnyOrder("bar", "baz", null, "foo", "baz2");
assertThat(SdkHttpUtils.firstMatchingHeaderFromCollection(headers, asList("nothing"))).isEmpty();
assertThat(SdkHttpUtils.firstMatchingHeaderFromCollection(headers, asList("foo"))).hasValue("bar");
assertThat(SdkHttpUtils.firstMatchingHeaderFromCollection(headers, asList("nothing", "foo"))).hasValue("bar");
assertThat(SdkHttpUtils.firstMatchingHeaderFromCollection(headers, asList("foo", "nothing"))).hasValue("bar");
assertThat(SdkHttpUtils.firstMatchingHeaderFromCollection(headers, asList("foo", "other"))).hasValue("foo");
}
@Test
public void isSingleHeader() {
assertThat(SdkHttpUtils.isSingleHeader("age")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("authorization")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("content-length")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("content-location")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("content-md5")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("content-range")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("content-type")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("date")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("etag")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("expires")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("from")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("host")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("if-modified-since")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("if-range")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("if-unmodified-since")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("last-modified")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("location")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("max-forwards")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("proxy-authorization")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("range")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("referer")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("retry-after")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("server")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("user-agent")).isTrue();
assertThat(SdkHttpUtils.isSingleHeader("custom")).isFalse();
}
@Test
public void uriParams() throws URISyntaxException {
URI uri = URI.create("https://github.com/aws/aws-sdk-java-v2/issues/2034?reqParam=1234&oParam=3456&reqParam=5678&noval"
+ "&decoded%26Part=equals%3Dval");
Map<String, List<String>> uriParams = SdkHttpUtils.uriParams(uri);
assertThat(uriParams).contains(entry("reqParam", Arrays.asList("1234", "5678")),
entry("oParam", Collections.singletonList("3456")),
entry("noval", Arrays.asList((String)null)),
entry("decoded&Part", Arrays.asList("equals=val")));
}
}
| 2,932 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/BinaryUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.internal.Base16Lower;
public class BinaryUtilsTest {
@Test
public void testHex() {
{
String hex = BinaryUtils.toHex(new byte[] {0});
String hex2 = Base16Lower.encodeAsString(new byte[] {0});
assertEquals(hex, hex2);
}
{
String hex = BinaryUtils.toHex(new byte[] {-1});
String hex2 = Base16Lower.encodeAsString(new byte[] {-1});
assertEquals(hex, hex2);
}
}
@Test
public void testCopyBytes_Nulls() {
assertNull(BinaryUtils.copyAllBytesFrom(null));
assertNull(BinaryUtils.copyBytesFrom(null));
}
@Test
public void testCopyBytesFromByteBuffer() {
byte[] ba = {1, 2, 3, 4, 5};
// capacity: 100
final ByteBuffer b = ByteBuffer.allocate(100);
b.put(ba);
// limit: 5
b.limit(5);
assertTrue(b.capacity() > b.limit());
b.rewind();
assertTrue(b.position() == 0);
b.get();
assertTrue(b.position() == 1);
// backing array
byte[] array = b.array();
assertTrue(array.length == 100);
// actual data length
byte[] allData = BinaryUtils.copyAllBytesFrom(b);
assertTrue(allData.length == 5);
// copy, not reference
assertFalse(ba == allData);
// partial data length
byte[] partialData = BinaryUtils.copyBytesFrom(b);
assertTrue(partialData.length == 4);
}
@Test
public void testCopyBytesFrom_DirectByteBuffer() {
byte[] ba = {1, 2, 3, 4, 5};
// capacity: 100
final ByteBuffer b = ByteBuffer.allocateDirect(100);
b.put(ba);
// limit: 5
b.limit(5);
assertTrue(b.capacity() > b.limit());
b.rewind();
assertTrue(b.position() == 0);
b.get();
assertTrue(b.position() == 1);
// backing array
assertFalse(b.hasArray());
assertTrue(b.capacity() == 100);
// actual data length
byte[] allData = BinaryUtils.copyAllBytesFrom(b);
assertTrue(allData.length == 5);
// copy, not reference
assertFalse(ba == allData);
// partial data length
byte[] partialData = BinaryUtils.copyBytesFrom(b);
assertTrue(partialData.length == 4);
}
@Test
public void testCopyBytesFromByteBuffer_Idempotent() {
byte[] ba = {1, 2, 3, 4, 5};
final ByteBuffer b = ByteBuffer.wrap(ba);
b.limit(4);
assertTrue(b.limit() == 4);
b.rewind();
assertTrue(b.position() == 0);
b.get();
assertTrue(b.position() == 1);
// copy all bytes should be idempotent
byte[] allData1 = BinaryUtils.copyAllBytesFrom(b);
assertTrue(b.position() == 1);
byte[] allData2 = BinaryUtils.copyAllBytesFrom(b);
assertTrue(b.position() == 1);
assertFalse(allData1 == allData2);
assertTrue(allData1.length == 4);
assertTrue(Arrays.equals(new byte[] {1, 2, 3, 4}, allData1));
// copy partial bytes should be idempotent
byte[] partial1 = BinaryUtils.copyBytesFrom(b);
assertTrue(b.position() == 1);
byte[] partial2 = BinaryUtils.copyBytesFrom(b);
assertTrue(b.position() == 1);
assertFalse(partial1 == partial2);
assertTrue(partial1.length == 3);
assertTrue(Arrays.equals(new byte[] {2, 3, 4}, partial1));
}
@Test
public void testCopyBytesFrom_DirectByteBuffer_Idempotent() {
byte[] ba = {1, 2, 3, 4, 5};
final ByteBuffer b = ByteBuffer.allocateDirect(ba.length);
b.put(ba).rewind();
b.limit(4);
assertTrue(b.limit() == 4);
b.rewind();
assertTrue(b.position() == 0);
b.get();
assertTrue(b.position() == 1);
// copy all bytes should be idempotent
byte[] allData1 = BinaryUtils.copyAllBytesFrom(b);
assertTrue(b.position() == 1);
byte[] allData2 = BinaryUtils.copyAllBytesFrom(b);
assertTrue(b.position() == 1);
assertFalse(allData1 == allData2);
assertTrue(allData1.length == 4);
assertTrue(Arrays.equals(new byte[] {1, 2, 3, 4}, allData1));
// copy partial bytes should be idempotent
byte[] partial1 = BinaryUtils.copyBytesFrom(b);
assertTrue(b.position() == 1);
byte[] partial2 = BinaryUtils.copyBytesFrom(b);
assertTrue(b.position() == 1);
assertFalse(partial1 == partial2);
assertTrue(partial1.length == 3);
assertTrue(Arrays.equals(new byte[] {2, 3, 4}, partial1));
}
@Test
public void testCopyRemainingBytesFrom_nullBuffer() {
assertThat(BinaryUtils.copyRemainingBytesFrom(null)).isNull();
}
@Test
public void testCopyRemainingBytesFrom_noRemainingBytes() {
ByteBuffer bb = ByteBuffer.allocate(1);
bb.put(new byte[] {1});
bb.flip();
bb.get();
assertThat(BinaryUtils.copyRemainingBytesFrom(bb)).hasSize(0);
}
@Test
public void testCopyRemainingBytesFrom_fullBuffer() {
ByteBuffer bb = ByteBuffer.allocate(4);
bb.put(new byte[] {1, 2, 3, 4});
bb.flip();
byte[] copy = BinaryUtils.copyRemainingBytesFrom(bb);
assertThat(bb).isEqualTo(ByteBuffer.wrap(copy));
assertThat(copy).hasSize(4);
}
@Test
public void testCopyRemainingBytesFrom_partiallyReadBuffer() {
ByteBuffer bb = ByteBuffer.allocate(4);
bb.put(new byte[] {1, 2, 3, 4});
bb.flip();
bb.get();
bb.get();
byte[] copy = BinaryUtils.copyRemainingBytesFrom(bb);
assertThat(bb).isEqualTo(ByteBuffer.wrap(copy));
assertThat(copy).hasSize(2);
}
@Test
public void testImmutableCopyOfByteBuffer() {
ByteBuffer sourceBuffer = ByteBuffer.allocate(4);
byte[] originalBytesInSource = {1, 2, 3, 4};
sourceBuffer.put(originalBytesInSource);
sourceBuffer.flip();
ByteBuffer immutableCopy = BinaryUtils.immutableCopyOf(sourceBuffer);
byte[] bytesInSourceAfterCopy = {-1, -2, -3, -4};
sourceBuffer.put(bytesInSourceAfterCopy);
sourceBuffer.flip();
assertTrue(immutableCopy.isReadOnly());
byte[] fromImmutableCopy = new byte[originalBytesInSource.length];
immutableCopy.get(fromImmutableCopy);
assertArrayEquals(originalBytesInSource, fromImmutableCopy);
assertEquals(0, sourceBuffer.position());
byte[] fromSource = new byte[bytesInSourceAfterCopy.length];
sourceBuffer.get(fromSource);
assertArrayEquals(bytesInSourceAfterCopy, fromSource);
}
@Test
public void immutableCopyOf_retainsOriginalLimit() {
ByteBuffer sourceBuffer = ByteBuffer.allocate(10);
byte[] bytes = {1, 2, 3, 4};
sourceBuffer.put(bytes);
sourceBuffer.rewind();
sourceBuffer.limit(bytes.length);
ByteBuffer copy = BinaryUtils.immutableCopyOf(sourceBuffer);
assertThat(copy.limit()).isEqualTo(sourceBuffer.limit());
}
@Test
public void testImmutableCopyOfByteBuffer_nullBuffer() {
assertNull(BinaryUtils.immutableCopyOf(null));
}
@Test
public void testImmutableCopyOfByteBuffer_partiallyReadBuffer() {
ByteBuffer sourceBuffer = ByteBuffer.allocate(4);
byte[] bytes = {1, 2, 3, 4};
sourceBuffer.put(bytes);
sourceBuffer.position(2);
ByteBuffer immutableCopy = BinaryUtils.immutableCopyOf(sourceBuffer);
assertEquals(sourceBuffer.position(), immutableCopy.position());
immutableCopy.rewind();
byte[] fromImmutableCopy = new byte[bytes.length];
immutableCopy.get(fromImmutableCopy);
assertArrayEquals(bytes, fromImmutableCopy);
}
@Test
public void testImmutableCopyOfRemainingByteBuffer() {
ByteBuffer sourceBuffer = ByteBuffer.allocate(4);
byte[] originalBytesInSource = {1, 2, 3, 4};
sourceBuffer.put(originalBytesInSource);
sourceBuffer.flip();
ByteBuffer immutableCopy = BinaryUtils.immutableCopyOfRemaining(sourceBuffer);
byte[] bytesInSourceAfterCopy = {-1, -2, -3, -4};
sourceBuffer.put(bytesInSourceAfterCopy);
sourceBuffer.flip();
assertTrue(immutableCopy.isReadOnly());
byte[] fromImmutableCopy = new byte[originalBytesInSource.length];
immutableCopy.get(fromImmutableCopy);
assertArrayEquals(originalBytesInSource, fromImmutableCopy);
assertEquals(0, sourceBuffer.position());
byte[] fromSource = new byte[bytesInSourceAfterCopy.length];
sourceBuffer.get(fromSource);
assertArrayEquals(bytesInSourceAfterCopy, fromSource);
}
@Test
public void testImmutableCopyOfByteBufferRemaining_nullBuffer() {
assertNull(BinaryUtils.immutableCopyOfRemaining(null));
}
@Test
public void testImmutableCopyOfByteBufferRemaining_partiallyReadBuffer() {
ByteBuffer sourceBuffer = ByteBuffer.allocate(4);
byte[] bytes = {1, 2, 3, 4};
sourceBuffer.put(bytes);
sourceBuffer.position(2);
ByteBuffer immutableCopy = BinaryUtils.immutableCopyOfRemaining(sourceBuffer);
assertEquals(2, immutableCopy.capacity());
assertEquals(2, immutableCopy.remaining());
assertEquals(0, immutableCopy.position());
assertEquals((byte) 3, immutableCopy.get());
assertEquals((byte) 4, immutableCopy.get());
}
@Test
public void testToNonDirectBuffer() {
ByteBuffer bb = ByteBuffer.allocateDirect(4);
byte[] expected = {1, 2, 3, 4};
bb.put(expected);
bb.flip();
ByteBuffer nonDirectBuffer = BinaryUtils.toNonDirectBuffer(bb);
assertFalse(nonDirectBuffer.isDirect());
byte[] bytes = new byte[expected.length];
nonDirectBuffer.get(bytes);
assertArrayEquals(expected, bytes);
}
@Test
public void testToNonDirectBuffer_nullBuffer() {
assertNull(BinaryUtils.toNonDirectBuffer(null));
}
@Test
public void testToNonDirectBuffer_partiallyReadBuffer() {
ByteBuffer sourceBuffer = ByteBuffer.allocateDirect(4);
byte[] bytes = {1, 2, 3, 4};
sourceBuffer.put(bytes);
sourceBuffer.position(2);
ByteBuffer nonDirectBuffer = BinaryUtils.toNonDirectBuffer(sourceBuffer);
assertEquals(sourceBuffer.position(), nonDirectBuffer.position());
nonDirectBuffer.rewind();
byte[] fromNonDirectBuffer = new byte[bytes.length];
nonDirectBuffer.get(fromNonDirectBuffer);
assertArrayEquals(bytes, fromNonDirectBuffer);
}
@Test
public void testToNonDirectBuffer_nonDirectBuffer() {
ByteBuffer nonDirectBuffer = ByteBuffer.allocate(0);
assertThrows(IllegalArgumentException.class, () -> BinaryUtils.toNonDirectBuffer(nonDirectBuffer));
}
}
| 2,933 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ImmutableMapTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.Collections;
import java.util.Map;
import org.junit.jupiter.api.Test;
/**
* Unit tests for the ImmutableMapTest class.
*/
public class ImmutableMapTest {
@Test
public void testMapBuilder() {
Map<Integer, String> builtMap = new ImmutableMap.Builder<Integer, String>()
.put(1, "one")
.put(2, "two")
.put(3, "three")
.build();
assertEquals(3, builtMap.size());
assertEquals("one", builtMap.get(1));
assertEquals("two", builtMap.get(2));
assertEquals("three", builtMap.get(3));
}
@Test
public void testOfBuilder() {
Map<Integer, String> builtMap = ImmutableMap.of(1, "one");
assertEquals(1, builtMap.size());
assertEquals("one", builtMap.get(1));
builtMap = ImmutableMap.of(1, "one", 2, "two");
assertEquals(2, builtMap.size());
assertEquals("one", builtMap.get(1));
assertEquals("two", builtMap.get(2));
builtMap = ImmutableMap.of(1, "one", 2, "two", 3, "three");
assertEquals(3, builtMap.size());
assertEquals("one", builtMap.get(1));
assertEquals("two", builtMap.get(2));
assertEquals("three", builtMap.get(3));
builtMap = ImmutableMap.of(1, "one", 2, "two", 3, "three", 4, "four");
assertEquals(4, builtMap.size());
assertEquals("one", builtMap.get(1));
assertEquals("two", builtMap.get(2));
assertEquals("three", builtMap.get(3));
assertEquals("four", builtMap.get(4));
builtMap = ImmutableMap.of(1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
assertEquals(5, builtMap.size());
assertEquals("one", builtMap.get(1));
assertEquals("two", builtMap.get(2));
assertEquals("three", builtMap.get(3));
assertEquals("four", builtMap.get(4));
assertEquals("five", builtMap.get(5));
}
@Test
public void testErrorOnDuplicateKeys() {
try {
Map<Integer, String> builtMap = new ImmutableMap.Builder<Integer, String>()
.put(1, "one")
.put(1, "two")
.build();
fail("IllegalArgumentException expected.");
} catch (IllegalArgumentException iae) {
// Ignored or expected.
} catch (Exception e) {
fail("IllegalArgumentException expected.");
}
}
@Test
public void testMapOperations() {
Map<Integer, String> builtMap = new ImmutableMap.Builder<Integer, String>()
.put(1, "one")
.put(2, "two")
.put(3, "three")
.build();
assertTrue(builtMap.containsKey(1));
assertTrue(builtMap.containsValue("one"));
assertTrue(builtMap.values().contains("one"));
assertEquals("one", builtMap.get(1));
assertEquals(3, builtMap.entrySet().size());
assertEquals(3, builtMap.values().size());
assertEquals(3, builtMap.size());
/** Unsupported methods **/
try {
builtMap.clear();
fail("UnsupportedOperationException expected.");
} catch (UnsupportedOperationException iae) {
// Ignored or expected.
} catch (Exception e) {
fail("UnsupportedOperationException expected.");
}
try {
builtMap.put(4, "four");
fail("UnsupportedOperationException expected.");
} catch (UnsupportedOperationException iae) {
// Ignored or expected.
} catch (Exception e) {
fail("UnsupportedOperationException expected.");
}
try {
builtMap.putAll(Collections.singletonMap(4, "four"));
fail("UnsupportedOperationException expected.");
} catch (UnsupportedOperationException iae) {
// Ignored or expected.
} catch (Exception e) {
fail("UnsupportedOperationException expected.");
}
try {
builtMap.remove(1);
fail("UnsupportedOperationException expected.");
} catch (UnsupportedOperationException iae) {
// Ignored or expected.
} catch (Exception e) {
fail("UnsupportedOperationException expected.");
}
}
}
| 2,934 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/FunctionalUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import static software.amazon.awssdk.utils.FunctionalUtils.safeConsumer;
import static software.amazon.awssdk.utils.FunctionalUtils.safeFunction;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Optional;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
public class FunctionalUtilsTest {
private static final boolean DONT_THROW_EXCEPTION = false;
private static final boolean THROW_EXCEPTION = true;
@Test
public void checkedExceptionsAreConvertedToRuntimeExceptions() {
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> invokeSafely(this::methodThatThrows))
.withCauseInstanceOf(Exception.class);
}
@Test
public void ioExceptionsAreConvertedToUncheckedIoExceptions() {
assertThatExceptionOfType(UncheckedIOException.class)
.isThrownBy(() -> invokeSafely(this::methodThatThrowsIOException))
.withCauseInstanceOf(IOException.class);
}
@Test
public void runtimeExceptionsAreNotWrapped() {
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> invokeSafely(this::methodWithCheckedSignatureThatThrowsRuntimeException))
.withNoCause();
}
@Test
public void canUseConsumerThatThrowsCheckedExceptionInLambda() {
Stream.of(DONT_THROW_EXCEPTION).forEach(safeConsumer(this::consumerMethodWithChecked));
}
@Test
public void exceptionsForConsumersAreConverted() {
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> Stream.of(THROW_EXCEPTION).forEach(safeConsumer(this::consumerMethodWithChecked)))
.withCauseExactlyInstanceOf(Exception.class);
}
@Test
public void canUseFunctionThatThrowsCheckedExceptionInLambda() {
Optional<String> result = Stream.of(DONT_THROW_EXCEPTION).map(safeFunction(this::functionMethodWithChecked)).findFirst();
assertThat(result).isPresent().contains("Hello");
}
@Test
@SuppressWarnings("ResultOfMethodCallIgnored")
public void exceptionsForFunctionsAreConverted() {
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> Stream.of(THROW_EXCEPTION).map(safeFunction(this::functionMethodWithChecked)).findFirst())
.withCauseExactlyInstanceOf(Exception.class);
}
@Test
public void interruptedExceptionShouldSetInterruptedOnTheThread() {
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> invokeSafely(this::methodThatThrowsInterruptedException))
.withCauseInstanceOf(InterruptedException.class);
assertThat(Thread.currentThread().isInterrupted()).isTrue();
// Clear interrupt flag
Thread.interrupted();
}
private String methodThatThrows() throws Exception {
throw new Exception("Ouch");
}
private String methodThatThrowsIOException() throws IOException {
throw new IOException("Boom");
}
private String methodWithCheckedSignatureThatThrowsRuntimeException() throws Exception {
throw new RuntimeException("Uh oh");
}
private String methodThatThrowsInterruptedException() throws InterruptedException {
throw new InterruptedException();
}
private void consumerMethodWithChecked(Boolean shouldThrow) throws Exception {
if (shouldThrow) {
throw new Exception("Duh, something went wrong");
}
}
private String functionMethodWithChecked(Boolean shouldThrow) throws Exception {
if (shouldThrow) {
throw new Exception("Duh, something went wrong");
}
return "Hello";
}
}
| 2,935 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/AttributeMapTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.mockito.Mockito;
import org.w3c.dom.Attr;
public class AttributeMapTest {
private static final AttributeMap.Key<String> STRING_KEY = new AttributeMap.Key<String>(String.class) {
};
private static final AttributeMap.Key<Integer> INTEGER_KEY = new AttributeMap.Key<Integer>(Integer.class) {
};
private static final AttributeMap.Key<AutoCloseable> CLOSEABLE_KEY = new AttributeMap.Key<AutoCloseable>(AutoCloseable.class) {
};
private static final AttributeMap.Key<ExecutorService> EXECUTOR_SERVICE_KEY =
new AttributeMap.Key<ExecutorService>(ExecutorService.class) {
};
@Test
public void copyCreatesNewOptionsObject() {
AttributeMap orig = AttributeMap.builder()
.put(STRING_KEY, "foo")
.build();
assertTrue(orig != orig.copy());
assertThat(orig).isEqualTo(orig.copy());
assertThat(orig.get(STRING_KEY)).isEqualTo(orig.copy().get(STRING_KEY));
}
@Test
public void mergeTreatsThisObjectWithHigherPrecedence() {
AttributeMap orig = AttributeMap.builder()
.put(STRING_KEY, "foo")
.build();
AttributeMap merged = orig.merge(AttributeMap.builder()
.put(STRING_KEY, "bar")
.put(INTEGER_KEY, 42)
.build());
assertThat(merged.containsKey(STRING_KEY)).isTrue();
assertThat(merged.get(STRING_KEY)).isEqualTo("foo");
// Integer key is not in 'this' object so it should be merged in from the lower precedence
assertThat(merged.get(INTEGER_KEY)).isEqualTo(42);
}
/**
* Options are optional.
*/
@Test
public void mergeWithOptionNotPresentInBoth_DoesNotThrow() {
AttributeMap orig = AttributeMap.builder()
.put(STRING_KEY, "foo")
.build();
AttributeMap merged = orig.merge(AttributeMap.builder()
.put(STRING_KEY, "bar")
.build());
assertThat(merged.get(INTEGER_KEY)).isNull();
}
@Test(expected = IllegalArgumentException.class)
public void putAll_ThrowsRuntimeExceptionWhenTypesMismatched() {
Map<AttributeMap.Key<?>, Object> attributes = new HashMap<>();
attributes.put(STRING_KEY, 42);
AttributeMap.builder()
.putAll(attributes)
.build();
}
@Test
public void close_closesAll() {
SdkAutoCloseable closeable = mock(SdkAutoCloseable.class);
ExecutorService executor = mock(ExecutorService.class);
AttributeMap.builder()
.put(CLOSEABLE_KEY, closeable)
.put(EXECUTOR_SERVICE_KEY, executor)
.build()
.close();
verify(closeable).close();
verify(executor).shutdown();
}
@Test
public void lazyAttributes_resolvedWhenRead() {
AttributeMap map = mapWithLazyString();
assertThat(map.get(STRING_KEY)).isEqualTo("5");
}
@Test
public void lazyAttributesBuilder_resolvedWhenRead() {
AttributeMap.Builder map = mapBuilderWithLazyString();
assertThat(map.get(STRING_KEY)).isEqualTo("5");
map.put(INTEGER_KEY, 6);
assertThat(map.get(STRING_KEY)).isEqualTo("6");
}
@Test
public void lazyAttributes_resultCached() {
AttributeMap.Builder map = mapBuilderWithLazyString();
String originalGet = map.get(STRING_KEY);
assertThat(map.get(STRING_KEY)).isSameAs(originalGet);
map.put(CLOSEABLE_KEY, null);
assertThat(map.get(STRING_KEY)).isSameAs(originalGet);
}
@Test
public void lazyAttributesBuilder_resolvedWhenBuilt() {
Runnable lazyRead = mock(Runnable.class);
AttributeMap.Builder map = mapBuilderWithLazyString(lazyRead);
verify(lazyRead, never()).run();
map.build();
verify(lazyRead, Mockito.times(1)).run();
}
@Test
public void lazyAttributes_notReResolvedAfterToBuilderBuild() {
Runnable lazyRead = mock(Runnable.class);
AttributeMap.Builder map = mapBuilderWithLazyString(lazyRead);
verify(lazyRead, never()).run();
AttributeMap builtMap = map.build();
verify(lazyRead, Mockito.times(1)).run();
builtMap.toBuilder().build().toBuilder().build();
verify(lazyRead, Mockito.times(1)).run();
}
@Test
public void changesInBuilder_doNotAffectBuiltMap() {
AttributeMap.Builder builder = mapBuilderWithLazyString();
AttributeMap map = builder.build();
builder.put(INTEGER_KEY, 6);
assertThat(builder.get(INTEGER_KEY)).isEqualTo(6);
assertThat(builder.get(STRING_KEY)).isEqualTo("6");
assertThat(map.get(INTEGER_KEY)).isEqualTo(5);
assertThat(map.get(STRING_KEY)).isEqualTo("5");
}
@Test
public void changesInToBuilder_doNotAffectBuiltMap() {
AttributeMap map = mapWithLazyString();
AttributeMap.Builder builder = map.toBuilder();
builder.put(INTEGER_KEY, 6);
assertThat(builder.get(INTEGER_KEY)).isEqualTo(6);
assertThat(builder.get(STRING_KEY)).isEqualTo("6");
assertThat(map.get(INTEGER_KEY)).isEqualTo(5);
assertThat(map.get(STRING_KEY)).isEqualTo("5");
}
@Test
public void close_ExecutorDoesNotDeadlockOnClose() throws Exception {
SdkAutoCloseable closeable = mock(SdkAutoCloseable.class);
ExecutorService executor = Executors.newSingleThreadExecutor();
AttributeMap attributeMap = AttributeMap.builder()
.put(CLOSEABLE_KEY, closeable)
.put(EXECUTOR_SERVICE_KEY, executor)
.build();
// Previously, running AttributeMap#close from a thread managed by the ExecutorService
// that's stored in that AttributeMap instance would result in a deadlock, where this
// invocation would time out. This verifies that that scenario no longer happens.
CompletableFuture.runAsync(attributeMap::close, executor).get(5L, TimeUnit.SECONDS);
verify(closeable).close();
assertThat(executor.isShutdown()).isTrue();
}
/**
* This tests that the {@link ExecutorService} which as of Java 21 implements the {@link AutoCloseable}
* interface, doesn't have its {@link AutoCloseable#close()} method called, but instead the expected
* {@link ExecutorService#shutdown()} method is.
*
* This test scenario can be removed when the SDK upgrades its minimum supported version to Java 21,
* whereupon this scenario will be handled by {@link AttributeMapTest#close_closesAll}.
*/
@Test
public void close_shutsDownExecutorService() throws Exception {
SdkAutoCloseable closeable = mock(SdkAutoCloseable.class);
CloseableExecutorService executor = mock(CloseableExecutorService.class);
AttributeMap.builder()
.put(CLOSEABLE_KEY, closeable)
.put(EXECUTOR_SERVICE_KEY, executor)
.build()
.close();
verify(closeable).close();
verify(executor, never()).close();
verify(executor).shutdown();
}
/**
* Simulates the API contract of the ExecutorService as of Java 21, where it extends the
* {@link AutoCloseable} interface and is susceptible to being closed by {@link AttributeMap#close()}.
*/
private interface CloseableExecutorService extends ExecutorService, AutoCloseable {}
private static AttributeMap mapWithLazyString() {
return mapBuilderWithLazyString().build();
}
private static AttributeMap.Builder mapBuilderWithLazyString() {
return mapBuilderWithLazyString(() -> {});
}
private static AttributeMap.Builder mapBuilderWithLazyString(Runnable runOnLazyRead) {
return AttributeMap.builder()
.putLazy(STRING_KEY, c -> {
runOnLazyRead.run();
return Integer.toString(c.get(INTEGER_KEY));
})
.put(INTEGER_KEY, 5);
}
}
| 2,936 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ReflectionMethodInvokerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.lang.reflect.InvocationTargetException;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ReflectionMethodInvokerTest {
private final InvokeTestClass invokeTestInstance = new InvokeTestClass();
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void invokeCanInvokeMethodAndReturnsCorrectResult() throws Exception {
ReflectionMethodInvoker<String, Integer> invoker =
new ReflectionMethodInvoker<>(String.class,
Integer.class,
"indexOf",
String.class,
int.class);
assertThat(invoker.invoke("ababab", "ab", 1), is(2));
}
@Test
public void invokeCanReturnVoid() throws Exception {
ReflectionMethodInvoker<InvokeTestClass, Void> invoker =
new ReflectionMethodInvoker<>(InvokeTestClass.class,
Void.class,
"happyVoid");
invoker.invoke(invokeTestInstance);
}
@Test
public void invokeThrowsNoSuchMethodExceptionWhenMethodSignatureNotFound() throws Exception {
ReflectionMethodInvoker<String, Integer> invoker =
new ReflectionMethodInvoker<>(String.class,
Integer.class,
"foo",
String.class,
int.class);
exception.expect(NoSuchMethodException.class);
invoker.invoke("ababab", "ab", 1);
}
@Test
public void invoke_callThrowsNullPointerException_throwsAsRuntimeException() throws Exception {
ReflectionMethodInvoker<String, Integer> invoker =
new ReflectionMethodInvoker<>(String.class,
Integer.class,
null,
String.class,
int.class);
exception.expect(RuntimeException.class);
exception.expectCause(Matchers.<NullPointerException>instanceOf(NullPointerException.class));
exception.expectMessage("String");
invoker.invoke("ababab", "ab", 1);
}
@Test
public void invoke_invokedMethodThrowsException_throwsAsRuntimeException() throws Exception {
ReflectionMethodInvoker<InvokeTestClass, Void> invoker =
new ReflectionMethodInvoker<>(InvokeTestClass.class,
Void.class,
"throwsException");
exception.expect(RuntimeException.class);
exception.expectMessage("InvokeTestClass");
exception.expectMessage("throwsException");
exception.expectCause(Matchers.<InvocationTargetException>instanceOf(InvocationTargetException.class));
invoker.invoke(invokeTestInstance);
}
@Test
public void invoke_invokePrivateMethod_throwsNoSuchMethodException() throws Exception {
ReflectionMethodInvoker<InvokeTestClass, Void> invoker =
new ReflectionMethodInvoker<>(InvokeTestClass.class,
Void.class,
"illegalAccessException");
exception.expect(NoSuchMethodException.class);
invoker.invoke(invokeTestInstance);
}
// This test assumes that the result of getMethod() may have been cached, and therefore asserts the correctness of
// a simple cache put and get.
@Test
public void invoke_canBeCalledMultipleTimes() throws Exception {
ReflectionMethodInvoker<String, Integer> invoker =
new ReflectionMethodInvoker<>(String.class,
Integer.class,
"indexOf",
String.class,
int.class);
assertThat(invoker.invoke("ababab", "ab", 1), is(2));
assertThat(invoker.invoke("ababab", "ab", 1), is(2));
}
@Test
public void initialize_methodNotFound_throwsMethodNotFoundException() throws NoSuchMethodException {
ReflectionMethodInvoker<String, Integer> invoker =
new ReflectionMethodInvoker<String, Integer>(String.class,
Integer.class,
"foo",
String.class,
int.class);
exception.expect(NoSuchMethodException.class);
invoker.initialize();
}
@Test
public void isInitialized_methodFoundAndInitialized_returnsTrue() throws Exception {
ReflectionMethodInvoker<String, Integer> invoker =
new ReflectionMethodInvoker<String, Integer>(String.class,
Integer.class,
"indexOf",
String.class,
int.class);
invoker.initialize();
assertThat(invoker.isInitialized(), is(true));
}
@Test
public void isInitialized_methodFoundAndNotInitialized_returnsFalse() throws Exception {
ReflectionMethodInvoker<String, Integer> invoker =
new ReflectionMethodInvoker<String, Integer>(String.class,
Integer.class,
"indexOf",
String.class,
int.class);
assertThat(invoker.isInitialized(), is(false));
}
@Test
public void isInitialized_methodNotFoundAndInitialized_returnsFalse() throws Exception {
ReflectionMethodInvoker<String, Integer> invoker =
new ReflectionMethodInvoker<String, Integer>(String.class,
Integer.class,
"foo",
String.class,
int.class);
try {
invoker.initialize();
fail("Excepted NoSuchMethodException to be thrown");
} catch (NoSuchMethodException ignored) {
}
assertThat(invoker.isInitialized(), is(false));
}
public static class InvokeTestClass {
public void throwsException() {
throw new RuntimeException();
}
private void illegalAccessException() {
// should never get here
}
public void happyVoid() {
}
}
}
| 2,937 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ComparableUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import org.junit.jupiter.api.Test;
public class ComparableUtilsTest {
@Test
public void safeCompare_SecondNull_ReturnsPositive() {
assertThat(ComparableUtils.safeCompare(1.0, null), greaterThan(0));
}
@Test
public void safeCompare_FirstNull_ReturnsNegative() {
assertThat(ComparableUtils.safeCompare(null, 7.0), lessThan(0));
}
@Test
public void safeCompare_BothNull_ReturnsZero() {
assertThat(ComparableUtils.safeCompare(null, null), equalTo(0));
}
@Test
public void safeCompare_FirstLarger_ReturnsPositive() {
assertThat(ComparableUtils.safeCompare(7.0, 6.0), greaterThan(0));
}
@Test
public void safeCompare_SecondLarger_ReturnsNegative() {
assertThat(ComparableUtils.safeCompare(6.0, 7.0), lessThan(0));
}
}
| 2,938 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/DateUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static java.time.ZoneOffset.UTC;
import static java.time.format.DateTimeFormatter.ISO_INSTANT;
import static java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME;
import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static software.amazon.awssdk.utils.DateUtils.ALTERNATE_ISO_8601_DATE_FORMAT;
import static software.amazon.awssdk.utils.DateUtils.RFC_822_DATE_TIME;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
public class DateUtilsTest {
private static final boolean DEBUG = false;
private static final int MAX_MILLIS_YEAR = 292278994;
private static final SimpleDateFormat COMMON_DATE_FORMAT =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
private static final SimpleDateFormat LONG_DATE_FORMAT =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
static {
COMMON_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone(UTC));
LONG_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone(UTC));
}
private static final Instant INSTANT = Instant.ofEpochMilli(1400284606000L);
@Test
public void tt0031561767() {
String input = "Fri, 16 May 2014 23:56:46 GMT";
Instant instant = DateUtils.parseRfc1123Date(input);
assertEquals(input, DateUtils.formatRfc1123Date(instant));
}
@Test
public void formatIso8601Date() throws ParseException {
Date date = Date.from(INSTANT);
String expected = COMMON_DATE_FORMAT.format(date);
String actual = DateUtils.formatIso8601Date(date.toInstant());
assertEquals(expected, actual);
Instant expectedDate = COMMON_DATE_FORMAT.parse(expected).toInstant();
Instant actualDate = DateUtils.parseIso8601Date(actual);
assertEquals(expectedDate, actualDate);
}
@Test
public void formatRfc822Date_DateWithTwoDigitDayOfMonth_ReturnsFormattedString() throws ParseException {
String string = DateUtils.formatRfc822Date(INSTANT);
Instant parsedDateAsInstant = LONG_DATE_FORMAT.parse(string).toInstant();
assertThat(parsedDateAsInstant).isEqualTo(INSTANT);
}
@Test
public void formatRfc822Date_DateWithSingleDigitDayOfMonth_ReturnsFormattedString() throws ParseException {
Instant INSTANT_SINGLE_DIGIT_DAY_OF_MONTH = Instant.ofEpochMilli(1399484606000L);;
String string = DateUtils.formatRfc822Date(INSTANT_SINGLE_DIGIT_DAY_OF_MONTH);
Instant parsedDateAsInstant = LONG_DATE_FORMAT.parse(string).toInstant();
assertThat(parsedDateAsInstant).isEqualTo(INSTANT_SINGLE_DIGIT_DAY_OF_MONTH);
}
@Test
public void formatRfc822Date_DateWithSingleDigitDayOfMonth_ReturnsStringWithZeroLeadingDayOfMonth() throws ParseException {
final Instant INSTANT_SINGLE_DIGIT_DAY_OF_MONTH = Instant.ofEpochMilli(1399484606000L);;
String string = DateUtils.formatRfc822Date(INSTANT_SINGLE_DIGIT_DAY_OF_MONTH);
String expectedString = "Wed, 07 May 2014 17:43:26 GMT";
assertThat(string).isEqualTo(expectedString);
}
@Test
public void parseRfc822Date_DateWithTwoDigitDayOfMonth_ReturnsInstantObject() throws ParseException {
String formattedDate = LONG_DATE_FORMAT.format(Date.from(INSTANT));
Instant parsedInstant = DateUtils.parseRfc822Date(formattedDate);
assertThat(parsedInstant).isEqualTo(INSTANT);
}
@Test
public void parseRfc822Date_DateWithSingleDigitDayOfMonth_ReturnsInstantObject() throws ParseException {
final Instant INSTANT_SINGLE_DIGIT_DAY_OF_MONTH = Instant.ofEpochMilli(1399484606000L);;
String formattedDate = LONG_DATE_FORMAT.format(Date.from(INSTANT_SINGLE_DIGIT_DAY_OF_MONTH));
Instant parsedInstant = DateUtils.parseRfc822Date(formattedDate);
assertThat(parsedInstant).isEqualTo(INSTANT_SINGLE_DIGIT_DAY_OF_MONTH);
}
@Test
public void parseRfc822Date_DateWithInvalidDayOfMonth_IsParsedWithSmartResolverStyle() {
String badDateString = "Wed, 31 Apr 2014 17:43:26 GMT";
String validDateString = "Wed, 30 Apr 2014 17:43:26 GMT";
Instant badDateParsedInstant = DateUtils.parseRfc822Date(badDateString);
Instant validDateParsedInstant = DateUtils.parseRfc1123Date(validDateString);
assertThat(badDateParsedInstant).isEqualTo(validDateParsedInstant);
}
@Test
public void parseRfc822Date_DateWithInvalidDayOfMonth_MatchesRfc1123Behavior() {
String dateString = "Wed, 31 Apr 2014 17:43:26 GMT";
Instant parsedInstantFromRfc822Parser = DateUtils.parseRfc822Date(dateString);
Instant parsedInstantFromRfc1123arser = DateUtils.parseRfc1123Date(dateString);
assertThat(parsedInstantFromRfc822Parser).isEqualTo(parsedInstantFromRfc1123arser);
}
@Test
public void parseRfc822Date_DateWithDayOfMonthLessThan10th_MatchesRfc1123Behavior() {
String rfc822DateString = "Wed, 02 Apr 2014 17:43:26 GMT";
String rfc1123DateString = "Wed, 2 Apr 2014 17:43:26 GMT";
Instant parsedInstantFromRfc822Parser = DateUtils.parseRfc822Date(rfc822DateString);
Instant parsedInstantFromRfc1123arser = DateUtils.parseRfc1123Date(rfc1123DateString);
assertThat(parsedInstantFromRfc822Parser).isEqualTo(parsedInstantFromRfc1123arser);
}
@Test
public void resolverStyleOfRfc822FormatterMatchesRfc1123Formatter() {
assertThat(RFC_822_DATE_TIME.getResolverStyle()).isSameAs(RFC_1123_DATE_TIME.getResolverStyle());
}
@Test
public void chronologyOfRfc822FormatterMatchesRfc1123Formatter() {
assertThat(RFC_822_DATE_TIME.getChronology()).isSameAs(RFC_1123_DATE_TIME.getChronology());
}
@Test
public void formatRfc1123Date() throws ParseException {
String string = DateUtils.formatRfc1123Date(INSTANT);
Instant parsedDateAsInstant = LONG_DATE_FORMAT.parse(string).toInstant();
assertEquals(INSTANT, parsedDateAsInstant);
String formattedDate = LONG_DATE_FORMAT.format(Date.from(INSTANT));
Instant parsedInstant = DateUtils.parseRfc1123Date(formattedDate);
assertEquals(INSTANT, parsedInstant);
}
@Test
public void parseRfc1123Date() throws ParseException {
String formatted = LONG_DATE_FORMAT.format(Date.from(INSTANT));
Instant expected = LONG_DATE_FORMAT.parse(formatted).toInstant();
Instant actual = DateUtils.parseRfc1123Date(formatted);
assertEquals(expected, actual);
}
@Test
public void parseIso8601Date() throws ParseException {
checkParsing(DateTimeFormatter.ISO_INSTANT, COMMON_DATE_FORMAT);
}
@Test
public void parseIso8601Date_withUtcOffset() {
String formatted = "2021-05-10T17:12:13-07:00";
Instant expected = ISO_OFFSET_DATE_TIME.parse(formatted, Instant::from);
Instant actual = DateUtils.parseIso8601Date(formatted);
assertEquals(expected, actual);
String actualString = OffsetDateTime.ofInstant(actual, ZoneId.of("-7")).toString();
assertEquals(formatted, actualString);
}
@Test
public void parseIso8601Date_usingAlternativeFormat() throws ParseException {
checkParsing(ALTERNATE_ISO_8601_DATE_FORMAT, COMMON_DATE_FORMAT);
}
private void checkParsing(DateTimeFormatter dateTimeFormatter, SimpleDateFormat dateFormat) throws ParseException {
String formatted = dateFormat.format(Date.from(INSTANT));
String alternative = dateTimeFormatter.format(INSTANT);
assertEquals(formatted, alternative);
Instant expected = dateFormat.parse(formatted).toInstant();
Instant actualDate = DateUtils.parseIso8601Date(formatted);
assertEquals(expected, actualDate);
}
@Test
public void alternateIso8601DateFormat() throws ParseException {
String expected = COMMON_DATE_FORMAT.format(Date.from(INSTANT));
String actual = ALTERNATE_ISO_8601_DATE_FORMAT.format(INSTANT);
assertEquals(expected, actual);
Date expectedDate = COMMON_DATE_FORMAT.parse(expected);
ZonedDateTime actualDateTime = ZonedDateTime.parse(actual, ALTERNATE_ISO_8601_DATE_FORMAT);
assertEquals(expectedDate, Date.from(actualDateTime.toInstant()));
}
@Test(expected = ParseException.class)
public void legacyHandlingOfInvalidDate() throws ParseException {
final String input = "2014-03-06T14:28:58.000Z.000Z";
COMMON_DATE_FORMAT.parse(input);
}
@Test(expected = DateTimeParseException.class)
public void invalidDate() {
final String input = "2014-03-06T14:28:58.000Z.000Z";
DateUtils.parseIso8601Date(input);
}
@Test
public void testIssue233() throws ParseException {
// https://github.com/aws/aws-sdk-java/issues/233
final String edgeCase = String.valueOf(MAX_MILLIS_YEAR) + "-08-17T07:12:00Z";
Instant expected = COMMON_DATE_FORMAT.parse(edgeCase).toInstant();
if (DEBUG) {
System.out.println("date: " + expected);
}
String formatted = DateUtils.formatIso8601Date(expected);
if (DEBUG) {
System.out.println("formatted: " + formatted);
}
// we have '+' sign as prefix for years. See java.time.format.SignStyle.EXCEEDS_PAD
assertEquals(edgeCase, formatted.substring(1));
Instant parsed = DateUtils.parseIso8601Date(formatted);
if (DEBUG) {
System.out.println("parsed: " + parsed);
}
assertEquals(expected, parsed);
String reformatted = ISO_INSTANT.format(parsed);
// we have '+' sign as prefix for years. See java.time.format.SignStyle.EXCEEDS_PAD
assertEquals(edgeCase, reformatted.substring(1));
}
@Test
public void testIssue233JavaTimeLimit() {
// https://github.com/aws/aws-sdk-java/issues/233
String s = ALTERNATE_ISO_8601_DATE_FORMAT.format(
ZonedDateTime.ofInstant(Instant.ofEpochMilli(Long.MAX_VALUE), UTC));
System.out.println("s: " + s);
Instant parsed = DateUtils.parseIso8601Date(s);
assertEquals(ZonedDateTime.ofInstant(parsed, UTC).getYear(), MAX_MILLIS_YEAR);
}
@Test
public void testIssueDaysDiff() throws ParseException {
// https://github.com/aws/aws-sdk-java/issues/233
COMMON_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone(UTC));
String edgeCase = String.valueOf(MAX_MILLIS_YEAR) + "-08-17T07:12:55Z";
String testCase = String.valueOf(MAX_MILLIS_YEAR - 1) + "-08-17T07:12:55Z";
Date edgeDate = COMMON_DATE_FORMAT.parse(edgeCase);
Date testDate = COMMON_DATE_FORMAT.parse(testCase);
long diff = edgeDate.getTime() - testDate.getTime();
assertTrue(diff == TimeUnit.DAYS.toMillis(365));
}
@Test
public void numberOfDaysSinceEpoch() {
final long now = System.currentTimeMillis();
final long days = DateUtils.numberOfDaysSinceEpoch(now);
final long oneDayMilli = Duration.ofDays(1).toMillis();
// Could be equal at 00:00:00.
assertTrue(now >= Duration.ofDays(days).toMillis());
assertTrue((now - Duration.ofDays(days).toMillis()) <= oneDayMilli);
}
/**
* Tests the Date marshalling and unmarshalling. Asserts that the value is
* same before and after marshalling/unmarshalling
*/
@Test
public void testUnixTimestampRoundtrip() throws Exception {
long[] testValues = new long[] {System.currentTimeMillis(), 1L, 0L};
Arrays.stream(testValues)
.mapToObj(Instant::ofEpochMilli)
.forEach(instant -> {
String serverSpecificDateFormat = DateUtils.formatUnixTimestampInstant(instant);
Instant parsed = DateUtils.parseUnixTimestampInstant(String.valueOf(serverSpecificDateFormat));
assertEquals(instant, parsed);
});
}
@Test
public void parseUnixTimestampInstant_longerThan20Char_throws() {
String largeNum = Stream.generate(() -> "9").limit(21).collect(Collectors.joining());
assertThatThrownBy(() -> DateUtils.parseUnixTimestampInstant(largeNum))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("20");
}
}
| 2,939 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/Base16LowerCodecTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.internal.Base16;
import software.amazon.awssdk.utils.internal.Base16Lower;
/**
* @author hchar
*/
public class Base16LowerCodecTest {
@Test
public void testVectorsPerRfc4648()
throws Exception {
String[] testVectors = {"", "f", "fo", "foo", "foob", "fooba", "foobar"};
String[] expected = {"", "66", "666f", "666f6f", "666f6f62", "666f6f6261", "666f6f626172"};
for (int i = 0; i < testVectors.length; i++) {
String data = testVectors[i];
byte[] source = data.getBytes("UTF-8");
String b16encoded = Base16Lower.encodeAsString(data.getBytes("UTF-8"));
assertEquals(expected[i], b16encoded);
byte[] b16 = b16encoded.getBytes("UTF-8");
byte[] decoded = Base16.decode(b16);
assertTrue(Arrays.equals(source, decoded));
decoded = Base16Lower.decode(b16);
assertTrue(Arrays.equals(source, decoded));
}
}
@Test
public void testCodecConsistency()
throws Exception {
byte[] decoded = null;
for (int h = 0; h < 1000; h++) {
byte[] digest = MessageDigest.getInstance("SHA-1").digest(
UUID.randomUUID().toString().getBytes("UTF-8")
);
String b16Encoded = Base16Lower.encodeAsString(digest);
{
decoded = Base16.decode(b16Encoded);
assertTrue(Arrays.equals(decoded, digest));
decoded = Base16Lower.decode(b16Encoded);
assertTrue(Arrays.equals(decoded, digest));
}
{ // test decoding case insensitivity
decoded = Base16.decode(b16Encoded.toLowerCase());
assertTrue(Arrays.equals(decoded, digest));
decoded = Base16Lower.decode(b16Encoded.toLowerCase());
assertTrue(Arrays.equals(decoded, digest));
}
}
}
}
| 2,940 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/CollectionUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
public class CollectionUtilsTest {
@Test
public void isEmpty_NullCollection_ReturnsTrue() {
assertTrue(CollectionUtils.isNullOrEmpty((Collection<?>) null));
}
@Test
public void isEmpty_EmptyCollection_ReturnsTrue() {
assertTrue(CollectionUtils.isNullOrEmpty(Collections.emptyList()));
}
@Test
public void isEmpty_NonEmptyCollection_ReturnsFalse() {
assertFalse(CollectionUtils.isNullOrEmpty(Arrays.asList("something")));
}
@Test
public void firstIfPresent_NullList_ReturnsNull() {
List<String> list = null;
assertThat(CollectionUtils.firstIfPresent(list)).isNull();
}
@Test
public void firstIfPresent_EmptyList_ReturnsNull() {
List<String> list = Collections.emptyList();
assertThat(CollectionUtils.firstIfPresent(list)).isNull();
}
@Test
public void firstIfPresent_SingleElementList_ReturnsOnlyElement() {
assertThat(CollectionUtils.firstIfPresent(singletonList("foo"))).isEqualTo("foo");
}
@Test
public void firstIfPresent_MultipleElementList_ReturnsFirstElement() {
assertThat(CollectionUtils.firstIfPresent(Arrays.asList("foo", "bar", "baz"))).isEqualTo("foo");
}
@Test
public void firstIfPresent_FirstElementNull_ReturnsNull() {
assertThat(CollectionUtils.firstIfPresent(Arrays.asList(null, "bar", "baz"))).isNull();
}
@Test
public void inverseMap_EmptyList_ReturnsNull() {
Map<String, String> map = Collections.emptyMap();
assertThat(CollectionUtils.inverseMap(map)).isEmpty();
}
@Test
public void inverseMap_SingleElementList_InversesKeyAndValue() {
assertThat(CollectionUtils.inverseMap(Collections.singletonMap("foo", "bar")).get("bar")).isEqualTo("foo");
}
@Test
public void inverseMap_MultipleElementList_InversesKeyAndValue() {
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
Map<String, String> inverseMap = CollectionUtils.inverseMap(map);
assertThat(inverseMap.get("value1")).isEqualTo("key1");
assertThat(inverseMap.get("value2")).isEqualTo("key2");
assertThat(inverseMap.get("value3")).isEqualTo("key3");
}
@Test
public void unmodifiableMapOfListsIsUnmodifiable() {
assertUnsupported(m -> m.clear());
assertUnsupported(m -> m.compute(null, null));
assertUnsupported(m -> m.computeIfAbsent(null, null));
assertUnsupported(m -> m.computeIfPresent(null, null));
assertUnsupported(m -> m.forEach((k, v) -> v.clear()));
assertUnsupported(m -> m.get("foo").clear());
assertUnsupported(m -> m.getOrDefault("", emptyList()).clear());
assertUnsupported(m -> m.getOrDefault("foo", null).clear());
assertUnsupported(m -> m.merge(null, null, null));
assertUnsupported(m -> m.put(null, null));
assertUnsupported(m -> m.putAll(null));
assertUnsupported(m -> m.putIfAbsent(null, null));
assertUnsupported(m -> m.remove(null));
assertUnsupported(m -> m.remove(null, null));
assertUnsupported(m -> m.replace(null, null));
assertUnsupported(m -> m.replace(null, null, null));
assertUnsupported(m -> m.replaceAll(null));
assertUnsupported(m -> m.values().clear());
assertUnsupported(m -> m.keySet().clear());
assertUnsupported(m -> m.keySet().add(null));
assertUnsupported(m -> m.keySet().addAll(null));
assertUnsupported(m -> m.keySet().remove(null));
assertUnsupported(m -> m.keySet().removeAll(null));
assertUnsupported(m -> m.keySet().retainAll(null));
assertUnsupported(m -> m.entrySet().clear());
assertUnsupported(m -> m.entrySet().add(null));
assertUnsupported(m -> m.entrySet().addAll(null));
assertUnsupported(m -> m.entrySet().remove(null));
assertUnsupported(m -> m.entrySet().removeAll(null));
assertUnsupported(m -> m.entrySet().retainAll(null));
assertUnsupported(m -> m.entrySet().iterator().next().setValue(emptyList()));
assertUnsupported(m -> m.values().clear());
assertUnsupported(m -> m.values().add(null));
assertUnsupported(m -> m.values().addAll(null));
assertUnsupported(m -> m.values().remove(null));
assertUnsupported(m -> m.values().removeAll(null));
assertUnsupported(m -> m.values().retainAll(null));
assertUnsupported(m -> m.values().iterator().next().clear());
assertUnsupported(m -> {
Iterator<Map.Entry<String, List<String>>> i = m.entrySet().iterator();
i.next();
i.remove();
});
assertUnsupported(m -> {
Iterator<List<String>> i = m.values().iterator();
i.next();
i.remove();
});
assertUnsupported(m -> {
Iterator<String> i = m.keySet().iterator();
i.next();
i.remove();
});
}
@Test
public void unmodifiableMapOfListsIsReadable() {
assertSupported(m -> m.containsKey("foo"));
assertSupported(m -> m.containsValue("foo"));
assertSupported(m -> m.equals(null));
assertSupported(m -> m.forEach((k, v) -> {}));
assertSupported(m -> m.get("foo"));
assertSupported(m -> m.getOrDefault("foo", null));
assertSupported(m -> m.hashCode());
assertSupported(m -> m.isEmpty());
assertSupported(m -> m.keySet());
assertSupported(m -> m.size());
assertSupported(m -> m.keySet().contains(null));
assertSupported(m -> m.keySet().containsAll(emptyList()));
assertSupported(m -> m.keySet().equals(null));
assertSupported(m -> m.keySet().hashCode());
assertSupported(m -> m.keySet().isEmpty());
assertSupported(m -> m.keySet().size());
assertSupported(m -> m.keySet().spliterator());
assertSupported(m -> m.keySet().toArray());
assertSupported(m -> m.keySet().toArray(new String[0]));
assertSupported(m -> m.keySet().stream());
assertSupported(m -> m.entrySet().contains(null));
assertSupported(m -> m.entrySet().containsAll(emptyList()));
assertSupported(m -> m.entrySet().equals(null));
assertSupported(m -> m.entrySet().hashCode());
assertSupported(m -> m.entrySet().isEmpty());
assertSupported(m -> m.entrySet().size());
assertSupported(m -> m.entrySet().spliterator());
assertSupported(m -> m.entrySet().toArray());
assertSupported(m -> m.entrySet().toArray(new Map.Entry[0]));
assertSupported(m -> m.entrySet().stream());
assertSupported(m -> m.values().contains(null));
assertSupported(m -> m.values().containsAll(emptyList()));
assertSupported(m -> m.values().equals(null));
assertSupported(m -> m.values().hashCode());
assertSupported(m -> m.values().isEmpty());
assertSupported(m -> m.values().size());
assertSupported(m -> m.values().spliterator());
assertSupported(m -> m.values().toArray());
assertSupported(m -> m.values().toArray(new Collection[0]));
assertSupported(m -> m.values().stream());
assertSupported(m -> m.entrySet().iterator().next());
assertSupported(m -> m.entrySet().iterator().hasNext());
assertSupported(m -> m.values().iterator().next());
assertSupported(m -> m.values().iterator().hasNext());
assertSupported(m -> m.keySet().iterator().next());
assertSupported(m -> m.keySet().iterator().hasNext());
}
public void assertUnsupported(Consumer<Map<String, List<String>>> mutation) {
Map<String, List<String>> map = new HashMap<>();
map.put("foo", singletonList("bar"));
assertThatThrownBy(() -> mutation.accept(CollectionUtils.unmodifiableMapOfLists(map)))
.isInstanceOf(UnsupportedOperationException.class);
}
public void assertSupported(Consumer<Map<String, List<String>>> mutation) {
Map<String, List<String>> map = new HashMap<>();
map.put("foo", singletonList("bar"));
mutation.accept(map);
}
@Test
public void uniqueIndex_noDuplicateIndices_correctlyIndexes() {
Set<String> values = Stream.of("a", "ab", "abc")
.collect(Collectors.toSet());
Map<Integer, String> map = CollectionUtils.uniqueIndex(values, String::length);
assertThat(map).hasSize(3)
.containsEntry(1, "a")
.containsEntry(2, "ab")
.containsEntry(3, "abc");
}
@Test
public void uniqueIndex_map_isModifiable() {
Set<String> values = Stream.of("a", "ab", "abc")
.collect(Collectors.toSet());
Map<Integer, String> map = CollectionUtils.uniqueIndex(values, String::length);
map.put(3, "bar");
assertThat(map).containsEntry(3, "bar");
}
@Test
public void uniqueIndex_duplicateIndices_throws() {
Set<String> values = Stream.of("foo", "bar")
.collect(Collectors.toSet());
assertThatThrownBy(() -> CollectionUtils.uniqueIndex(values, String::length))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContainingAll("foo", "bar", "3");
}
}
| 2,941 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ThreadFactoryBuilderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Java6Assertions.assertThat;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ThreadFactoryBuilderTest {
@BeforeEach
public void setup() {
ThreadFactoryBuilder.resetPoolNumber();
}
@Test
public void poolNumberWrapsAround() {
for (int i = 0; i < 9_9999; i++) {
new ThreadFactoryBuilder().build();
}
Thread threadBeforeWrap = new ThreadFactoryBuilder().build().newThread(this::doNothing);
assertThat(threadBeforeWrap.getName()).isEqualTo("aws-java-sdk-9999-0");
// Next factory should cause the pool number to wrap
Thread threadAfterWrap = new ThreadFactoryBuilder().build().newThread(this::doNothing);
assertThat(threadAfterWrap.getName()).isEqualTo("aws-java-sdk-0-0");
}
@Test
public void customPrefixAppendsPoolNumber() {
Thread thread = new ThreadFactoryBuilder()
.threadNamePrefix("custom-name")
.build()
.newThread(this::doNothing);
assertThat(thread.getName()).isEqualTo("custom-name-0-0");
}
@Test
public void daemonThreadRespected() {
Thread thread = new ThreadFactoryBuilder()
.daemonThreads(true)
.build()
.newThread(this::doNothing);
assertThat(thread.isDaemon()).isTrue();
}
/**
* To use as a {@link Runnable} method reference.
*/
private void doNothing() {
}
}
| 2,942 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/UserHomeDirectoryUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.utils.UserHomeDirectoryUtils.userHomeDirectory;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
public class UserHomeDirectoryUtilsTest {
private final Map<String, String> savedEnvironmentVariableValues = new HashMap<>();
private static final List<String> SAVED_ENVIRONMENT_VARIABLES = Arrays.asList("HOME",
"USERPROFILE",
"HOMEDRIVE",
"HOMEPATH");
private EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper();
/**
* Save the current state of the environment variables we're messing around with in these tests so that we can restore them
* when we are done.
*/
@BeforeEach
public void saveEnvironment() throws Exception {
// The tests in this file change the os.home for testing windows vs non-windows loading. We need to load the home
// directory that should be used for the stored file before changing the os.home so that it doesn't try to load
// the file system separator during the test. If we don't, it'll complain that it doesn't recognize the file system.
userHomeDirectory();
for (String variable : SAVED_ENVIRONMENT_VARIABLES) {
savedEnvironmentVariableValues.put(variable, System.getenv(variable));
}
}
/**
* Reset the environment variables after each test.
*/
@AfterEach
public void restoreEnvironment() throws Exception {
for (String variable : SAVED_ENVIRONMENT_VARIABLES) {
String savedValue = savedEnvironmentVariableValues.get(variable);
if (savedValue == null) {
ENVIRONMENT_VARIABLE_HELPER.remove(variable);
} else {
ENVIRONMENT_VARIABLE_HELPER.set(variable, savedValue);
}
}
}
@Test
public void homeDirectoryResolutionPriorityIsCorrectOnWindows() throws Exception {
String osName = System.getProperty("os.name");
try {
System.setProperty("os.name", "Windows 7");
ENVIRONMENT_VARIABLE_HELPER.set("HOME", "home");
ENVIRONMENT_VARIABLE_HELPER.set("USERPROFILE", "userprofile");
ENVIRONMENT_VARIABLE_HELPER.set("HOMEDRIVE", "homedrive");
ENVIRONMENT_VARIABLE_HELPER.set("HOMEPATH", "homepath");
assertThat(userHomeDirectory()).isEqualTo("home");
ENVIRONMENT_VARIABLE_HELPER.remove("HOME");
assertThat(userHomeDirectory()).isEqualTo("userprofile");
ENVIRONMENT_VARIABLE_HELPER.remove("USERPROFILE");
assertThat(userHomeDirectory()).isEqualTo("homedrivehomepath");
ENVIRONMENT_VARIABLE_HELPER.remove("HOMEDRIVE");
ENVIRONMENT_VARIABLE_HELPER.remove("HOMEPATH");
assertThat(userHomeDirectory()).isEqualTo(System.getProperty("user.home"));
} finally {
System.setProperty("os.name", osName);
}
}
@Test
public void homeDirectoryResolutionPriorityIsCorrectOnNonWindows() throws Exception {
String osName = System.getProperty("os.name");
try {
System.setProperty("os.name", "Linux");
ENVIRONMENT_VARIABLE_HELPER.set("HOME", "home");
ENVIRONMENT_VARIABLE_HELPER.set("USERPROFILE", "userprofile");
ENVIRONMENT_VARIABLE_HELPER.set("HOMEDRIVE", "homedrive");
ENVIRONMENT_VARIABLE_HELPER.set("HOMEPATH", "homepath");
assertThat(userHomeDirectory()).isEqualTo("home");
ENVIRONMENT_VARIABLE_HELPER.remove("HOME");
assertThat(userHomeDirectory()).isEqualTo(System.getProperty("user.home"));
ENVIRONMENT_VARIABLE_HELPER.remove("USERPROFILE");
assertThat(userHomeDirectory()).isEqualTo(System.getProperty("user.home"));
ENVIRONMENT_VARIABLE_HELPER.remove("HOMEDRIVE");
ENVIRONMENT_VARIABLE_HELPER.remove("HOMEPATH");
assertThat(userHomeDirectory()).isEqualTo(System.getProperty("user.home"));
} finally {
System.setProperty("os.name", osName);
}
}
} | 2,943 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/PairTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
public class PairTest {
@Test
public void equalsMethodWorksAsExpected() {
Pair foo = Pair.of("Foo", 50);
assertThat(foo).isEqualTo(Pair.of("Foo", 50));
assertThat(foo).isNotEqualTo(Pair.of("Foo-bar", 50));
}
@Test
public void canBeUseAsMapKey() {
Map<Pair<String, Integer>, String> map = new HashMap<>();
map.put(Pair.of("Hello", 100), "World");
assertThat(map.get(Pair.of("Hello", 100))).isEqualTo("World");
}
@Test
public void prettyToString() {
assertThat(Pair.of("Hello", "World").toString()).isEqualTo("Pair(left=Hello, right=World)");
}
}
| 2,944 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ToStringTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Collections;
import org.junit.jupiter.api.Test;
/**
* Validate the functionality of {@link ToString}.
*/
public class ToStringTest {
@Test
public void createIsCorrect() {
assertThat(ToString.create("Foo")).isEqualTo("Foo()");
}
@Test
public void buildIsCorrect() {
assertThat(ToString.builder("Foo").build()).isEqualTo("Foo()");
assertThat(ToString.builder("Foo").add("a", "a").build()).isEqualTo("Foo(a=a)");
assertThat(ToString.builder("Foo").add("a", "a").add("b", "b").build()).isEqualTo("Foo(a=a, b=b)");
assertThat(ToString.builder("Foo").add("a", 1).build()).isEqualTo("Foo(a=1)");
assertThat(ToString.builder("Foo").add("a", 'a').build()).isEqualTo("Foo(a=a)");
assertThat(ToString.builder("Foo").add("a", Arrays.asList("a", "b")).build()).isEqualTo("Foo(a=[a, b])");
assertThat(ToString.builder("Foo").add("a", new String[] {"a", "b"}).build()).isEqualTo("Foo(a=[a, b])");
assertThat(ToString.builder("Foo").add("a", Collections.singletonMap("a", "b")).build()).isEqualTo("Foo(a={a=b})");
}
}
| 2,945 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/CompletableFutureUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class CompletableFutureUtilsTest {
private static ExecutorService executors;
@BeforeClass
public static void setup() {
executors = Executors.newFixedThreadPool(2);
}
@AfterClass
public static void tearDown() {
executors.shutdown();
}
@Test(timeout = 1000)
public void testForwardException() {
CompletableFuture src = new CompletableFuture();
CompletableFuture dst = new CompletableFuture();
Exception e = new RuntimeException("BOOM");
CompletableFutureUtils.forwardExceptionTo(src, dst);
src.completeExceptionally(e);
try {
dst.join();
fail();
} catch (Throwable t) {
assertThat(t.getCause()).isEqualTo(e);
}
}
@Test(timeout = 1000)
public void forwardResultTo_srcCompletesSuccessfully_shouldCompleteDstFuture() {
CompletableFuture<String> src = new CompletableFuture<>();
CompletableFuture<String> dst = new CompletableFuture<>();
CompletableFuture<String> returnedFuture = CompletableFutureUtils.forwardResultTo(src, dst, executors);
assertThat(returnedFuture).isEqualTo(src);
src.complete("foobar");
assertThat(dst.join()).isEqualTo("foobar");
}
@Test(timeout = 1000)
public void forwardResultTo_srcCompletesExceptionally_shouldCompleteDstFuture() {
CompletableFuture<String> src = new CompletableFuture<>();
CompletableFuture<String> dst = new CompletableFuture<>();
RuntimeException exception = new RuntimeException("foobar");
CompletableFutureUtils.forwardResultTo(src, dst, executors);
src.completeExceptionally(exception);
assertThatThrownBy(dst::join).hasCause(exception);
}
@Test(timeout = 1000)
public void forwardTransformedResultTo_srcCompletesSuccessfully_shouldCompleteDstFuture() {
CompletableFuture<Integer> src = new CompletableFuture<>();
CompletableFuture<String> dst = new CompletableFuture<>();
CompletableFuture<Integer> returnedFuture = CompletableFutureUtils.forwardTransformedResultTo(src, dst, String::valueOf);
assertThat(returnedFuture).isSameAs(src);
src.complete(123);
assertThat(dst.join()).isEqualTo("123");
}
@Test(timeout = 1000)
public void forwardTransformedResultTo_srcCompletesExceptionally_shouldCompleteDstFuture() {
CompletableFuture<Integer> src = new CompletableFuture<>();
CompletableFuture<String> dst = new CompletableFuture<>();
RuntimeException exception = new RuntimeException("foobar");
CompletableFutureUtils.forwardTransformedResultTo(src, dst, String::valueOf);
src.completeExceptionally(exception);
assertThatThrownBy(dst::join).hasCause(exception);
}
@Test(timeout = 1000)
public void anyFail_shouldCompleteWhenAnyFutureFails() {
RuntimeException exception = new RuntimeException("blah");
CompletableFuture[] completableFutures = new CompletableFuture[2];
completableFutures[0] = new CompletableFuture();
completableFutures[1] = new CompletableFuture();
CompletableFuture<Void> anyFail = CompletableFutureUtils.anyFail(completableFutures);
completableFutures[0] = CompletableFuture.completedFuture("test");
completableFutures[1].completeExceptionally(exception);
assertThatThrownBy(anyFail::join).hasCause(exception);
}
@Test(timeout = 1000)
public void anyFail_shouldNotCompleteWhenAllFuturesSucceed() {
CompletableFuture[] completableFutures = new CompletableFuture[2];
completableFutures[0] = new CompletableFuture();
completableFutures[1] = new CompletableFuture();
CompletableFuture<Void> anyFail = CompletableFutureUtils.anyFail(completableFutures);
completableFutures[0] = CompletableFuture.completedFuture("test");
completableFutures[1] = CompletableFuture.completedFuture("test");
assertThat(anyFail.isDone()).isFalse();
}
@Test(timeout = 1000)
public void allOfExceptionForwarded_anyFutureFails_shouldForwardExceptionToOthers() {
RuntimeException exception = new RuntimeException("blah");
CompletableFuture[] completableFutures = new CompletableFuture[2];
completableFutures[0] = new CompletableFuture();
completableFutures[1] = new CompletableFuture();
CompletableFuture<Void> resultFuture = CompletableFutureUtils.allOfExceptionForwarded(completableFutures);
completableFutures[0].completeExceptionally(exception);
assertThatThrownBy(resultFuture::join).hasCause(exception);
assertThatThrownBy(completableFutures[1]::join).hasCause(exception);
}
@Test(timeout = 1000)
public void allOfExceptionForwarded_allFutureSucceed_shouldComplete() {
RuntimeException exception = new RuntimeException("blah");
CompletableFuture[] completableFutures = new CompletableFuture[2];
completableFutures[0] = new CompletableFuture();
completableFutures[1] = new CompletableFuture();
CompletableFuture<Void> resultFuture = CompletableFutureUtils.allOfExceptionForwarded(completableFutures);
completableFutures[0].complete("test");
completableFutures[1].complete("test");
assertThat(resultFuture.isDone()).isTrue();
assertThat(resultFuture.isCompletedExceptionally()).isFalse();
}
@Test(timeout = 1000)
public void joinLikeSync_completesExceptionally_throwsUnderlyingException() {
Exception e = new RuntimeException("BOOM");
CompletableFuture future = new CompletableFuture();
future.completeExceptionally(e);
assertThatThrownBy(() -> CompletableFutureUtils.joinLikeSync(future))
.hasSuppressedException(new RuntimeException("Task failed."))
.isEqualTo(e);
}
@Test(timeout = 1000)
public void joinLikeSync_completesExceptionallyChecked_throwsCompletionException() {
Exception e = new Exception("BOOM");
CompletableFuture future = new CompletableFuture();
future.completeExceptionally(e);
assertThatThrownBy(() -> CompletableFutureUtils.joinLikeSync(future))
.hasNoSuppressedExceptions()
.hasCause(e)
.isInstanceOf(CompletionException.class);
}
@Test(timeout = 1000)
public void joinLikeSync_completesExceptionallyWithError_throwsError() {
Error e = new Error("BOOM");
CompletableFuture future = new CompletableFuture();
future.completeExceptionally(e);
assertThatThrownBy(() -> CompletableFutureUtils.joinLikeSync(future))
.hasNoSuppressedExceptions()
.isEqualTo(e);
}
@Test(timeout = 1000)
public void joinLikeSync_canceled_throwsCancellationException() {
Exception e = new Exception("BOOM");
CompletableFuture future = new CompletableFuture();
future.cancel(false);
assertThatThrownBy(() -> CompletableFutureUtils.joinLikeSync(future))
.hasNoSuppressedExceptions()
.hasNoCause()
.isInstanceOf(CancellationException.class);
}}
| 2,946 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/Base64UtilsCodecTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.UUID;
import org.junit.jupiter.api.Test;
public class Base64UtilsCodecTest {
@Test
public void testVectorsPerRfc4648() throws Exception {
String[] testVectors = {"", "f", "fo", "foo", "foob", "fooba", "foobar"};
String[] expected = {"", "Zg==", "Zm8=", "Zm9v", "Zm9vYg==", "Zm9vYmE=", "Zm9vYmFy"};
for (int i = 0; i < testVectors.length; i++) {
String data = testVectors[i];
byte[] source = data.getBytes("UTF-8");
String b64encoded = BinaryUtils.toBase64(data.getBytes("UTF-8"));
assertEquals(expected[i], b64encoded);
byte[] b64 = b64encoded.getBytes("UTF-8");
byte[] decoded = BinaryUtils.fromBase64Bytes(b64);
assertTrue(Arrays.equals(source, decoded));
}
}
@Test
public void testCodecConsistency() throws Exception {
byte[] decoded = null;
for (int h = 0; h < 1000; h++) {
byte[] digest = MessageDigest.getInstance("SHA-1").digest(UUID.randomUUID().toString().getBytes("UTF-8"));
String b64Encoded = BinaryUtils.toBase64(digest);
decoded = BinaryUtils.fromBase64(b64Encoded);
assertTrue(Arrays.equals(decoded, digest));
}
}
}
| 2,947 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/NumericUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static software.amazon.awssdk.utils.NumericUtils.max;
import static software.amazon.awssdk.utils.NumericUtils.min;
import java.time.Duration;
import org.junit.jupiter.api.Test;
public class NumericUtilsTest {
private final Duration SHORT_DURATION = Duration.ofMillis(10);
private final Duration SHORT_SAME_DURATION = Duration.ofMillis(10);
private final Duration LONG_DURATION = Duration.ofMillis(100);
private final Duration NEGATIVE_SHORT_DURATION = Duration.ofMillis(-10);
private final Duration NEGATIVE_SHORT_SAME_DURATION = Duration.ofMillis(-10);
private final Duration NEGATIVE_LONG_DURATION = Duration.ofMillis(-100);
@Test
public void minTestDifferentDurations() {
assertThat(min(SHORT_DURATION, LONG_DURATION), is(SHORT_DURATION));
}
@Test
public void minTestDifferentDurationsReverse() {
assertThat(min(LONG_DURATION, SHORT_DURATION), is(SHORT_DURATION));
}
@Test
public void minTestSameDurations() {
assertThat(min(SHORT_DURATION, SHORT_SAME_DURATION), is(SHORT_SAME_DURATION));
}
@Test
public void minTestDifferentNegativeDurations() {
assertThat(min(NEGATIVE_SHORT_DURATION, NEGATIVE_LONG_DURATION), is(NEGATIVE_LONG_DURATION));
}
@Test
public void minTestNegativeSameDurations() {
assertThat(min(NEGATIVE_SHORT_DURATION, NEGATIVE_SHORT_SAME_DURATION), is(NEGATIVE_SHORT_DURATION));
}
@Test
public void maxTestDifferentDurations() {
assertThat(max(LONG_DURATION, SHORT_DURATION), is(LONG_DURATION));
}
@Test
public void maxTestDifferentDurationsReverse() {
assertThat(max(SHORT_DURATION, LONG_DURATION), is(LONG_DURATION));
}
@Test
public void maxTestSameDurations() {
assertThat(max(SHORT_DURATION, SHORT_SAME_DURATION), is(SHORT_SAME_DURATION));
}
@Test
public void maxTestDifferentNegativeDurations() {
assertThat(max(NEGATIVE_SHORT_DURATION, NEGATIVE_LONG_DURATION), is(NEGATIVE_SHORT_DURATION));
}
@Test
public void maxTestNegativeSameDurations() {
assertThat(max(NEGATIVE_SHORT_DURATION, NEGATIVE_SHORT_SAME_DURATION), is(NEGATIVE_SHORT_DURATION));
}
} | 2,948 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/StringUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static software.amazon.awssdk.utils.StringUtils.replacePrefixIgnoreCase;
import org.assertj.core.api.Assertions;
import org.junit.Test;
/**
* Unit tests for methods of {@link StringUtils}.
*
* Adapted from https://github.com/apache/commons-lang.
*/
public class StringUtilsTest {
private static final String FOO_UNCAP = "foo";
private static final String FOO_CAP = "Foo";
private static final String SENTENCE_UNCAP = "foo bar baz";
private static final String SENTENCE_CAP = "Foo Bar Baz";
@Test
public void testUpperCase() {
assertNull(StringUtils.upperCase(null));
assertEquals("upperCase(String) failed",
"FOO TEST THING", StringUtils.upperCase("fOo test THING"));
assertEquals("upperCase(empty-string) failed",
"", StringUtils.upperCase(""));
}
@Test
public void testLowerCase() {
assertNull(StringUtils.lowerCase(null));
assertEquals("lowerCase(String) failed",
"foo test thing", StringUtils.lowerCase("fOo test THING"));
assertEquals("lowerCase(empty-string) failed",
"", StringUtils.lowerCase(""));
}
@Test
public void testCapitalize() {
assertNull(StringUtils.capitalize(null));
assertEquals("capitalize(empty-string) failed",
"", StringUtils.capitalize(""));
assertEquals("capitalize(single-char-string) failed",
"X", StringUtils.capitalize("x"));
assertEquals("capitalize(String) failed",
FOO_CAP, StringUtils.capitalize(FOO_CAP));
assertEquals("capitalize(string) failed",
FOO_CAP, StringUtils.capitalize(FOO_UNCAP));
assertEquals("capitalize(String) is not using TitleCase",
"\u01C8", StringUtils.capitalize("\u01C9"));
// Javadoc examples
assertNull(StringUtils.capitalize(null));
assertEquals("", StringUtils.capitalize(""));
assertEquals("Cat", StringUtils.capitalize("cat"));
assertEquals("CAt", StringUtils.capitalize("cAt"));
assertEquals("'cat'", StringUtils.capitalize("'cat'"));
}
@Test
public void testUnCapitalize() {
assertNull(StringUtils.uncapitalize(null));
assertEquals("uncapitalize(String) failed",
FOO_UNCAP, StringUtils.uncapitalize(FOO_CAP));
assertEquals("uncapitalize(string) failed",
FOO_UNCAP, StringUtils.uncapitalize(FOO_UNCAP));
assertEquals("uncapitalize(empty-string) failed",
"", StringUtils.uncapitalize(""));
assertEquals("uncapitalize(single-char-string) failed",
"x", StringUtils.uncapitalize("X"));
// Examples from uncapitalize Javadoc
assertEquals("cat", StringUtils.uncapitalize("cat"));
assertEquals("cat", StringUtils.uncapitalize("Cat"));
assertEquals("cAT", StringUtils.uncapitalize("CAT"));
}
@Test
public void testReCapitalize() {
// reflection type of tests: Sentences.
assertEquals("uncapitalize(capitalize(String)) failed",
SENTENCE_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(SENTENCE_UNCAP)));
assertEquals("capitalize(uncapitalize(String)) failed",
SENTENCE_CAP, StringUtils.capitalize(StringUtils.uncapitalize(SENTENCE_CAP)));
// reflection type of tests: One word.
assertEquals("uncapitalize(capitalize(String)) failed",
FOO_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(FOO_UNCAP)));
assertEquals("capitalize(uncapitalize(String)) failed",
FOO_CAP, StringUtils.capitalize(StringUtils.uncapitalize(FOO_CAP)));
}
@Test
public void testStartsWithIgnoreCase() {
assertTrue(StringUtils.startsWithIgnoreCase("helloworld", "hello"));
assertTrue(StringUtils.startsWithIgnoreCase("hELlOwOrlD", "hello"));
assertFalse(StringUtils.startsWithIgnoreCase("hello", "world"));
}
@Test
public void testReplacePrefixIgnoreCase() {
assertEquals("lloWorld" ,replacePrefixIgnoreCase("helloWorld", "he", ""));
assertEquals("lloWORld" ,replacePrefixIgnoreCase("helloWORld", "He", ""));
assertEquals("llOwOrld" ,replacePrefixIgnoreCase("HEllOwOrld", "he", ""));
}
@Test
public void findFirstOccurrence() {
assertEquals((Character) ':', StringUtils.findFirstOccurrence("abc:def/ghi:jkl/mno", ':', '/'));
assertEquals((Character) ':', StringUtils.findFirstOccurrence("abc:def/ghi:jkl/mno", '/', ':'));
}
@Test
public void findFirstOccurrence_NoMatch() {
assertNull(StringUtils.findFirstOccurrence("abc", ':'));
}
@Test
public void safeStringTooBoolean_mixedSpaceTrue_shouldReturnTrue() {
assertTrue(StringUtils.safeStringToBoolean("TrUe"));
}
@Test
public void safeStringTooBoolean_mixedSpaceFalse_shouldReturnFalse() {
assertFalse(StringUtils.safeStringToBoolean("fAlSE"));
}
@Test(expected = IllegalArgumentException.class)
public void safeStringTooBoolean_invalidValue_shouldThrowException() {
assertFalse(StringUtils.safeStringToBoolean("foobar"));
}
@Test
public void testRepeat() {
assertNull(StringUtils.repeat(null, 0));
assertNull(StringUtils.repeat(null, 1));
assertNull(StringUtils.repeat(null, 2));
assertEquals("", StringUtils.repeat("", 0));
assertEquals("", StringUtils.repeat("", 1));
assertEquals("", StringUtils.repeat("", 2));
assertEquals("", StringUtils.repeat("ab", 0));
assertEquals("ab", StringUtils.repeat("ab", 1));
assertEquals("abab", StringUtils.repeat("ab", 2));
assertEquals("ababab", StringUtils.repeat("ab", 3));
}
@Test(expected = IllegalArgumentException.class)
public void repeat_negativeCount_shouldThrowIae() {
StringUtils.repeat("a", -1);
}
@Test(expected = OutOfMemoryError.class)
public void repeat_maxCount_shouldThrowOom() {
StringUtils.repeat("a", Integer.MAX_VALUE);
}
}
| 2,949 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ValidateTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Unit tests {@link Validate}.
*
* Adapted from https://github.com/apache/commons-lang.
*/
public class ValidateTest {
@Rule
public ExpectedException expected = ExpectedException.none();
//-----------------------------------------------------------------------
@Test
public void testIsTrue2() {
Validate.isTrue(true, "MSG");
try {
Validate.isTrue(false, "MSG");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {
assertEquals("MSG", ex.getMessage());
}
}
//-----------------------------------------------------------------------
@Test
public void testIsTrue3() {
Validate.isTrue(true, "MSG", 6);
try {
Validate.isTrue(false, "MSG", 6);
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {
assertEquals("MSG", ex.getMessage());
}
}
//-----------------------------------------------------------------------
@Test
public void testIsTrue4() {
Validate.isTrue(true, "MSG", 7);
try {
Validate.isTrue(false, "MSG", 7);
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {
assertEquals("MSG", ex.getMessage());
}
}
//-----------------------------------------------------------------------
@Test
public void testIsTrue5() {
Validate.isTrue(true, "MSG", 7.4d);
try {
Validate.isTrue(false, "MSG", 7.4d);
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {
assertEquals("MSG", ex.getMessage());
}
}
//-----------------------------------------------------------------------
@SuppressWarnings("unused")
@Test
public void testNotNull2() {
Validate.notNull(new Object(), "MSG");
try {
Validate.notNull(null, "MSG");
fail("Expecting NullPointerException");
} catch (final NullPointerException ex) {
assertEquals("MSG", ex.getMessage());
}
final String str = "Hi";
final String testStr = Validate.notNull(str, "Message");
assertSame(str, testStr);
}
//-----------------------------------------------------------------------
@Test
public void testNotEmptyArray2() {
Validate.notEmpty(new Object[] {null}, "MSG");
try {
Validate.notEmpty((Object[]) null, "MSG");
fail("Expecting NullPointerException");
} catch (final NullPointerException ex) {
assertEquals("MSG", ex.getMessage());
}
try {
Validate.notEmpty(new Object[0], "MSG");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {
assertEquals("MSG", ex.getMessage());
}
final String[] array = new String[] {"hi"};
final String[] test = Validate.notEmpty(array, "Message");
assertSame(array, test);
}
//-----------------------------------------------------------------------
@Test
public void testNotEmptyCollection2() {
final Collection<Integer> coll = new ArrayList<>();
try {
Validate.notEmpty((Collection<?>) null, "MSG");
fail("Expecting NullPointerException");
} catch (final NullPointerException ex) {
assertEquals("MSG", ex.getMessage());
}
try {
Validate.notEmpty(coll, "MSG");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {
assertEquals("MSG", ex.getMessage());
}
coll.add(8);
Validate.notEmpty(coll, "MSG");
final Collection<Integer> test = Validate.notEmpty(coll, "Message");
assertSame(coll, test);
}
//-----------------------------------------------------------------------
@Test
public void testNotEmptyMap2() {
final Map<String, Integer> map = new HashMap<>();
try {
Validate.notEmpty((Map<?, ?>) null, "MSG");
fail("Expecting NullPointerException");
} catch (final NullPointerException ex) {
assertEquals("MSG", ex.getMessage());
}
try {
Validate.notEmpty(map, "MSG");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {
assertEquals("MSG", ex.getMessage());
}
map.put("ll", 8);
Validate.notEmpty(map, "MSG");
final Map<String, Integer> test = Validate.notEmpty(map, "Message");
assertSame(map, test);
}
//-----------------------------------------------------------------------
@Test
public void testNotEmptyString2() {
Validate.notEmpty("a", "MSG");
try {
Validate.notEmpty((String) null, "MSG");
fail("Expecting NullPointerException");
} catch (final NullPointerException ex) {
assertEquals("MSG", ex.getMessage());
}
try {
Validate.notEmpty("", "MSG");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {
assertEquals("MSG", ex.getMessage());
}
final String str = "Hi";
final String testStr = Validate.notEmpty(str, "Message");
assertSame(str, testStr);
}
//-----------------------------------------------------------------------
@Test
public void testNotBlankMsgNullStringShouldThrow() {
//given
final String string = null;
try {
//when
Validate.notBlank(string, "Message");
fail("Expecting NullPointerException");
} catch (final NullPointerException e) {
//then
assertEquals("Message", e.getMessage());
}
}
//-----------------------------------------------------------------------
@Test
public void testNotBlankMsgBlankStringShouldThrow() {
//given
final String string = " \n \t \r \n ";
try {
//when
Validate.notBlank(string, "Message");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException e) {
//then
assertEquals("Message", e.getMessage());
}
}
//-----------------------------------------------------------------------
@Test
public void testNotBlankMsgBlankStringWithWhitespacesShouldThrow() {
//given
final String string = " ";
try {
//when
Validate.notBlank(string, "Message");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException e) {
//then
assertEquals("Message", e.getMessage());
}
}
//-----------------------------------------------------------------------
@Test
public void testNotBlankMsgEmptyStringShouldThrow() {
//given
final String string = "";
try {
//when
Validate.notBlank(string, "Message");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException e) {
//then
assertEquals("Message", e.getMessage());
}
}
//-----------------------------------------------------------------------
@Test
public void testNotBlankMsgNotBlankStringShouldNotThrow() {
//given
final String string = "abc";
//when
Validate.notBlank(string, "Message");
//then should not throw
}
//-----------------------------------------------------------------------
@Test
public void testNotBlankMsgNotBlankStringWithWhitespacesShouldNotThrow() {
//given
final String string = " abc ";
//when
Validate.notBlank(string, "Message");
//then should not throw
}
//-----------------------------------------------------------------------
@Test
public void testNotBlankMsgNotBlankStringWithNewlinesShouldNotThrow() {
//given
final String string = " \n \t abc \r \n ";
//when
Validate.notBlank(string, "Message");
//then should not throw
}
//-----------------------------------------------------------------------
@Test
public void testNoNullElementsArray2() {
String[] array = new String[] {"a", "b"};
Validate.noNullElements(array, "MSG");
try {
Validate.noNullElements((Object[]) null, "MSG");
fail("Expecting NullPointerException");
} catch (final NullPointerException ex) {
assertEquals("MSG", ex.getMessage());
}
array[1] = null;
try {
Validate.noNullElements(array, "MSG");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {
assertEquals("MSG", ex.getMessage());
}
array = new String[] {"a", "b"};
final String[] test = Validate.noNullElements(array, "Message");
assertSame(array, test);
}
//-----------------------------------------------------------------------
@Test
public void testNoNullElementsCollection2() {
final List<String> coll = new ArrayList<>();
coll.add("a");
coll.add("b");
Validate.noNullElements(coll, "MSG");
try {
Validate.noNullElements((Collection<?>) null, "MSG");
fail("Expecting NullPointerException");
} catch (final NullPointerException ex) {
assertEquals("The validated object is null", ex.getMessage());
}
coll.set(1, null);
try {
Validate.noNullElements(coll, "MSG");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {
assertEquals("MSG", ex.getMessage());
}
coll.set(1, "b");
final List<String> test = Validate.noNullElements(coll, "Message");
assertSame(coll, test);
}
@Test
public void testInclusiveBetween_withMessage()
{
Validate.inclusiveBetween("a", "c", "b", "Error");
try {
Validate.inclusiveBetween("0", "5", "6", "Error");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Error", e.getMessage());
}
}
@Test
public void testInclusiveBetweenLong_withMessage()
{
Validate.inclusiveBetween(0, 2, 1, "Error");
Validate.inclusiveBetween(0, 2, 2, "Error");
try {
Validate.inclusiveBetween(0, 5, 6, "Error");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Error", e.getMessage());
}
}
@Test
public void testInclusiveBetweenDouble_withMessage()
{
Validate.inclusiveBetween(0.1, 2.1, 1.1, "Error");
Validate.inclusiveBetween(0.1, 2.1, 2.1, "Error");
try {
Validate.inclusiveBetween(0.1, 5.1, 6.1, "Error");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Error", e.getMessage());
}
}
@Test
public void testExclusiveBetween_withMessage()
{
Validate.exclusiveBetween("a", "c", "b", "Error");
try {
Validate.exclusiveBetween("0", "5", "6", "Error");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Error", e.getMessage());
}
try {
Validate.exclusiveBetween("0", "5", "5", "Error");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Error", e.getMessage());
}
}
@Test
public void testExclusiveBetweenLong_withMessage()
{
Validate.exclusiveBetween(0, 2, 1, "Error");
try {
Validate.exclusiveBetween(0, 5, 6, "Error");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Error", e.getMessage());
}
try {
Validate.exclusiveBetween(0, 5, 5, "Error");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Error", e.getMessage());
}
}
@Test
public void testExclusiveBetweenDouble_withMessage()
{
Validate.exclusiveBetween(0.1, 2.1, 1.1, "Error");
try {
Validate.exclusiveBetween(0.1, 5.1, 6.1, "Error");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Error", e.getMessage());
}
try {
Validate.exclusiveBetween(0.1, 5.1, 5.1, "Error");
fail("Expecting IllegalArgumentException");
} catch (final IllegalArgumentException e) {
assertEquals("Error", e.getMessage());
}
}
@Test
public void testIsInstanceOf_withMessage() {
Validate.isInstanceOf(String.class, "hi", "Error");
Validate.isInstanceOf(Integer.class, 1, "Error");
try {
Validate.isInstanceOf(List.class, "hi", "Error");
fail("Expecting IllegalArgumentException");
} catch(final IllegalArgumentException e) {
assertEquals("Error", e.getMessage());
}
}
@Test
public void testIsInstanceOf_withMessageArgs() {
Validate.isInstanceOf(String.class, "hi", "Error %s=%s", "Name", "Value");
Validate.isInstanceOf(Integer.class, 1, "Error %s=%s", "Name", "Value");
try {
Validate.isInstanceOf(List.class, "hi", "Error %s=%s", "Name", "Value");
fail("Expecting IllegalArgumentException");
} catch(final IllegalArgumentException e) {
assertEquals("Error Name=Value", e.getMessage());
}
try {
Validate.isInstanceOf(List.class, "hi", "Error %s=%s", List.class, "Value");
fail("Expecting IllegalArgumentException");
} catch(final IllegalArgumentException e) {
assertEquals("Error interface java.util.List=Value", e.getMessage());
}
try {
Validate.isInstanceOf(List.class, "hi", "Error %s=%s", List.class, null);
fail("Expecting IllegalArgumentException");
} catch(final IllegalArgumentException e) {
assertEquals("Error interface java.util.List=null", e.getMessage());
}
}
@Test
public void testIsAssignable_withMessage() {
Validate.isAssignableFrom(CharSequence.class, String.class, "Error");
Validate.isAssignableFrom(AbstractList.class, ArrayList.class, "Error");
try {
Validate.isAssignableFrom(List.class, String.class, "Error");
fail("Expecting IllegalArgumentException");
} catch(final IllegalArgumentException e) {
assertEquals("Error", e.getMessage());
}
}
@Test
public void paramNotNull_NullParam_ThrowsException() {
try {
Validate.paramNotNull(null, "someField");
} catch (NullPointerException e) {
assertEquals(e.getMessage(), "someField must not be null.");
}
}
@Test
public void paramNotNull_NonNullParam_ReturnsObject() {
assertEquals("foo", Validate.paramNotNull("foo", "someField"));
}
@Test
public void getOrDefault_ParamNotNull_ReturnsParam() {
assertEquals("foo", Validate.getOrDefault("foo", () -> "bar"));
}
@Test
public void getOrDefault_ParamNull_ReturnsDefaultValue() {
assertEquals("bar", Validate.getOrDefault(null, () -> "bar"));
}
@Test(expected = NullPointerException.class)
public void getOrDefault_DefaultValueNull_ThrowsException() {
Validate.getOrDefault("bar", null);
}
@Test
public void mutuallyExclusive_AllNull_DoesNotThrow() {
Validate.mutuallyExclusive("error", null, null, null);
}
@Test
public void mutuallyExclusive_OnlyOneProvided_DoesNotThrow() {
Validate.mutuallyExclusive("error", null, "foo", null);
}
@Test(expected = IllegalArgumentException.class)
public void mutuallyExclusive_MultipleProvided_DoesNotThrow() {
Validate.mutuallyExclusive("error", null, "foo", "bar");
}
@Test
public void isPositiveOrNullInteger_null_returnsNull() {
assertNull(Validate.isPositiveOrNull((Integer) null, "foo"));
}
@Test
public void isPositiveOrNullInteger_positive_returnsInteger() {
Integer num = 42;
assertEquals(num, Validate.isPositiveOrNull(num, "foo"));
}
@Test
public void isPositiveOrNullInteger_zero_throws() {
expected.expect(IllegalArgumentException.class);
expected.expectMessage("foo");
Validate.isPositiveOrNull(0, "foo");
}
@Test
public void isPositiveOrNullInteger_negative_throws() {
expected.expect(IllegalArgumentException.class);
expected.expectMessage("foo");
Validate.isPositiveOrNull(-1, "foo");
}
@Test
public void isPositiveOrNullLong_null_returnsNull() {
assertNull(Validate.isPositiveOrNull((Long) null, "foo"));
}
@Test
public void isPositiveOrNullLong_positive_returnsInteger() {
Long num = 42L;
assertEquals(num, Validate.isPositiveOrNull(num, "foo"));
}
@Test
public void isPositiveOrNullLong_zero_throws() {
expected.expect(IllegalArgumentException.class);
expected.expectMessage("foo");
Validate.isPositiveOrNull(0L, "foo");
}
@Test
public void isPositiveOrNullLong_negative_throws() {
expected.expect(IllegalArgumentException.class);
expected.expectMessage("foo");
Validate.isPositiveOrNull(-1L, "foo");
}
@Test
public void isPositiveOrNullDouble_null_returnsNull() {
assertNull(Validate.isPositiveOrNull((Double) null, "foo"));
}
@Test
public void isPositiveOrNullDouble_positive_returnsInteger() {
Double num = 100.0;
assertEquals(num, Validate.isPositiveOrNull(num, "foo"));
}
@Test
public void isPositiveOrNullDouble_zero_throws() {
expected.expect(IllegalArgumentException.class);
expected.expectMessage("foo");
Validate.isPositiveOrNull(0.0, "foo");
}
@Test
public void isPositiveOrNullDouble_negative_throws() {
expected.expect(IllegalArgumentException.class);
expected.expectMessage("foo");
Validate.isPositiveOrNull(-1.0, "foo");
}
@Test
public void isNull_notNull_shouldThrow() {
expected.expect(IllegalArgumentException.class);
expected.expectMessage("not null");
Validate.isNull("string", "not null");
}
@Test
public void isNotNegativeOrNull_negative_throws() {
expected.expect(IllegalArgumentException.class);
expected.expectMessage("foo");
Validate.isNotNegativeOrNull(-1L, "foo");
}
@Test
public void isNotNegativeOrNull_notNegative_notThrow() {
assertThat(Validate.isNotNegativeOrNull(5L, "foo")).isEqualTo(5L);
assertThat(Validate.isNotNegativeOrNull(0L, "foo")).isEqualTo(0L);
}
@Test
public void isNull_null_shouldPass() {
Validate.isNull(null, "not null");
}
}
| 2,950 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/EitherTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
import org.junit.Test;
public class EitherTest {
@Test(expected = NullPointerException.class)
public void leftValueNull_ThrowsException() {
Either.left(null);
}
@Test(expected = NullPointerException.class)
public void rightValueNull_ThrowsException() {
Either.right(null);
}
@Test
public void mapWhenLeftValuePresent_OnlyCallsLeftFunction() {
final Either<String, Integer> either = Either.left("left val");
final Boolean mapped = either.map(s -> {
assertThat(s).isEqualTo("left val");
return Boolean.TRUE;
},
this::assertNotCalled);
assertThat(mapped).isTrue();
}
@Test
public void mapWhenRightValuePresent_OnlyCallsRightFunction() {
final Either<String, Integer> either = Either.right(42);
final Boolean mapped = either.map(this::assertNotCalled,
i -> {
assertThat(i).isEqualTo(42);
return Boolean.TRUE;
});
assertThat(mapped).isTrue();
}
@Test
public void mapLeftWhenLeftValuePresent_OnlyMapsLeftValue() {
final String value = "left val";
final Either<String, Integer> either = Either.left(value);
either.mapLeft(String::hashCode)
.apply(l -> assertThat(l).isEqualTo(value.hashCode()),
this::assertNotCalled);
}
@Test
public void mapLeftWhenLeftValueNotPresent_DoesNotMapValue() {
final Integer value = 42;
final Either<String, Integer> either = Either.right(value);
either.mapLeft(this::assertNotCalled)
.apply(this::assertNotCalled,
i -> assertThat(i).isEqualTo(42));
}
@Test
public void mapRightWhenRightValuePresent_OnlyMapsLeftValue() {
final Integer value = 42;
final Either<String, Integer> either = Either.right(value);
either.mapRight(i -> "num=" + i)
.apply(this::assertNotCalled,
v -> assertThat(v).isEqualTo("num=42"));
}
@Test
public void mapRightWhenRightValueNotPresent_DoesNotMapValue() {
final String value = "left val";
final Either<String, Integer> either = Either.left(value);
either.mapRight(this::assertNotCalled)
.apply(s -> assertThat(s).isEqualTo(value),
this::assertNotCalled);
}
@Test
public void fromNullable() {
assertThat(Either.fromNullable("left", null)).contains(Either.left("left"));
assertThat(Either.fromNullable(null, "right")).contains(Either.right("right"));
assertThat(Either.fromNullable(null, null)).isEmpty();
assertThatThrownBy(() -> Either.fromNullable("left", "right")).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void eitherLeft_returnLeft() {
assertThat(Either.left("test").left()).contains("test");
assertThat(Either.left("test").right()).isEmpty();
}
@Test
public void eitherRight_returnRight() {
assertThat(Either.right("test").right()).contains("test");
assertThat(Either.right("test").left()).isEmpty();
}
private <InT, OutT> OutT assertNotCalled(InT in) {
fail("Mapping function should not have been called");
return null;
}
}
| 2,951 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/LazyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.times;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
public class LazyTest {
private Lazy<String> lazy;
private Supplier<String> mockDelegate;
@Before
public void setup() {
mockDelegate = Mockito.mock(Supplier.class);
lazy = new Lazy<>(mockDelegate);
}
@Test
public void delegateNotCalledOnCreation() {
Mockito.verifyNoMoreInteractions(mockDelegate);
}
@Test
public void nullIsNotCached() {
Mockito.when(mockDelegate.get()).thenReturn(null);
lazy.getValue();
lazy.getValue();
Mockito.verify(mockDelegate, times(2)).get();
}
@Test
public void exceptionsAreNotCached() {
IllegalStateException exception = new IllegalStateException();
Mockito.when(mockDelegate.get()).thenThrow(exception);
assertThatThrownBy(lazy::getValue).isEqualTo(exception);
assertThatThrownBy(lazy::getValue).isEqualTo(exception);
Mockito.verify(mockDelegate, times(2)).get();
}
@Test(timeout = 10_000)
public void delegateCalledOnlyOnce() throws Exception {
final int threads = 5;
ExecutorService executor = Executors.newFixedThreadPool(threads);
try {
for (int i = 0; i < 1000; ++i) {
mockDelegate = Mockito.mock(Supplier.class);
Mockito.when(mockDelegate.get()).thenReturn("");
lazy = new Lazy<>(mockDelegate);
CountDownLatch everyoneIsWaitingLatch = new CountDownLatch(threads);
CountDownLatch everyoneIsDoneLatch = new CountDownLatch(threads);
CountDownLatch callGetValueLatch = new CountDownLatch(1);
for (int j = 0; j < threads; ++j) {
executor.submit(() -> {
everyoneIsWaitingLatch.countDown();
callGetValueLatch.await();
lazy.getValue();
everyoneIsDoneLatch.countDown();
return null;
});
}
everyoneIsWaitingLatch.await();
callGetValueLatch.countDown();
everyoneIsDoneLatch.await();
Mockito.verify(mockDelegate, times(1)).get();
}
} finally {
executor.shutdownNow();
}
}
} | 2,952 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ConditionalDecoratorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
public class ConditionalDecoratorTest {
@Test
void basicTransform_directlyCalled_isSuccessful() {
ConditionalDecorator<Integer> decorator = ConditionalDecorator.create(i -> true, i -> i + 1);
assertThat(decorator.transform().apply(3)).isEqualTo(4);
}
@Test
void listOfOrderedTransforms_singleTransformAlwaysTrue_isSuccessful() {
ConditionalDecorator<Integer> d1 = ConditionalDecorator.create(i -> true, i -> i + 1);
assertThat(ConditionalDecorator.decorate(2, Collections.singletonList(d1))).isEqualTo(3);
}
@Test
void listOfOrderedTransforms_alwaysTrue_isSuccessful() {
ConditionalDecorator<Integer> d1 = ConditionalDecorator.create(i -> true, i -> i + 1);
ConditionalDecorator<Integer> d2 = ConditionalDecorator.create(i -> true, i -> i * 2);
assertThat(ConditionalDecorator.decorate(2, Arrays.asList(d1, d2))).isEqualTo(6);
}
@Test
void listOfOrderedTransformsInReverse_alwaysTrue_isSuccessful() {
ConditionalDecorator<Integer> d1 = ConditionalDecorator.create(i -> true, i -> i + 1);
ConditionalDecorator<Integer> d2 = ConditionalDecorator.create(i -> true, i -> i * 2);
assertThat(ConditionalDecorator.decorate(2, Arrays.asList(d2, d1))).isEqualTo(5);
}
@Test
void listOfOrderedTransforms_onlyAddsEvenNumbers_isSuccessful() {
List<ConditionalDecorator<Integer>> decorators =
IntStream.range(0, 9)
.<ConditionalDecorator<Integer>>mapToObj(i -> ConditionalDecorator.create(j -> i % 2 == 0,
j -> j + i))
.collect(Collectors.toList());
assertThat(ConditionalDecorator.decorate(0, decorators)).isEqualTo(20);
}
}
| 2,953 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/proxy/ProxyConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.proxy;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
import software.amazon.awssdk.utils.ProxyConfigProvider;
import software.amazon.awssdk.utils.Pair;
public class ProxyConfigurationTest {
private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper();
public static Stream<Arguments> proxyConfigurationSetting() {
return Stream.of(
Arguments.of(Arrays.asList(
Pair.of("%s.proxyHost", "foo.com"),
Pair.of("%s.proxyPort", "555"),
Pair.of("http.nonProxyHosts", "bar.com"),
Pair.of("%s.proxyUser", "UserOne"),
Pair.of("%s.proxyPassword", "passwordSecret")),
Arrays.asList(
Pair.of("%s_proxy", "http://UserOne:passwordSecret@foo.com:555/"),
Pair.of("no_proxy", "bar.com")
),
new ExpectedProxySetting().host("foo.com")
.port(555).userName("UserOne")
.password("passwordSecret")
.nonProxyHost("bar.com"),
"All Proxy Parameters are Set"),
Arguments.of(Arrays.asList(
Pair.of("%s.proxyHost", "foo.com"),
Pair.of("%s.proxyPort", "555")),
Collections.singletonList(
Pair.of("%s_proxy", "http://foo.com:555/")
),
new ExpectedProxySetting().host("foo.com").port(555),
"Optional Parameters are not set"),
Arguments.of(Collections.singletonList(
Pair.of("proxy", "")),
Arrays.asList(
Pair.of("%s_proxy", ""),
Pair.of("no_proxy", "")
),
new ExpectedProxySetting().port(0),
"All parameters are Blank"),
Arguments.of(Collections.singletonList(
Pair.of("http.nonProxyHosts", "one,two,three")),
Collections.singletonList(
Pair.of("no_proxy", "one,two,three")
),
new ExpectedProxySetting().port(0).nonProxyHost("one,two,three"),
"Only Non Proxy Hosts are set with multiple value"),
Arguments.of(Arrays.asList(
Pair.of("%s.proxyVaildHost", "foo.com"),
Pair.of("%s.proxyPorts", "555")),
Collections.singletonList(
Pair.of("%s_proxy", "http://foo:com:Incorrects:555/")
),
new ExpectedProxySetting().port(0),
"Incorrect local Setting"),
Arguments.of(Arrays.asList(
Pair.of("%s.proxyHost", "foo.com"),
Pair.of("%s.proxyPort", "555"),
Pair.of("http.nonProxyHosts", "bar.com"),
Pair.of("%s.proxyUser", ""),
Pair.of("%s.proxyPassword", "passwordSecret")),
Arrays.asList(
Pair.of("%s_proxy", "http://:passwordSecret@foo.com:555/"),
Pair.of("no_proxy", "bar.com")
),
new ExpectedProxySetting().host("foo.com").userName("").port(555).password("passwordSecret").nonProxyHost("bar.com"),
"No User is left empty"),
Arguments.of(Arrays.asList(
Pair.of("%s.proxyHost", "foo.com"),
Pair.of("%s.proxyPort", "555"),
Pair.of("http.nonProxyHosts", "bar.com"),
Pair.of("%s.proxyUser", "UserOne")
),
Arrays.asList(
Pair.of("%s_proxy", "http://UserOne@foo.com:555/"),
Pair.of("no_proxy", "bar.com")
),
new ExpectedProxySetting().host("foo.com").port(555).userName("UserOne").nonProxyHost("bar.com"),
"Password not present"),
Arguments.of(Arrays.asList(
Pair.of("%s.proxyHost", "555"),
Pair.of("%s.proxyPort", "-1"),
Pair.of("http.nonProxyHosts", "bar.com")
),
Arrays.asList(
Pair.of("%s_proxy", "http://555/"),
Pair.of("no_proxy", "bar.com")
),
new ExpectedProxySetting().host("555").port(-1).nonProxyHost("bar.com"),
"Host name is just a number"),
Arguments.of(Arrays.asList(
Pair.of("%s.proxyHost", "foo.com"),
Pair.of("%s.proxyPort", "abcde"),
Pair.of("http.nonProxyHosts", "bar.com"),
Pair.of("%s.proxyUser", "UserOne"),
Pair.of("%s.proxyPassword", "passwordSecret")),
Arrays.asList(
Pair.of("%s_proxy", "http://UserOne:passwordSecret@foo.com:0/"),
Pair.of("no_proxy", "bar.com")
),
new ExpectedProxySetting().host("foo.com").port(0).userName("UserOne").password("passwordSecret").nonProxyHost("bar.com"),
"Number format exception for SystemProperty is handled by defaulting it to 0")
);
}
private static void assertProxyEquals(ProxyConfigProvider actualConfiguration,
ExpectedProxySetting expectedProxySetting) {
assertThat(actualConfiguration.port()).isEqualTo(expectedProxySetting.port);
assertThat(actualConfiguration.host()).isEqualTo(expectedProxySetting.host);
assertThat(actualConfiguration.nonProxyHosts()).isEqualTo(expectedProxySetting.nonProxyHosts);
assertThat(actualConfiguration.userName().orElse(null)).isEqualTo(expectedProxySetting.userName);
assertThat(actualConfiguration.password().orElse(null)).isEqualTo(expectedProxySetting.password);
}
static void setSystemProperties(List<Pair<String, String>> settingsPairs, String protocol) {
settingsPairs.forEach(settingsPair -> System.setProperty(String.format(settingsPair.left(), protocol),
settingsPair.right()));
}
static void setEnvironmentProperties(List<Pair<String, String>> settingsPairs, String protocol) {
settingsPairs.forEach(settingsPair -> ENVIRONMENT_VARIABLE_HELPER.set(String.format(settingsPair.left(), protocol),
settingsPair.right()));
}
@BeforeEach
void setUp() {
Stream.of("http", "https").forEach(protocol ->
Stream.of("%s.proxyHost", "%s.proxyPort", "%s.nonProxyHosts", "%s.proxyUser",
"%s.proxyPassword")
.forEach(property -> System.clearProperty(String.format(property, protocol)))
);
ENVIRONMENT_VARIABLE_HELPER.reset();
}
@ParameterizedTest(name = "{index} - {3}.")
@MethodSource("proxyConfigurationSetting")
void given_LocalSetting_when_httpProtocol_then_correctProxyConfiguration(List<Pair<String, String>> systemSettingsPair,
List<Pair<String, String>> envSystemSetting,
ExpectedProxySetting expectedProxySetting,
String testCaseName) {
setSystemProperties(systemSettingsPair, "http");
setEnvironmentProperties(envSystemSetting, "http");
assertProxyEquals(ProxyConfigProvider.fromSystemPropertySettings("http"), expectedProxySetting);
assertProxyEquals(ProxyConfigProvider.fromEnvironmentSettings("http"), expectedProxySetting);
}
@ParameterizedTest(name = "{index} - {3}.")
@MethodSource("proxyConfigurationSetting")
void given_LocalSetting_when_httpsProtocol_then_correctProxyConfiguration(List<Pair<String, String>> systemSettingsPair,
List<Pair<String, String>> envSystemSetting,
ExpectedProxySetting expectedProxySetting,
String testCaseName) {
setSystemProperties(systemSettingsPair, "https");
setEnvironmentProperties(envSystemSetting, "https");
assertProxyEquals(ProxyConfigProvider.fromSystemPropertySettings("https"), expectedProxySetting);
assertProxyEquals(ProxyConfigProvider.fromEnvironmentSettings("https"), expectedProxySetting);
}
private static class ExpectedProxySetting {
private int port;
private String host;
private String userName;
private String password;
private Set<String> nonProxyHosts = new HashSet<>();
public ExpectedProxySetting port(int port) {
this.port = port;
return this;
}
public ExpectedProxySetting host(String host) {
this.host = host;
return this;
}
public ExpectedProxySetting userName(String userName) {
this.userName = userName;
return this;
}
public ExpectedProxySetting password(String password) {
this.password = password;
return this;
}
public ExpectedProxySetting nonProxyHost(String... nonProxyHosts) {
this.nonProxyHosts = nonProxyHosts != null ? Arrays.stream(nonProxyHosts)
.collect(Collectors.toSet()) : new HashSet<>();
return this;
}
}
}
| 2,954 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/cache/CachedSupplierTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.cache;
import static java.time.Instant.now;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import static software.amazon.awssdk.utils.cache.CachedSupplier.StaleValueBehavior.ALLOW;
import static software.amazon.awssdk.utils.cache.CachedSupplier.StaleValueBehavior.STRICT;
import java.io.Closeable;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.cache.CachedSupplier.StaleValueBehavior;
/**
* Validate the functionality of {@link CachedSupplier}.
*/
public class CachedSupplierTest {
/**
* An executor for performing "get" on the cached supplier asynchronously. This, along with the {@link WaitingSupplier} allows
* near-manual scheduling of threads so that we can test that the cache is only calling the underlying supplier when we want
* it to.
*/
private ExecutorService executorService;
/**
* All executions added to the {@link #executorService} since the beginning of an individual test method.
*/
private List<Future<?>> allExecutions;
/**
* Create an executor service for async testing.
*/
@BeforeEach
public void setup() {
executorService = Executors.newFixedThreadPool(50);
allExecutions = new ArrayList<>();
}
/**
* Shut down the executor service when we're done.
*/
@AfterEach
public void shutdown() {
executorService.shutdown();
}
private static class MutableSupplier implements Supplier<RefreshResult<String>> {
private volatile RuntimeException thingToThrow;
private volatile RefreshResult<String> thingToReturn;
@Override
public RefreshResult<String> get() {
if (thingToThrow != null) {
throw thingToThrow;
}
return thingToReturn;
}
private MutableSupplier set(RuntimeException exception) {
this.thingToThrow = exception;
this.thingToReturn = null;
return this;
}
private MutableSupplier set(RefreshResult<String> value) {
this.thingToThrow = null;
this.thingToReturn = value;
return this;
}
}
/**
* An implementation of {@link Supplier} that allows us to (more or less) manually schedule threads so that we can make sure
* the CachedSupplier is only calling the underlying supplier when we expect it to.
*/
private static class WaitingSupplier implements Supplier<RefreshResult<String>>, Closeable {
/**
* A semaphore that is counted up each time a "get" is started. This is useful during testing for waiting for a certain
* number of "gets" to start.
*/
private final Semaphore startedGetPermits = new Semaphore(0);
/**
* A semaphore that is counted down each time a "get" is started. This is useful during testing for blocking the threads
* performing the "get" until it is time for them to complete.
*/
private final Semaphore permits = new Semaphore(0);
/**
* A semaphore that is counted up each time a "get" is finished. This is useful during testing for waiting for a certain
* number of "gets" to finish.
*/
private final Semaphore finishedGetPermits = new Semaphore(0);
private final Supplier<Instant> staleTime;
private final Supplier<Instant> prefetchTime;
private WaitingSupplier(Instant staleTime, Instant prefetchTime) {
this(() -> staleTime, () -> prefetchTime);
}
private WaitingSupplier(Supplier<Instant> staleTime, Supplier<Instant> prefetchTime) {
this.staleTime = staleTime;
this.prefetchTime = prefetchTime;
}
@Override
public RefreshResult<String> get() {
startedGetPermits.release(1);
try {
permits.acquire(1);
} catch (InterruptedException e) {
e.printStackTrace();
fail();
}
finishedGetPermits.release(1);
return RefreshResult.builder("value")
.staleTime(staleTime.get())
.prefetchTime(prefetchTime.get())
.build();
}
/**
* Wait for a certain number of "gets" to have started. This will time out and fail the test after a certain amount of
* time if the "gets" never actually start.
*/
public void waitForGetsToHaveStarted(int numExpectedGets) {
assertTrue(invokeSafely(() -> startedGetPermits.tryAcquire(numExpectedGets, 10, TimeUnit.SECONDS)));
}
/**
* Wait for a certain number of "gets" to have finished. This will time out and fail the test after a certain amount of
* time if the "gets" never finish.
*/
public void waitForGetsToHaveFinished(int numExpectedGets) {
assertTrue(invokeSafely(() -> finishedGetPermits.tryAcquire(numExpectedGets, 10, TimeUnit.SECONDS)));
}
/**
* Release all threads blocked in this supplier.
*/
@Override
public void close() {
permits.release(50);
}
}
@Test
public void allCallsBeforeInitializationBlock() {
try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), future())) {
CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier).build();
// Perform two "gets".
performAsyncGets(cachedSupplier, 2);
// Make sure both "gets" are started.
waitingSupplier.waitForGetsToHaveStarted(2);
}
}
@Test
public void staleValueBlocksAllCalls() throws InterruptedException {
AdjustableClock clock = new AdjustableClock();
try (WaitingSupplier waitingSupplier = new WaitingSupplier(() -> now().plus(1, ChronoUnit.MINUTES), this::future)) {
CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier)
.clock(clock)
.build();
// Perform one successful "get".
waitingSupplier.permits.release(1);
clock.time = now();
waitFor(performAsyncGet(cachedSupplier));
// Perform two "get"s that will attempt to refresh the value, and wait for them to get stuck.
clock.time = now().plus(61, ChronoUnit.SECONDS);
List<Future<?>> futures = performAsyncGets(cachedSupplier, 2);
waitingSupplier.waitForGetsToHaveStarted(3);
Thread.sleep(1_000);
assertThat(futures).allMatch(f -> !f.isDone());
// Release any "gets" that blocked and wait for them to finish.
waitingSupplier.permits.release(50);
waitForAsyncGetsToFinish();
// Make extra sure all 3 "gets" actually happened.
waitingSupplier.waitForGetsToHaveFinished(3);
}
}
@Test
public void staleValueBlocksAllCallsEvenWithStaleValuesAllowed() throws InterruptedException {
// This test case may seem unintuitive: why block for a stale value refresh if we allow stale values to be used? We do
// this because values may become stale from disuse in sync prefetch strategies. If there's a new value available, we'd
// still like to hold threads a little to give them a chance at a non-stale value.
AdjustableClock clock = new AdjustableClock();
try (WaitingSupplier waitingSupplier = new WaitingSupplier(() -> now().plus(1, ChronoUnit.MINUTES), this::future)) {
CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier)
.clock(clock)
.staleValueBehavior(ALLOW)
.build();
// Perform one successful "get".
waitingSupplier.permits.release(1);
clock.time = now();
waitFor(performAsyncGet(cachedSupplier));
// Perform two "get"s that will attempt to refresh the value, and wait for them to get stuck.
clock.time = now().plus(61, ChronoUnit.SECONDS);
List<Future<?>> futures = performAsyncGets(cachedSupplier, 2);
waitingSupplier.waitForGetsToHaveStarted(3);
Thread.sleep(1_000);
assertThat(futures).allMatch(f -> !f.isDone());
// Release any "gets" that blocked and wait for them to finish.
waitingSupplier.permits.release(50);
waitForAsyncGetsToFinish();
// Make extra sure all 3 "gets" actually happened.
waitingSupplier.waitForGetsToHaveFinished(3);
}
}
@Test
public void firstRetrieveFailureThrowsForStrictStaleMode() {
firstRetrievalFails(STRICT);
}
@Test
public void firstRetrieveFailureThrowsForAllowStaleMode() {
firstRetrievalFails(ALLOW);
}
private void firstRetrievalFails(StaleValueBehavior staleValueBehavior) {
RuntimeException e = new RuntimeException();
try (CachedSupplier<?> cachedSupplier = CachedSupplier.builder(() -> { throw e; })
.staleValueBehavior(staleValueBehavior)
.build()) {
assertThatThrownBy(cachedSupplier::get).isEqualTo(e);
}
}
@Test
public void prefetchThrowIsHiddenIfValueIsNotStaleForStrictMode() {
prefetchThrowIsHiddenIfValueIsNotStale(STRICT);
}
@Test
public void prefetchThrowIsHiddenIfValueIsNotStaleForAllowMode() {
prefetchThrowIsHiddenIfValueIsNotStale(ALLOW);
}
private void prefetchThrowIsHiddenIfValueIsNotStale(StaleValueBehavior staleValueBehavior) {
MutableSupplier supplier = new MutableSupplier();
try (CachedSupplier<?> cachedSupplier = CachedSupplier.builder(supplier)
.staleValueBehavior(staleValueBehavior)
.build()) {
supplier.set(RefreshResult.builder("")
.prefetchTime(now())
.build());
assertThat(cachedSupplier.get()).isEqualTo("");
supplier.set(new RuntimeException());
assertThat(cachedSupplier.get()).isEqualTo("");
}
}
@Test
public void valueIsCachedForAShortTimeIfValueIsStaleInStrictMode() throws Throwable {
MutableSupplier supplier = new MutableSupplier();
try (CachedSupplier<?> cachedSupplier = CachedSupplier.builder(supplier)
.staleValueBehavior(STRICT)
.build()) {
supplier.set(RefreshResult.builder("")
.staleTime(now())
.build());
assertThat(cachedSupplier.get()).isEqualTo("");
RuntimeException e = new RuntimeException();
supplier.set(e);
assertThat(cachedSupplier.get()).isEqualTo("");
}
}
@Test
public void throwIsPropagatedIfValueIsStaleInStrictMode() throws InterruptedException {
MutableSupplier supplier = new MutableSupplier();
try (CachedSupplier<?> cachedSupplier = CachedSupplier.builder(supplier)
.staleValueBehavior(STRICT)
.build()) {
supplier.set(RefreshResult.builder("")
.staleTime(now())
.build());
assertThat(cachedSupplier.get()).isEqualTo("");
RuntimeException e = new RuntimeException();
supplier.set(e);
Thread.sleep(1001); // Wait to avoid the light rate-limiting we apply
assertThatThrownBy(cachedSupplier::get).isEqualTo(e);
}
}
@Test
public void throwIsHiddenIfValueIsStaleInAllowMode() throws InterruptedException {
MutableSupplier supplier = new MutableSupplier();
try (CachedSupplier<?> cachedSupplier = CachedSupplier.builder(supplier)
.staleValueBehavior(ALLOW)
.build()) {
supplier.set(RefreshResult.builder("")
.staleTime(now().plusSeconds(1))
.build());
assertThat(cachedSupplier.get()).isEqualTo("");
RuntimeException e = new RuntimeException();
supplier.set(e);
Thread.sleep(1000);
assertThat(cachedSupplier.get()).isEqualTo("");
}
}
@Test
public void basicCachingWorks() {
try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), future())) {
CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier).build();
// Perform 5 "gets".
waitingSupplier.permits.release(5);
waitFor(performAsyncGets(cachedSupplier, 5));
// Make extra sure only 1 "get" actually happened.
waitingSupplier.waitForGetsToHaveFinished(1);
}
}
@Test
public void oneCallerBlocksPrefetchStrategyWorks() throws InterruptedException {
try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), past())) {
CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier)
.prefetchStrategy(new OneCallerBlocks())
.jitterEnabled(false)
.build();
// Perform one successful "get" to prime the cache.
waitingSupplier.permits.release(1);
waitFor(performAsyncGet(cachedSupplier));
// Perform one "get" that will attempt to refresh the value, and wait for that one to get stuck.
performAsyncGet(cachedSupplier);
waitingSupplier.waitForGetsToHaveStarted(2);
// Perform a successful "get" because one is already blocked to refresh.
waitFor(performAsyncGet(cachedSupplier));
// Release any "gets" that blocked and wait for them to finish.
waitingSupplier.permits.release(50);
waitForAsyncGetsToFinish();
// Make extra sure only 2 "gets" actually happened.
waitingSupplier.waitForGetsToHaveFinished(2);
}
}
@Test
public void nonBlockingPrefetchStrategyWorks() {
try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), past());
CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier)
.prefetchStrategy(new NonBlocking("test-%s"))
.jitterEnabled(false)
.build()) {
// Perform one successful "get" to prime the cache.
waitingSupplier.permits.release(1);
waitFor(performAsyncGet(cachedSupplier));
// Perform one successful "get" to kick off the async refresh.
waitFor(performAsyncGet(cachedSupplier));
// Wait for the async "get" in the background to start (if it hasn't already).
waitingSupplier.waitForGetsToHaveStarted(2);
// Make sure only one "get" has actually happened (the async get is currently waiting to be released).
waitingSupplier.waitForGetsToHaveFinished(1);
}
}
@Test
public void nonBlockingPrefetchStrategyRefreshesInBackground() {
try (WaitingSupplier waitingSupplier = new WaitingSupplier(now().plusSeconds(62), now().plusSeconds(1));
CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier)
.prefetchStrategy(new NonBlocking("test-%s"))
.jitterEnabled(false)
.build()) {
waitingSupplier.permits.release(2);
cachedSupplier.get();
// Ensure two "get"s happens even though we only made one call to the cached supplier.
waitingSupplier.waitForGetsToHaveStarted(2);
assertThat(cachedSupplier.get()).isNotNull();
}
}
@Test
public void nonBlockingPrefetchStrategyHasOneMinuteMinimumByDefault() {
try (WaitingSupplier waitingSupplier = new WaitingSupplier(now().plusSeconds(60), now());
CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier)
.prefetchStrategy(new NonBlocking("test-%s"))
.build()) {
waitingSupplier.permits.release(2);
cachedSupplier.get();
// Ensure two "get"s happens even though we only made one call to the cached supplier.
assertThat(invokeSafely(() -> waitingSupplier.startedGetPermits.tryAcquire(2, 2, TimeUnit.SECONDS))).isFalse();
}
}
@Test
public void nonBlockingPrefetchStrategyBackgroundRefreshesHitCache() throws InterruptedException {
try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), future());
CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier)
.prefetchStrategy(new NonBlocking("test-%s"))
.build()) {
waitingSupplier.permits.release(5);
cachedSupplier.get();
Thread.sleep(1_000);
assertThat(waitingSupplier.permits.availablePermits()).isEqualTo(4); // Only 1 call to supplier
}
}
@Test
public void nonBlockingPrefetchStrategyDoesNotRefreshUntilItIsCalled() throws InterruptedException {
try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), past());
CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier)
.prefetchStrategy(new NonBlocking("test-%s"))
.build()) {
waitingSupplier.startedGetPermits.release();
Thread.sleep(1_000);
assertThat(waitingSupplier.startedGetPermits.availablePermits()).isEqualTo(1);
}
}
@Test
public void threadsAreSharedBetweenNonBlockingInstances() throws InterruptedException {
int maxActive = runAndCountThreads(() -> {
List<CachedSupplier<?>> css = new ArrayList<>();
for (int i = 0; i < 99; i++) {
CachedSupplier<?> supplier =
CachedSupplier.builder(() -> RefreshResult.builder("foo")
.prefetchTime(now().plusMillis(10))
.staleTime(future())
.build())
.prefetchStrategy(new NonBlocking("test"))
.jitterEnabled(false)
.build();
supplier.get();
css.add(supplier);
}
return css;
});
assertThat(maxActive).isBetween(1, 99);
}
@Test
public void activeThreadsHaveMaxCount() throws InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
try {
int maxActive = runAndCountThreads(() -> {
List<CachedSupplier<?>> css = new ArrayList<>();
// Create 1000 concurrent non-blocking instances
for (int i = 0; i < 1000; i++) {
CachedSupplier<String> supplier =
CachedSupplier.builder(() -> {
invokeSafely(() -> Thread.sleep(100));
return RefreshResult.builder("foo")
.prefetchTime(now().plusMillis(10))
.staleTime(now().plusSeconds(60))
.build();
}).prefetchStrategy(new NonBlocking("test"))
.jitterEnabled(false)
.build();
executor.submit(supplier::get);
css.add(supplier);
}
executor.shutdown();
assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue();
return css;
});
assertThat(maxActive).isBetween(2, 150);
} finally {
executor.shutdownNow();
}
}
/**
* Run the provided supplier, measure the non-blocking executor thread count, and return the result. If the result is 0,
* try again. This makes our stochastic tests ~100% reliable instead of ~99%.
*/
private int runAndCountThreads(ThrowingSupplier suppliersConstructor) throws InterruptedException {
for (int attempt = 0; attempt < 10; attempt++) {
Collection<CachedSupplier<?>> suppliers = emptyList();
try {
suppliers = suppliersConstructor.get();
int maxActive = 0;
for (int j = 0; j < 1000; j++) {
maxActive = Math.max(maxActive, NonBlocking.executor().getActiveCount());
Thread.sleep(1);
}
if (maxActive != 0) {
return maxActive;
}
} finally {
suppliers.forEach(CachedSupplier::close);
}
}
throw new AssertionError("Thread count never exceeded 0.");
}
@FunctionalInterface
interface ThrowingSupplier {
Collection<CachedSupplier<?>> get() throws InterruptedException;
}
/**
* Asynchronously perform a "get" on the provided supplier, returning the future that will be completed when the "get"
* finishes.
*/
private Future<?> performAsyncGet(CachedSupplier<?> supplier) {
return executorService.submit(supplier::get);
}
/**
* Asynchronously perform multiple "gets" on the provided supplier, returning the collection of futures to be completed when
* the "get" finishes.
*/
private List<Future<?>> performAsyncGets(CachedSupplier<?> supplier, int count) {
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < count; ++i) {
futures.add(performAsyncGet(supplier));
}
allExecutions.addAll(futures);
return futures;
}
/**
* Wait for the provided future to complete, failing the test if it does not.
*/
private void waitFor(Future<?> future) {
invokeSafely(() -> future.get(10, TimeUnit.SECONDS));
}
/**
* Wait for all futures in the provided collection fo complete, failing the test if they do not all complete.
*/
private void waitFor(Collection<Future<?>> futures) {
futures.forEach(this::waitFor);
}
/**
* Wait for all async gets ever created by this class to complete, failing the test if they do not all complete.
*/
private void waitForAsyncGetsToFinish() {
waitFor(allExecutions);
}
private Instant past() {
return now().minusSeconds(1);
}
private Instant future() {
return Instant.MAX;
}
private static class AdjustableClock extends Clock {
private Instant time;
@Override
public ZoneId getZone() {
return ZoneOffset.UTC;
}
@Override
public Clock withZone(ZoneId zone) {
throw new UnsupportedOperationException();
}
@Override
public Instant instant() {
return time;
}
}
}
| 2,955 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/cache | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/cache/lru/LruCacheTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.cache.lru;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class LruCacheTest {
private static final int MAX_SIMPLE_TEST_ENTRIES = 10;
private static final int MAX_SIMPLE_CACHE_SIZE = 3;
private static final List<Integer> simpleTestKeys = IntStream.range(0, MAX_SIMPLE_TEST_ENTRIES)
.boxed()
.collect(Collectors.toList());
private static final List<String> simpleTestValues = IntStream.range(0, MAX_SIMPLE_TEST_ENTRIES)
.mapToObj(Integer::toString)
.map(String::new)
.collect(Collectors.toList());
@Spy
private Function<Integer, String> simpleValueSupplier = new SimpleValueSupplier(simpleTestValues);
private final Function<Integer, String> identitySupplier = key -> Integer.toString(key);
private final Supplier<LruCache<Integer, String>> simpleCache = () -> LruCache.builder(simpleValueSupplier)
.maxSize(MAX_SIMPLE_CACHE_SIZE)
.build();
@Test
void when_cacheHasMiss_ValueIsCalculatedAndCached() {
LruCache<Integer, String> cache = simpleCache.get();
primeAndVerifySimpleCache(cache, 1);
}
@Test
void when_cacheHasHit_ValueIsRetrievedFromCache() {
LruCache<Integer, String> cache = simpleCache.get();
primeAndVerifySimpleCache(cache, MAX_SIMPLE_CACHE_SIZE);
//get 2, the last added value. Should get it from cache
String result = cache.get(simpleTestKeys.get(2));
assertThat(cache.size()).isEqualTo(MAX_SIMPLE_CACHE_SIZE);
assertThat(result).isNotNull();
assertThat(result).isEqualTo(simpleTestValues.get(2));
//item 2 was only retrieved once from the supplier, but twice from cache
verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(2));
}
@Test
void when_cacheFillsUp_ValuesAreEvictedFromCache() {
LruCache<Integer, String> cache = simpleCache.get();
//fill cache [2, 1, 0]
primeAndVerifySimpleCache(cache, MAX_SIMPLE_CACHE_SIZE);
//new item requested, evict 0 -> [3, 2, 1]
String result = cache.get(simpleTestKeys.get(3));
assertCacheState(cache, result, MAX_SIMPLE_CACHE_SIZE, 3);
//move 2 up -> [2, 3, 1]
cache.get(simpleTestKeys.get(2));
//evict 1 -> [4, 2, 3]
cache.get(simpleTestKeys.get(4));
//move 2 up -> [2, 4, 3]
cache.get(simpleTestKeys.get(2));
//get 1 back -> [1, 2, 4]
result = cache.get(simpleTestKeys.get(1));
assertCacheState(cache, result, MAX_SIMPLE_CACHE_SIZE, 1);
//each item in the test is only retrieved once except for 1
verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(0));
verify(simpleValueSupplier, times(2)).apply(simpleTestKeys.get(1));
verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(2));
verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(3));
verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(4));
}
@Test
void when_closeableValuesAreEvicted_CloseMethodIsCalled() {
int cacheSize = 3;
int evictNum = 2;
LruCache<Integer, CloseableClass> cache = LruCache.builder(CloseableClass::new)
.maxSize(cacheSize)
.build();
CloseableClass.reset();
for (int i = 0; i < cacheSize + evictNum; i++) {
cache.get(i);
}
assertThat(CloseableClass.evictedItems()).isNotEmpty();
assertThat(CloseableClass.evictedItems()).hasSize(evictNum);
assertThat(CloseableClass.evictedItems().get(0)).isEqualTo(0);
assertThat(CloseableClass.evictedItems().get(1)).isEqualTo(1);
}
@Test
void when_closeableValuesAreEvicted_NoExceptionsAreThrownIfCloseFails() {
int cacheSize = 3;
int evictNum = 2;
LruCache<Integer, FaultyCloseableClass> cache = LruCache.builder(FaultyCloseableClass::new)
.maxSize(cacheSize)
.build();
CloseableClass.reset();
for (int i = 0; i < cacheSize + evictNum; i++) {
cache.get(i);
}
assertThat(CloseableClass.evictedItems()).isEmpty();
}
@Test
void when_mostRecentValueIsHit_ValuesAreReorderedCorrectly() {
LruCache<Integer, String> cache = simpleCache.get();
//fill cache [2, 1, 0]
primeAndVerifySimpleCache(cache, MAX_SIMPLE_CACHE_SIZE);
//get current mru (most recently used). Cache should stay the same: [2, 1, 0]
cache.get(simpleTestKeys.get(2));
//evict items 1,2 -> [3, 4, 2]
cache.get(simpleTestKeys.get(3));
cache.get(simpleTestKeys.get(4));
//get 2, it should come from cache -> [2, 3, 4]
cache.get(simpleTestKeys.get(2));
//each value in the test is only retrieved once
verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(0));
verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(1));
verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(2));
verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(3));
verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(4));
}
@Test
void when_leastRecentValueIsHit_ValuesAreReorderedCorrectly() {
LruCache<Integer, String> cache = simpleCache.get();
//fill cache [2, 1, 0]
primeAndVerifySimpleCache(cache, MAX_SIMPLE_CACHE_SIZE);
//get current lru (least recently used) and move up
cache.get(simpleTestKeys.get(0));
//evict items 1, 2 -> [3, 4, 0]
cache.get(simpleTestKeys.get(3));
cache.get(simpleTestKeys.get(4));
//get 0, should return cached value -> [0, 3, 4]
cache.get(simpleTestKeys.get(0));
//get 1, should get from supplier
cache.get(simpleTestKeys.get(1));
//get 2, should get from supplier
cache.get(simpleTestKeys.get(2));
//1, 2 fell out of cache and were retrieved
verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(0));
verify(simpleValueSupplier, times(2)).apply(simpleTestKeys.get(1));
verify(simpleValueSupplier, times(2)).apply(simpleTestKeys.get(2));
}
@Test
void when_cacheHasMiss_AndNoValueIsFound_ReturnsNull() {
LruCache<Integer, String> cache = simpleCache.get();
primeAndVerifySimpleCache(cache, 1);
Integer keyMissingValue = 200;
String value = cache.get(keyMissingValue);
assertThat(value).isNull();
cache.get(keyMissingValue);
verify(simpleValueSupplier, times(1)).apply(keyMissingValue);
}
@ParameterizedTest
@MethodSource("concurrencyTestValues")
void when_multipleThreadsAreCallingCache_WorksAsExpected(Integer numThreads,
Integer numGetsPerThread,
boolean sleep,
Integer cacheSize) throws Exception {
ExecutorService executor = Executors.newCachedThreadPool();
try {
Function<Integer, String> sleepySupplier = num -> {
if (sleep) {
invokeSafely(() -> Thread.sleep(ThreadLocalRandom.current().nextInt(0, 5)));
}
return identitySupplier.apply(num);
};
LruCache<Integer, String> cache = LruCache.builder(sleepySupplier)
.maxSize(cacheSize)
.build();
List<Future<?>> results = new ArrayList<>();
for (int i = 0; i < numThreads; i++) {
results.add(executor.submit(() -> {
for (int j = 0; j < numGetsPerThread; j++) {
int key = ThreadLocalRandom.current().nextInt(cacheSize * 2);
String value = cache.get(key);
assertThat(value).isEqualTo(Integer.toString(key));
}
}));
}
for (Future<?> result : results) {
result.get(20, TimeUnit.SECONDS);
}
} finally {
executor.shutdownNow();
}
}
private static Stream<Arguments> concurrencyTestValues() {
// numThreads, numGetsPerThreads, sleepDurationMillis, cacheSize
return Stream.of(Arguments.of(1000, 5000, false, 5),
Arguments.of(1000, 5000, false, 50),
Arguments.of(100, 1000, true, 5)
);
}
private void assertCacheState(LruCache<Integer, String> cache, String result, int size, int index) {
assertThat(cache.size()).isEqualTo(size);
assertThat(result).isNotNull();
assertThat(result).isEqualTo(simpleTestValues.get(index));
}
private void primeAndVerifySimpleCache(LruCache<Integer, String> cache, int numEntries) {
IntStream.range(0, numEntries).forEach(i -> {
String result = cache.get(simpleTestKeys.get(i));
assertThat(cache.size()).isEqualTo(i + 1);
assertThat(result).isNotNull();
assertThat(result).isEqualTo(simpleTestValues.get(i));
verify(simpleValueSupplier).apply(simpleTestKeys.get(i));
});
}
private static class SimpleValueSupplier implements Function<Integer, String> {
List<String> values;
SimpleValueSupplier(List<String> values) {
this.values = values;
}
@Override
public String apply(Integer key) {
String value = null;
try {
value = values.get(key);
} catch (Exception ignored) {
}
return value;
}
}
private static class CloseableClass implements AutoCloseable {
private static List<Integer> evictedList = new ArrayList<>();
private final Integer key;
CloseableClass(Integer key) {
this.key = key;
}
public Integer get() throws Exception {
return key;
}
public static void reset() {
evictedList = new ArrayList<>();
}
public static List<Integer> evictedItems() {
return Collections.unmodifiableList(evictedList);
}
@Override
public void close() {
evictedList.add(key);
}
}
private static class FaultyCloseableClass extends CloseableClass {
FaultyCloseableClass(Integer key) {
super(key);
}
@Override
public void close() {
throw new RuntimeException("Could not close resources!");
}
}
}
| 2,956 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/InputStreamConsumingPublisherTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult.END_OF_STREAM;
import static software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult.SUCCESS;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.ThreadFactoryBuilder;
public class InputStreamConsumingPublisherTest {
private static final ExecutorService EXECUTOR =
Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build());
private ByteBufferStoringSubscriber subscriber;
private InputStreamConsumingPublisher publisher;
@BeforeEach
public void setup() {
this.subscriber = new ByteBufferStoringSubscriber(Long.MAX_VALUE);
this.publisher = new InputStreamConsumingPublisher();
}
@Test
public void subscribeAfterWrite_completes() throws InterruptedException {
EXECUTOR.submit(() -> publisher.doBlockingWrite(streamOfLength(0)));
Thread.sleep(200);
publisher.subscribe(subscriber);
assertThat(subscriber.transferTo(ByteBuffer.allocate(0))).isEqualTo(END_OF_STREAM);
}
@Test
public void zeroKb_completes() {
publisher.subscribe(subscriber);
assertThat(publisher.doBlockingWrite(streamOfLength(0))).isEqualTo(0);
assertThat(subscriber.transferTo(ByteBuffer.allocate(0))).isEqualTo(END_OF_STREAM);
}
@Test
public void oneKb_writesAndCompletes() {
publisher.subscribe(subscriber);
assertThat(publisher.doBlockingWrite(streamOfLength(1024))).isEqualTo(1024);
assertThat(subscriber.transferTo(ByteBuffer.allocate(1023))).isEqualTo(SUCCESS);
assertThat(subscriber.transferTo(ByteBuffer.allocate(1))).isEqualTo(END_OF_STREAM);
}
@Test
public void bytesAreDeliveredInOrder() {
publisher.subscribe(subscriber);
assertThat(publisher.doBlockingWrite(streamWithAllBytesInOrder())).isEqualTo(256);
ByteBuffer output = ByteBuffer.allocate(256);
assertThat(subscriber.transferTo(output)).isEqualTo(END_OF_STREAM);
output.flip();
for (int i = 0; i < 256; i++) {
assertThat(output.get()).isEqualTo((byte) i);
}
}
@Test
public void failedRead_signalsOnError() {
publisher.subscribe(subscriber);
assertThatThrownBy(() -> publisher.doBlockingWrite(streamWithFailedReadAfterLength(1024)))
.isInstanceOf(UncheckedIOException.class);
}
@Test
public void cancel_signalsOnError() {
publisher.subscribe(subscriber);
publisher.cancel();
assertThatThrownBy(() -> subscriber.transferTo(ByteBuffer.allocate(0))).isInstanceOf(CancellationException.class);
}
@Test
public void cancel_stopsRunningWrites() {
publisher.subscribe(subscriber);
Future<?> write = EXECUTOR.submit(() -> publisher.doBlockingWrite(streamOfLength(Integer.MAX_VALUE)));
publisher.cancel();
assertThatThrownBy(write::get).hasRootCauseInstanceOf(CancellationException.class);
}
@Test
public void cancel_beforeWrite_stopsWrite() {
publisher.subscribe(subscriber);
publisher.cancel();
assertThatThrownBy(() -> publisher.doBlockingWrite(streamOfLength(Integer.MAX_VALUE)))
.hasRootCauseInstanceOf(CancellationException.class);
}
@Test
public void cancel_beforeSubscribe_stopsWrite() {
publisher.cancel();
publisher.subscribe(subscriber);
assertThatThrownBy(() -> publisher.doBlockingWrite(streamOfLength(Integer.MAX_VALUE)))
.hasRootCauseInstanceOf(CancellationException.class);
}
public InputStream streamOfLength(int length) {
return new InputStream() {
int i = 0;
@Override
public int read() throws IOException {
if (i >= length) {
return -1;
}
++i;
return 1;
}
};
}
public InputStream streamWithAllBytesInOrder() {
return new InputStream() {
int i = 0;
@Override
public int read() throws IOException {
if (i > 255) {
return -1;
}
return i++;
}
};
}
public InputStream streamWithFailedReadAfterLength(int length) {
return new InputStream() {
int i = 0;
@Override
public int read() throws IOException {
if (i > length) {
throw new IOException("Failed to read!");
}
++i;
return 1;
}
};
}
} | 2,957 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/FlatteningSubscriberTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import static java.time.temporal.ChronoUnit.SECONDS;
import static org.mockito.Mockito.times;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
public class FlatteningSubscriberTest {
private Subscriber<String> mockDelegate;
private Subscription mockUpstream;
private FlatteningSubscriber<String> flatteningSubscriber;
@BeforeEach
@SuppressWarnings("unchecked")
public void setup() {
mockDelegate = Mockito.mock(Subscriber.class);
mockUpstream = Mockito.mock(Subscription.class);
flatteningSubscriber = new FlatteningSubscriber<>(mockDelegate);
}
@Test
public void requestOne() {
flatteningSubscriber.onSubscribe(mockUpstream);
Subscription downstream = getDownstreamFromDelegate();
downstream.request(1);
Mockito.verify(mockUpstream).request(1);
flatteningSubscriber.onNext(Arrays.asList("foo", "bar"));
Mockito.verify(mockDelegate).onNext("foo");
Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate);
}
@Test
public void requestTwo() {
flatteningSubscriber.onSubscribe(mockUpstream);
Subscription downstream = getDownstreamFromDelegate();
downstream.request(2);
Mockito.verify(mockUpstream).request(1);
flatteningSubscriber.onNext(Arrays.asList("foo", "bar"));
Mockito.verify(mockDelegate).onNext("foo");
Mockito.verify(mockDelegate).onNext("bar");
Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate);
}
@Test
public void requestThree() {
flatteningSubscriber.onSubscribe(mockUpstream);
Subscription downstream = getDownstreamFromDelegate();
downstream.request(3);
Mockito.verify(mockUpstream, times(1)).request(1);
Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate);
Mockito.reset(mockUpstream, mockDelegate);
flatteningSubscriber.onNext(Arrays.asList("foo", "bar"));
Mockito.verify(mockDelegate).onNext("foo");
Mockito.verify(mockDelegate).onNext("bar");
Mockito.verify(mockUpstream).request(1);
Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate);
Mockito.reset(mockUpstream, mockDelegate);
flatteningSubscriber.onNext(Arrays.asList("baz"));
Mockito.verify(mockDelegate).onNext("baz");
Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate);
}
@Test
public void requestInfinite() {
flatteningSubscriber.onSubscribe(mockUpstream);
Subscription downstream = getDownstreamFromDelegate();
downstream.request(1);
downstream.request(Long.MAX_VALUE);
downstream.request(Long.MAX_VALUE);
downstream.request(Long.MAX_VALUE);
downstream.request(Long.MAX_VALUE);
Mockito.verify(mockUpstream, times(1)).request(1);
flatteningSubscriber.onNext(Arrays.asList("foo", "bar"));
flatteningSubscriber.onComplete();
Mockito.verify(mockDelegate).onNext("foo");
Mockito.verify(mockDelegate).onNext("bar");
Mockito.verify(mockDelegate).onComplete();
Mockito.verifyNoMoreInteractions(mockDelegate);
}
@Test
public void onCompleteDelayedUntilAllDataDelivered() {
flatteningSubscriber.onSubscribe(mockUpstream);
Subscription downstream = getDownstreamFromDelegate();
downstream.request(1);
Mockito.verify(mockUpstream).request(1);
flatteningSubscriber.onNext(Arrays.asList("foo", "bar"));
flatteningSubscriber.onComplete();
Mockito.verify(mockDelegate).onNext("foo");
Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate);
Mockito.reset(mockUpstream, mockDelegate);
downstream.request(1);
Mockito.verify(mockDelegate).onNext("bar");
Mockito.verify(mockDelegate).onComplete();
Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate);
}
@Test
public void onErrorDropsBufferedData() {
Throwable t = new Throwable();
flatteningSubscriber.onSubscribe(mockUpstream);
Subscription downstream = getDownstreamFromDelegate();
downstream.request(1);
Mockito.verify(mockUpstream).request(1);
flatteningSubscriber.onNext(Arrays.asList("foo", "bar"));
flatteningSubscriber.onError(t);
Mockito.verify(mockDelegate).onNext("foo");
Mockito.verify(mockDelegate).onError(t);
Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate);
}
@Test
public void requestsFromDownstreamDoNothingAfterOnComplete() {
flatteningSubscriber.onSubscribe(mockUpstream);
Subscription downstream = getDownstreamFromDelegate();
downstream.request(1);
Mockito.verify(mockUpstream).request(1);
flatteningSubscriber.onComplete();
Mockito.verify(mockDelegate).onComplete();
Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate);
downstream.request(1);
Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate);
}
@Test
public void requestsFromDownstreamDoNothingAfterOnError() {
Throwable t = new Throwable();
flatteningSubscriber.onSubscribe(mockUpstream);
Subscription downstream = getDownstreamFromDelegate();
downstream.request(1);
Mockito.verify(mockUpstream).request(1);
flatteningSubscriber.onError(t);
Mockito.verify(mockDelegate).onError(t);
Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate);
downstream.request(1);
Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate);
}
@Test
public void stochastic_dataFlushedBeforeOnComplete() {
ExecutorService exec = Executors.newSingleThreadExecutor();
Instant end = Instant.now().plus(10, SECONDS);
try {
while (Instant.now().isBefore(end)) {
Publisher<List<String>> iterablePublisher = subscriber -> subscriber.onSubscribe(new Subscription() {
@Override
public void request(long l) {
exec.submit(() -> {
subscriber.onNext(Collections.singletonList("data"));
subscriber.onComplete();
});
}
@Override
public void cancel() {
}
});
AtomicInteger seen = new AtomicInteger(0);
CompletableFuture<Void> finished = new CompletableFuture<>();
FlatteningSubscriber<String> elementSubscriber = new FlatteningSubscriber<>(new Subscriber<String>() {
@Override
public void onSubscribe(Subscription subscription) {
subscription.request(1);
}
@Override
public void onNext(String s) {
seen.incrementAndGet();
}
@Override
public void onError(Throwable e) {
finished.completeExceptionally(e);
}
@Override
public void onComplete() {
if (seen.get() != 1) {
finished.completeExceptionally(
new RuntimeException("Should have gotten 1 element before onComplete"));
} else {
finished.complete(null);
}
}
});
iterablePublisher.subscribe(elementSubscriber);
finished.join();
}
} finally {
exec.shutdown();
}
}
private Subscription getDownstreamFromDelegate() {
ArgumentCaptor<Subscription> subscriptionCaptor = ArgumentCaptor.forClass(Subscription.class);
Mockito.verify(mockDelegate).onSubscribe(subscriptionCaptor.capture());
return subscriptionCaptor.getValue();
}
}
| 2,958 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/ByteBufferStoringSubscriberTckTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import java.nio.ByteBuffer;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.reactivestreams.tck.SubscriberWhiteboxVerification;
import org.reactivestreams.tck.TestEnvironment;
public class ByteBufferStoringSubscriberTckTest extends SubscriberWhiteboxVerification<ByteBuffer> {
protected ByteBufferStoringSubscriberTckTest() {
super(new TestEnvironment());
}
@Override
public Subscriber<ByteBuffer> createSubscriber(WhiteboxSubscriberProbe<ByteBuffer> probe) {
return new ByteBufferStoringSubscriber(16) {
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
probe.registerOnError(throwable);
}
@Override
public void onSubscribe(Subscription subscription) {
super.onSubscribe(subscription);
probe.registerOnSubscribe(new SubscriberPuppet() {
@Override
public void triggerRequest(long elements) {
subscription.request(elements);
}
@Override
public void signalCancel() {
subscription.cancel();
}
});
}
@Override
public void onNext(ByteBuffer next) {
super.onNext(next);
probe.registerOnNext(next);
}
@Override
public void onComplete() {
super.onComplete();
probe.registerOnComplete();
}
};
}
@Override
public ByteBuffer createElement(int element) {
return ByteBuffer.wrap(new byte[0]);
}
} | 2,959 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/SimplePublisherTckTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
import org.reactivestreams.tck.TestEnvironment;
public class SimplePublisherTckTest extends PublisherVerification<Integer> {
public SimplePublisherTckTest() {
super(new TestEnvironment());
}
@Override
public Publisher<Integer> createPublisher(long elements) {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
for (int i = 0; i < elements; i++) {
publisher.send(i);
}
publisher.complete();
return publisher;
}
@Override
public Publisher<Integer> createFailedPublisher() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
publisher.error(new RuntimeException());
return publisher;
}
@Override
public long maxElementsFromPublisher() {
return 256L;
}
} | 2,960 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/AddingTrailingDataSubscriberTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Subscriber;
public class AddingTrailingDataSubscriberTest {
@Test
void trailingDataSupplierNull_shouldThrowException() {
SequentialSubscriber<Integer> downstreamSubscriber = new SequentialSubscriber<Integer>(i -> {}, new CompletableFuture());
assertThatThrownBy(() -> new AddingTrailingDataSubscriber<>(downstreamSubscriber, null))
.hasMessageContaining("must not be null");
}
@Test
void subscriberNull_shouldThrowException() {
assertThatThrownBy(() -> new AddingTrailingDataSubscriber<>(null, () -> Arrays.asList(1, 2)))
.hasMessageContaining("must not be null");
}
@Test
void trailingDataHasItems_shouldSendAdditionalData() {
List<Integer> result = new ArrayList<>();
CompletableFuture future = new CompletableFuture();
SequentialSubscriber<Integer> downstreamSubscriber = new SequentialSubscriber<Integer>(i -> result.add(i), future);
Subscriber<Integer> subscriber = new AddingTrailingDataSubscriber<>(downstreamSubscriber,
() -> Arrays.asList(Integer.MAX_VALUE,
Integer.MIN_VALUE));
publishData(subscriber);
future.join();
assertThat(result).containsExactly(0, 1, 2, Integer.MAX_VALUE, Integer.MIN_VALUE);
}
@Test
void trailingDataEmpty_shouldNotSendAdditionalData() {
List<Integer> result = new ArrayList<>();
CompletableFuture future = new CompletableFuture();
SequentialSubscriber<Integer> downstreamSubscriber = new SequentialSubscriber<Integer>(i -> result.add(i), future);
Subscriber<Integer> subscriber = new AddingTrailingDataSubscriber<>(downstreamSubscriber, () -> new ArrayList<>());
publishData(subscriber);
future.join();
assertThat(result).containsExactly(0, 1, 2);
}
@Test
void trailingDataNull_shouldCompleteNormally() {
List<Integer> result = new ArrayList<>();
CompletableFuture future = new CompletableFuture();
SequentialSubscriber<Integer> downstreamSubscriber = new SequentialSubscriber<Integer>(i -> result.add(i), future);
Subscriber<Integer> subscriber = new AddingTrailingDataSubscriber<>(downstreamSubscriber, () -> null);
publishData(subscriber);
future.join();
assertThat(result).containsExactly(0, 1, 2);
}
private void publishData(Subscriber<Integer> subscriber) {
SimplePublisher<Integer> simplePublisher = new SimplePublisher<>();
simplePublisher.subscribe(subscriber);
for (int i = 0; i < 3; i++) {
simplePublisher.send(i);
}
simplePublisher.complete();
}
}
| 2,961 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/OutputStreamPublisherTckTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
import org.reactivestreams.tck.TestEnvironment;
import software.amazon.awssdk.utils.ThreadFactoryBuilder;
public class OutputStreamPublisherTckTest extends PublisherVerification<ByteBuffer> {
private final ExecutorService executor =
Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build());
public OutputStreamPublisherTckTest() {
super(new TestEnvironment());
}
@Override
public Publisher<ByteBuffer> createPublisher(long elements) {
OutputStreamPublisher publisher = new OutputStreamPublisher();
executor.submit(() -> {
for (int i = 0; i < elements; i++) {
publisher.write(new byte[1]);
}
publisher.close();
});
return publisher;
}
@Override
public Publisher<ByteBuffer> createFailedPublisher() {
OutputStreamPublisher publisher = new OutputStreamPublisher();
executor.submit(publisher::cancel);
return publisher;
}
} | 2,962 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/SimplePublisherTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.async.StoringSubscriber.Event;
import software.amazon.awssdk.utils.async.StoringSubscriber.EventType;
public class SimplePublisherTest {
/**
* This class has tests that try to break things for a fixed period of time, and then make sure nothing broke.
* This flag controls how long those tests run. Longer values provider a better guarantee of catching an issue, but
* increase the build time. 5 seconds seems okay for now, but if a flaky test is found try increasing the duration to make
* it reproduce more reliably.
*/
private static final Duration STOCHASTIC_TEST_DURATION = Duration.ofSeconds(5);
@Test
public void immediateSuccessWorks() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(1);
publisher.subscribe(subscriber);
publisher.complete();
assertThat(subscriber.poll().get().type()).isEqualTo(EventType.ON_COMPLETE);
assertThat(subscriber.poll()).isNotPresent();
}
@Test
public void immediateFailureWorks() {
RuntimeException error = new RuntimeException();
SimplePublisher<Integer> publisher = new SimplePublisher<>();
StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(1);
publisher.subscribe(subscriber);
publisher.error(error);
assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_ERROR);
assertThat(subscriber.peek().get().runtimeError()).isEqualTo(error);
subscriber.poll();
assertThat(subscriber.poll()).isNotPresent();
}
@Test
public void writeAfterCompleteFails() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
publisher.subscribe(new StoringSubscriber<>(1));
publisher.complete();
assertThat(publisher.send(5)).isCompletedExceptionally();
}
@Test
public void writeAfterErrorFails() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
publisher.subscribe(new StoringSubscriber<>(1));
publisher.error(new Throwable());
assertThat(publisher.send(5)).isCompletedExceptionally();
}
@Test
public void completeAfterCompleteFails() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
publisher.subscribe(new StoringSubscriber<>(1));
publisher.complete();
assertThat(publisher.complete()).isCompletedExceptionally();
}
@Test
public void completeAfterErrorFails() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
publisher.subscribe(new StoringSubscriber<>(1));
publisher.error(new Throwable());
assertThat(publisher.complete()).isCompletedExceptionally();
}
@Test
public void errorAfterCompleteFails() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
publisher.subscribe(new StoringSubscriber<>(1));
publisher.complete();
assertThat(publisher.error(new Throwable())).isCompletedExceptionally();
}
@Test
public void errorAfterErrorFails() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
publisher.subscribe(new StoringSubscriber<>(1));
publisher.error(new Throwable());
assertThat(publisher.error(new Throwable())).isCompletedExceptionally();
}
@Test
public void oneDemandWorks() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(1);
publisher.subscribe(subscriber);
publisher.send(1);
publisher.send(2);
publisher.complete();
assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_NEXT);
assertThat(subscriber.peek().get().value()).isEqualTo(1);
subscriber.poll();
assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_NEXT);
assertThat(subscriber.peek().get().value()).isEqualTo(2);
subscriber.poll();
assertThat(subscriber.poll().get().type()).isEqualTo(EventType.ON_COMPLETE);
assertThat(subscriber.poll()).isNotPresent();
}
@Test
public void highDemandWorks() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>();
publisher.subscribe(subscriber);
subscriber.subscription.request(Long.MAX_VALUE);
publisher.send(1);
subscriber.subscription.request(Long.MAX_VALUE);
publisher.send(2);
subscriber.subscription.request(Long.MAX_VALUE);
publisher.complete();
subscriber.subscription.request(Long.MAX_VALUE);
assertThat(subscriber.eventQueue.peek().get().type()).isEqualTo(EventType.ON_NEXT);
assertThat(subscriber.eventQueue.peek().get().value()).isEqualTo(1);
subscriber.eventQueue.poll();
assertThat(subscriber.eventQueue.peek().get().type()).isEqualTo(EventType.ON_NEXT);
assertThat(subscriber.eventQueue.peek().get().value()).isEqualTo(2);
subscriber.eventQueue.poll();
assertThat(subscriber.eventQueue.peek().get().type()).isEqualTo(EventType.ON_COMPLETE);
subscriber.eventQueue.poll();
assertThat(subscriber.eventQueue.poll()).isNotPresent();
}
@Test
public void writeFuturesDoNotCompleteUntilAfterOnNext() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>();
publisher.subscribe(subscriber);
CompletableFuture<Void> writeFuture = publisher.send(5);
assertThat(subscriber.eventQueue.peek()).isNotPresent();
assertThat(writeFuture).isNotCompleted();
subscriber.subscription.request(1);
assertThat(subscriber.eventQueue.peek().get().type()).isEqualTo(EventType.ON_NEXT);
assertThat(subscriber.eventQueue.peek().get().value()).isEqualTo(5);
assertThat(writeFuture).isCompletedWithValue(null);
}
@Test
public void completeFuturesDoNotCompleteUntilAfterOnComplete() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>();
publisher.subscribe(subscriber);
publisher.send(5);
CompletableFuture<Void> completeFuture = publisher.complete();
assertThat(subscriber.eventQueue.peek()).isNotPresent();
assertThat(completeFuture).isNotCompleted();
subscriber.subscription.request(1);
subscriber.eventQueue.poll(); // Drop the 5 value
assertThat(subscriber.eventQueue.peek().get().type()).isEqualTo(EventType.ON_COMPLETE);
assertThat(completeFuture).isCompletedWithValue(null);
}
@Test
public void errorFuturesDoNotCompleteUntilAfterOnError() {
RuntimeException error = new RuntimeException();
SimplePublisher<Integer> publisher = new SimplePublisher<>();
ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>();
publisher.subscribe(subscriber);
publisher.send(5);
CompletableFuture<Void> errorFuture = publisher.error(error);
assertThat(subscriber.eventQueue.peek()).isNotPresent();
assertThat(errorFuture).isNotCompleted();
subscriber.subscription.request(1);
subscriber.eventQueue.poll(); // Drop the 5 value
assertThat(subscriber.eventQueue.peek().get().type()).isEqualTo(EventType.ON_ERROR);
assertThat(subscriber.eventQueue.peek().get().runtimeError()).isEqualTo(error);
assertThat(errorFuture).isCompletedWithValue(null);
}
@Test
public void completeBeforeSubscribeIsDeliveredOnSubscribe() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(Integer.MAX_VALUE);
publisher.complete();
publisher.subscribe(subscriber);
assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_COMPLETE);
}
@Test
public void errorBeforeSubscribeIsDeliveredOnSubscribe() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(Integer.MAX_VALUE);
RuntimeException error = new RuntimeException();
publisher.error(error);
publisher.subscribe(subscriber);
assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_ERROR);
assertThat(subscriber.peek().get().runtimeError()).isEqualTo(error);
}
@Test
public void writeBeforeSubscribeIsDeliveredOnSubscribe() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(Integer.MAX_VALUE);
publisher.send(5);
publisher.subscribe(subscriber);
assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_NEXT);
assertThat(subscriber.peek().get().value()).isEqualTo(5);
}
@Test
public void cancelFailsAnyInFlightFutures() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>();
publisher.subscribe(subscriber);
CompletableFuture<Void> writeFuture = publisher.send(5);
CompletableFuture<Void> completeFuture = publisher.complete();
subscriber.subscription.cancel();
assertThat(writeFuture).isCompletedExceptionally();
assertThat(completeFuture).isCompletedExceptionally();
}
@Test
public void newCallsAfterCancelFail() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>();
publisher.subscribe(subscriber);
subscriber.subscription.cancel();
assertThat(publisher.send(5)).isCompletedExceptionally();
assertThat(publisher.complete()).isCompletedExceptionally();
assertThat(publisher.error(new Throwable())).isCompletedExceptionally();
}
@Test
public void negativeDemandSkipsOutstandingMessages() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>();
publisher.subscribe(subscriber);
CompletableFuture<Void> sendFuture = publisher.send(0);
CompletableFuture<Void> completeFuture = publisher.complete();
subscriber.subscription.request(-1);
assertThat(sendFuture).isCompletedExceptionally();
assertThat(completeFuture).isCompletedExceptionally();
assertThat(subscriber.eventQueue.poll().get().type()).isEqualTo(EventType.ON_ERROR);
}
@Test
public void evilDownstreamPublisherThrowingInOnNextStillCancelsInFlightFutures() {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>();
subscriber.failureInOnNext = new RuntimeException();
CompletableFuture<Void> writeFuture = publisher.send(5);
CompletableFuture<Void> completeFuture = publisher.complete();
publisher.subscribe(subscriber);
subscriber.subscription.request(1);
assertThat(writeFuture).isCompletedExceptionally();
assertThat(completeFuture).isCompletedExceptionally();
}
@Test
public void stochastic_onNext_singleProducerSeemsThreadSafe() throws Exception {
// Single-producer is interesting because we can validate the ordering of messages, unlike with multi-producer.
seemsThreadSafeWithProducerCount(1);
}
@Test
public void stochastic_onNext_multiProducerSeemsThreadSafe() throws Exception {
seemsThreadSafeWithProducerCount(3);
}
@Test
public void stochastic_completeAndError_seemThreadSafe() throws Exception {
assertTimeoutPreemptively(STOCHASTIC_TEST_DURATION.plusSeconds(5), () -> {
Instant start = Instant.now();
Instant end = start.plus(STOCHASTIC_TEST_DURATION);
ExecutorService executor = Executors.newCachedThreadPool();
while (end.isAfter(Instant.now())) {
SimplePublisher<Integer> publisher = new SimplePublisher<>();
ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>();
publisher.subscribe(subscriber);
subscriber.subscription.request(1);
AtomicBoolean scenarioStart = new AtomicBoolean(false);
CountDownLatch allAreWaiting = new CountDownLatch(3);
Runnable waitForStart = () -> {
allAreWaiting.countDown();
while (!scenarioStart.get()) {
Thread.yield();
}
};
Future<?> writeCall = executor.submit(() -> {
waitForStart.run();
publisher.send(0).join();
});
Future<?> completeCall = executor.submit(() -> {
waitForStart.run();
publisher.complete().join();
});
Future<?> errorCall = executor.submit(() -> {
Throwable t = new Throwable();
waitForStart.run();
publisher.error(t).join();
});
allAreWaiting.await();
scenarioStart.set(true);
List<Pair<String, Throwable>> failures = new ArrayList<>();
addIfFailed(failures, "write", writeCall);
boolean writeSucceeded = failures.isEmpty();
addIfFailed(failures, "complete", completeCall);
addIfFailed(failures, "error", errorCall);
int expectedFailures = writeSucceeded ? 1 : 2;
assertThat(failures).hasSize(expectedFailures);
}
});
}
private void addIfFailed(List<Pair<String, Throwable>> failures, String callName, Future<?> call) {
try {
call.get();
} catch (Throwable t) {
failures.add(Pair.of(callName, t));
}
}
private void seemsThreadSafeWithProducerCount(int producerCount) {
assertTimeoutPreemptively(STOCHASTIC_TEST_DURATION.plusSeconds(5), () -> {
AtomicBoolean runProducers = new AtomicBoolean(true);
AtomicBoolean runConsumers = new AtomicBoolean(true);
AtomicInteger completesReceived = new AtomicInteger(0);
AtomicLong messageSendCount = new AtomicLong(0);
AtomicLong messageReceiveCount = new AtomicLong(0);
CountDownLatch producersDone = new CountDownLatch(producerCount);
Semaphore productionLimiter = new Semaphore(101);
Semaphore requestLimiter = new Semaphore(57);
ExecutorService executor = Executors.newFixedThreadPool(2 + producerCount);
SimplePublisher<Long> publisher = new SimplePublisher<>();
ControllableSubscriber<Long> subscriber = new ControllableSubscriber<>();
publisher.subscribe(subscriber);
// Producer tasks
CompletableFuture<?> completed = new CompletableFuture<>();
List<Future<?>> producers = new ArrayList<>();
for (int i = 0; i < producerCount; i++) {
producers.add(executor.submit(() -> {
while (runProducers.get()) {
productionLimiter.acquire();
publisher.send(messageSendCount.getAndIncrement());
}
// Complete once all producers are done
producersDone.countDown();
producersDone.await();
publisher.complete().thenRun(() -> completed.complete(null)); // All but one producer sending this will fail.
return null;
}));
}
// Requester Task
Future<?> requester = executor.submit(() -> {
while (runConsumers.get()) {
requestLimiter.acquire();
subscriber.subscription.request(1);
}
return null;
});
// Consumer Task
Future<?> consumer = executor.submit(() -> {
int expectedEvent = 0;
while (runConsumers.get() || subscriber.eventQueue.peek().isPresent()) {
Optional<Event<Long>> event = subscriber.eventQueue.poll();
if (!event.isPresent()) {
continue;
}
// When we only have 1 producer, we can verify the messages are in order.
if (producerCount == 1 && event.get().type() == EventType.ON_NEXT) {
assertThat(event.get().value()).isEqualTo(expectedEvent);
expectedEvent++;
}
if (event.get().type() == EventType.ON_NEXT) {
messageReceiveCount.incrementAndGet();
productionLimiter.release();
requestLimiter.release();
}
if (event.get().type() == EventType.ON_COMPLETE) {
completesReceived.incrementAndGet();
}
}
});
Thread.sleep(STOCHASTIC_TEST_DURATION.toMillis());
// Shut down producers
runProducers.set(false);
productionLimiter.release(producerCount);
for (Future<?> producer : producers) {
producer.get();
}
// Make sure to flush out everything left in the queue.
completed.get();
subscriber.subscription.request(Long.MAX_VALUE);
// Shut down consumers
runConsumers.set(false);
requestLimiter.release();
requester.get();
consumer.get();
assertThat(messageReceiveCount.get()).isEqualTo(messageSendCount.get());
assertThat(completesReceived.get()).isEqualTo(1);
// Make sure we actually tested something
assertThat(messageSendCount.get()).isGreaterThan(10);
});
}
private class ControllableSubscriber<T> implements Subscriber<T> {
private final StoringSubscriber<T> eventQueue = new StoringSubscriber<>(Integer.MAX_VALUE);
private Subscription subscription;
private RuntimeException failureInOnNext;
@Override
public void onSubscribe(Subscription s) {
this.subscription = new ControllableSubscription(s);
// Give the event queue a subscription we just ignore. We are the captain of the subscription!
eventQueue.onSubscribe(new Subscription() {
@Override
public void request(long n) {
}
@Override
public void cancel() {
}
});
}
@Override
public void onNext(T o) {
if (failureInOnNext != null) {
throw failureInOnNext;
}
eventQueue.onNext(o);
}
@Override
public void onError(Throwable t) {
eventQueue.onError(t);
}
@Override
public void onComplete() {
eventQueue.onComplete();
}
private class ControllableSubscription implements Subscription {
private final Subscription delegate;
private ControllableSubscription(Subscription s) {
delegate = s;
}
@Override
public void request(long n) {
delegate.request(n);
}
@Override
public void cancel() {
delegate.cancel();
}
}
}
} | 2,963 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/ByteBufferStoringSubscriberTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.utils.ThreadFactoryBuilder;
import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult;
public class ByteBufferStoringSubscriberTest {
@Test
public void constructorCalled_withNonPositiveSize_throwsException() {
assertThatCode(() -> new ByteBufferStoringSubscriber(1)).doesNotThrowAnyException();
assertThatCode(() -> new ByteBufferStoringSubscriber(Integer.MAX_VALUE)).doesNotThrowAnyException();
assertThatThrownBy(() -> new ByteBufferStoringSubscriber(0)).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new ByteBufferStoringSubscriber(-1)).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new ByteBufferStoringSubscriber(Integer.MIN_VALUE)).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void doesNotRequestMoreThanMaxBytes() {
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(3);
Subscription subscription = mock(Subscription.class);
subscriber.onSubscribe(subscription);
verify(subscription).request(1);
subscriber.onNext(fullByteBufferOfSize(2));
verify(subscription, times(2)).request(1);
subscriber.onNext(fullByteBufferOfSize(0));
verify(subscription, times(3)).request(1);
subscriber.onNext(fullByteBufferOfSize(1));
verifyNoMoreInteractions(subscription);
}
@Test
public void canStoreMoreThanMaxBytesButWontAskForMoreUntilBelowMax() {
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(3);
Subscription subscription = mock(Subscription.class);
subscriber.onSubscribe(subscription);
verify(subscription).request(1);
subscriber.onNext(fullByteBufferOfSize(1)); // After: Storing 1
verify(subscription, times(2)).request(1); // It should request more
subscriber.onNext(fullByteBufferOfSize(50)); // After: Storing 51
subscriber.transferTo(emptyByteBufferOfSize(48)); // After: Storing 3
verifyNoMoreInteractions(subscription); // It should NOT request more
subscriber.transferTo(emptyByteBufferOfSize(1)); // After: Storing 2
verify(subscription, times(3)).request(1); // It should request more
}
@Test
@Timeout(10)
public void blockingTransfer_waitsForFullOutputBuffer() throws InterruptedException, ExecutionException {
int outputBufferSize = 256;
ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build());
try {
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(1);
Subscription subscription = mock(Subscription.class);
AtomicInteger bufferNumber = new AtomicInteger(0);
doAnswer(i -> {
int bufferN = bufferNumber.getAndIncrement();
for (long j = 0; j < i.<Long>getArgument(0); j++) {
if (bufferN <= outputBufferSize + 1) {
subscriber.onNext(byteBufferWithContent(bufferN));
}
}
return null;
}).when(subscription).request(anyLong());
subscriber.onSubscribe(subscription);
Future<ByteBuffer> blockingRead = executor.submit(() -> {
ByteBuffer out = ByteBuffer.allocate(outputBufferSize);
TransferResult transferResult = subscriber.blockingTransferTo(out);
assertThat(transferResult).isEqualTo(TransferResult.SUCCESS);
return out;
});
ByteBuffer output = blockingRead.get();
output.flip();
for (int i = 0; i < outputBufferSize; i++) {
assertThat(output.get()).isEqualTo((byte) i);
}
} finally {
executor.shutdownNow();
}
}
@Test
@Timeout(10)
public void blockingTransfer_stopsOnComplete() throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build());
try {
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(Long.MAX_VALUE);
subscriber.onSubscribe(mock(Subscription.class));
Future<ByteBuffer> blockingRead = executor.submit(() -> {
ByteBuffer out = ByteBuffer.allocate(1024);
TransferResult transferResult = subscriber.blockingTransferTo(out);
assertThat(transferResult).isEqualTo(TransferResult.END_OF_STREAM);
return out;
});
ByteBuffer input = fullByteBufferOfSize(1);
subscriber.onNext(input);
subscriber.onComplete();
ByteBuffer output = blockingRead.get();
output.flip();
assertThat(output.get()).isEqualTo(input.get());
} finally {
executor.shutdownNow();
}
}
@Test
@Timeout(10)
public void blockingTransfer_stopsOnError() throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build());
try {
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(Long.MAX_VALUE);
subscriber.onSubscribe(mock(Subscription.class));
Future<?> blockingRead = executor.submit(() -> {
subscriber.blockingTransferTo(ByteBuffer.allocate(1024)); // Expected to throw
return null;
});
ByteBuffer input = fullByteBufferOfSize(1);
IllegalStateException exception = new IllegalStateException();
subscriber.onNext(input);
subscriber.onError(exception);
assertThatThrownBy(blockingRead::get).hasRootCause(exception);
} finally {
executor.shutdownNow();
}
}
@Test
@Timeout(10)
public void blockingTransfer_stopsOnInterrupt() throws InterruptedException {
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(Long.MAX_VALUE);
AtomicBoolean threadIsInterruptedInCatch = new AtomicBoolean(false);
AtomicReference<Throwable> failureReason = new AtomicReference<>();
subscriber.onSubscribe(mock(Subscription.class));
CountDownLatch threadIsRunning = new CountDownLatch(1);
Thread thread = new Thread(() -> {
try {
threadIsRunning.countDown();
subscriber.blockingTransferTo(ByteBuffer.allocate(1024));
} catch (Throwable t) {
threadIsInterruptedInCatch.set(Thread.currentThread().isInterrupted());
failureReason.set(t);
}
});
thread.setDaemon(true);
thread.start();
threadIsRunning.await();
thread.interrupt();
thread.join();
assertThat(threadIsInterruptedInCatch).isTrue();
assertThat(failureReason.get()).hasRootCauseInstanceOf(InterruptedException.class);
}
@Test
@Timeout(10)
public void blockingTransfer_returnsEndOfStreamWithRepeatedCalls() {
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(Long.MAX_VALUE);
subscriber.onSubscribe(mock(Subscription.class));
subscriber.onComplete();
ByteBuffer buffer = ByteBuffer.allocate(0);
assertThat(subscriber.blockingTransferTo(buffer)).isEqualTo(TransferResult.END_OF_STREAM);
assertThat(subscriber.blockingTransferTo(buffer)).isEqualTo(TransferResult.END_OF_STREAM);
assertThat(subscriber.blockingTransferTo(buffer)).isEqualTo(TransferResult.END_OF_STREAM);
}
@Test
public void noDataTransferredIfNoDataBuffered() {
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2);
subscriber.onSubscribe(mock(Subscription.class));
ByteBuffer out = emptyByteBufferOfSize(1);
assertThat(subscriber.transferTo(out)).isEqualTo(TransferResult.SUCCESS);
assertThat(out.remaining()).isEqualTo(1);
}
@Test
public void noDataTransferredIfComplete() {
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2);
subscriber.onSubscribe(mock(Subscription.class));
subscriber.onComplete();
ByteBuffer out = emptyByteBufferOfSize(1);
assertThat(subscriber.transferTo(out)).isEqualTo(TransferResult.END_OF_STREAM);
assertThat(out.remaining()).isEqualTo(1);
}
@Test
public void noDataTransferredIfError() {
RuntimeException error = new RuntimeException();
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2);
subscriber.onSubscribe(mock(Subscription.class));
subscriber.onError(error);
ByteBuffer out = emptyByteBufferOfSize(1);
assertThatThrownBy(() -> subscriber.transferTo(out)).isEqualTo(error);
assertThat(out.remaining()).isEqualTo(1);
}
@Test
public void checkedExceptionsAreWrapped() {
Exception error = new Exception();
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2);
subscriber.onSubscribe(mock(Subscription.class));
subscriber.onError(error);
ByteBuffer out = emptyByteBufferOfSize(1);
assertThatThrownBy(() -> subscriber.transferTo(out)).hasCause(error);
assertThat(out.remaining()).isEqualTo(1);
}
@Test
public void completeIsReportedEvenWithExactOutSize() {
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2);
subscriber.onSubscribe(mock(Subscription.class));
subscriber.onNext(fullByteBufferOfSize(2));
subscriber.onComplete();
ByteBuffer out = emptyByteBufferOfSize(2);
assertThat(subscriber.transferTo(out)).isEqualTo(TransferResult.END_OF_STREAM);
assertThat(out.remaining()).isEqualTo(0);
}
@Test
public void completeIsReportedEvenWithExtraOutSize() {
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2);
subscriber.onSubscribe(mock(Subscription.class));
subscriber.onNext(fullByteBufferOfSize(2));
subscriber.onComplete();
ByteBuffer out = emptyByteBufferOfSize(3);
assertThat(subscriber.transferTo(out)).isEqualTo(TransferResult.END_OF_STREAM);
assertThat(out.remaining()).isEqualTo(1);
}
@Test
public void errorIsReportedEvenWithExactOutSize() {
RuntimeException error = new RuntimeException();
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2);
subscriber.onSubscribe(mock(Subscription.class));
subscriber.onNext(fullByteBufferOfSize(2));
subscriber.onError(error);
ByteBuffer out = emptyByteBufferOfSize(2);
assertThatThrownBy(() -> subscriber.transferTo(out)).isEqualTo(error);
assertThat(out.remaining()).isEqualTo(0);
}
@Test
public void errorIsReportedEvenWithExtraOutSize() {
RuntimeException error = new RuntimeException();
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2);
subscriber.onSubscribe(mock(Subscription.class));
subscriber.onNext(fullByteBufferOfSize(2));
subscriber.onError(error);
ByteBuffer out = emptyByteBufferOfSize(3);
assertThatThrownBy(() -> subscriber.transferTo(out)).isEqualTo(error);
assertThat(out.remaining()).isEqualTo(1);
}
@Test
public void dataIsDeliveredInTheRightOrder() {
ByteBuffer buffer1 = fullByteBufferOfSize(1);
ByteBuffer buffer2 = fullByteBufferOfSize(1);
ByteBuffer buffer3 = fullByteBufferOfSize(1);
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(3);
subscriber.onSubscribe(mock(Subscription.class));
subscriber.onNext(buffer1);
subscriber.onNext(buffer2);
subscriber.onNext(buffer3);
subscriber.onComplete();
ByteBuffer out = emptyByteBufferOfSize(4);
subscriber.transferTo(out);
out.flip();
assertThat(out.get()).isEqualTo(buffer1.get());
assertThat(out.get()).isEqualTo(buffer2.get());
assertThat(out.get()).isEqualTo(buffer3.get());
assertThat(out.hasRemaining()).isFalse();
}
@Test
@Timeout(30)
public void stochastic_subscriberSeemsThreadSafe() throws Throwable {
ExecutorService producer = Executors.newFixedThreadPool(1);
ExecutorService consumer = Executors.newFixedThreadPool(1);
try {
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(50);
AtomicBoolean testRunning = new AtomicBoolean(true);
AtomicInteger messageNumber = new AtomicInteger(0);
AtomicReference<Throwable> producerFailure = new AtomicReference<>();
Subscription subscription = new Subscription() {
@Override
public void request(long n) {
producer.submit(() -> {
try {
for (int i = 0; i < n; i++) {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putInt(messageNumber.getAndIncrement());
buffer.flip();
subscriber.onNext(buffer);
}
} catch (Throwable t) {
producerFailure.set(t);
}
});
}
@Override
public void cancel() {
producerFailure.set(new AssertionError("Cancel not expected."));
}
};
subscriber.onSubscribe(subscription);
Future<Object> consumerFuture = consumer.submit(() -> {
ByteBuffer carryOver = ByteBuffer.allocate(4);
int expectedMessageNumber = 0;
while (testRunning.get()) {
Thread.sleep(1);
ByteBuffer out = ByteBuffer.allocate(4 + expectedMessageNumber);
subscriber.transferTo(out);
out.flip();
if (carryOver.position() > 0) {
int oldOutLimit = out.limit();
out.limit(carryOver.remaining());
carryOver.put(out);
out.limit(oldOutLimit);
carryOver.flip();
assertThat(carryOver.getInt()).isEqualTo(expectedMessageNumber);
++expectedMessageNumber;
carryOver.clear();
}
while (out.remaining() >= 4) {
assertThat(out.getInt()).isEqualTo(expectedMessageNumber);
++expectedMessageNumber;
}
if (out.hasRemaining()) {
carryOver.put(out);
}
}
return null;
});
Thread.sleep(5_000);
testRunning.set(false);
consumerFuture.get();
if (producerFailure.get() != null) {
throw producerFailure.get();
}
assertThat(messageNumber.get()).isGreaterThan(10); // ensure we actually tested something
} finally {
producer.shutdownNow();
consumer.shutdownNow();
}
}
@Test
@Timeout(30)
public void stochastic_blockingTransferSeemsThreadSafe() throws Throwable {
ExecutorService producer = Executors.newFixedThreadPool(1);
ExecutorService consumer = Executors.newFixedThreadPool(1);
try {
ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(50);
AtomicBoolean testRunning = new AtomicBoolean(true);
AtomicInteger messageNumber = new AtomicInteger(0);
AtomicReference<Throwable> producerFailure = new AtomicReference<>();
Subscription subscription = new Subscription() {
@Override
public void request(long n) {
producer.submit(() -> {
if (!testRunning.get()) {
return;
}
try {
for (int i = 0; i < n; i++) {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putInt(messageNumber.getAndIncrement());
buffer.flip();
subscriber.onNext(buffer);
}
} catch (Throwable t) {
producerFailure.set(t);
}
});
}
@Override
public void cancel() {
producerFailure.set(new AssertionError("Cancel not expected."));
}
};
subscriber.onSubscribe(subscription);
Future<Object> consumerFuture = consumer.submit(() -> {
int expectedMessageNumber = 0;
while (testRunning.get()) {
ByteBuffer out = ByteBuffer.allocate(12); // 4 integers at a time seems good
subscriber.blockingTransferTo(out);
out.flip();
while (out.hasRemaining()) {
assertThat(out.getInt()).isEqualTo(expectedMessageNumber);
++expectedMessageNumber;
}
}
return null;
});
Thread.sleep(5_000);
testRunning.set(false);
producer.submit(subscriber::onComplete);
consumerFuture.get();
if (producerFailure.get() != null) {
throw producerFailure.get();
}
assertThat(messageNumber.get()).isGreaterThan(10); // ensure we actually tested something
} finally {
producer.shutdownNow();
consumer.shutdownNow();
}
}
private ByteBuffer fullByteBufferOfSize(int size) {
byte[] data = new byte[size];
ThreadLocalRandom.current().nextBytes(data);
return ByteBuffer.wrap(data);
}
private ByteBuffer byteBufferWithContent(int b) {
return ByteBuffer.wrap(new byte[] { (byte) b });
}
private ByteBuffer emptyByteBufferOfSize(int size) {
return ByteBuffer.allocate(size);
}
} | 2,964 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/InputStreamConsumingPublisherTckTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
import org.reactivestreams.tck.TestEnvironment;
import software.amazon.awssdk.utils.ThreadFactoryBuilder;
public class InputStreamConsumingPublisherTckTest extends PublisherVerification<ByteBuffer> {
private final ExecutorService executor =
Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build());
public InputStreamConsumingPublisherTckTest() {
super(new TestEnvironment());
}
@Override
public Publisher<ByteBuffer> createPublisher(long elements) {
InputStreamConsumingPublisher publisher = new InputStreamConsumingPublisher();
executor.submit(() -> {
publisher.doBlockingWrite(new InputStream() {
int i = 0;
@Override
public int read() throws IOException {
throw new IOException();
}
@Override
public int read(byte[] b) throws IOException {
if (i >= elements) {
return -1;
}
++i;
assert b.length > 0;
return 1;
}
});
});
return publisher;
}
@Override
public Publisher<ByteBuffer> createFailedPublisher() {
InputStreamConsumingPublisher publisher = new InputStreamConsumingPublisher();
executor.submit(publisher::cancel);
return publisher;
}
} | 2,965 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/InputStreamSubscriberTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Consumer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.utils.ThreadFactoryBuilder;
public class InputStreamSubscriberTest {
private SimplePublisher<ByteBuffer> publisher;
private InputStreamSubscriber subscriber;
@BeforeEach
public void setup() {
publisher = new SimplePublisher<>();
subscriber = new InputStreamSubscriber();
}
@Test
public void onComplete_returnsEndOfStream_onRead() {
publisher.subscribe(subscriber);
publisher.complete();
assertThat(subscriber.read()).isEqualTo(-1);
assertThat(subscriber.read(new byte[1])).isEqualTo(-1);
assertThat(subscriber.read(new byte[1], 0, 1)).isEqualTo(-1);
}
@Test
public void onError_throws_onRead() {
IllegalStateException exception = new IllegalStateException();
publisher.subscribe(subscriber);
publisher.error(exception);
assertThatThrownBy(() -> subscriber.read()).isEqualTo(exception);
assertThatThrownBy(() -> subscriber.read(new byte[1])).isEqualTo(exception);
assertThatThrownBy(() -> subscriber.read(new byte[1], 0, 1)).isEqualTo(exception);
}
@Test
public void onComplete_afterOnNext_returnsEndOfStream() {
publisher.subscribe(subscriber);
publisher.send(byteBufferOfLength(1));
publisher.complete();
assertThat(subscriber.read()).isEqualTo(0);
assertThat(subscriber.read()).isEqualTo(-1);
}
@Test
public void onComplete_afterEmptyOnNext_returnsEndOfStream() {
publisher.subscribe(subscriber);
publisher.send(byteBufferOfLength(0));
publisher.send(byteBufferOfLength(0));
publisher.send(byteBufferOfLength(0));
publisher.complete();
assertThat(subscriber.read()).isEqualTo(-1);
}
@Test
public void read_afterOnNext_returnsData() {
publisher.subscribe(subscriber);
publisher.send(byteBufferWithByte(10));
assertThat(subscriber.read()).isEqualTo(10);
}
@Test
public void readBytes_afterOnNext_returnsData() {
publisher.subscribe(subscriber);
publisher.send(byteBufferWithByte(10));
publisher.send(byteBufferWithByte(20));
byte[] bytes = new byte[2];
assertThat(subscriber.read(bytes)).isEqualTo(2);
assertThat(bytes[0]).isEqualTo((byte) 10);
assertThat(bytes[1]).isEqualTo((byte) 20);
}
@Test
public void readBytesWithOffset_afterOnNext_returnsData() {
publisher.subscribe(subscriber);
publisher.send(byteBufferWithByte(10));
publisher.send(byteBufferWithByte(20));
byte[] bytes = new byte[3];
assertThat(subscriber.read(bytes, 1, 2)).isEqualTo(2);
assertThat(bytes[1]).isEqualTo((byte) 10);
assertThat(bytes[2]).isEqualTo((byte) 20);
}
@Test
public void read_afterClose_fails() {
publisher.subscribe(subscriber);
subscriber.close();
assertThatThrownBy(() -> subscriber.read()).isInstanceOf(CancellationException.class);
assertThatThrownBy(() -> subscriber.read(new byte[1])).isInstanceOf(CancellationException.class);
assertThatThrownBy(() -> subscriber.read(new byte[1], 0, 1)).isInstanceOf(CancellationException.class);
}
@Test
public void readByteArray_0Len_returns0() {
publisher.subscribe(subscriber);
assertThat(subscriber.read(new byte[1], 0, 0)).isEqualTo(0);
}
public static List<Arguments> stochastic_methodCallsSeemThreadSafe_parameters() {
Object[][] inputStreamOperations = {
{ "read();", subscriberRead1() },
{ "read(); close();", subscriberRead1().andThen(subscriberClose()) },
{ "read(byte[]); close();", subscriberReadArray().andThen(subscriberClose()) },
{ "read(byte[]); read(byte[]);", subscriberReadArray().andThen(subscriberReadArray()) }
};
Object[][] publisherOperations = {
{ "onNext(...);", subscriberOnNext() },
{ "onNext(...); onComplete();", subscriberOnNext().andThen(subscriberOnComplete()) },
{ "onNext(...); onError(...);", subscriberOnNext().andThen(subscriberOnError()) },
{ "onComplete();", subscriberOnComplete() },
{ "onError(...);", subscriberOnError() }
};
List<Arguments> result = new ArrayList<>();
for (Object[] iso : inputStreamOperations) {
for (Object[] po : publisherOperations) {
result.add(Arguments.of(iso[1], po[1], iso[0] + " and " + po[0] + " in parallel"));
}
}
return result;
}
@ParameterizedTest(name = "{2}")
@MethodSource("stochastic_methodCallsSeemThreadSafe_parameters")
@Timeout(10)
public void stochastic_methodCallsSeemThreadSafe(Consumer<InputStreamSubscriber> inputStreamOperation,
Consumer<InputStreamSubscriber> publisherOperation,
String testName)
throws InterruptedException, ExecutionException {
int numIterations = 100;
// Read/close aren't mutually thread safe, and onNext/onComplete/onError aren't mutually thread safe, but one
// group of functions might be executed in parallel with the others. We try to make sure that this is safe.
ExecutorService executor = Executors.newFixedThreadPool(10, new ThreadFactoryBuilder().daemonThreads(true).build());
try {
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < numIterations; i++) {
CountDownLatch waitingAtStartLine = new CountDownLatch(2);
CountDownLatch startLine = new CountDownLatch(1);
InputStreamSubscriber subscriber = new InputStreamSubscriber();
subscriber.onSubscribe(mockSubscription(subscriber));
futures.add(executor.submit(() -> {
waitingAtStartLine.countDown();
startLine.await();
inputStreamOperation.accept(subscriber);
return null;
}));
futures.add(executor.submit(() -> {
waitingAtStartLine.countDown();
startLine.await();
publisherOperation.accept(subscriber);
return null;
}));
waitingAtStartLine.await();
startLine.countDown();
}
for (Future<?> future : futures) {
future.get();
}
} finally {
executor.shutdownNow();
}
}
public static Consumer<InputStreamSubscriber> subscriberOnNext() {
return s -> s.onNext(ByteBuffer.allocate(1));
}
public static Consumer<InputStreamSubscriber> subscriberOnComplete() {
return s -> s.onComplete();
}
public static Consumer<InputStreamSubscriber> subscriberOnError() {
return s -> s.onError(new Throwable());
}
public static Consumer<InputStreamSubscriber> subscriberRead1() {
return s -> s.read();
}
public static Consumer<InputStreamSubscriber> subscriberReadArray() {
return s -> s.read(new byte[4]);
}
public static Consumer<InputStreamSubscriber> subscriberClose() {
return s -> s.close();
}
private Subscription mockSubscription(Subscriber<ByteBuffer> subscriber) {
Subscription subscription = mock(Subscription.class);
doAnswer(new Answer<Void>() {
boolean done = false;
@Override
public Void answer(InvocationOnMock invocation) {
if (!done) {
subscriber.onNext(ByteBuffer.wrap(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }));
subscriber.onComplete();
done = true;
}
return null;
}
}).when(subscription).request(anyLong());
return subscription;
}
private ByteBuffer byteBufferOfLength(int length) {
return ByteBuffer.allocate(length);
}
public ByteBuffer byteBufferWithByte(int b) {
ByteBuffer buffer = ByteBuffer.allocate(1);
buffer.put((byte) b);
buffer.flip();
return buffer;
}
} | 2,966 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/OutputStreamPublisherTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import software.amazon.awssdk.utils.ThreadFactoryBuilder;
import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult;
public class OutputStreamPublisherTest {
private StoringSubscriber<ByteBuffer> storingSubscriber;
private ByteBufferStoringSubscriber byteStoringSubscriber;
private OutputStreamPublisher publisher;
@BeforeEach
public void setup() {
storingSubscriber = new StoringSubscriber<>(Integer.MAX_VALUE);
byteStoringSubscriber = new ByteBufferStoringSubscriber(Integer.MAX_VALUE);
publisher = new OutputStreamPublisher();
}
@Test
public void oneByteWritesAreBuffered() {
publisher.subscribe(storingSubscriber);
publisher.write(0);
assertThat(storingSubscriber.poll()).isNotPresent();
}
@Test
public void oneByteWritesAreFlushedEventually() {
publisher.subscribe(storingSubscriber);
for (int i = 0; i < 1024 * 1024; i++) {
publisher.write(0);
}
assertThat(storingSubscriber.poll()).hasValueSatisfying(e -> {
assertThat(e.value().get()).isEqualTo((byte) 0);
});
}
@Test
public void flushDrainsBufferedBytes() {
publisher.subscribe(storingSubscriber);
publisher.write(0);
publisher.flush();
assertThat(storingSubscriber.poll()).hasValueSatisfying(v -> {
assertThat(v.value().remaining()).isEqualTo(1);
});
}
@Test
public void emptyFlushDoesNothing() {
publisher.subscribe(storingSubscriber);
publisher.flush();
assertThat(storingSubscriber.poll()).isNotPresent();
}
@Test
public void oneByteWritesAreSentInOrder() {
publisher.subscribe(storingSubscriber);
for (int i = 0; i < 256; i++) {
publisher.write(i);
}
publisher.flush();
assertThat(storingSubscriber.poll()).hasValueSatisfying(e -> {
assertThat(e.value().get()).isEqualTo((byte) 0);
});
}
@Test
@Timeout(30)
public void writesBeforeSubscribeBlockUntilSubscribe() throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build());
try {
Future<?> writes = executor.submit(() -> {
publisher.write(new byte[256]);
publisher.close();
});
Thread.sleep(200);
assertThat(storingSubscriber.poll()).isNotPresent();
assertThat(writes.isDone()).isFalse();
publisher.subscribe(storingSubscriber);
assertThat(storingSubscriber.poll()).isPresent();
writes.get();
} finally {
executor.shutdownNow();
}
}
@Test
public void mixedWriteTypesAreSentInOrder() {
publisher.subscribe(byteStoringSubscriber);
AtomicInteger i = new AtomicInteger(0);
writeByte(i);
writeBytes(i);
writeOffsetBytes(i);
writeByte(i);
writeOffsetBytes(i);
writeBytes(i);
writeBytes(i);
writeByte(i);
writeOffsetBytes(i);
writeBytes(i);
writeOffsetBytes(i);
writeByte(i);
writeOffsetBytes(i);
writeByte(i);
writeBytes(i);
writeOffsetBytes(i);
writeByte(i);
writeBytes(i);
publisher.close();
ByteBuffer out = ByteBuffer.allocate(i.get() + 1);
assertThat(byteStoringSubscriber.blockingTransferTo(out)).isEqualTo(TransferResult.END_OF_STREAM);
out.flip();
for (int j = 0; j < i.get(); j++) {
assertThat(out.get()).isEqualTo((byte) j);
}
}
@Test
public void cancel_preventsSingleByteWrites() {
publisher.subscribe(byteStoringSubscriber);
publisher.cancel();
assertThatThrownBy(() -> publisher.write(1)).isInstanceOf(IllegalStateException.class);
}
@Test
public void cancel_preventsMultiByteWrites() {
publisher.subscribe(byteStoringSubscriber);
publisher.cancel();
assertThatThrownBy(() -> publisher.write(new byte[8])).hasRootCauseInstanceOf(IllegalStateException.class);
}
@Test
public void cancel_preventsOffsetByteWrites() {
publisher.subscribe(byteStoringSubscriber);
publisher.cancel();
assertThatThrownBy(() -> publisher.write(new byte[8], 0, 1)).hasRootCauseInstanceOf(IllegalStateException.class);
}
@Test
public void close_preventsSingleByteWrites() {
publisher.subscribe(byteStoringSubscriber);
publisher.close();
assertThatThrownBy(() -> publisher.write(1)).isInstanceOf(IllegalStateException.class);
}
@Test
public void close_preventsMultiByteWrites() {
publisher.subscribe(byteStoringSubscriber);
publisher.close();
assertThatThrownBy(() -> publisher.write(new byte[8])).hasRootCauseInstanceOf(IllegalStateException.class);
}
@Test
public void close_preventsOffsetByteWrites() {
publisher.subscribe(byteStoringSubscriber);
publisher.close();
assertThatThrownBy(() -> publisher.write(new byte[8], 0, 1)).hasRootCauseInstanceOf(IllegalStateException.class);
}
private void writeByte(AtomicInteger i) {
publisher.write(i.getAndIncrement());
}
private void writeBytes(AtomicInteger i) {
publisher.write(new byte[] { (byte) i.getAndIncrement(), (byte) i.getAndIncrement() });
}
private void writeOffsetBytes(AtomicInteger i) {
publisher.write(new byte[] {
0,
0,
(byte) i.getAndIncrement(),
(byte) i.getAndIncrement(),
(byte) i.getAndIncrement()
},
2, 3);
}
} | 2,967 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/InputStreamSubscriberTckTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import java.nio.ByteBuffer;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.reactivestreams.tck.SubscriberWhiteboxVerification;
import org.reactivestreams.tck.TestEnvironment;
public class InputStreamSubscriberTckTest extends SubscriberWhiteboxVerification<ByteBuffer> {
protected InputStreamSubscriberTckTest() {
super(new TestEnvironment());
}
@Override
public Subscriber<ByteBuffer> createSubscriber(WhiteboxSubscriberProbe<ByteBuffer> probe) {
return new ByteBufferStoringSubscriber(16) {
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
probe.registerOnError(throwable);
}
@Override
public void onSubscribe(Subscription subscription) {
super.onSubscribe(subscription);
probe.registerOnSubscribe(new SubscriberPuppet() {
@Override
public void triggerRequest(long elements) {
subscription.request(elements);
}
@Override
public void signalCancel() {
subscription.cancel();
}
});
}
@Override
public void onNext(ByteBuffer next) {
super.onNext(next);
probe.registerOnNext(next);
}
@Override
public void onComplete() {
super.onComplete();
probe.registerOnComplete();
}
};
}
@Override
public ByteBuffer createElement(int element) {
return ByteBuffer.wrap(new byte[0]);
}
} | 2,968 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/StoringSubscriberTckTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.reactivestreams.tck.SubscriberWhiteboxVerification;
import org.reactivestreams.tck.TestEnvironment;
public class StoringSubscriberTckTest extends SubscriberWhiteboxVerification<Integer> {
protected StoringSubscriberTckTest() {
super(new TestEnvironment());
}
@Override
public Subscriber<Integer> createSubscriber(WhiteboxSubscriberProbe<Integer> probe) {
return new StoringSubscriber<Integer>(16) {
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
probe.registerOnError(throwable);
}
@Override
public void onSubscribe(Subscription subscription) {
super.onSubscribe(subscription);
probe.registerOnSubscribe(new SubscriberPuppet() {
@Override
public void triggerRequest(long elements) {
subscription.request(elements);
}
@Override
public void signalCancel() {
subscription.cancel();
}
});
}
@Override
public void onNext(Integer nextItems) {
super.onNext(nextItems);
probe.registerOnNext(nextItems);
}
@Override
public void onComplete() {
super.onComplete();
probe.registerOnComplete();
}
};
}
@Override
public Integer createElement(int element) {
return element;
}
} | 2,969 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/BufferingSubscriberTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
@RunWith(MockitoJUnitRunner.class)
public class BufferingSubscriberTest {
private static final int BUFFER_SIZE = 6;
private static final Object data = new Object();
@Mock
private Subscriber mockSubscriber;
@Mock
private Subscription mockSubscription;
private Subscriber bufferingSubscriber;
@Before
public void setup() {
doNothing().when(mockSubscriber).onSubscribe(any());
doNothing().when(mockSubscriber).onNext(any());
doNothing().when(mockSubscriber).onComplete();
doNothing().when(mockSubscription).request(anyLong());
bufferingSubscriber = new BufferingSubscriber(mockSubscriber, BUFFER_SIZE);
bufferingSubscriber.onSubscribe(mockSubscription);
}
@Test
public void onNextNotCalled_WhenCurrentSizeLessThanBufferSize() {
int count = 3;
callOnNext(count);
verify(mockSubscription, times(count)).request(1);
verify(mockSubscriber, times(0)).onNext(any());
}
@Test
public void onNextIsCalled_onlyWhen_BufferSizeRequirementIsMet() {
callOnNext(BUFFER_SIZE);
verify(mockSubscriber, times(1)).onNext(any());
}
@Test
public void onNextIsCalled_DuringOnComplete_WhenBufferNotEmpty() {
int count = 8;
callOnNext(count);
bufferingSubscriber.onComplete();
verify(mockSubscriber, times(count/BUFFER_SIZE + 1)).onNext(any());
}
private void callOnNext(int times) {
IntStream.range(0, times).forEach(i -> bufferingSubscriber.onNext(data));
}
}
| 2,970 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/StoringSubscriberTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.utils.async.StoringSubscriber.Event;
import software.amazon.awssdk.utils.async.StoringSubscriber.EventType;
public class StoringSubscriberTest {
@Test
public void constructorCalled_withNonPositiveSize_throwsException() {
assertThatCode(() -> new StoringSubscriber<>(1)).doesNotThrowAnyException();
assertThatCode(() -> new StoringSubscriber<>(Integer.MAX_VALUE)).doesNotThrowAnyException();
assertThatThrownBy(() -> new StoringSubscriber<>(0)).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new StoringSubscriber<>(-1)).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new StoringSubscriber<>(Integer.MIN_VALUE)).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void doesNotStoreMoreThanMaxElements() {
StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(2);
Subscription subscription = mock(Subscription.class);
subscriber.onSubscribe(subscription);
verify(subscription).request(2);
subscriber.onNext(0);
subscriber.onNext(0);
subscriber.peek();
verifyNoMoreInteractions(subscription);
subscriber.poll();
subscriber.poll();
verify(subscription, times(2)).request(1);
assertThat(subscriber.peek()).isNotPresent();
verifyNoMoreInteractions(subscription);
}
@Test
public void returnsEmptyEventWithOutstandingDemand() {
StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(2);
subscriber.onSubscribe(mock(Subscription.class));
assertThat(subscriber.peek()).isNotPresent();
}
@Test
public void returnsCompleteOnComplete() {
StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(2);
subscriber.onSubscribe(mock(Subscription.class));
subscriber.onComplete();
assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_COMPLETE);
}
@Test
public void returnsErrorOnError() {
RuntimeException error = new RuntimeException();
StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(2);
subscriber.onSubscribe(mock(Subscription.class));
subscriber.onError(error);
assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_ERROR);
assertThat(subscriber.peek().get().runtimeError()).isEqualTo(error);
}
@Test
public void errorWrapsCheckedExceptions() {
Exception error = new Exception();
StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(2);
subscriber.onSubscribe(mock(Subscription.class));
subscriber.onError(error);
assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_ERROR);
assertThat(subscriber.peek().get().runtimeError()).hasCause(error);
}
@Test
public void deliversMessagesInTheCorrectOrder() {
StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(2);
Subscription subscription = mock(Subscription.class);
subscriber.onSubscribe(subscription);
subscriber.onNext(1);
subscriber.onNext(2);
subscriber.onComplete();
assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_NEXT);
assertThat(subscriber.peek().get().value()).isEqualTo(1);
subscriber.poll();
assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_NEXT);
assertThat(subscriber.peek().get().value()).isEqualTo(2);
subscriber.poll();
assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_COMPLETE);
subscriber.poll();
assertThat(subscriber.peek()).isNotPresent();
}
@Test
@Timeout(30)
public void stochastic_subscriberSeemsThreadSafe() throws Throwable {
ExecutorService producer = Executors.newFixedThreadPool(1);
ExecutorService consumer = Executors.newFixedThreadPool(1);
try {
StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(10);
AtomicBoolean testRunning = new AtomicBoolean(true);
AtomicInteger messageNumber = new AtomicInteger(0);
AtomicReference<Throwable> producerFailure = new AtomicReference<>();
Subscription subscription = new Subscription() {
@Override
public void request(long n) {
producer.submit(() -> {
try {
for (int i = 0; i < n; i++) {
subscriber.onNext(messageNumber.getAndIncrement());
}
} catch (Throwable t) {
producerFailure.set(t);
}
});
}
@Override
public void cancel() {
producerFailure.set(new AssertionError("Cancel not expected."));
}
};
subscriber.onSubscribe(subscription);
Future<Object> consumerFuture = consumer.submit(() -> {
int expectedMessageNumber = 0;
while (testRunning.get()) {
Thread.sleep(1);
Optional<Event<Integer>> current = subscriber.peek();
Optional<Event<Integer>> current2 = subscriber.peek();
if (current.isPresent()) {
assertThat(current.get()).isSameAs(current2.get());
Event<Integer> event = current.get();
assertThat(event.type()).isEqualTo(EventType.ON_NEXT);
assertThat(event.value()).isEqualTo(expectedMessageNumber);
expectedMessageNumber++;
}
subscriber.poll();
}
return null;
});
Thread.sleep(5_000);
testRunning.set(false);
consumerFuture.get();
if (producerFailure.get() != null) {
throw producerFailure.get();
}
assertThat(messageNumber.get()).isGreaterThan(10); // ensure we actually tested something
} finally {
producer.shutdownNow();
consumer.shutdownNow();
}
}
} | 2,971 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/FlatteningSubscriberTckTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.reactivestreams.tck.SubscriberWhiteboxVerification;
import org.reactivestreams.tck.TestEnvironment;
public class FlatteningSubscriberTckTest extends SubscriberWhiteboxVerification<Iterable<Integer>> {
protected FlatteningSubscriberTckTest() {
super(new TestEnvironment());
}
@Override
public Subscriber<Iterable<Integer>> createSubscriber(WhiteboxSubscriberProbe<Iterable<Integer>> probe) {
Subscriber<Integer> foo = new SequentialSubscriber<>(s -> {}, new CompletableFuture<>());
return new FlatteningSubscriber<Integer>(foo) {
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
probe.registerOnError(throwable);
}
@Override
public void onSubscribe(Subscription subscription) {
super.onSubscribe(subscription);
probe.registerOnSubscribe(new SubscriberPuppet() {
@Override
public void triggerRequest(long elements) {
subscription.request(elements);
}
@Override
public void signalCancel() {
subscription.cancel();
}
});
}
@Override
public void onNext(Iterable<Integer> nextItems) {
super.onNext(nextItems);
probe.registerOnNext(nextItems);
}
@Override
public void onComplete() {
super.onComplete();
probe.registerOnComplete();
}
};
}
@Override
public Iterable<Integer> createElement(int element) {
return Arrays.asList(element, element);
}
} | 2,972 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/AddingTrailingDataSubscriberTckTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.async;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.reactivestreams.tck.SubscriberWhiteboxVerification;
import org.reactivestreams.tck.TestEnvironment;
public class AddingTrailingDataSubscriberTckTest extends SubscriberWhiteboxVerification<Integer> {
protected AddingTrailingDataSubscriberTckTest() {
super(new TestEnvironment());
}
@Override
public Subscriber<Integer> createSubscriber(WhiteboxSubscriberProbe<Integer> probe) {
Subscriber<Integer> foo = new SequentialSubscriber<>(s -> {}, new CompletableFuture<>());
return new AddingTrailingDataSubscriber<Integer>(foo, () -> Arrays.asList(0, 1, 2)) {
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
probe.registerOnError(throwable);
}
@Override
public void onSubscribe(Subscription subscription) {
super.onSubscribe(subscription);
probe.registerOnSubscribe(new SubscriberPuppet() {
@Override
public void triggerRequest(long elements) {
subscription.request(elements);
}
@Override
public void signalCancel() {
subscription.cancel();
}
});
}
@Override
public void onNext(Integer nextItem) {
super.onNext(nextItem);
probe.registerOnNext(nextItem);
}
@Override
public void onComplete() {
super.onComplete();
probe.registerOnComplete();
}
};
}
@Override
public Integer createElement(int i) {
return i;
}
}
| 2,973 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/internal/SystemSettingUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.internal;
import static org.assertj.core.api.Java6Assertions.assertThat;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.SystemSetting;
public class SystemSettingUtilsTest {
@Test
public void resolveNonDefaultSetting_doesNotReturnDefaultValue() {
TestSystemSetting setting = new TestSystemSetting("prop", "env", "default");
assertThat(SystemSettingUtils.resolveNonDefaultSetting(setting).isPresent()).isFalse();
}
private static class TestSystemSetting implements SystemSetting {
private final String property;
private final String environmentVariable;
private final String defaultValue;
public TestSystemSetting(String property, String environmentVariable, String defaultValue) {
this.property = property;
this.environmentVariable = environmentVariable;
this.defaultValue = defaultValue;
}
@Override
public String property() {
return property;
}
@Override
public String environmentVariable() {
return environmentVariable;
}
@Override
public String defaultValue() {
return defaultValue;
}
}
}
| 2,974 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/internal/ReflectionUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.internal;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import org.junit.jupiter.api.Test;
public class ReflectionUtilsTest {
@Test
public void getWrappedClass_primitiveClass_returnsWrappedClass() {
assertThat(ReflectionUtils.getWrappedClass(int.class), is(equalTo(Integer.class)));
}
@Test
public void getWrappedClass_nonPrimitiveClass_returnsSameClass() {
assertThat(ReflectionUtils.getWrappedClass(String.class), is(equalTo(String.class)));
}
} | 2,975 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/internal/MappingSubscriberTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.internal;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
@RunWith(MockitoJUnitRunner.class)
public class MappingSubscriberTest {
@Mock
private Subscription mockSubscription;
@Mock
private Subscriber<String> mockSubscriber;
@Test
public void verifyNormalFlow() {
MappingSubscriber<String, String> mappingSubscriber =
MappingSubscriber.create(mockSubscriber, String::toUpperCase);
mappingSubscriber.onSubscribe(mockSubscription);
verify(mockSubscriber).onSubscribe(mockSubscription);
verifyNoMoreInteractions(mockSubscriber);
reset(mockSubscriber);
mappingSubscriber.onNext("one");
verify(mockSubscriber).onNext("ONE");
verifyNoMoreInteractions(mockSubscriber);
reset(mockSubscriber);
mappingSubscriber.onNext("two");
verify(mockSubscriber).onNext("TWO");
verifyNoMoreInteractions(mockSubscriber);
reset(mockSubscriber);
mappingSubscriber.onComplete();
verify(mockSubscriber).onComplete();
verifyNoMoreInteractions(mockSubscriber);
}
@Test
public void verifyMappingExceptionFlow() {
RuntimeException exception = new IllegalArgumentException("Twos are not supported");
MappingSubscriber<String, String> mappingSubscriber =
MappingSubscriber.create(mockSubscriber, s -> {
if ("two".equals(s)) {
throw exception;
}
return s.toUpperCase();
});
mappingSubscriber.onSubscribe(mockSubscription);
verify(mockSubscriber).onSubscribe(mockSubscription);
verifyNoMoreInteractions(mockSubscriber);
reset(mockSubscriber);
mappingSubscriber.onNext("one");
verify(mockSubscriber).onNext("ONE");
verifyNoMoreInteractions(mockSubscriber);
reset(mockSubscriber);
mappingSubscriber.onNext("two");
verify(mockSubscriber).onError(exception);
verifyNoMoreInteractions(mockSubscriber);
verify(mockSubscription).cancel();
reset(mockSubscriber);
mappingSubscriber.onNext("three");
verifyNoMoreInteractions(mockSubscriber);
reset(mockSubscriber);
mappingSubscriber.onComplete();
verifyNoMoreInteractions(mockSubscriber);
}
} | 2,976 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/builder/CopyableBuilderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils.builder;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
public class CopyableBuilderTest {
@Test
public void canApplyAFunctionToTheBuilder() {
ClassToBuild builtClass = ClassToBuild.builder().name("jeffery").applyMutation(this::upperCaseName).build();
assertThat(builtClass.name).isEqualTo("JEFFERY");
}
@Test
public void canCopyABuilder() {
ClassToBuild.Builder builder = ClassToBuild.builder().name("Stanley");
ClassToBuild.Builder copied = builder.copy().name("Alexander");
assertThat(builder.build().name).isEqualTo("Stanley");
assertThat(copied.build().name).isEqualTo("Alexander");
}
private ClassToBuild.Builder upperCaseName(ClassToBuild.Builder builder) {
return builder.name(builder.name.toUpperCase());
}
private static class ClassToBuild implements ToCopyableBuilder<ClassToBuild.Builder, ClassToBuild> {
private final String name;
private ClassToBuild(Builder builder) {
this.name = builder.name;
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
public static Builder builder() {
return new Builder();
}
static class Builder implements CopyableBuilder<Builder, ClassToBuild> {
private String name;
private Builder() {}
private Builder(ClassToBuild source) {
this.name = source.name;
}
public Builder name(String name) {
this.name = name;
return this;
}
@Override
public ClassToBuild build() {
return new ClassToBuild(this);
}
}
}
}
| 2,977 |
0 | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/testutils/EnvironmentVariableHelper.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.testutils;
import java.util.function.Consumer;
import org.junit.rules.ExternalResource;
import software.amazon.awssdk.utils.SystemSetting;
import software.amazon.awssdk.utils.internal.SystemSettingUtilsTestBackdoor;
/**
* A utility that can temporarily forcibly set environment variables and then allows resetting them to the original values.
*
* This only works for environment variables read by the SDK.
*/
public class EnvironmentVariableHelper extends ExternalResource {
public void remove(SystemSetting setting) {
remove(setting.environmentVariable());
}
public void remove(String key) {
SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride(key, null);
}
public void set(SystemSetting setting, String value) {
set(setting.environmentVariable(), value);
}
public void set(String key, String value) {
SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride(key, value);
}
public void reset() {
SystemSettingUtilsTestBackdoor.clearEnvironmentVariableOverrides();
}
@Override
protected void after() {
reset();
}
/**
* Static run method that allows for "single-use" environment variable modification.
*
* Example use:
* <pre>
* {@code
* EnvironmentVariableHelper.run(helper -> {
* helper.set("variable", "value");
* //run some test that uses "variable"
* });
* }
* </pre>
*
* Will call {@link #reset} at the end of the block (even if the block exits exceptionally).
*
* @param helperConsumer a code block to run that gets an {@link EnvironmentVariableHelper} as an argument
*/
public static void run(Consumer<EnvironmentVariableHelper> helperConsumer) {
EnvironmentVariableHelper helper = new EnvironmentVariableHelper();
try {
helperConsumer.accept(helper);
} finally {
helper.reset();
}
}
}
| 2,978 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/DaemonThreadFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.util.concurrent.ThreadFactory;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* An decorator for {@link ThreadFactory} that sets all threads it creates to be daemon threads.
*/
@SdkProtectedApi
public class DaemonThreadFactory implements ThreadFactory {
private final ThreadFactory delegate;
public DaemonThreadFactory(ThreadFactory delegate) {
this.delegate = Validate.notNull(delegate, "delegate must not be null");
}
@Override
public Thread newThread(Runnable runnable) {
Thread thread = delegate.newThread(runnable);
thread.setDaemon(true);
return thread;
}
}
| 2,979 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/IoUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Utilities for IO operations.
*/
@SdkProtectedApi
public final class IoUtils {
private static final int BUFFER_SIZE = 1024 * 4;
private static final Logger DEFAULT_LOG = LoggerFactory.getLogger(IoUtils.class);
private IoUtils() {
}
/**
* Reads and returns the rest of the given input stream as a byte array.
* Caller is responsible for closing the given input stream.
*/
public static byte[] toByteArray(InputStream is) throws IOException {
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
byte[] b = new byte[BUFFER_SIZE];
int n = 0;
while ((n = is.read(b)) != -1) {
output.write(b, 0, n);
}
return output.toByteArray();
}
}
/**
* Reads and returns the rest of the given input stream as a string.
* Caller is responsible for closing the given input stream.
*/
public static String toUtf8String(InputStream is) throws IOException {
return new String(toByteArray(is), StandardCharsets.UTF_8);
}
/**
* Closes the given Closeable quietly.
* @param is the given closeable
* @param log logger used to log any failure should the close fail
*/
public static void closeQuietly(AutoCloseable is, Logger log) {
if (is != null) {
try {
is.close();
} catch (Exception ex) {
Logger logger = log == null ? DEFAULT_LOG : log;
if (logger.isDebugEnabled()) {
logger.debug("Ignore failure in closing the Closeable", ex);
}
}
}
}
/**
* Closes the given Closeable quietly.
* @param maybeCloseable the given closeable
* @param log logger used to log any failure should the close fail
*/
public static void closeIfCloseable(Object maybeCloseable, Logger log) {
if (maybeCloseable instanceof AutoCloseable) {
IoUtils.closeQuietly((AutoCloseable) maybeCloseable, log);
}
}
/**
* Copies all bytes from the given input stream to the given output stream.
* Caller is responsible for closing the streams.
*
* @throws IOException
* if there is any IO exception during read or write.
*/
public static long copy(InputStream in, OutputStream out) throws IOException {
return copy(in, out, Long.MAX_VALUE);
}
/**
* Copies all bytes from the given input stream to the given output stream.
* Caller is responsible for closing the streams.
*
* @throws IOException if there is any IO exception during read or write or the read limit is exceeded.
*/
public static long copy(InputStream in, OutputStream out, long readLimit) throws IOException {
byte[] buf = new byte[BUFFER_SIZE];
long count = 0;
int n = 0;
while ((n = in.read(buf)) > -1) {
out.write(buf, 0, n);
count += n;
if (count >= readLimit) {
throw new IOException("Read limit exceeded: " + readLimit);
}
}
return count;
}
/**
* Read all remaining data in the stream.
*
* @param in InputStream to read.
*/
public static void drainInputStream(InputStream in) {
try {
while (in.read() != -1) {
// Do nothing.
}
} catch (IOException ignored) {
// Stream may be self closed by HTTP client so we ignore any failures.
}
}
/**
* If the stream supports marking, marks the stream at the current position with a {@code readLimit} value of
* 128 KiB.
*
* @param s The stream.
*/
public static void markStreamWithMaxReadLimit(InputStream s) {
if (s.markSupported()) {
s.mark(1 << 17);
}
}
/**
* If the stream supports marking, marks the stream at the current position with a read limit specified in {@code
* maxReadLimit}.
*
* @param maxReadLimit the maxReadLimit, if it's null, 128 KiB will be used.
* @param s The stream.
*/
public static void markStreamWithMaxReadLimit(InputStream s, Integer maxReadLimit) {
Validate.isPositiveOrNull(maxReadLimit, "maxReadLimit");
if (s.markSupported()) {
int maxLimit = maxReadLimit == null ? 1 << 17 : maxReadLimit;
s.mark(maxLimit);
}
}
}
| 2,980 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/StringUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.util.Locale;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* <p>Operations on {@link java.lang.String} that are
* {@code null} safe.</p>
*
* <ul>
* <li><b>IsEmpty/IsBlank</b>
* - checks if a String contains text</li>
* <li><b>Trim/Strip</b>
* - removes leading and trailing whitespace</li>
* <li><b>Equals/Compare</b>
* - compares two strings null-safe</li>
* <li><b>startsWith</b>
* - check if a String starts with a prefix null-safe</li>
* <li><b>endsWith</b>
* - check if a String ends with a suffix null-safe</li>
* <li><b>IndexOf/LastIndexOf/Contains</b>
* - null-safe index-of checks
* <li><b>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</b>
* - index-of any of a set of Strings</li>
* <li><b>ContainsOnly/ContainsNone/ContainsAny</b>
* - does String contains only/none/any of these characters</li>
* <li><b>Substring/Left/Right/Mid</b>
* - null-safe substring extractions</li>
* <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b>
* - substring extraction relative to other strings</li>
* <li><b>Split/Join</b>
* - splits a String into an array of substrings and vice versa</li>
* <li><b>Remove/Delete</b>
* - removes part of a String</li>
* <li><b>Replace/Overlay</b>
* - Searches a String and replaces one String with another</li>
* <li><b>Chomp/Chop</b>
* - removes the last part of a String</li>
* <li><b>AppendIfMissing</b>
* - appends a suffix to the end of the String if not present</li>
* <li><b>PrependIfMissing</b>
* - prepends a prefix to the start of the String if not present</li>
* <li><b>LeftPad/RightPad/Center/Repeat</b>
* - pads a String</li>
* <li><b>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</b>
* - changes the case of a String</li>
* <li><b>CountMatches</b>
* - counts the number of occurrences of one String in another</li>
* <li><b>IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable</b>
* - checks the characters in a String</li>
* <li><b>DefaultString</b>
* - protects against a null input String</li>
* <li><b>Rotate</b>
* - rotate (circular shift) a String</li>
* <li><b>Reverse/ReverseDelimited</b>
* - reverses a String</li>
* <li><b>Abbreviate</b>
* - abbreviates a string using ellipsis or another given String</li>
* <li><b>Difference</b>
* - compares Strings and reports on their differences</li>
* <li><b>LevenshteinDistance</b>
* - the number of changes needed to change one String into another</li>
* </ul>
*
* <p>The {@code StringUtils} class defines certain words related to
* String handling.</p>
*
* <ul>
* <li>null - {@code null}</li>
* <li>empty - a zero-length string ({@code ""})</li>
* <li>space - the space character ({@code ' '}, char 32)</li>
* <li>whitespace - the characters defined by {@link Character#isWhitespace(char)}</li>
* <li>trim - the characters <= 32 as in {@link String#trim()}</li>
* </ul>
*
* <p>{@code StringUtils} handles {@code null} input Strings quietly.
* That is to say that a {@code null} input will return {@code null}.
* Where a {@code boolean} or {@code int} is being returned
* details vary by method.</p>
*
* <p>A side effect of the {@code null} handling is that a
* {@code NullPointerException} should be considered a bug in
* {@code StringUtils}.</p>
*
* <p>This class's source was modified from the Apache commons-lang library: https://github.com/apache/commons-lang/</p>
*
* <p>#ThreadSafe#</p>
* @see java.lang.String
*/
@SdkProtectedApi
public final class StringUtils {
// Performance testing notes (JDK 1.4, Jul03, scolebourne)
// Whitespace:
// Character.isWhitespace() is faster than WHITESPACE.indexOf()
// where WHITESPACE is a string of all whitespace characters
//
// Character access:
// String.charAt(n) versus toCharArray(), then array[n]
// String.charAt(n) is about 15% worse for a 10K string
// They are about equal for a length 50 string
// String.charAt(n) is about 4 times better for a length 3 string
// String.charAt(n) is best bet overall
//
// Append:
// String.concat about twice as fast as StringBuffer.append
// (not sure who tested this)
/**
* The empty String {@code ""}.
*/
private static final String EMPTY = "";
/**
* <p>{@code StringUtils} instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* {@code StringUtils.trim(" foo ");}.</p>
*/
private StringUtils() {
}
// Empty checks
//-----------------------------------------------------------------------
/**
* <p>Checks if a CharSequence is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the CharSequence.
* That functionality is available in isBlank().</p>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is empty or null
* @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
*/
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
/**
* <p>Checks if a CharSequence is empty (""), null or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is null, empty or whitespace only
* @since 2.0
* @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
*/
public static boolean isBlank(final CharSequence cs) {
if (cs == null || cs.length() == 0) {
return true;
}
for (int i = 0; i < cs.length(); i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
* StringUtils.isNotBlank(" ") = false
* StringUtils.isNotBlank("bob") = true
* StringUtils.isNotBlank(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is not empty and not null and not whitespace only
* @since 2.0
* @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence)
*/
public static boolean isNotBlank(final CharSequence cs) {
return !isBlank(cs);
}
// Trim
//-----------------------------------------------------------------------
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String, handling {@code null} by returning
* {@code null}.</p>
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.</p>
*
* <pre>
* StringUtils.trim(null) = null
* StringUtils.trim("") = ""
* StringUtils.trim(" ") = ""
* StringUtils.trim("abc") = "abc"
* StringUtils.trim(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed string, {@code null} if null String input
*/
public static String trim(final String str) {
return str == null ? null : str.trim();
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning {@code null} if the String is
* empty ("") after the trim or if it is {@code null}.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.</p>
*
* <pre>
* StringUtils.trimToNull(null) = null
* StringUtils.trimToNull("") = null
* StringUtils.trimToNull(" ") = null
* StringUtils.trimToNull("abc") = "abc"
* StringUtils.trimToNull(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String,
* {@code null} if only chars <= 32, empty or null String input
* @since 2.0
*/
public static String trimToNull(final String str) {
String ts = trim(str);
return isEmpty(ts) ? null : ts;
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning an empty String ("") if the String
* is empty ("") after the trim or if it is {@code null}.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.</p>
*
* <pre>
* StringUtils.trimToEmpty(null) = ""
* StringUtils.trimToEmpty("") = ""
* StringUtils.trimToEmpty(" ") = ""
* StringUtils.trimToEmpty("abc") = "abc"
* StringUtils.trimToEmpty(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String, or an empty String if {@code null} input
* @since 2.0
*/
public static String trimToEmpty(final String str) {
return str == null ? EMPTY : str.trim();
}
// Equals
//-----------------------------------------------------------------------
/**
* <p>Compares two Strings, returning {@code true} if they represent
* equal sequences of characters.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.equals(null, null) = true
* StringUtils.equals(null, "abc") = false
* StringUtils.equals("abc", null) = false
* StringUtils.equals("abc", "abc") = true
* StringUtils.equals("abc", "ABC") = false
* </pre>
*
* @see Object#equals(Object)
* @param cs1 the first String, may be {@code null}
* @param cs2 the second String, may be {@code null}
* @return {@code true} if the Strings are equal (case-sensitive), or both {@code null}
*/
public static boolean equals(final String cs1, final String cs2) {
if (cs1 == null || cs2 == null) {
return false;
}
if (cs1.length() != cs2.length()) {
return false;
}
return cs1.equals(cs2);
}
// Substring
//-----------------------------------------------------------------------
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start {@code n}
* characters from the end of the String.</p>
*
* <p>A {@code null} String will return {@code null}.
* An empty ("") String will return "".</p>
*
* <pre>
* StringUtils.substring(null, *) = null
* StringUtils.substring("", *) = ""
* StringUtils.substring("abc", 0) = "abc"
* StringUtils.substring("abc", 2) = "c"
* StringUtils.substring("abc", 4) = ""
* StringUtils.substring("abc", -2) = "bc"
* StringUtils.substring("abc", -4) = "abc"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means count back from the end of the String by this many characters
* @return substring from start position, {@code null} if null String input
*/
public static String substring(final String str, int start) {
if (str == null) {
return null;
}
// handle negatives, which means last n characters
if (start < 0) {
start = str.length() + start; // remember start is negative
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return EMPTY;
}
return str.substring(start);
}
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start/end {@code n}
* characters from the end of the String.</p>
*
* <p>The returned substring starts with the character in the {@code start}
* position and ends before the {@code end} position. All position counting is
* zero-based -- i.e., to start at the beginning of the string use
* {@code start = 0}. Negative start and end positions can be used to
* specify offsets relative to the end of the String.</p>
*
* <p>If {@code start} is not strictly to the left of {@code end}, ""
* is returned.</p>
*
* <pre>
* StringUtils.substring(null, *, *) = null
* StringUtils.substring("", * , *) = "";
* StringUtils.substring("abc", 0, 2) = "ab"
* StringUtils.substring("abc", 2, 0) = ""
* StringUtils.substring("abc", 2, 4) = "c"
* StringUtils.substring("abc", 4, 6) = ""
* StringUtils.substring("abc", 2, 2) = ""
* StringUtils.substring("abc", -2, -1) = "b"
* StringUtils.substring("abc", -4, 2) = "ab"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means count back from the end of the String by this many characters
* @param end the position to end at (exclusive), negative means count back from the end of the String by this many
* characters
* @return substring from start position to end position,
* {@code null} if null String input
*/
public static String substring(final String str, int start, int end) {
if (str == null) {
return null;
}
// handle negatives
if (end < 0) {
end = str.length() + end; // remember end is negative
}
if (start < 0) {
start = str.length() + start; // remember start is negative
}
// check length next
if (end > str.length()) {
end = str.length();
}
// if start is greater than end, return ""
if (start > end) {
return EMPTY;
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
// Case conversion
//-----------------------------------------------------------------------
/**
* <p>Converts a String to upper case as per {@link String#toUpperCase()}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.upperCase(null) = null
* StringUtils.upperCase("") = ""
* StringUtils.upperCase("aBc") = "ABC"
* </pre>
*
* <p>This uses "ENGLISH" as the locale.
*
* @param str the String to upper case, may be null
* @return the upper cased String, {@code null} if null String input
*/
public static String upperCase(final String str) {
if (str == null) {
return null;
}
return str.toUpperCase(Locale.ENGLISH);
}
/**
* <p>Converts a String to lower case as per {@link String#toLowerCase()}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.lowerCase(null) = null
* StringUtils.lowerCase("") = ""
* StringUtils.lowerCase("aBc") = "abc"
* </pre>
*
* <p>This uses "ENGLISH" as the locale.
*
* @param str the String to lower case, may be null
* @return the lower cased String, {@code null} if null String input
*/
public static String lowerCase(final String str) {
if (str == null) {
return null;
}
return str.toLowerCase(Locale.ENGLISH);
}
/**
* <p>Capitalizes a String changing the first character to title case as
* per {@link Character#toTitleCase(int)}. No other characters are changed.</p>
*
* <pre>
* StringUtils.capitalize(null) = null
* StringUtils.capitalize("") = ""
* StringUtils.capitalize("cat") = "Cat"
* StringUtils.capitalize("cAt") = "CAt"
* StringUtils.capitalize("'cat'") = "'cat'"
* </pre>
*
* @param str the String to capitalize, may be null
* @return the capitalized String, {@code null} if null String input
* @see #uncapitalize(String)
* @since 2.0
*/
public static String capitalize(final String str) {
if (str == null || str.length() == 0) {
return str;
}
int firstCodepoint = str.codePointAt(0);
int newCodePoint = Character.toTitleCase(firstCodepoint);
if (firstCodepoint == newCodePoint) {
// already capitalized
return str;
}
int[] newCodePoints = new int[str.length()]; // cannot be longer than the char array
int outOffset = 0;
newCodePoints[outOffset++] = newCodePoint; // copy the first codepoint
for (int inOffset = Character.charCount(firstCodepoint); inOffset < str.length(); ) {
int codepoint = str.codePointAt(inOffset);
newCodePoints[outOffset++] = codepoint; // copy the remaining ones
inOffset += Character.charCount(codepoint);
}
return new String(newCodePoints, 0, outOffset);
}
/**
* <p>Uncapitalizes a String, changing the first character to lower case as
* per {@link Character#toLowerCase(int)}. No other characters are changed.</p>
*
* <pre>
* StringUtils.uncapitalize(null) = null
* StringUtils.uncapitalize("") = ""
* StringUtils.uncapitalize("cat") = "cat"
* StringUtils.uncapitalize("Cat") = "cat"
* StringUtils.uncapitalize("CAT") = "cAT"
* </pre>
*
* @param str the String to uncapitalize, may be null
* @return the uncapitalized String, {@code null} if null String input
* @see #capitalize(String)
* @since 2.0
*/
public static String uncapitalize(final String str) {
if (str == null || str.length() == 0) {
return str;
}
int firstCodepoint = str.codePointAt(0);
int newCodePoint = Character.toLowerCase(firstCodepoint);
if (firstCodepoint == newCodePoint) {
// already capitalized
return str;
}
int[] newCodePoints = new int[str.length()]; // cannot be longer than the char array
int outOffset = 0;
newCodePoints[outOffset++] = newCodePoint; // copy the first codepoint
for (int inOffset = Character.charCount(firstCodepoint); inOffset < str.length(); ) {
int codepoint = str.codePointAt(inOffset);
newCodePoints[outOffset++] = codepoint; // copy the remaining ones
inOffset += Character.charCount(codepoint);
}
return new String(newCodePoints, 0, outOffset);
}
/**
* Encode the given bytes as a string using the given charset
* @throws UncheckedIOException with a {@link CharacterCodingException} as the cause if the bytes cannot be encoded using the
* provided charset.
*/
public static String fromBytes(byte[] bytes, Charset charset) throws UncheckedIOException {
try {
return charset.newDecoder().decode(ByteBuffer.wrap(bytes)).toString();
} catch (CharacterCodingException e) {
throw new UncheckedIOException("Cannot encode string.", e);
}
}
/**
* Tests if this string starts with the specified prefix ignoring case considerations.
*
* @param str the string to be tested
* @param prefix the prefix
* @return true if the string starts with the prefix ignoring case
*/
public static boolean startsWithIgnoreCase(String str, String prefix) {
return str.regionMatches(true, 0, prefix, 0, prefix.length());
}
/**
* <p>Replaces a String with another String inside a larger String, once.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replaceOnce(null, *, *) = null
* StringUtils.replaceOnce("", *, *) = ""
* StringUtils.replaceOnce("any", null, *) = "any"
* StringUtils.replaceOnce("any", *, null) = "any"
* StringUtils.replaceOnce("any", "", *) = "any"
* StringUtils.replaceOnce("aba", "a", null) = "aba"
* StringUtils.replaceOnce("aba", "a", "") = "ba"
* StringUtils.replaceOnce("aba", "a", "z") = "zba"
* </pre>
*
* @see #replace(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
*/
public static String replaceOnce(String text, String searchString, String replacement) {
return replace(text, searchString, replacement, 1);
}
/**
* <p>Replaces a String with another String inside a larger String,
* for the first {@code max} values of the search String,
* case sensitively/insensitively based on {@code ignoreCase} value.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *, *, false) = null
* StringUtils.replace("", *, *, *, false) = ""
* StringUtils.replace("any", null, *, *, false) = "any"
* StringUtils.replace("any", *, null, *, false) = "any"
* StringUtils.replace("any", "", *, *, false) = "any"
* StringUtils.replace("any", *, *, 0, false) = "any"
* StringUtils.replace("abaa", "a", null, -1, false) = "abaa"
* StringUtils.replace("abaa", "a", "", -1, false) = "b"
* StringUtils.replace("abaa", "a", "z", 0, false) = "abaa"
* StringUtils.replace("abaa", "A", "z", 1, false) = "abaa"
* StringUtils.replace("abaa", "A", "z", 1, true) = "zbaa"
* StringUtils.replace("abAa", "a", "z", 2, true) = "zbza"
* StringUtils.replace("abAa", "a", "z", -1, true) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for (case insensitive), may be null
* @param replacement the String to replace it with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
*/
public static String replace(String text, String searchString, String replacement) {
return replace(text, searchString, replacement, -1);
}
/**
* <p>Replaces a String with another String inside a larger String,
* for the first {@code max} values of the search String,
* case sensitively/insensitively based on {@code ignoreCase} value.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *, *, false) = null
* StringUtils.replace("", *, *, *, false) = ""
* StringUtils.replace("any", null, *, *, false) = "any"
* StringUtils.replace("any", *, null, *, false) = "any"
* StringUtils.replace("any", "", *, *, false) = "any"
* StringUtils.replace("any", *, *, 0, false) = "any"
* StringUtils.replace("abaa", "a", null, -1, false) = "abaa"
* StringUtils.replace("abaa", "a", "", -1, false) = "b"
* StringUtils.replace("abaa", "a", "z", 0, false) = "abaa"
* StringUtils.replace("abaa", "A", "z", 1, false) = "abaa"
* StringUtils.replace("abaa", "A", "z", 1, true) = "zbaa"
* StringUtils.replace("abAa", "a", "z", 2, true) = "zbza"
* StringUtils.replace("abAa", "a", "z", -1, true) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for (case insensitive), may be null
* @param replacement the String to replace it with, may be null
* @param max maximum number of values to replace, or {@code -1} if no maximum
* @return the text with any replacements processed,
* {@code null} if null String input
*/
private static String replace(String text, String searchString, String replacement, int max) {
if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
return text;
}
int start = 0;
int end = indexOf(text, searchString, start);
if (end == -1) {
return text;
}
int replLength = searchString.length();
int increase = Math.max(replacement.length() - replLength, 0);
increase *= max < 0 ? 16 : Math.min(max, 64);
StringBuilder buf = new StringBuilder(text.length() + increase);
while (end != -1) {
buf.append(text, start, end).append(replacement);
start = end + replLength;
if (--max == 0) {
break;
}
end = indexOf(text, searchString, start);
}
buf.append(text, start, text.length());
return buf.toString();
}
/**
* <p>
* Replaces all occurrences of Strings within another String.
* </p>
*
* <p>
* A {@code null} reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored. This will not repeat. For repeating replaces, call the
* overloaded method.
* </p>
*
* <pre>
* StringUtils.replaceEach(null, *, *) = null
* StringUtils.replaceEach("", *, *) = ""
* StringUtils.replaceEach("aba", null, null) = "aba"
* StringUtils.replaceEach("aba", new String[0], null) = "aba"
* StringUtils.replaceEach("aba", null, new String[0]) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
* (example of how it does not repeat)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte"
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @return the text with any replacements processed, {@code null} if
* null String input
* @throws IllegalArgumentException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
public static String replaceEach(String text, String[] searchList, String[] replacementList) {
// mchyzer Performance note: This creates very few new objects (one major goal)
// let me know if there are performance requests, we can create a harness to measure
if (isEmpty(text)) {
return text;
}
int searchLength = searchList.length;
int replacementLength = replacementList.length;
// make sure lengths are ok, these need to be equal
if (searchLength != replacementLength) {
throw new IllegalArgumentException("Search and Replace array lengths don't match: "
+ searchLength
+ " vs "
+ replacementLength);
}
// keep track of which still have matches
boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];
// index on index that the match was found
int textIndex = -1;
int replaceIndex = -1;
int tempIndex;
// index of replace array that will replace the search string found
// NOTE: logic duplicated below START
for (int i = 0; i < searchLength; i++) {
if (noMoreMatchesForReplIndex[i] || isEmpty(searchList[i]) || replacementList[i] == null) {
continue;
}
tempIndex = text.indexOf(searchList[i]);
// see if we need to keep searching for this
if (tempIndex == -1) {
noMoreMatchesForReplIndex[i] = true;
} else if (textIndex == -1 || tempIndex < textIndex) {
textIndex = tempIndex;
replaceIndex = i;
}
}
// NOTE: logic mostly below END
// no search strings found, we are done
if (textIndex == -1) {
return text;
}
int start = 0;
// get a good guess on the size of the result buffer so it doesn't have to double if it goes over a bit
int increase = 0;
// count the replacement text elements that are larger than their corresponding text being replaced
for (int i = 0; i < searchList.length; i++) {
if (searchList[i] == null || replacementList[i] == null) {
continue;
}
int greater = replacementList[i].length() - searchList[i].length();
if (greater > 0) {
increase += 3 * greater; // assume 3 matches
}
}
// have upper-bound at 20% increase, then let Java take over
increase = Math.min(increase, text.length() / 5);
StringBuilder buf = new StringBuilder(text.length() + increase);
while (textIndex != -1) {
for (int i = start; i < textIndex; i++) {
buf.append(text.charAt(i));
}
buf.append(replacementList[replaceIndex]);
start = textIndex + searchList[replaceIndex].length();
textIndex = -1;
replaceIndex = -1;
// find the next earliest match
// NOTE: logic mostly duplicated above START
for (int i = 0; i < searchLength; i++) {
if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
searchList[i].isEmpty() || replacementList[i] == null) {
continue;
}
tempIndex = text.indexOf(searchList[i], start);
// see if we need to keep searching for this
if (tempIndex == -1) {
noMoreMatchesForReplIndex[i] = true;
} else if (textIndex == -1 || tempIndex < textIndex) {
textIndex = tempIndex;
replaceIndex = i;
}
}
// NOTE: logic duplicated above END
}
int textLength = text.length();
for (int i = start; i < textLength; i++) {
buf.append(text.charAt(i));
}
return buf.toString();
}
/**
* <p>Finds the first index within a CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String, int)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf(*, null) = -1
* StringUtils.indexOf("", "") = 0
* StringUtils.indexOf("", *) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a") = 0
* StringUtils.indexOf("aabaabaa", "b") = 2
* StringUtils.indexOf("aabaabaa", "ab") = 1
* StringUtils.indexOf("aabaabaa", "") = 0
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @return the first index of the search CharSequence,
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from indexOf(String, String) to indexOf(CharSequence, CharSequence)
*/
private static int indexOf(String seq, String searchSeq, int start) {
if (seq == null || searchSeq == null) {
return -1;
}
return seq.indexOf(searchSeq, start);
}
/**
* Replace the prefix of the string provided ignoring case considerations.
*
* <p>
* The unmatched part is unchanged.
*
*
* @param str the string to replace
* @param prefix the prefix to find
* @param replacement the replacement
* @return the replaced string
*/
public static String replacePrefixIgnoreCase(String str, String prefix, String replacement) {
return str.replaceFirst("(?i)" + prefix, replacement);
}
/**
* Searches a string for the first occurrence of a character specified by a list of characters.
* @param s The string to search.
* @param charsToMatch A list of characters to search the string for.
* @return The character that was first matched in the string or null if none of the characters were found.
*/
public static Character findFirstOccurrence(String s, char ...charsToMatch) {
int lowestIndex = Integer.MAX_VALUE;
for (char toMatch : charsToMatch) {
int currentIndex = s.indexOf(toMatch);
if (currentIndex != -1 && currentIndex < lowestIndex) {
lowestIndex = currentIndex;
}
}
return lowestIndex == Integer.MAX_VALUE ? null : s.charAt(lowestIndex);
}
/**
* Convert a string to boolean safely (as opposed to the less strict {@link Boolean#parseBoolean(String)}). If a customer
* specifies a boolean value it should be "true" or "false" (case insensitive) or an exception will be thrown.
*/
public static boolean safeStringToBoolean(String value) {
if (value.equalsIgnoreCase("true")) {
return true;
} else if (value.equalsIgnoreCase("false")) {
return false;
}
throw new IllegalArgumentException("Value was defined as '" + value + "', but should be 'false' or 'true'");
}
/**
* Returns a string whose value is the concatenation of this string repeated {@code count} times.
* <p>
* If this string is empty or count is zero then the empty string is returned.
* <p>
* Logical clone of JDK11's {@link String#repeat(int)}.
*
* @param value the string to repeat
* @param count number of times to repeat
* @return A string composed of this string repeated {@code count} times or the empty string if this string is empty or count
* is zero
* @throws IllegalArgumentException if the {@code count} is negative.
*/
public static String repeat(String value, int count) {
if (count < 0) {
throw new IllegalArgumentException("count is negative: " + count);
}
if (value == null || value.length() == 0 || count == 1) {
return value;
}
if (count == 0) {
return "";
}
if (value.length() > Integer.MAX_VALUE / count) {
throw new OutOfMemoryError("Repeating " + value.length() + " bytes String " + count +
" times will produce a String exceeding maximum size.");
}
int len = value.length();
int limit = len * count;
char[] array = new char[limit];
value.getChars(0, len, array, 0);
int copied;
for (copied = len; copied < limit - copied; copied <<= 1) {
System.arraycopy(array, 0, array, copied, copied);
}
System.arraycopy(array, 0, array, copied, limit - copied);
return new String(array);
}
} | 2,981 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ExecutorUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Utilities that make it easier to create, use and destroy {@link ExecutorService}s.
*/
@SdkProtectedApi
public final class ExecutorUtils {
private ExecutorUtils() {
}
/**
* Create a bounded-queue executor with one thread for performing background tasks. The thread in the service is marked as a
* daemon thread.
*/
public static ExecutorService newSingleDaemonThreadExecutor(int queueCapacity, String threadNameFormat) {
return new ThreadPoolExecutor(0, 1, 5, SECONDS,
new LinkedBlockingQueue<>(queueCapacity),
new ThreadFactoryBuilder().daemonThreads(true).threadNamePrefix(threadNameFormat).build());
}
/**
* Wrap an executor in a type that cannot be closed, or shut down.
*/
public static Executor unmanagedExecutor(Executor executor) {
return new UnmanagedExecutor(executor);
}
private static class UnmanagedExecutor implements Executor {
private final Executor executor;
private UnmanagedExecutor(Executor executor) {
this.executor = executor;
}
@Override
public void execute(Runnable command) {
executor.execute(command);
}
}
}
| 2,982 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/NamedThreadFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* An decorator for {@link ThreadFactory} that allows naming threads based on a format.
*/
@SdkProtectedApi
public class NamedThreadFactory implements ThreadFactory {
private final ThreadFactory delegate;
private final String namePrefix;
private final AtomicInteger threadCount = new AtomicInteger(0);
public NamedThreadFactory(ThreadFactory delegate, String namePrefix) {
this.delegate = Validate.notNull(delegate, "delegate must not be null");
this.namePrefix = Validate.notBlank(namePrefix, "namePrefix must not be blank");
}
@Override
public Thread newThread(Runnable runnable) {
Thread thread = delegate.newThread(runnable);
thread.setName(namePrefix + "-" + threadCount.getAndIncrement());
return thread;
}
}
| 2,983 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/FunctionalUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.slf4j.Logger;
import software.amazon.awssdk.annotations.SdkProtectedApi;
@SdkProtectedApi
public final class FunctionalUtils {
private FunctionalUtils() {
}
/**
* Runs a given {@link UnsafeRunnable} and logs an error without throwing.
*
* @param errorMsg Message to log with exception thrown.
* @param runnable Action to perform.
*/
public static void runAndLogError(Logger log, String errorMsg, UnsafeRunnable runnable) {
try {
runnable.run();
} catch (Exception e) {
log.error(errorMsg, e);
}
}
/**
* @param <T> Type of object to be consumed.
* @return A {@link Consumer} that does nothing.
*/
public static <T> Consumer<T> noOpConsumer() {
return ignored -> {
};
}
/**
* @return A {@link Runnable} that does nothing.
*/
public static Runnable noOpRunnable() {
return () -> {
};
}
/**
* A wrapper around a Consumer that throws a checked exception.
*
* @param unsafeConsumer - something that acts like a consumer but throws an exception
* @return a consumer that is wrapped in a try-catch converting the checked exception into a runtime exception
*/
public static <I> Consumer<I> safeConsumer(UnsafeConsumer<I> unsafeConsumer) {
return (input) -> {
try {
unsafeConsumer.accept(input);
} catch (Exception e) {
throw asRuntimeException(e);
}
};
}
/**
* Takes a functional interface that throws an exception and returns a {@link Function} that deals with that exception by
* wrapping in a runtime exception. Useful for APIs that use the standard Java functional interfaces that don't throw checked
* exceptions.
*
* @param unsafeFunction Functional interface that throws checked exception.
* @param <T> Input
* @param <R> Output
* @return New {@link Function} that handles checked exception.
*/
public static <T, R> Function<T, R> safeFunction(UnsafeFunction<T, R> unsafeFunction) {
return t -> {
try {
return unsafeFunction.apply(t);
} catch (Exception e) {
throw asRuntimeException(e);
}
};
}
/**
* A wrapper around a BiConsumer that throws a checked exception.
*
* @param unsafeSupplier - something that acts like a BiConsumer but throws an exception
* @return a consumer that is wrapped in a try-catch converting the checked exception into a runtime exception
*/
public static <T> Supplier<T> safeSupplier(UnsafeSupplier<T> unsafeSupplier) {
return () -> {
try {
return unsafeSupplier.get();
} catch (Exception e) {
throw asRuntimeException(e);
}
};
}
/**
* A wrapper around a Runnable that throws a checked exception.
*
* @param unsafeRunnable Something that acts like a Runnable but throws an exception
* @return A Runnable that is wrapped in a try-catch converting the checked exception into a runtime exception
*/
public static Runnable safeRunnable(UnsafeRunnable unsafeRunnable) {
return () -> {
try {
unsafeRunnable.run();
} catch (Exception e) {
throw asRuntimeException(e);
}
};
}
public static <I, O> Function<I, O> toFunction(Supplier<O> supplier) {
return ignore -> supplier.get();
}
public static <T> T invokeSafely(UnsafeSupplier<T> unsafeSupplier) {
return safeSupplier(unsafeSupplier).get();
}
public static void invokeSafely(UnsafeRunnable unsafeRunnable) {
safeRunnable(unsafeRunnable).run();
}
/**
* Equivalent of {@link Consumer} that throws a checked exception.
*/
@FunctionalInterface
public interface UnsafeConsumer<I> {
void accept(I input) throws Exception;
}
/**
* Equivalent of {@link Function} that throws a checked exception.
*/
@FunctionalInterface
public interface UnsafeFunction<T, R> {
R apply(T t) throws Exception;
}
/**
* Equivalent of {@link Supplier} that throws a checked exception.
*/
@FunctionalInterface
public interface UnsafeSupplier<T> {
T get() throws Exception;
}
/**
* Equivalent of {@link Runnable} that throws a checked exception.
*/
@FunctionalInterface
public interface UnsafeRunnable {
void run() throws Exception;
}
private static RuntimeException asRuntimeException(Exception exception) {
if (exception instanceof RuntimeException) {
return (RuntimeException) exception;
}
if (exception instanceof IOException) {
return new UncheckedIOException((IOException) exception);
}
if (exception instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
return new RuntimeException(exception);
}
}
| 2,984 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/UnmodifiableMapOfLists.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.io.Serializable;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* An unmodifiable view of a {@code Map<T, List<U>>}. Created using {@link CollectionUtils#unmodifiableMapOfLists(Map)}.
*/
@SdkInternalApi
class UnmodifiableMapOfLists<T, U> implements Map<T, List<U>>, Serializable {
private static final long serialVersionUID = 1L;
private final Map<T, List<U>> delegate;
UnmodifiableMapOfLists(Map<T, List<U>> delegate) {
this.delegate = delegate;
}
@Override
public int size() {
return delegate.size();
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return delegate.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return delegate.containsValue(value);
}
@Override
public List<U> get(Object key) {
return delegate.get(key);
}
@Override
public List<U> getOrDefault(Object key, List<U> defaultValue) {
return unmodifiableList(delegate.getOrDefault(key, defaultValue));
}
@Override
public List<U> put(T key, List<U> value) {
throw new UnsupportedOperationException();
}
@Override
public List<U> remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map<? extends T, ? extends List<U>> m) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public Set<T> keySet() {
return Collections.unmodifiableSet(delegate.keySet());
}
@Override
public Collection<List<U>> values() {
return new UnmodifiableCollection<>(delegate.values());
}
@Override
public Set<Entry<T, List<U>>> entrySet() {
Set<? extends Entry<T, ? extends List<U>>> entries = delegate.entrySet();
return new UnmodifiableEntrySet<>(entries);
}
@Override
public void forEach(BiConsumer<? super T, ? super List<U>> action) {
delegate.forEach((k, v) -> action.accept(k, unmodifiableList(v)));
}
@Override
public void replaceAll(BiFunction<? super T, ? super List<U>, ? extends List<U>> function) {
throw new UnsupportedOperationException();
}
@Override
public List<U> putIfAbsent(T key, List<U> value) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object key, Object value) {
throw new UnsupportedOperationException();
}
@Override
public boolean replace(T key, List<U> oldValue, List<U> newValue) {
throw new UnsupportedOperationException();
}
@Override
public List<U> replace(T key, List<U> value) {
throw new UnsupportedOperationException();
}
@Override
public List<U> computeIfAbsent(T key, Function<? super T, ? extends List<U>> mappingFunction) {
throw new UnsupportedOperationException();
}
@Override
public List<U> computeIfPresent(T key, BiFunction<? super T, ? super List<U>, ? extends List<U>> remappingFunction) {
throw new UnsupportedOperationException();
}
@Override
public List<U> compute(T key, BiFunction<? super T, ? super List<U>, ? extends List<U>> remappingFunction) {
throw new UnsupportedOperationException();
}
@Override
public List<U> merge(T key, List<U> value,
BiFunction<? super List<U>, ? super List<U>, ? extends List<U>> remappingFunction) {
throw new UnsupportedOperationException();
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public boolean equals(Object obj) {
return delegate.equals(obj);
}
@Override
public String toString() {
return delegate.toString();
}
private static class UnmodifiableEntrySet<T, U> implements Set<Entry<T, List<U>>> {
private final Set<? extends Entry<T, ? extends List<U>>> delegate;
private UnmodifiableEntrySet(Set<? extends Entry<T, ? extends List<U>>> delegate) {
this.delegate = delegate;
}
@Override
public int size() {
return delegate.size();
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public boolean contains(Object o) {
return delegate.contains(o);
}
@Override
public Iterator<Entry<T, List<U>>> iterator() {
return new UnmodifiableEntryIterator<>(delegate.iterator());
}
@Override
public void forEach(Consumer<? super Entry<T, List<U>>> action) {
delegate.forEach(e -> action.accept(new SimpleImmutableEntry<>(e.getKey(), unmodifiableList(e.getValue()))));
}
@Override
@SuppressWarnings("unchecked")
public Object[] toArray() {
Object[] result = delegate.toArray();
for (int i = 0; i < result.length; i++) {
Entry<T, List<U>> e = (Entry<T, List<U>>) result[i];
result[i] = new SimpleImmutableEntry<>(e.getKey(), unmodifiableList(e.getValue()));
}
return result;
}
@Override
@SuppressWarnings("unchecked")
public <A> A[] toArray(A[] a) {
// Technically this could give the caller access very brief access to the modifiable entries from a different thread,
// but that's on them. They had to have done it purposefully with a different thread, and it wouldn't be very
// reliable.
Object[] result = delegate.toArray(a);
for (int i = 0; i < result.length; i++) {
Entry<T, List<U>> e = (Entry<T, List<U>>) result[i];
result[i] = new SimpleImmutableEntry<>(e.getKey(), unmodifiableList(e.getValue()));
}
return (A[]) result;
}
@Override
public boolean add(Entry<T, List<U>> tListEntry) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> c) {
return delegate.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends Entry<T, List<U>>> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public boolean equals(Object obj) {
return delegate.equals(obj);
}
@Override
public String toString() {
return delegate.toString();
}
}
private static class UnmodifiableEntryIterator<T, U> implements Iterator<Entry<T, List<U>>> {
private final Iterator<? extends Entry<T, ? extends List<U>>> delegate;
private UnmodifiableEntryIterator(Iterator<? extends Entry<T, ? extends List<U>>> delegate) {
this.delegate = delegate;
}
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public Entry<T, List<U>> next() {
Entry<T, ? extends List<U>> next = delegate.next();
return new SimpleImmutableEntry<>(next.getKey(), unmodifiableList(next.getValue()));
}
}
private static class UnmodifiableCollection<U> implements Collection<List<U>> {
private final Collection<? extends List<U>> delegate;
private UnmodifiableCollection(Collection<? extends List<U>> delegate) {
this.delegate = delegate;
}
@Override
public int size() {
return delegate.size();
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public boolean contains(Object o) {
return delegate.contains(o);
}
@Override
public Iterator<List<U>> iterator() {
return new UnmodifiableListIterator<>(delegate.iterator());
}
@Override
@SuppressWarnings("unchecked")
public Object[] toArray() {
Object[] result = delegate.toArray();
for (int i = 0; i < result.length; i++) {
result[i] = unmodifiableList((List<U>) result[i]);
}
return result;
}
@Override
@SuppressWarnings("unchecked")
public <A> A[] toArray(A[] a) {
// Technically this could give the caller access very brief access to the modifiable entries from a different thread,
// but that's on them. They had to have done it purposefully with a different thread, and it wouldn't be very
// reliable.
Object[] result = delegate.toArray(a);
for (int i = 0; i < result.length; i++) {
result[i] = unmodifiableList((List<U>) result[i]);
}
return (A[]) result;
}
@Override
public boolean add(List<U> us) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> c) {
return delegate.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends List<U>> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public boolean equals(Object obj) {
return delegate.equals(obj);
}
@Override
public String toString() {
return delegate.toString();
}
}
private static class UnmodifiableListIterator<U> implements Iterator<List<U>> {
private final Iterator<? extends List<U>> delegate;
private UnmodifiableListIterator(Iterator<? extends List<U>> delegate) {
this.delegate = delegate;
}
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public List<U> next() {
return unmodifiableList(delegate.next());
}
@Override
public int hashCode() {
return delegate.hashCode();
}
@Override
public boolean equals(Object obj) {
return delegate.equals(obj);
}
@Override
public String toString() {
return delegate.toString();
}
}
private static <T> List<T> unmodifiableList(List<T> list) {
if (list == null) {
return null;
}
return Collections.unmodifiableList(list);
}
}
| 2,985 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ClassLoaderHelper.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import software.amazon.awssdk.annotations.SdkProtectedApi;
@SdkProtectedApi
public final class ClassLoaderHelper {
private ClassLoaderHelper() {
}
private static Class<?> loadClassViaClasses(String fqcn, Class<?>[] classes) {
if (classes == null) {
return null;
}
for (Class<?> clzz: classes) {
if (clzz == null) {
continue;
}
ClassLoader loader = clzz.getClassLoader();
if (loader != null) {
try {
return loader.loadClass(fqcn);
} catch (ClassNotFoundException e) {
// move on to try the next class loader
}
}
}
return null;
}
private static Class<?> loadClassViaContext(String fqcn) {
ClassLoader loader = contextClassLoader();
try {
return loader == null ? null : loader.loadClass(fqcn);
} catch (ClassNotFoundException e) {
// Ignored.
}
return null;
}
/**
* Loads the class via the optionally specified classes in the order of
* their specification, and if not found, via the context class loader of
* the current thread, and if not found, from the caller class loader as the
* last resort.
*
* @param fqcn
* fully qualified class name of the target class to be loaded
* @param classes
* class loader providers
* @return the class loaded; never null
*
* @throws ClassNotFoundException
* if failed to load the class
*/
public static Class<?> loadClass(String fqcn, Class<?>... classes) throws ClassNotFoundException {
return loadClass(fqcn, true, classes);
}
/**
* If classesFirst is false, loads the class via the context class
* loader of the current thread, and if not found, via the class loaders of
* the optionally specified classes in the order of their specification, and
* if not found, from the caller class loader as the
* last resort.
* <p>
* If classesFirst is true, loads the class via the optionally
* specified classes in the order of their specification, and if not found,
* via the context class loader of the current thread, and if not found,
* from the caller class loader as the last resort.
*
* @param fqcn
* fully qualified class name of the target class to be loaded
* @param classesFirst
* true if the class loaders of the optionally specified classes
* take precedence over the context class loader of the current
* thread; false if the opposite is true.
* @param classes
* class loader providers
* @return the class loaded; never null
*
* @throws ClassNotFoundException if failed to load the class
*/
public static Class<?> loadClass(String fqcn, boolean classesFirst,
Class<?>... classes) throws ClassNotFoundException {
Class<?> target = null;
if (classesFirst) {
target = loadClassViaClasses(fqcn, classes);
if (target == null) {
target = loadClassViaContext(fqcn);
}
} else {
target = loadClassViaContext(fqcn);
if (target == null) {
target = loadClassViaClasses(fqcn, classes);
}
}
return target == null ? Class.forName(fqcn) : target;
}
/**
* Attempt to get the current thread's class loader and fallback to the system classloader if null
* @return a {@link ClassLoader} or null if none found
*/
private static ClassLoader contextClassLoader() {
ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();
if (threadClassLoader != null) {
return threadClassLoader;
}
return ClassLoader.getSystemClassLoader();
}
/**
* Attempt to get class loader that loads the classes and fallback to the thread context classloader if null.
*
* @param classes the classes
* @return a {@link ClassLoader} or null if none found
*/
public static ClassLoader classLoader(Class<?>... classes) {
if (classes != null) {
for (Class clzz : classes) {
ClassLoader classLoader = clzz.getClassLoader();
if (classLoader != null) {
return classLoader;
}
}
}
return contextClassLoader();
}
} | 2,986 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/AttributeMap.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.function.Function;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.ToBuilderIgnoreField;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A map from {@code AttributeMap.Key<T>} to {@code T} that ensures the values stored with a key matches the type associated with
* the key. This does not implement {@link Map} because it has more strict typing requirements, but a {@link Map} can be
* converted
* to an {code AttributeMap} via the type-unsafe {@link AttributeMap} method.
*
* This can be used for storing configuration values ({@code OptionKey.LOG_LEVEL} to {@code Boolean.TRUE}), attaching
* arbitrary attributes to a request chain ({@code RequestAttribute.CONFIGURATION} to {@code ClientConfiguration}) or similar
* use-cases.
*/
@SdkProtectedApi
@Immutable
public final class AttributeMap implements ToCopyableBuilder<AttributeMap.Builder, AttributeMap>, SdkAutoCloseable {
private static final AttributeMap EMPTY = AttributeMap.builder().build();
private final Map<Key<?>, Value<?>> attributes;
private final DependencyGraph dependencyGraph;
private AttributeMap(Builder builder) {
this.attributes = builder.attributes;
this.dependencyGraph = builder.dependencyGraph;
}
/**
* Return true if the provided key is configured in this map. Useful for differentiating between whether the provided key was
* not configured in the map or if it is configured, but its value is null.
*/
public <T> boolean containsKey(Key<T> typedKey) {
return attributes.containsKey(typedKey);
}
/**
* Get the value associated with the provided key from this map. This will return null if the value is not set or if the
* value stored is null. These cases can be disambiguated using {@link #containsKey(Key)}.
*/
public <T> T get(Key<T> key) {
Validate.notNull(key, "Key to retrieve must not be null.");
Value<?> value = attributes.get(key);
if (value == null) {
return null;
}
return key.convertValue(value.get(new ExpectCachedLazyValueSource()));
}
/**
* Merges two AttributeMaps into one. This object is given higher precedence then the attributes passed in as a parameter.
*
* @param lowerPrecedence Options to merge into 'this' AttributeMap object. Any attribute already specified in 'this' object
* will be left as is since it has higher precedence.
* @return New options with values merged.
*/
public AttributeMap merge(AttributeMap lowerPrecedence) {
Builder resultBuilder = new AttributeMap.Builder(this);
lowerPrecedence.attributes.forEach((k, v) -> {
resultBuilder.internalComputeIfAbsent(k, () -> {
Value<?> result = v.copy();
result.clearCache();
return result;
});
});
return resultBuilder.build();
}
public static AttributeMap empty() {
return EMPTY;
}
@Override
public void close() {
attributes.values().forEach(Value::close);
}
/**
* An abstract class extended by pseudo-enums defining the key for data that is stored in the {@link AttributeMap}. For
* example, a {@code ClientOption<T>} may extend this to define options that can be stored in an {@link AttributeMap}.
*/
public abstract static class Key<T> {
private final Class<?> valueType;
private final Function<Object, T> convertMethod;
protected Key(Class<T> valueType) {
this.valueType = valueType;
this.convertMethod = valueType::cast;
}
protected Key(UnsafeValueType unsafeValueType) {
this.valueType = unsafeValueType.valueType;
this.convertMethod = v -> (T) v; // 🙏
}
@Override
public String toString() {
return "Key(" + valueType.getName() + ")";
}
/**
* Useful for parameterized types.
*/
protected static class UnsafeValueType {
private final Class<?> valueType;
public UnsafeValueType(Class<?> valueType) {
this.valueType = valueType;
}
}
/**
* Validate the provided value is of the correct type and convert it to the proper type for this option.
*/
public final T convertValue(Object value) {
return convertMethod.apply(value);
}
}
@Override
public String toString() {
return attributes.toString();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof AttributeMap)) {
return false;
}
AttributeMap rhs = (AttributeMap) obj;
if (attributes.size() != rhs.attributes.size()) {
return false;
}
for (Key<?> lhsKey : attributes.keySet()) {
Object lhsValue = get(lhsKey);
Object rhsValue = rhs.get(lhsKey);
if (!Objects.equals(lhsValue, rhsValue)) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
for (Key<?> key : attributes.keySet()) {
hashCode = 31 * hashCode + Objects.hashCode(get(key));
}
return hashCode;
}
public AttributeMap copy() {
return toBuilder().build();
}
@Override
@ToBuilderIgnoreField("configuration")
public Builder toBuilder() {
return new Builder(this);
}
public static Builder builder() {
return new Builder();
}
public static final class Builder implements CopyableBuilder<Builder, AttributeMap> {
private Map<Key<?>, Value<?>> attributes;
private DependencyGraph dependencyGraph;
private boolean copyOnUpdate;
private Builder() {
this.attributes = new HashMap<>();
this.dependencyGraph = new DependencyGraph();
this.copyOnUpdate = false;
}
private Builder(AttributeMap attributeMap) {
this.attributes = attributeMap.attributes;
this.dependencyGraph = attributeMap.dependencyGraph;
this.copyOnUpdate = true;
}
private Builder(Builder builder) {
this.attributes = builder.attributes;
this.dependencyGraph = builder.dependencyGraph;
this.copyOnUpdate = true;
checkCopyOnUpdate(); // Proactively copy the values out of the source builder.
}
/**
* Get the value for the provided key.
*/
public <T> T get(Key<T> key) {
return key.convertValue(internalGet(null, key));
}
/**
* Add a mapping between the provided key and value, if the current value for the key is null. Returns the value.
*/
public <T> T computeIfAbsent(Key<T> key, Supplier<T> valueIfAbsent) {
Validate.notNull(key, "Key to set must not be null.");
Value<?> result = internalComputeIfAbsent(key, () -> {
T value = valueIfAbsent.get();
return new ConstantValue<>(value);
});
return key.convertValue(resolveValue(result));
}
/**
* Add a mapping between the provided key and value.
*/
public <T> Builder put(Key<T> key, T value) {
Validate.notNull(key, "Key to set must not be null.");
internalPut(key, new ConstantValue<>(value));
return this;
}
/**
* Add a mapping between the provided key and value provider.
*
* The lazy value will only be resolved when the value is needed. During resolution, the lazy value is provided with a
* value reader. The value reader will fail if the reader attempts to read its own value (directly, or indirectly
* through other lazy values).
*
* If a value is updated that a lazy value is depended on, the lazy value will be re-resolved the next time the lazy
* value is accessed.
*/
public <T> Builder putLazy(Key<T> key, LazyValue<T> lazyValue) {
Validate.notNull(key, "Key to set must not be null.");
internalPut(key, new DerivedValue<>(lazyValue));
return this;
}
/**
* Equivalent to {@link #putLazy(Key, LazyValue)}, but does not assign the value if there is
* already a non-null value assigned for the provided key.
*/
public <T> Builder putLazyIfAbsent(Key<T> key, LazyValue<T> lazyValue) {
Validate.notNull(key, "Key to set must not be null.");
internalComputeIfAbsent(key, () -> new DerivedValue<>(lazyValue));
return this;
}
/**
* Adds all the attributes from the map provided. This is not type safe, and will throw an exception during creation if
* a value in the map is not of the correct type for its key.
*/
public Builder putAll(Map<? extends Key<?>, ?> attributes) {
attributes.forEach(this::unsafeInternalPutConstant);
return this;
}
/**
* Put all of the attributes from the provided map into this one. This will resolve lazy attributes and store their
* value as a constant, so this should only be used when the source attributes are constants or it's okay that the
* values will no longer be lazy.
*/
public Builder putAll(AttributeMap attributes) {
attributes.attributes.forEach((k, v) -> unsafeInternalPutConstant(k, attributes.get(k)));
return this;
}
/**
* Equivalent to {@link #internalPut(Key, Value)} with a constant value, but uses runtime check to verify the value.
* This is useful when type safety of the value isn't possible.
*/
private <T> void unsafeInternalPutConstant(Key<T> key, Object value) {
try {
T tValue = key.convertValue(value);
internalPut(key, new ConstantValue<>(tValue));
} catch (ClassCastException e) {
throw new IllegalArgumentException("Cannot write " + value.getClass() + " type to key " + key, e);
}
}
/**
* Update the value for the provided key.
*/
private void internalPut(Key<?> key, Value<?> value) {
Validate.notNull(value, "Value must not be null.");
checkCopyOnUpdate();
Value<?> oldValue = attributes.put(key, value);
if (oldValue != null) {
dependencyGraph.valueUpdated(oldValue, value);
}
}
/**
* If the current value for the provided key is null (or doesn't exist), set it using the provided value supplier.
* Returns the new value that was set.
*/
private Value<?> internalComputeIfAbsent(Key<?> key, Supplier<Value<?>> value) {
checkCopyOnUpdate();
return attributes.compute(key, (k, v) -> {
if (v == null || resolveValue(v) == null) {
Value<?> newValue = value.get();
Validate.notNull(newValue, "Supplied value must not be null.");
if (v != null) {
dependencyGraph.valueUpdated(v, newValue);
}
return newValue;
}
return v;
});
}
private void checkCopyOnUpdate() {
if (copyOnUpdate) {
Map<Key<?>, Value<?>> attributesToCopy = attributes;
attributes = new HashMap<>(attributesToCopy.size());
Map<Value<?>, Value<?>> valueRemapping = new IdentityHashMap<>(attributesToCopy.size());
attributesToCopy.forEach((k, v) -> {
Value<?> newValue = v.copy();
valueRemapping.put(v, newValue);
attributes.put(k, newValue);
});
dependencyGraph = dependencyGraph.copy(valueRemapping);
copyOnUpdate = false;
}
}
@Override
public AttributeMap build() {
// Resolve all of the attributes ahead of creating the attribute map, so that values can be read without any magic.
Collection<Value<?>> valuesToPrime = new ArrayList<>(this.attributes.values());
valuesToPrime.forEach(this::resolveValue);
copyOnUpdate = true;
return new AttributeMap(this);
}
@Override
public Builder copy() {
return new Builder(this);
}
/**
* Retrieve the value for the provided key, with the provided requesting value (used for tracking consumers in the
* dependency graph). Requester may be null if this isn't a call within a derived value.
*/
private <T> T internalGet(Value<?> requester, Key<T> key) {
Validate.notNull(key, "Key to retrieve must not be null.");
Value<?> value;
if (requester != null) {
checkCopyOnUpdate();
value = attributes.computeIfAbsent(key, k -> new ConstantValue<>(null));
dependencyGraph.addDependency(requester, value);
} else {
value = attributes.get(key);
if (value == null) {
return null;
}
}
return key.convertValue(resolveValue(value));
}
/**
* Resolve the provided value, making sure to record any of its dependencies in the dependency graph.
*/
private <T> T resolveValue(Value<T> value) {
return value.get(new LazyValueSource() {
@Override
public <U> U get(Key<U> innerKey) {
return internalGet(value, innerKey);
}
});
}
}
/**
* A value that is evaluated lazily. See {@link Builder#putLazy(Key, LazyValue)}.
*/
@FunctionalInterface
public interface LazyValue<T> {
T get(LazyValueSource source);
}
/**
* A source for other values, provided to a {@link LazyValue} when the value is resolved.
*/
@FunctionalInterface
public interface LazyValueSource {
<T> T get(Key<T> sourceKey);
}
/**
* Tracks which values "depend on" other values, so that when we update one value, when can clear the cache of any other
* values that were derived from the value that was updated.
*/
private static final class DependencyGraph {
/**
* Inverted adjacency list of dependencies between derived values. Mapping from a value to what depends on that value.
*/
private final Map<Value<?>, Set<Value<?>>> dependents;
private DependencyGraph() {
this.dependents = new IdentityHashMap<>();
}
private DependencyGraph(DependencyGraph source,
Map<Value<?>, Value<?>> valueRemapping) {
this.dependents = new IdentityHashMap<>(source.dependents.size());
source.dependents.forEach((key, values) -> {
Set<Value<?>> newValues = new HashSet<>(values.size());
Value<?> remappedKey = valueRemapping.get(key);
Validate.notNull(remappedKey, "Remapped key must not be null.");
this.dependents.put(remappedKey, newValues);
values.forEach(v -> {
Value<?> remappedValue = valueRemapping.get(v);
Validate.notNull(remappedValue, "Remapped value must not be null.");
newValues.add(remappedValue);
});
});
}
private void addDependency(Value<?> consumer, Value<?> dependency) {
Validate.notNull(consumer, "Consumer must not be null.");
dependents.computeIfAbsent(dependency, k -> new HashSet<>()).add(consumer);
}
private void valueUpdated(Value<?> oldValue, Value<?> newValue) {
if (oldValue == newValue) {
// Optimization: if we didn't actually update the value, do nothing.
return;
}
CachedValue<?> oldCachedValue = oldValue.cachedValue();
CachedValue<?> newCachedValue = newValue.cachedValue();
if (!CachedValue.haveSameCachedValues(oldCachedValue, newCachedValue)) {
// Optimization: don't invalidate consumer caches if the value hasn't changed.
invalidateConsumerCaches(oldValue);
}
Set<Value<?>> oldValueDependents = dependents.remove(oldValue);
if (oldValueDependents != null) {
dependents.put(newValue, oldValueDependents);
}
// TODO: Explore optimizations to not have to update every dependent value.
dependents.values().forEach(v -> {
if (v.remove(oldValue)) {
v.add(newValue);
}
});
}
private void invalidateConsumerCaches(Value<?> value) {
Queue<Value<?>> unloadQueue = new ArrayDeque<>();
unloadQueue.add(value);
while (!unloadQueue.isEmpty()) {
Value<?> toUnload = unloadQueue.poll();
toUnload.clearCache();
Set<Value<?>> toUnloadDependents = dependents.remove(toUnload);
if (toUnloadDependents != null) {
unloadQueue.addAll(toUnloadDependents);
}
}
}
public DependencyGraph copy(Map<Value<?>, Value<?>> valueRemapping) {
return new DependencyGraph(this, valueRemapping);
}
}
/**
* A value stored in this attribute map.
*/
private interface Value<T> extends SdkAutoCloseable {
/**
* Resolve the stored value using the provided value source.
*/
T get(LazyValueSource source);
/**
* Copy this value, so that modifications like {@link #clearCache()} on this object do not affect the copy.
*/
Value<T> copy();
/**
* If this value is cached, clear that cache.
*/
void clearCache();
/**
* Read the cached value. This will return null if there is no value currently cached.
*/
CachedValue<T> cachedValue();
}
/**
* A constant (unchanging) {@link Value}.
*/
private static class ConstantValue<T> implements Value<T> {
private final T value;
private ConstantValue(T value) {
this.value = value;
}
@Override
public T get(LazyValueSource source) {
return value;
}
@Override
public Value<T> copy() {
return this;
}
@Override
public void clearCache() {
}
@Override
public CachedValue<T> cachedValue() {
return new CachedValue<>(value);
}
@Override
public void close() {
closeIfPossible(value);
}
@Override
public String toString() {
return "Value(" + value + ")";
}
}
/**
* A value that is derived from other {@link Value}s.
*/
private static final class DerivedValue<T> implements Value<T> {
private final LazyValue<T> lazyValue;
private boolean valueCached = false;
private T value;
private boolean onStack = false;
private DerivedValue(LazyValue<T> lazyValue) {
this.lazyValue = lazyValue;
}
private DerivedValue(LazyValue<T> lazyValue, boolean valueCached, T value) {
this.lazyValue = lazyValue;
this.valueCached = valueCached;
this.value = value;
}
@Override
public T get(LazyValueSource source) {
primeCache(source);
return value;
}
private void primeCache(LazyValueSource source) {
if (!valueCached) {
if (onStack) {
throw new IllegalStateException("Derived key attempted to read itself");
}
try {
onStack = true;
value = lazyValue.get(source);
} finally {
onStack = false;
}
valueCached = true;
}
}
@Override
public Value<T> copy() {
return new DerivedValue<>(lazyValue, valueCached, value);
}
@Override
public void clearCache() {
valueCached = false;
}
@Override
public CachedValue<T> cachedValue() {
if (!valueCached) {
return null;
}
return new CachedValue<>(value);
}
@Override
public void close() {
closeIfPossible(value);
}
@Override
public String toString() {
if (valueCached) {
return "Value(" + value + ")";
}
return "Value(<<lazy>>)";
}
}
private static class CachedValue<T> {
private final T value;
private CachedValue(T value) {
this.value = value;
}
private static boolean haveSameCachedValues(CachedValue<?> lhs, CachedValue<?> rhs) {
// If one is null, we can't guarantee that they have the same cached value.
if (lhs == null || rhs == null) {
return false;
}
return lhs.value == rhs.value;
}
}
/**
* An implementation of {@link LazyValueSource} that expects all values to be cached.
*/
static class ExpectCachedLazyValueSource implements LazyValueSource {
@Override
public <T> T get(Key<T> sourceKey) {
throw new IllegalStateException("Value should be cached.");
}
}
private static void closeIfPossible(Object object) {
// We're explicitly checking for whether the provided object is an ExecutorService instance, because as of
// Java 21, it extends AutoCloseable, which triggers an ExecutorService#close call, which in turn can
// result in deadlocks. Instead, we safely shut it down, and close any other objects that are closeable.
if (object instanceof ExecutorService) {
((ExecutorService) object).shutdown();
} else {
IoUtils.closeIfCloseable(object, null);
}
}
}
| 2,987 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/LookaheadInputStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* A wrapper for an {@link InputStream} that allows {@link #peek()}ing one byte ahead in the stream. This is useful for
* detecting the end of a stream without actually consuming any data in the process (e.g. so the stream can be passed to
* another library that doesn't handle end-of-stream as the first byte well).
*/
@SdkProtectedApi
public class LookaheadInputStream extends FilterInputStream {
private Integer next;
private Integer nextAtMark;
public LookaheadInputStream(InputStream in) {
super(in);
}
public int peek() throws IOException {
if (next == null) {
next = read();
}
return next;
}
@Override
public int read() throws IOException {
if (next == null) {
return super.read();
}
Integer next = this.next;
this.next = null;
return next;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (next == null) {
return super.read(b, off, len);
}
if (len == 0) {
return 0;
}
if (next == -1) {
return -1;
}
b[off] = (byte) (int) next;
next = null;
if (len == 1) {
return 1;
}
return super.read(b, off + 1, b.length - 1) + 1;
}
@Override
public long skip(long n) throws IOException {
if (next == null) {
return super.skip(n);
}
if (n == 0) {
return 0;
}
if (next == -1) {
return 0;
}
next = null;
if (n == 1) {
return 1;
}
return super.skip(n - 1);
}
@Override
public int available() throws IOException {
if (next == null) {
return super.available();
}
return super.available() + 1;
}
@Override
public synchronized void mark(int readlimit) {
if (next == null) {
super.mark(readlimit);
} else {
nextAtMark = next;
super.mark(readlimit - 1);
}
}
@Override
public synchronized void reset() throws IOException {
next = nextAtMark;
super.reset();
}
}
| 2,988 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Pair.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static software.amazon.awssdk.utils.Validate.paramNotNull;
import java.util.function.BiFunction;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Simple struct of two values, possibly of different types.
*
* @param <LeftT> Left type
* @param <RightT> Right Type
*/
@SdkProtectedApi
public final class Pair<LeftT, RightT> {
private final LeftT left;
private final RightT right;
private Pair(LeftT left, RightT right) {
this.left = paramNotNull(left, "left");
this.right = paramNotNull(right, "right");
}
/**
* @return Left value
*/
public LeftT left() {
return this.left;
}
/**
* @return Right value
*/
public RightT right() {
return this.right;
}
/**
* Apply the function to both the left and right values and return the transformed result.
*
* @param function Function to apply on the {@link Pair}
* @param <ReturnT> Transformed return type of {@link BiFunction}.
* @return Result of {@link BiFunction} applied on left and right values of the pair.
*/
public <ReturnT> ReturnT apply(BiFunction<LeftT, RightT, ReturnT> function) {
return function.apply(left, right);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair)) {
return false;
}
Pair other = (Pair) obj;
return other.left.equals(left) && other.right.equals(right);
}
@Override
public int hashCode() {
return getClass().hashCode() + left.hashCode() + right.hashCode();
}
@Override
public String toString() {
return "Pair(left=" + left + ", right=" + right + ")";
}
public static <LeftT, RightT> Pair<LeftT, RightT> of(LeftT left, RightT right) {
return new Pair<>(left, right);
}
}
| 2,989 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/BinaryUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.io.ByteArrayInputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.internal.Base16Lower;
/**
* Utilities for encoding and decoding binary data to and from different forms.
*/
@SdkProtectedApi
public final class BinaryUtils {
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
private BinaryUtils() {
}
/**
* Converts byte data to a Hex-encoded string in lower case.
*
* @param data
* data to hex encode.
*
* @return hex-encoded string.
*/
public static String toHex(byte[] data) {
return Base16Lower.encodeAsString(data);
}
/**
* Converts a Hex-encoded data string to the original byte data.
*
* @param hexData
* hex-encoded data to decode.
* @return decoded data from the hex string.
*/
public static byte[] fromHex(String hexData) {
return Base16Lower.decode(hexData);
}
/**
* Converts byte data to a Base64-encoded string.
* @param data
*
* data to Base64 encode.
* @return encoded Base64 string.
*/
public static String toBase64(byte[] data) {
return data == null ? null : new String(toBase64Bytes(data), StandardCharsets.UTF_8);
}
/**
* Converts byte data to a Base64-encoded string.
* @param data
*
* data to Base64 encode.
* @return encoded Base64 string.
*/
public static byte[] toBase64Bytes(byte[] data) {
return data == null ? null : Base64.getEncoder().encode(data);
}
/**
* Converts a Base64-encoded string to the original byte data.
*
* @param b64Data
* a Base64-encoded string to decode.
*
* @return bytes decoded from a Base64 string.
*/
public static byte[] fromBase64(String b64Data) {
return b64Data == null ? null : Base64.getDecoder().decode(b64Data);
}
/**
* Converts a Base64-encoded string to the original byte data.
*
* @param b64Data
* a Base64-encoded string to decode.
*
* @return bytes decoded from a Base64 string.
*/
public static byte[] fromBase64Bytes(byte[] b64Data) {
return b64Data == null ? null : Base64.getDecoder().decode(b64Data);
}
/**
* Wraps a ByteBuffer in an InputStream. If the input {@code byteBuffer}
* is null, returns an empty stream.
*
* @param byteBuffer The ByteBuffer to wrap.
*
* @return An InputStream wrapping the ByteBuffer content.
*/
public static ByteArrayInputStream toStream(ByteBuffer byteBuffer) {
if (byteBuffer == null) {
return new ByteArrayInputStream(new byte[0]);
}
return new ByteArrayInputStream(copyBytesFrom(byteBuffer));
}
/**
* Returns an immutable copy of the given {@code ByteBuffer}.
* <p>
* The new buffer's position will be set to the position of the given {@code ByteBuffer}, but the mark if defined will be
* ignored.
* <p>
* <b>NOTE:</b> this method intentionally converts direct buffers to non-direct though there is no guarantee this will always
* be the case, if this is required see {@link #toNonDirectBuffer(ByteBuffer)}
*
* @param bb the source {@code ByteBuffer} to copy.
* @return a read only {@code ByteBuffer}.
*/
public static ByteBuffer immutableCopyOf(ByteBuffer bb) {
if (bb == null) {
return null;
}
ByteBuffer readOnlyCopy = bb.asReadOnlyBuffer();
readOnlyCopy.rewind();
ByteBuffer cloned = ByteBuffer.allocate(readOnlyCopy.capacity())
.put(readOnlyCopy);
cloned.position(bb.position());
cloned.limit(bb.limit());
return cloned.asReadOnlyBuffer();
}
/**
* Returns an immutable copy of the remaining bytes of the given {@code ByteBuffer}.
* <p>
* <b>NOTE:</b> this method intentionally converts direct buffers to non-direct though there is no guarantee this will always
* be the case, if this is required see {@link #toNonDirectBuffer(ByteBuffer)}
*
* @param bb the source {@code ByteBuffer} to copy.
* @return a read only {@code ByteBuffer}.
*/
public static ByteBuffer immutableCopyOfRemaining(ByteBuffer bb) {
if (bb == null) {
return null;
}
ByteBuffer readOnlyCopy = bb.asReadOnlyBuffer();
ByteBuffer cloned = ByteBuffer.allocate(readOnlyCopy.remaining())
.put(readOnlyCopy);
cloned.flip();
return cloned.asReadOnlyBuffer();
}
/**
* Returns a copy of the given {@code DirectByteBuffer} from its current position as a non-direct {@code HeapByteBuffer}
* <p>
* The new buffer's position will be set to the position of the given {@code ByteBuffer}, but the mark if defined will be
* ignored.
*
* @param bb the source {@code ByteBuffer} to copy.
* @return {@code ByteBuffer}.
*/
public static ByteBuffer toNonDirectBuffer(ByteBuffer bb) {
if (bb == null) {
return null;
}
if (!bb.isDirect()) {
throw new IllegalArgumentException("Provided ByteBuffer is already non-direct");
}
int sourceBufferPosition = bb.position();
ByteBuffer readOnlyCopy = bb.asReadOnlyBuffer();
readOnlyCopy.rewind();
ByteBuffer cloned = ByteBuffer.allocate(bb.capacity())
.put(readOnlyCopy);
cloned.rewind();
cloned.position(sourceBufferPosition);
if (bb.isReadOnly()) {
return cloned.asReadOnlyBuffer();
}
return cloned;
}
/**
* Returns a copy of all the bytes from the given <code>ByteBuffer</code>,
* from the beginning to the buffer's limit; or null if the input is null.
* <p>
* The internal states of the given byte buffer will be restored when this
* method completes execution.
* <p>
* When handling <code>ByteBuffer</code> from user's input, it's typical to
* call the {@link #copyBytesFrom(ByteBuffer)} instead of
* {@link #copyAllBytesFrom(ByteBuffer)} so as to account for the position
* of the input <code>ByteBuffer</code>. The opposite is typically true,
* however, when handling <code>ByteBuffer</code> from withint the
* unmarshallers of the low-level clients.
*/
public static byte[] copyAllBytesFrom(ByteBuffer bb) {
if (bb == null) {
return null;
}
if (bb.hasArray()) {
return Arrays.copyOfRange(
bb.array(),
bb.arrayOffset(),
bb.arrayOffset() + bb.limit());
}
ByteBuffer copy = bb.asReadOnlyBuffer();
copy.rewind();
byte[] dst = new byte[copy.remaining()];
copy.get(dst);
return dst;
}
public static byte[] copyRemainingBytesFrom(ByteBuffer bb) {
if (bb == null) {
return null;
}
if (!bb.hasRemaining()) {
return EMPTY_BYTE_ARRAY;
}
if (bb.hasArray()) {
int endIdx = bb.arrayOffset() + bb.limit();
int startIdx = endIdx - bb.remaining();
return Arrays.copyOfRange(bb.array(), startIdx, endIdx);
}
ByteBuffer copy = bb.asReadOnlyBuffer();
byte[] dst = new byte[copy.remaining()];
copy.get(dst);
return dst;
}
/**
* Returns a copy of the bytes from the given <code>ByteBuffer</code>,
* ranging from the the buffer's current position to the buffer's limit; or
* null if the input is null.
* <p>
* The internal states of the given byte buffer will be restored when this
* method completes execution.
* <p>
* When handling <code>ByteBuffer</code> from user's input, it's typical to
* call the {@link #copyBytesFrom(ByteBuffer)} instead of
* {@link #copyAllBytesFrom(ByteBuffer)} so as to account for the position
* of the input <code>ByteBuffer</code>. The opposite is typically true,
* however, when handling <code>ByteBuffer</code> from withint the
* unmarshallers of the low-level clients.
*/
public static byte[] copyBytesFrom(ByteBuffer bb) {
if (bb == null) {
return null;
}
if (bb.hasArray()) {
return Arrays.copyOfRange(
bb.array(),
bb.arrayOffset() + bb.position(),
bb.arrayOffset() + bb.limit());
}
byte[] dst = new byte[bb.remaining()];
bb.asReadOnlyBuffer().get(dst);
return dst;
}
/**
* This behaves identically to {@link #copyBytesFrom(ByteBuffer)}, except
* that the readLimit acts as a limit to the number of bytes that should be
* read from the byte buffer.
*/
public static byte[] copyBytesFrom(ByteBuffer bb, int readLimit) {
if (bb == null) {
return null;
}
int numBytesToRead = Math.min(readLimit, bb.limit() - bb.position());
if (bb.hasArray()) {
return Arrays.copyOfRange(
bb.array(),
bb.arrayOffset() + bb.position(),
bb.arrayOffset() + bb.position() + numBytesToRead);
}
byte[] dst = new byte[numBytesToRead];
bb.asReadOnlyBuffer().get(dst);
return dst;
}
}
| 2,990 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/MapUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.util.HashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
@SdkProtectedApi
public final class MapUtils {
private MapUtils() {
}
public static <K, V> Map<K, V> of(K k1, V v1) {
Map<K, V> m = new HashMap<>();
m.put(k1, v1);
return m;
}
public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2) {
Map<K, V> m = new HashMap<>();
m.put(k1, v1);
m.put(k2, v2);
return m;
}
public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
Map<K, V> m = new HashMap<>();
m.put(k1, v1);
m.put(k2, v2);
m.put(k3, v3);
return m;
}
public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
Map<K, V> m = new HashMap<>();
m.put(k1, v1);
m.put(k2, v2);
m.put(k3, v3);
m.put(k4, v4);
return m;
}
public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
Map<K, V> m = new HashMap<>();
m.put(k1, v1);
m.put(k2, v2);
m.put(k3, v3);
m.put(k4, v4);
m.put(k5, v5);
return m;
}
public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) {
Map<K, V> m = new HashMap<>();
m.put(k1, v1);
m.put(k2, v2);
m.put(k3, v3);
m.put(k4, v4);
m.put(k5, v5);
m.put(k6, v6);
return m;
}
}
| 2,991 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/NumericUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkProtectedApi;
@SdkProtectedApi
public final class NumericUtils {
private NumericUtils() {
}
/**
* Returns the {@code int} nearest in value to {@code value}.
*
* @param value any {@code long} value
* @return the same value cast to {@code int} if it is in the range of the {@code int} type,
* {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if it is too
* small
*/
public static int saturatedCast(long value) {
if (value > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (value < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) value;
}
public static Duration min(Duration a, Duration b) {
return (a.compareTo(b) < 0) ? a : b;
}
public static Duration max(Duration a, Duration b) {
return (a.compareTo(b) > 0) ? a : b;
}
}
| 2,992 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ReflectionMethodInvoker.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* This class acts as a proxy to invoke a specific method on objects of a specific class. It will use the JDK's
* reflection library to find and invoke the method.
* <p>
* The relatively expensive call to find the correct method on the class is lazy and will not be performed until the
* first invocation or until the invoker is explicitly initialized. Once found, the method is cached so repeated
* calls to initialize() or invoke() will not incur the reflection cost of searching for the method on the class.
* <p>
* Example:
* {@code
* ReflectionMethodInvoker<String, Integer> invoker =
* new ReflectionMethodInvoker<String, Integer>(String.class, Integer.class, "indexOf", String.class, int.class);
* invoker.invoke("ababab", "ab", 1); // This is equivalent to calling "ababab".indexOf("ab", 1);
* }
* @param <T> The class type that has the method to be invoked.
* @param <R> The expected return type of the method invocation.
*/
@SdkProtectedApi
public class ReflectionMethodInvoker<T, R> {
private final Class<T> clazz;
private final String methodName;
private final Class<R> returnType;
private final Class<?>[] parameterTypes;
private Method targetMethod;
/**
* Construct an instance of {@code ReflectionMethodInvoker}.
* <p>
* This constructor will not make any reflection calls as part of initialization; i.e. no validation of the
* existence of the given method signature will occur.
* @param clazz The class that has the method to be invoked.
* @param returnType The expected return class of the method invocation. The object returned by the invocation
* will be cast to this class.
* @param methodName The name of the method to invoke.
* @param parameterTypes The classes of the parameters of the method to invoke.
*/
public ReflectionMethodInvoker(Class<T> clazz,
Class<R> returnType,
String methodName,
Class<?>... parameterTypes) {
this.clazz = clazz;
this.methodName = methodName;
this.returnType = returnType;
this.parameterTypes = parameterTypes;
}
/**
* Attempt to invoke the method this proxy targets for on the given object with the given arguments. If the
* invoker has not yet been initialized, an attempt to initialize the invoker will be made first. If the call
* succeeds the invoker will be in an initialized state after this call and future calls to the same method will
* not incur an initialization cost. If the call fails because the target method could not be found, the invoker
* will remain in an uninitialized state after the exception is thrown.
* @param obj The object to invoke the method on.
* @param args The arguments to pass to the method. These arguments must match the signature of the method.
* @return The returned value of the method cast to the 'returnType' class that this proxy was initialized with.
* @throws NoSuchMethodException if the JVM could not find a method matching the signature specified in the
* initialization of this proxy.
* @throws RuntimeException if any other exception is thrown when attempting to invoke the method or by the
* method itself. The cause of this exception will be the exception that was actually thrown.
*/
public R invoke(T obj, Object... args) throws NoSuchMethodException {
Method targetMethod = getTargetMethod();
try {
Object rawResult = targetMethod.invoke(obj, args);
return returnType.cast(rawResult);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(createInvocationErrorMessage(), e);
}
}
/**
* Initializes the method invoker by finding and caching the target method from the target class that will be used
* for subsequent invoke operations. If the invoker is already initialized this call will do nothing.
* @throws NoSuchMethodException if the JVM could not find a method matching the signature specified in the
* initialization of this proxy.
*/
public void initialize() throws NoSuchMethodException {
getTargetMethod();
}
/**
* Gets the initialization state of the invoker.
* @return true if the invoker has been initialized and the method has been cached for invocation; otherwise false.
*/
public boolean isInitialized() {
return targetMethod != null;
}
private Method getTargetMethod() throws NoSuchMethodException {
if (targetMethod != null) {
return targetMethod;
}
try {
targetMethod = clazz.getMethod(methodName, parameterTypes);
return targetMethod;
} catch (RuntimeException e) {
throw new RuntimeException(createInvocationErrorMessage(), e);
}
}
private String createInvocationErrorMessage() {
return String.format("Failed to reflectively invoke method %s on %s", methodName, clazz.getName());
}
}
| 2,993 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Logger.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static software.amazon.awssdk.utils.StringUtils.lowerCase;
import java.util.function.Supplier;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import software.amazon.awssdk.annotations.SdkProtectedApi;
@SdkProtectedApi
public final class Logger {
private final org.slf4j.Logger log;
Logger(org.slf4j.Logger log) {
this.log = log;
}
public org.slf4j.Logger logger() {
return log;
}
/**
* Checks if info is enabled and if so logs the supplied message
* @param msg - supplier for the log message
*/
public void info(Supplier<String> msg) {
if (log.isInfoEnabled()) {
log.info(msg.get());
}
}
/**
* Checks if info is enabled and if so logs the supplied message and exception
* @param msg - supplier for the log message
* @param throwable - a throwable to log
*/
public void info(Supplier<String> msg, Throwable throwable) {
if (log.isInfoEnabled()) {
log.info(msg.get(), throwable);
}
}
/**
* Checks if error is enabled and if so logs the supplied message
* @param msg - supplier for the log message
*/
public void error(Supplier<String> msg) {
if (log.isErrorEnabled()) {
log.error(msg.get());
}
}
/**
* Checks if error is enabled and if so logs the supplied message and exception
* @param msg - supplier for the log message
* @param throwable - a throwable to log
*/
public void error(Supplier<String> msg, Throwable throwable) {
if (log.isErrorEnabled()) {
log.error(msg.get(), throwable);
}
}
/**
* Checks if debug is enabled and if so logs the supplied message
* @param msg - supplier for the log message
*/
public void debug(Supplier<String> msg) {
if (log.isDebugEnabled()) {
log.debug(msg.get());
}
}
/**
* Checks if debug is enabled and if so logs the supplied message and exception
* @param msg - supplier for the log message
* @param throwable - a throwable to log
*/
public void debug(Supplier<String> msg, Throwable throwable) {
if (log.isDebugEnabled()) {
log.debug(msg.get(), throwable);
}
}
/**
* Checks if warn is enabled and if so logs the supplied message
* @param msg - supplier for the log message
*/
public void warn(Supplier<String> msg) {
if (log.isWarnEnabled()) {
log.warn(msg.get());
}
}
/**
* Checks if warn is enabled and if so logs the supplied message and exception
* @param msg - supplier for the log message
* @param throwable - a throwable to log
*/
public void warn(Supplier<String> msg, Throwable throwable) {
if (log.isWarnEnabled()) {
log.warn(msg.get(), throwable);
}
}
/**
* Checks if trace is enabled and if so logs the supplied message
* @param msg - supplier for the log message
*/
public void trace(Supplier<String> msg) {
if (log.isTraceEnabled()) {
log.trace(msg.get());
}
}
/**
* Checks if trace is enabled and if so logs the supplied message and exception
* @param msg - supplier for the log message
* @param throwable - a throwable to log
*/
public void trace(Supplier<String> msg, Throwable throwable) {
if (log.isTraceEnabled()) {
log.trace(msg.get(), throwable);
}
}
/**
* Determines if the provided log-level is enabled.
* @param logLevel the SLF4J log level enum
* @return whether that level is enabled
*/
public boolean isLoggingLevelEnabled(Level logLevel) {
switch (logLevel) {
case TRACE:
return log.isTraceEnabled();
case DEBUG:
return log.isDebugEnabled();
case INFO:
return log.isInfoEnabled();
case WARN:
return log.isWarnEnabled();
case ERROR:
return log.isErrorEnabled();
default:
throw new IllegalStateException("Unsupported log level: " + logLevel);
}
}
/**
* Determines if the log-level passed is enabled
* @param logLevel a string representation of the log level, e.g. "debug"
* @return whether or not that level is enable
*/
public boolean isLoggingLevelEnabled(String logLevel) {
String lowerLogLevel = lowerCase(logLevel);
switch (lowerLogLevel) {
case "debug":
return log.isDebugEnabled();
case "trace":
return log.isTraceEnabled();
case "error":
return log.isErrorEnabled();
case "info":
return log.isInfoEnabled();
case "warn":
return log.isWarnEnabled();
default:
throw new IllegalArgumentException("Unknown log level: " + lowerLogLevel);
}
}
/**
* Log a message at the given log level (if it is enabled).
*
* @param logLevel the SLF4J log level
* @param msg supplier for the log message
*/
public void log(Level logLevel, Supplier<String> msg) {
switch (logLevel) {
case TRACE:
trace(msg);
break;
case DEBUG:
debug(msg);
break;
case INFO:
info(msg);
break;
case WARN:
warn(msg);
break;
case ERROR:
error(msg);
break;
default:
throw new IllegalStateException("Unsupported log level: " + logLevel);
}
}
/**
* Static factory to get a logger instance for a given class
* @param clz - class to get the logger for
* @return a Logger instance
*/
public static Logger loggerFor(Class<?> clz) {
return new Logger(LoggerFactory.getLogger(clz));
}
/**
* Static factory to get a logger instance with a specific name.
* @param name - The name of the logger to create
* @return a Logger instance
*/
public static Logger loggerFor(String name) {
return new Logger(LoggerFactory.getLogger(name));
}
}
| 2,994 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/CompletableFutureUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Utility class for working with {@link CompletableFuture}.
*/
@SdkProtectedApi
public final class CompletableFutureUtils {
private static final Logger log = Logger.loggerFor(CompletableFutureUtils.class);
private CompletableFutureUtils() {
}
/**
* Convenience method for creating a future that is immediately completed
* exceptionally with the given {@code Throwable}.
* <p>
* Similar to {@code CompletableFuture#failedFuture} which was added in
* Java 9.
*
* @param t The failure.
* @param <U> The type of the element.
* @return The failed future.
*/
public static <U> CompletableFuture<U> failedFuture(Throwable t) {
CompletableFuture<U> cf = new CompletableFuture<>();
cf.completeExceptionally(t);
return cf;
}
/**
* Wraps the given error in a {@link CompletionException} if necessary.
* Useful if an exception needs to be rethrown from within {@link
* CompletableFuture#handle(java.util.function.BiFunction)} or similar
* methods.
*
* @param t The error.
* @return The error as a CompletionException.
*/
public static CompletionException errorAsCompletionException(Throwable t) {
if (t instanceof CompletionException) {
return (CompletionException) t;
}
return new CompletionException(t);
}
/**
* Forward the {@code Throwable} from {@code src} to {@code dst}.
* @param src The source of the {@code Throwable}.
* @param dst The destination where the {@code Throwable} will be forwarded to.
*
* @return {@code src}.
*/
public static <T> CompletableFuture<T> forwardExceptionTo(CompletableFuture<T> src, CompletableFuture<?> dst) {
src.whenComplete((r, e) -> {
if (e != null) {
dst.completeExceptionally(e);
}
});
return src;
}
/**
* Forward the {@code Throwable} that can be transformed as per the transformationFunction
* from {@code src} to {@code dst}.
* @param src The source of the {@code Throwable}.
* @param dst The destination where the {@code Throwable} will be forwarded to
* @param transformationFunction Transformation function taht will be applied on to the forwarded exception.
* @return
*/
public static <T> CompletableFuture<T> forwardTransformedExceptionTo(CompletableFuture<T> src,
CompletableFuture<?> dst,
Function<Throwable, Throwable>
transformationFunction) {
src.whenComplete((r, e) -> {
if (e != null) {
dst.completeExceptionally(transformationFunction.apply(e));
}
});
return src;
}
/**
* Completes the {@code dst} future based on the result of the {@code src} future asynchronously on
* the provided {@link Executor} and return the {@code src} future.
*
* @param src The source {@link CompletableFuture}
* @param dst The destination where the {@code Throwable} or response will be forwarded to.
* @return the {@code src} future.
*/
public static <T> CompletableFuture<T> forwardResultTo(CompletableFuture<T> src,
CompletableFuture<T> dst) {
src.whenComplete((r, e) -> {
if (e != null) {
dst.completeExceptionally(e);
} else {
dst.complete(r);
}
});
return src;
}
/**
* Completes the {@code dst} future based on the result of the {@code src} future asynchronously on
* the provided {@link Executor} and return the {@code src} future.
*
* @param src The source {@link CompletableFuture}
* @param dst The destination where the {@code Throwable} or response will be forwarded to.
* @param executor the executor to complete the des future
* @return the {@code src} future.
*/
public static <T> CompletableFuture<T> forwardResultTo(CompletableFuture<T> src,
CompletableFuture<T> dst,
Executor executor) {
src.whenCompleteAsync((r, e) -> {
if (e != null) {
dst.completeExceptionally(e);
} else {
dst.complete(r);
}
}, executor);
return src;
}
/**
* Completes the {@code dst} future based on the result of the {@code src} future, synchronously,
* after applying the provided transformation {@link Function} if successful.
*
* @param src The source {@link CompletableFuture}
* @param dst The destination where the {@code Throwable} or transformed result will be forwarded to.
* @return the {@code src} future.
*/
public static <SourceT, DestT> CompletableFuture<SourceT> forwardTransformedResultTo(CompletableFuture<SourceT> src,
CompletableFuture<DestT> dst,
Function<SourceT, DestT> function) {
src.whenComplete((r, e) -> {
if (e != null) {
dst.completeExceptionally(e);
} else {
dst.complete(function.apply(r));
}
});
return src;
}
/**
* Similar to {@link CompletableFuture#allOf(CompletableFuture[])}, but
* when any future is completed exceptionally, forwards the
* exception to other futures.
*
* @param futures The futures.
* @return The new future that is completed when all the futures in {@code
* futures} are.
*/
public static CompletableFuture<Void> allOfExceptionForwarded(CompletableFuture<?>[] futures) {
CompletableFuture<Void> anyFail = anyFail(futures);
anyFail.whenComplete((r, t) -> {
if (t != null) {
for (CompletableFuture<?> cf : futures) {
cf.completeExceptionally(t);
}
}
});
return CompletableFuture.allOf(futures);
}
/**
* Returns a new CompletableFuture that is completed when any of
* the given CompletableFutures completes exceptionally.
*
* @param futures the CompletableFutures
* @return a new CompletableFuture that is completed if any provided
* future completed exceptionally.
*/
static CompletableFuture<Void> anyFail(CompletableFuture<?>[] futures) {
CompletableFuture<Void> completableFuture = new CompletableFuture<>();
for (CompletableFuture<?> future : futures) {
future.whenComplete((r, t) -> {
if (t != null) {
completableFuture.completeExceptionally(t);
}
});
}
return completableFuture;
}
public static <T> T joinInterruptibly(CompletableFuture<T> future) {
try {
return future.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CompletionException("Interrupted while waiting on a future.", e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof Error) {
throw (Error) cause;
}
throw new CompletionException(cause);
}
}
public static void joinInterruptiblyIgnoringFailures(CompletableFuture<?> future) {
try {
future.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
// Ignore
}
}
/**
* Joins (interruptibly) on the future, and re-throws any RuntimeExceptions or Errors just like the async task would have
* thrown if it was executed synchronously.
*/
public static <T> T joinLikeSync(CompletableFuture<T> future) {
try {
return joinInterruptibly(future);
} catch (CompletionException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
// Make sure we don't lose the context of where the join is in the stack...
cause.addSuppressed(new RuntimeException("Task failed."));
throw (RuntimeException) cause;
}
throw e;
}
}
}
| 2,995 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/CollectionUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkProtectedApi;
@SdkProtectedApi
public final class CollectionUtils {
private CollectionUtils() {
}
public static boolean isNullOrEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
public static boolean isNullOrEmpty(Map<?, ?> map) {
return map == null || map.isEmpty();
}
public static boolean isNotEmpty(Map<?, ?> map) {
return map != null && !map.isEmpty();
}
/**
* Returns a new list containing the second list appended to the first list.
*/
public static <T> List<T> mergeLists(List<T> list1, List<T> list2) {
List<T> merged = new LinkedList<>();
if (list1 != null) {
merged.addAll(list1);
}
if (list2 != null) {
merged.addAll(list2);
}
return merged;
}
/**
* @param list List to get first element from.
* @param <T> Type of elements in the list.
* @return The first element in the list if it exists. If the list is null or empty this will
* return null.
*/
public static <T> T firstIfPresent(List<T> list) {
if (list == null || list.isEmpty()) {
return null;
} else {
return list.get(0);
}
}
/**
* Perform a deep copy of the provided map of lists. This only performs a deep copy of the map and lists. Entries are not
* copied, so care should be taken to ensure that entries are immutable if preventing unwanted mutations of the elements is
* desired.
*/
public static <T, U> Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map) {
return deepCopyMap(map, () -> new LinkedHashMap<>(map.size()));
}
/**
* Perform a deep copy of the provided map of lists. This only performs a deep copy of the map and lists. Entries are not
* copied, so care should be taken to ensure that entries are immutable if preventing unwanted mutations of the elements is
* desired.
*/
public static <T, U> Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor) {
Map<T, List<U>> result = mapConstructor.get();
map.forEach((k, v) -> result.put(k, new ArrayList<>(v)));
return result;
}
public static <T, U> Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map) {
return new UnmodifiableMapOfLists<>(map);
}
/**
* Perform a deep copy of the provided map of lists, and make the result unmodifiable.
*
* This is equivalent to calling {@link #deepCopyMap} followed by {@link #unmodifiableMapOfLists}.
*/
public static <T, U> Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map) {
return unmodifiableMapOfLists(deepCopyMap(map));
}
/**
* Perform a deep copy of the provided map of lists, and make the result unmodifiable.
*
* This is equivalent to calling {@link #deepCopyMap} followed by {@link #unmodifiableMapOfLists}.
*/
public static <T, U> Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor) {
return unmodifiableMapOfLists(deepCopyMap(map, mapConstructor));
}
/**
* Collect a stream of {@link Map.Entry} to a {@link Map} with the same key/value types
* @param <K> the key type
* @param <V> the value type
* @return a map
*/
public static <K, V> Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap() {
return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}
/**
* Transforms the values of a map to another map with the same keys, using the supplied function.
*
* @param inputMap the input map
* @param mapper the function used to transform the map values
* @param <K> the key type
* @param <VInT> the value type for the input map
* @param <VOutT> the value type for the output map
* @return a map
*/
public static <K, VInT, VOutT> Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper) {
return inputMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> mapper.apply(e.getValue())));
}
/**
* Filters a map based on a condition
*
* @param map the input map
* @param condition the predicate to filter on
* @param <K> the key type
* @param <V> the value type
* @return the filtered map
*/
public static <K, V> Map<K, V> filterMap(Map<K, V> map, Predicate<Map.Entry<K, V>> condition) {
return map.entrySet()
.stream()
.filter(condition)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
/**
* Return a new map that is the inverse of the supplied map, with the values becoming the keys
* and vice versa. Requires the values to be unique.
*
* @param inputMap a map where both the keys and values are unique
* @param <K> the key type
* @param <V> the value type
* @return a map
*/
public static <K, V> Map<K, V> inverseMap(Map<V, K> inputMap) {
return inputMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
}
/**
* For a collection of values of type {@code V} that can all be converted to type {@code K}, create a map that
* indexes all of the values by {@code K}. This requires that no two values map to the same index.
*
* @param values the collection of values to index
* @param indexFunction the function used to convert a value to its index
* @param <K> the index (or key) type
* @param <V> the value type
* @return a (modifiable) map that indexes K to its unique value V
* @throws IllegalArgumentException if any of the values map to the same index
*/
public static <K, V> Map<K, V> uniqueIndex(Iterable<V> values, Function<? super V, K> indexFunction) {
Map<K, V> map = new HashMap<>();
for (V value : values) {
K index = indexFunction.apply(value);
V prev = map.put(index, value);
Validate.isNull(prev, "No duplicate indices allowed but both %s and %s have the same index: %s",
prev, value, index);
}
return map;
}
}
| 2,996 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Md5Utils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Utility methods for computing MD5 sums.
*/
@SdkProtectedApi
public final class Md5Utils {
private static final int SIXTEEN_K = 1 << 14;
private Md5Utils() {
}
/**
* Computes the MD5 hash of the data in the given input stream and returns
* it as an array of bytes.
* Note this method closes the given input stream upon completion.
*/
public static byte[] computeMD5Hash(InputStream is) throws IOException {
BufferedInputStream bis = new BufferedInputStream(is);
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[SIXTEEN_K];
int bytesRead;
while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) {
messageDigest.update(buffer, 0, bytesRead);
}
return messageDigest.digest();
} catch (NoSuchAlgorithmException e) {
// should never get here
throw new IllegalStateException(e);
} finally {
try {
bis.close();
} catch (Exception e) {
LoggerFactory.getLogger(Md5Utils.class).debug("Unable to close input stream of hash candidate: {}", e);
}
}
}
/**
* Returns the MD5 in base64 for the data from the given input stream.
* Note this method closes the given input stream upon completion.
*/
public static String md5AsBase64(InputStream is) throws IOException {
return BinaryUtils.toBase64(computeMD5Hash(is));
}
/**
* Computes the MD5 hash of the given data and returns it as an array of
* bytes.
*/
public static byte[] computeMD5Hash(byte[] input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
return md.digest(input);
} catch (NoSuchAlgorithmException e) {
// should never get here
throw new IllegalStateException(e);
}
}
/**
* Returns the MD5 in base64 for the given byte array.
*/
public static String md5AsBase64(byte[] input) {
return BinaryUtils.toBase64(computeMD5Hash(input));
}
/**
* Computes the MD5 of the given file.
*/
public static byte[] computeMD5Hash(File file) throws FileNotFoundException, IOException {
return computeMD5Hash(new FileInputStream(file));
}
/**
* Returns the MD5 in base64 for the given file.
*/
public static String md5AsBase64(File file) throws FileNotFoundException, IOException {
return BinaryUtils.toBase64(computeMD5Hash(file));
}
}
| 2,997 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ScheduledExecutorUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import static software.amazon.awssdk.utils.Validate.paramNotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
/**
* Utilities that make it easier to create, use and destroy
* {@link ScheduledExecutor}s.
*/
@SdkProtectedApi
public final class ScheduledExecutorUtils {
private ScheduledExecutorUtils() {
}
/**
* Wrap a scheduled executor in a type that cannot be closed, or shut down.
*/
public static ScheduledExecutorService unmanagedScheduledExecutor(ScheduledExecutorService executor) {
if (executor instanceof UnmanagedScheduledExecutorService) {
return executor;
}
if (executor == null) {
return null;
}
return new UnmanagedScheduledExecutorService(executor);
}
/**
* Unwrap a scheduled executor. Requires the UnmanagedScheduledExecutorService to be the "outer" type.
*/
public static ScheduledExecutorService unwrapUnmanagedScheduledExecutor(ScheduledExecutorService executor) {
if (executor instanceof UnmanagedScheduledExecutorService) {
return ((UnmanagedScheduledExecutorService) executor).delegate;
}
return executor;
}
/**
* Wrapper around {@link ScheduledExecutorService} to prevent it from being
* closed. Used when the customer provides
* a custom scheduled executor service in which case they are responsible for
* the lifecycle of it.
*/
@SdkTestInternalApi
public static final class UnmanagedScheduledExecutorService implements ScheduledExecutorService {
private final ScheduledExecutorService delegate;
UnmanagedScheduledExecutorService(ScheduledExecutorService delegate) {
this.delegate = paramNotNull(delegate, "ScheduledExecutorService");
}
public ScheduledExecutorService scheduledExecutorService() {
return delegate;
}
@Override
public void shutdown() {
// Do nothing, this executor service is managed by the customer.
}
@Override
public List<Runnable> shutdownNow() {
return new ArrayList<>();
}
@Override
public boolean isShutdown() {
return delegate.isShutdown();
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return delegate.awaitTermination(timeout, unit);
}
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return delegate.schedule(command, delay, unit);
}
@Override
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
return delegate.schedule(callable, delay, unit);
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
return delegate.scheduleAtFixedRate(command, initialDelay, period, unit);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,
TimeUnit unit) {
return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit);
}
@Override
public boolean isTerminated() {
return delegate.isTerminated();
}
@Override
public <T> Future<T> submit(Callable<T> task) {
return delegate.submit(task);
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
return delegate.submit(task, result);
}
@Override
public Future<?> submit(Runnable task) {
return delegate.submit(task);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
return delegate.invokeAll(tasks);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException {
return delegate.invokeAll(tasks, timeout, unit);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
return delegate.invokeAny(tasks);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return delegate.invokeAny(tasks, timeout, unit);
}
@Override
public void execute(Runnable command) {
delegate.execute(command);
}
}
}
| 2,998 |
0 | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/StringInputStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.utils;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Simple wrapper for ByteArrayInputStream that will automatically encode the
* string as UTF-8 data, and still allows access to the original string.
*/
@SdkProtectedApi
public class StringInputStream extends ByteArrayInputStream {
private final String string;
public StringInputStream(String s) {
super(s.getBytes(StandardCharsets.UTF_8));
this.string = s;
}
/**
* Returns the original string specified when this input stream was
* constructed.
*
* @return The original string specified when this input stream was
* constructed.
*/
public String getString() {
return string;
}
}
| 2,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.