index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/V1TransferManagerDownloadDirectoryBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.testutils.FileUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class V1TransferManagerDownloadDirectoryBenchmark extends V1BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("V1TransferManagerDownloadDirectoryBenchmark"); private final TransferManagerBenchmarkConfig config; V1TransferManagerDownloadDirectoryBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.filePath(), "File path must not be null"); this.config = config; } @Override protected void doRunBenchmark() { downloadDirectory(); } private void downloadDirectory() { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to download to file"); for (int i = 0; i < iteration; i++) { downloadOnce(metrics); } printOutResult(metrics, "TM v1 Download Directory"); } private void downloadOnce(List<Double> latencies) { Path downloadPath = new File(this.path).toPath(); long start = System.currentTimeMillis(); try { transferManager.downloadDirectory(bucket, config.prefix(), new File(this.path)).waitForCompletion(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn(() -> "Thread interrupted when waiting for completion", e); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); runAndLogError(logger.logger(), "Deleting directory failed " + downloadPath, () -> FileUtils.cleanUpTestDirectory(downloadPath)); } }
3,000
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerDownloadDirectoryBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.testutils.FileUtils; import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload; import software.amazon.awssdk.transfer.s3.model.DirectoryDownload; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class TransferManagerDownloadDirectoryBenchmark extends BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("TransferManagerDownloadDirectoryBenchmark"); private final TransferManagerBenchmarkConfig config; public TransferManagerDownloadDirectoryBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.filePath(), "File path must not be null"); this.config = config; } @Override protected void doRunBenchmark() { try { downloadDirectory(iteration, true); } catch (Exception exception) { logger.error(() -> "Request failed: ", exception); } } private void downloadDirectory(int count, boolean printoutResult) throws Exception { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to download to file"); for (int i = 0; i < count; i++) { downloadOnce(metrics); } if (printoutResult) { printOutResult(metrics, "TM v2 Download Directory"); } } private void downloadOnce(List<Double> latencies) throws Exception { Path downloadPath = new File(this.path).toPath(); long start = System.currentTimeMillis(); DirectoryDownload download = transferManager.downloadDirectory(b -> b.bucket(bucket) .destination(downloadPath) .listObjectsV2RequestTransformer(l -> l.prefix(config.prefix()))); CompletedDirectoryDownload completedDirectoryDownload = download.completionFuture().get(timeout.getSeconds(), TimeUnit.SECONDS); if (completedDirectoryDownload.failedTransfers().isEmpty()) { long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } else { logger.error(() -> "Some transfers failed: " + completedDirectoryDownload.failedTransfers()); } runAndLogError(logger.logger(), "Deleting directory failed " + downloadPath, () -> FileUtils.cleanUpTestDirectory(downloadPath)); } }
3,001
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/BenchmarkRunner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import java.time.Duration; import java.util.EnumMap; import java.util.Locale; import java.util.Map; import java.util.function.Function; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Options; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; public final class BenchmarkRunner { private static final String PART_SIZE_IN_MB = "partSizeInMB"; private static final String FILE = "file"; private static final String BUCKET = "bucket"; private static final String MAX_THROUGHPUT = "maxThroughput"; private static final String KEY = "key"; private static final String OPERATION = "operation"; private static final String CHECKSUM_ALGORITHM = "checksumAlgo"; private static final String ITERATION = "iteration"; private static final String CONTENT_LENGTH = "contentLengthInMB"; private static final String READ_BUFFER_IN_MB = "readBufferInMB"; private static final String VERSION = "version"; private static final String PREFIX = "prefix"; private static final String TIMEOUT = "timeoutInMin"; private static final String CONN_ACQ_TIMEOUT_IN_SEC = "connAcqTimeoutInSec"; private static final String FORCE_CRT_HTTP_CLIENT = "crtHttp"; private static final String MAX_CONCURRENCY = "maxConcurrency"; private static final Map<TransferManagerOperation, Function<TransferManagerBenchmarkConfig, TransferManagerBenchmark>> OPERATION_TO_BENCHMARK_V1 = new EnumMap<>(TransferManagerOperation.class); private static final Map<TransferManagerOperation, Function<TransferManagerBenchmarkConfig, TransferManagerBenchmark>> OPERATION_TO_BENCHMARK_V2 = new EnumMap<>(TransferManagerOperation.class); static { OPERATION_TO_BENCHMARK_V2.put(TransferManagerOperation.COPY, TransferManagerBenchmark::copy); OPERATION_TO_BENCHMARK_V2.put(TransferManagerOperation.DOWNLOAD, TransferManagerBenchmark::v2Download); OPERATION_TO_BENCHMARK_V2.put(TransferManagerOperation.UPLOAD, TransferManagerBenchmark::v2Upload); OPERATION_TO_BENCHMARK_V2.put(TransferManagerOperation.DOWNLOAD_DIRECTORY, TransferManagerBenchmark::downloadDirectory); OPERATION_TO_BENCHMARK_V2.put(TransferManagerOperation.UPLOAD_DIRECTORY, TransferManagerBenchmark::uploadDirectory); OPERATION_TO_BENCHMARK_V1.put(TransferManagerOperation.COPY, TransferManagerBenchmark::v1Copy); OPERATION_TO_BENCHMARK_V1.put(TransferManagerOperation.DOWNLOAD, TransferManagerBenchmark::v1Download); OPERATION_TO_BENCHMARK_V1.put(TransferManagerOperation.UPLOAD, TransferManagerBenchmark::v1Upload); OPERATION_TO_BENCHMARK_V1.put(TransferManagerOperation.DOWNLOAD_DIRECTORY, TransferManagerBenchmark::v1DownloadDirectory); OPERATION_TO_BENCHMARK_V1.put(TransferManagerOperation.UPLOAD_DIRECTORY, TransferManagerBenchmark::v1UploadDirectory); } private BenchmarkRunner() { } public static void main(String... args) throws org.apache.commons.cli.ParseException { CommandLineParser parser = new DefaultParser(); Options options = new Options(); options.addRequiredOption(null, BUCKET, true, "The s3 bucket"); options.addOption(null, KEY, true, "The s3 key"); options.addRequiredOption(null, OPERATION, true, "The operation to run tests: download | upload | download_directory | " + "upload_directory | copy"); options.addOption(null, FILE, true, "Destination file path to be written to or source file path to be " + "uploaded"); options.addOption(null, PART_SIZE_IN_MB, true, "Part size in MB"); options.addOption(null, MAX_THROUGHPUT, true, "The max throughput"); options.addOption(null, CHECKSUM_ALGORITHM, true, "The checksum algorithm to use"); options.addOption(null, ITERATION, true, "The number of iterations"); options.addOption(null, READ_BUFFER_IN_MB, true, "Read buffer size in MB"); options.addOption(null, VERSION, true, "The major version of the transfer manager to run test: " + "v1 | v2 | crt | java, default: v2"); options.addOption(null, PREFIX, true, "S3 Prefix used in downloadDirectory and uploadDirectory"); options.addOption(null, CONTENT_LENGTH, true, "Content length to upload from memory. Used only in the " + "CRT Upload Benchmark, but " + "is required for this test case."); options.addOption(null, TIMEOUT, true, "Amount of minute to wait before a single operation " + "times out and is cancelled. Optional, defaults to 10 minutes if no specified"); options.addOption(null, CONN_ACQ_TIMEOUT_IN_SEC, true, "Timeout for acquiring an already-established" + " connection from a connection pool to a remote service."); options.addOption(null, FORCE_CRT_HTTP_CLIENT, true, "Force the CRT http client to be used in JavaBased benchmarks"); options.addOption(null, MAX_CONCURRENCY, true, "The Maximum number of allowed concurrent requests. For HTTP/1.1 this is the same as max connections."); CommandLine cmd = parser.parse(options, args); TransferManagerBenchmarkConfig config = parseConfig(cmd); SdkVersion version = SdkVersion.valueOf(cmd.getOptionValue(VERSION, "V2") .toUpperCase(Locale.ENGLISH)); TransferManagerOperation operation = config.operation(); TransferManagerBenchmark benchmark; switch (version) { case V1: benchmark = OPERATION_TO_BENCHMARK_V1.get(operation).apply(config); break; case V2: benchmark = OPERATION_TO_BENCHMARK_V2.get(operation).apply(config); break; case CRT: if (operation == TransferManagerOperation.DOWNLOAD) { benchmark = new CrtS3ClientDownloadBenchmark(config); break; } if (operation == TransferManagerOperation.UPLOAD) { benchmark = new CrtS3ClientUploadBenchmark(config); break; } throw new UnsupportedOperationException(); case JAVA: if (operation == TransferManagerOperation.UPLOAD) { benchmark = new JavaS3ClientUploadBenchmark(config); break; } if (operation == TransferManagerOperation.COPY) { benchmark = new JavaS3ClientCopyBenchmark(config); break; } throw new UnsupportedOperationException("Java based s3 client benchmark only support upload and copy"); default: throw new UnsupportedOperationException(); } benchmark.run(); } private static TransferManagerBenchmarkConfig parseConfig(CommandLine cmd) { TransferManagerOperation operation = TransferManagerOperation.valueOf(cmd.getOptionValue(OPERATION) .toUpperCase(Locale.ENGLISH)); String filePath = cmd.getOptionValue(FILE); String bucket = cmd.getOptionValue(BUCKET); String key = cmd.getOptionValue(KEY); Long partSize = cmd.getOptionValue(PART_SIZE_IN_MB) == null ? null : Long.parseLong(cmd.getOptionValue(PART_SIZE_IN_MB)); Double maxThroughput = cmd.getOptionValue(MAX_THROUGHPUT) == null ? null : Double.parseDouble(cmd.getOptionValue(MAX_THROUGHPUT)); ChecksumAlgorithm checksumAlgorithm = null; if (cmd.getOptionValue(CHECKSUM_ALGORITHM) != null) { checksumAlgorithm = ChecksumAlgorithm.fromValue(cmd.getOptionValue(CHECKSUM_ALGORITHM) .toUpperCase(Locale.ENGLISH)); } Integer iteration = cmd.getOptionValue(ITERATION) == null ? null : Integer.parseInt(cmd.getOptionValue(ITERATION)); Long readBufferInMB = cmd.getOptionValue(READ_BUFFER_IN_MB) == null ? null : Long.parseLong(cmd.getOptionValue(READ_BUFFER_IN_MB)); String prefix = cmd.getOptionValue(PREFIX); Long contentLengthInMb = cmd.getOptionValue(CONTENT_LENGTH) == null ? null : Long.parseLong(cmd.getOptionValue(CONTENT_LENGTH)); Duration timeout = cmd.getOptionValue(TIMEOUT) == null ? null : Duration.ofMinutes(Long.parseLong(cmd.getOptionValue(TIMEOUT))); Long connAcqTimeoutInSec = cmd.getOptionValue(CONN_ACQ_TIMEOUT_IN_SEC) == null ? null : Long.parseLong(cmd.getOptionValue(CONN_ACQ_TIMEOUT_IN_SEC)); Boolean forceCrtHttpClient = cmd.getOptionValue(FORCE_CRT_HTTP_CLIENT) != null && Boolean.parseBoolean(cmd.getOptionValue(FORCE_CRT_HTTP_CLIENT)); Integer maxConcurrency = cmd.getOptionValue(MAX_CONCURRENCY) == null ? null : Integer.parseInt(cmd.getOptionValue(MAX_CONCURRENCY)); return TransferManagerBenchmarkConfig.builder() .key(key) .bucket(bucket) .partSizeInMb(partSize) .checksumAlgorithm(checksumAlgorithm) .targetThroughput(maxThroughput) .readBufferSizeInMb(readBufferInMB) .filePath(filePath) .iteration(iteration) .operation(operation) .prefix(prefix) .contentLengthInMb(contentLengthInMb) .timeout(timeout) .connectionAcquisitionTimeoutInSec(connAcqTimeoutInSec) .forceCrtHttpClient(forceCrtHttpClient) .maxConcurrency(maxConcurrency) .build(); } public enum TransferManagerOperation { DOWNLOAD, UPLOAD, COPY, DOWNLOAD_DIRECTORY, UPLOAD_DIRECTORY } private enum SdkVersion { V1, V2, CRT, JAVA } }
3,002
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerCopyBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.COPY_SUFFIX; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.transfer.s3.model.Copy; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class TransferManagerCopyBenchmark extends BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("TransferManagerCopyBenchmark"); private final long contentLength; public TransferManagerCopyBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.key(), "Key must not be null"); this.contentLength = s3Sync.headObject(b -> b.bucket(bucket).key(key)).contentLength(); } @Override protected void doRunBenchmark() { try { copy(iteration, true); } catch (Exception exception) { logger.error(() -> "Request failed: ", exception); } } @Override protected void additionalWarmup() throws Exception { copy(5, false); } private void copy(int count, boolean printoutResult) throws Exception { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to copy"); for (int i = 0; i < count; i++) { copyOnce(metrics); } if (printoutResult) { printOutResult(metrics, "TM v2 copy", contentLength); } } private void copyOnce(List<Double> latencies) throws Exception { long start = System.currentTimeMillis(); Copy copy = transferManager.copy(b -> b.copyObjectRequest(c -> c.sourceBucket(bucket).sourceKey(key) .destinationBucket(bucket).destinationKey(key + COPY_SUFFIX))); copy.completionFuture().get(timeout.getSeconds(), TimeUnit.SECONDS); long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
3,003
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerDownloadBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.transfer.s3.model.DownloadRequest; import software.amazon.awssdk.transfer.s3.model.FileDownload; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class TransferManagerDownloadBenchmark extends BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("TransferManagerDownloadBenchmark"); private final long contentLength; public TransferManagerDownloadBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.key(), "Key must not be null"); this.contentLength = s3Sync.headObject(b -> b.bucket(bucket).key(key)).contentLength(); } @Override protected void doRunBenchmark() { if (path == null) { try { downloadToMemory(iteration, true); } catch (Exception exception) { logger.error(() -> "Request failed: ", exception); } return; } try { downloadToFile(iteration, true); } catch (Exception exception) { logger.error(() -> "Request failed: ", exception); } } private void downloadToMemory(int count, boolean printoutResult) throws Exception { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to download to memory"); for (int i = 0; i < count; i++) { downloadOnceToMemory(metrics); } if (printoutResult) { printOutResult(metrics, "TM v2 Download to Memory", contentLength); } } private void downloadToFile(int count, boolean printoutResult) throws Exception { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to download to file"); for (int i = 0; i < count; i++) { downloadOnceToFile(metrics); } if (printoutResult) { printOutResult(metrics, "TM v2 Download to File", contentLength); } } private void downloadOnceToFile(List<Double> latencies) throws Exception { Path downloadPath = new File(this.path).toPath(); long start = System.currentTimeMillis(); FileDownload download = transferManager.downloadFile(b -> b.getObjectRequest(r -> r.bucket(bucket).key(key)) .destination(downloadPath)); download.completionFuture().get(10, TimeUnit.MINUTES); long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); runAndLogError(logger.logger(), "Deleting file failed", () -> Files.delete(downloadPath)); } private void downloadOnceToMemory(List<Double> latencies) throws Exception { long start = System.currentTimeMillis(); AsyncResponseTransformer<GetObjectResponse, Void> responseTransformer = new NoOpResponseTransformer<>(); transferManager.download(DownloadRequest.builder() .getObjectRequest(req -> req.bucket(bucket).key(key)) .responseTransformer(responseTransformer) .build()) .completionFuture() .get(timeout.getSeconds(), TimeUnit.SECONDS); long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
3,004
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/CrtS3ClientUploadBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import java.net.URI; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.crt.http.HttpHeader; import software.amazon.awssdk.crt.http.HttpRequest; import software.amazon.awssdk.crt.http.HttpRequestBodyStream; import software.amazon.awssdk.crt.s3.S3MetaRequest; import software.amazon.awssdk.crt.s3.S3MetaRequestOptions; import software.amazon.awssdk.crt.s3.S3MetaRequestResponseHandler; import software.amazon.awssdk.crt.utils.ByteBufferUtils; public class CrtS3ClientUploadBenchmark extends BaseCrtClientBenchmark { private final String filepath; public CrtS3ClientUploadBenchmark(TransferManagerBenchmarkConfig config) { super(config); this.filepath = config.filePath(); } @Override public void sendOneRequest(List<Double> latencies) throws Exception { CompletableFuture<Void> resultFuture = new CompletableFuture<>(); S3MetaRequestResponseHandler responseHandler = new TestS3MetaRequestResponseHandler(resultFuture); String endpoint = bucket + ".s3." + region + ".amazonaws.com"; ByteBuffer payload = ByteBuffer.wrap(Files.readAllBytes(Paths.get(filepath))); HttpRequestBodyStream payloadStream = new PayloadStream(payload); HttpHeader[] headers = {new HttpHeader("Host", endpoint)}; HttpRequest httpRequest = new HttpRequest( "PUT", "/" + key, headers, payloadStream); S3MetaRequestOptions metaRequestOptions = new S3MetaRequestOptions() .withEndpoint(URI.create("https://" + endpoint)) .withMetaRequestType(S3MetaRequestOptions.MetaRequestType.PUT_OBJECT) .withHttpRequest(httpRequest) .withResponseHandler(responseHandler); long start = System.currentTimeMillis(); try (S3MetaRequest metaRequest = crtS3Client.makeMetaRequest(metaRequestOptions)) { resultFuture.get(10, TimeUnit.MINUTES); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } private static class PayloadStream implements HttpRequestBodyStream { private ByteBuffer payload; private PayloadStream(ByteBuffer payload) { this.payload = payload; } @Override public boolean sendRequestBody(ByteBuffer outBuffer) { ByteBufferUtils.transferData(payload, outBuffer); return payload.remaining() == 0; } @Override public boolean resetPosition() { return true; } @Override public long getLength() { return payload.capacity(); } } }
3,005
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/BaseTransferManagerBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.BENCHMARK_ITERATIONS; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.COPY_SUFFIX; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.DEFAULT_TIMEOUT; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.WARMUP_KEY; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3CrtAsyncClientBuilder; import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.utils.Logger; public abstract class BaseTransferManagerBenchmark implements TransferManagerBenchmark { protected static final int WARMUP_ITERATIONS = 10; private static final Logger logger = Logger.loggerFor("TransferManagerBenchmark"); protected final S3TransferManager transferManager; protected final S3AsyncClient s3; protected final S3Client s3Sync; protected final String bucket; protected final String key; protected final String path; protected final int iteration; protected final Duration timeout; private final File file; BaseTransferManagerBenchmark(TransferManagerBenchmarkConfig config) { logger.info(() -> "Benchmark config: " + config); Long partSizeInMb = config.partSizeInMb() == null ? null : config.partSizeInMb() * MB; Long readBufferSizeInMb = config.readBufferSizeInMb() == null ? null : config.readBufferSizeInMb() * MB; S3CrtAsyncClientBuilder builder = S3CrtAsyncClient.builder() .targetThroughputInGbps(config.targetThroughput()) .minimumPartSizeInBytes(partSizeInMb) .initialReadBufferSizeInBytes(readBufferSizeInMb) .targetThroughputInGbps(config.targetThroughput() == null ? Double.valueOf(100.0) : config.targetThroughput()); if (config.maxConcurrency() != null) { builder.maxConcurrency(config.maxConcurrency()); } s3 = builder.build(); s3Sync = S3Client.builder().build(); transferManager = S3TransferManager.builder() .s3Client(s3) .build(); bucket = config.bucket(); key = config.key(); path = config.filePath(); iteration = config.iteration() == null ? BENCHMARK_ITERATIONS : config.iteration(); timeout = config.timeout() == null ? DEFAULT_TIMEOUT : config.timeout(); try { file = new RandomTempFile(10 * MB); file.deleteOnExit(); } catch (IOException e) { logger.error(() -> "Failed to create the file"); throw new RuntimeException("Failed to create the temp file", e); } } @Override public void run() { try { warmUp(); doRunBenchmark(); } catch (Exception e) { logger.error(() -> "Exception occurred", e); } finally { cleanup(); } } /** * Hook method to allow subclasses to add additional warm up */ protected void additionalWarmup() throws Exception { // default to no-op } protected abstract void doRunBenchmark(); private void cleanup() { try { s3Sync.deleteObject(b -> b.bucket(bucket).key(WARMUP_KEY)); } catch (Exception exception) { logger.error(() -> "Failed to delete object: " + WARMUP_KEY); } String copyObject = WARMUP_KEY + COPY_SUFFIX; try { s3Sync.deleteObject(b -> b.bucket(bucket).key(copyObject)); } catch (Exception exception) { logger.error(() -> "Failed to delete object: " + copyObject); } s3.close(); s3Sync.close(); transferManager.close(); } private void warmUp() throws Exception { logger.info(() -> "Starting to warm up"); for (int i = 0; i < WARMUP_ITERATIONS; i++) { warmUpUploadBatch(); warmUpDownloadBatch(); warmUpCopyBatch(); Thread.sleep(500); } additionalWarmup(); logger.info(() -> "Ending warm up"); } private void warmUpCopyBatch() { List<CompletableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < 5; i++) { futures.add(transferManager.copy( c -> c.copyObjectRequest(r -> r.sourceKey(WARMUP_KEY) .sourceBucket(bucket) .destinationKey(WARMUP_KEY + "_copy") .destinationBucket(bucket))) .completionFuture()); } CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0])).join(); } private void warmUpDownloadBatch() { List<CompletableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < 20; i++) { Path tempFile = RandomTempFile.randomUncreatedFile().toPath(); futures.add(s3.getObject(GetObjectRequest.builder().bucket(bucket).key(WARMUP_KEY).build(), AsyncResponseTransformer.toFile(tempFile)).whenComplete((r, t) -> runAndLogError( logger.logger(), "Deleting file failed", () -> Files.delete(tempFile)))); } CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0])).join(); } private void warmUpUploadBatch() { List<CompletableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < 20; i++) { futures.add(s3.putObject(PutObjectRequest.builder().bucket(bucket).key(WARMUP_KEY).build(), AsyncRequestBody.fromFile(file))); } CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0])).join(); } }
3,006
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/V1BaseTransferManagerBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.BENCHMARK_ITERATIONS; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.COPY_SUFFIX; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.PRE_WARMUP_ITERATIONS; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.PRE_WARMUP_RUNS; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.WARMUP_KEY; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import com.amazonaws.ClientConfiguration; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.transfer.Copy; import com.amazonaws.services.s3.transfer.Download; import com.amazonaws.services.s3.transfer.TransferManager; import com.amazonaws.services.s3.transfer.TransferManagerBuilder; import com.amazonaws.services.s3.transfer.Upload; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.utils.Logger; abstract class V1BaseTransferManagerBenchmark implements TransferManagerBenchmark { private static final int MAX_CONCURRENCY = 100; private static final Logger logger = Logger.loggerFor("TransferManagerBenchmark"); protected final TransferManager transferManager; protected final AmazonS3 s3Client; protected final String bucket; protected final String key; protected final int iteration; protected final String path; private final File tmpFile; private final ExecutorService executorService; V1BaseTransferManagerBenchmark(TransferManagerBenchmarkConfig config) { logger.info(() -> "Benchmark config: " + config); Long partSizeInMb = config.partSizeInMb() == null ? null : config.partSizeInMb() * MB; s3Client = AmazonS3Client.builder() .withClientConfiguration(new ClientConfiguration().withMaxConnections(MAX_CONCURRENCY)) .build(); executorService = Executors.newFixedThreadPool(MAX_CONCURRENCY); transferManager = TransferManagerBuilder.standard() .withMinimumUploadPartSize(partSizeInMb) .withS3Client(s3Client) .withExecutorFactory(() -> executorService) .build(); bucket = config.bucket(); key = config.key(); path = config.filePath(); iteration = config.iteration() == null ? BENCHMARK_ITERATIONS : config.iteration(); try { tmpFile = new RandomTempFile(20 * MB); } catch (IOException e) { logger.error(() -> "Failed to create the file"); throw new RuntimeException("Failed to create the temp file", e); } } @Override public void run() { try { warmUp(); additionalWarmup(); doRunBenchmark(); } catch (Exception e) { logger.error(() -> "Exception occurred", e); } finally { cleanup(); } } protected void additionalWarmup() { // default to no-op } protected abstract void doRunBenchmark(); private void cleanup() { executorService.shutdown(); transferManager.shutdownNow(); s3Client.shutdown(); } private void warmUp() { logger.info(() -> "Starting to warm up"); for (int i = 0; i < PRE_WARMUP_ITERATIONS; i++) { warmUpUploadBatch(); warmUpDownloadBatch(); warmUpCopyBatch(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn(() -> "Thread interrupted when waiting for completion", e); } } logger.info(() -> "Ending warm up"); } private void warmUpCopyBatch() { List<Copy> uploads = new ArrayList<>(); for (int i = 0; i < 3; i++) { uploads.add(transferManager.copy(bucket, WARMUP_KEY, bucket, WARMUP_KEY + COPY_SUFFIX)); } uploads.forEach(u -> { try { u.waitForCopyResult(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error(() -> "Thread interrupted ", e); } }); } private void warmUpDownloadBatch() { List<Download> downloads = new ArrayList<>(); List<File> tmpFiles = new ArrayList<>(); for (int i = 0; i < PRE_WARMUP_RUNS; i++) { File tmpFile = RandomTempFile.randomUncreatedFile(); tmpFiles.add(tmpFile); downloads.add(transferManager.download(bucket, WARMUP_KEY, tmpFile)); } downloads.forEach(u -> { try { u.waitForCompletion(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error(() -> "Thread interrupted ", e); } }); tmpFiles.forEach(f -> runAndLogError(logger.logger(), "Deleting file failed", () -> Files.delete(f.toPath()))); } private void warmUpUploadBatch() { List<Upload> uploads = new ArrayList<>(); for (int i = 0; i < PRE_WARMUP_RUNS; i++) { uploads.add(transferManager.upload(bucket, WARMUP_KEY, tmpFile)); } uploads.forEach(u -> { try { u.waitForUploadResult(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error(() -> "Thread interrupted ", e); } }); } }
3,007
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/NoOpResponseTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.SdkPublisher; /** * A no-op {@link AsyncResponseTransformer} */ public class NoOpResponseTransformer<T> implements AsyncResponseTransformer<T, Void> { private CompletableFuture<Void> future; @Override public CompletableFuture<Void> prepare() { future = new CompletableFuture<>(); return future; } @Override public void onResponse(T response) { // do nothing } @Override public void onStream(SdkPublisher<ByteBuffer> publisher) { publisher.subscribe(new NoOpSubscriber(future)); } @Override public void exceptionOccurred(Throwable error) { future.completeExceptionally(error); } static class NoOpSubscriber implements Subscriber<ByteBuffer> { private final CompletableFuture<Void> future; private Subscription subscription; NoOpSubscriber(CompletableFuture<Void> future) { this.future = future; } @Override public void onSubscribe(Subscription s) { this.subscription = s; subscription.request(Long.MAX_VALUE); } @Override public void onNext(ByteBuffer byteBuffer) { subscription.request(1); } @Override public void onError(Throwable throwable) { future.completeExceptionally(throwable); } @Override public void onComplete() { future.complete(null); } } }
3,008
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/V1TransferManagerCopyBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.COPY_SUFFIX; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public class V1TransferManagerCopyBenchmark extends V1BaseTransferManagerBenchmark { private static final Logger logger = Logger.loggerFor("V1TransferManagerCopyBenchmark"); V1TransferManagerCopyBenchmark(TransferManagerBenchmarkConfig config) { super(config); Validate.notNull(config.key(), "Key must not be null"); } @Override protected void doRunBenchmark() { copy(); } @Override protected void additionalWarmup() { for (int i = 0; i < 3; i++) { copyOnce(new ArrayList<>()); } } private void copy() { List<Double> metrics = new ArrayList<>(); logger.info(() -> "Starting to copy"); for (int i = 0; i < iteration; i++) { copyOnce(metrics); } long contentLength = s3Client.getObjectMetadata(bucket, key).getContentLength(); printOutResult(metrics, "V1 copy", contentLength); } private void copyOnce(List<Double> latencies) { long start = System.currentTimeMillis(); try { transferManager.copy(bucket, key, bucket, key + COPY_SUFFIX).waitForCompletion(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn(() -> "Thread interrupted when waiting for completion", e); } long end = System.currentTimeMillis(); latencies.add((end - start) / 1000.0); } }
3,009
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/BaseJavaS3ClientBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.BENCHMARK_ITERATIONS; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.DEFAULT_TIMEOUT; import static software.amazon.awssdk.s3benchmarks.BenchmarkUtils.printOutResult; import static software.amazon.awssdk.transfer.s3.SizeConstant.MB; import java.time.Duration; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; public abstract class BaseJavaS3ClientBenchmark implements TransferManagerBenchmark { private static final Logger logger = Logger.loggerFor(BaseJavaS3ClientBenchmark.class); protected final S3Client s3Client; protected final S3AsyncClient s3AsyncClient; protected final String bucket; protected final String key; protected final Duration timeout; private final ChecksumAlgorithm checksumAlgorithm; private final int iteration; protected BaseJavaS3ClientBenchmark(TransferManagerBenchmarkConfig config) { this.bucket = Validate.paramNotNull(config.bucket(), "bucket"); this.key = Validate.paramNotNull(config.key(), "key"); this.timeout = Validate.getOrDefault(config.timeout(), () -> DEFAULT_TIMEOUT); this.iteration = Validate.getOrDefault(config.iteration(), () -> BENCHMARK_ITERATIONS); this.checksumAlgorithm = config.checksumAlgorithm(); this.s3Client = S3Client.create(); long partSizeInMb = Validate.paramNotNull(config.partSizeInMb(), "partSize"); long readBufferInMb = Validate.paramNotNull(config.readBufferSizeInMb(), "readBufferSizeInMb"); Validate.mutuallyExclusive("cannot use forceCrtHttpClient and connectionAcquisitionTimeoutInSec", config.forceCrtHttpClient(), config.connectionAcquisitionTimeoutInSec()); this.s3AsyncClient = S3AsyncClient.builder() .multipartEnabled(true) .multipartConfiguration(c -> c.minimumPartSizeInBytes(partSizeInMb * MB) .thresholdInBytes(partSizeInMb * 2 * MB) .apiCallBufferSizeInBytes(readBufferInMb * MB)) .httpClientBuilder(httpClient(config)) .build(); } private SdkAsyncHttpClient.Builder httpClient(TransferManagerBenchmarkConfig config) { if (config.forceCrtHttpClient()) { logger.info(() -> "Using CRT HTTP client"); AwsCrtAsyncHttpClient.Builder builder = AwsCrtAsyncHttpClient.builder(); if (config.readBufferSizeInMb() != null) { builder.readBufferSizeInBytes(config.readBufferSizeInMb() * MB); } if (config.maxConcurrency() != null) { builder.maxConcurrency(config.maxConcurrency()); } return builder; } NettyNioAsyncHttpClient.Builder builder = NettyNioAsyncHttpClient.builder(); if (config.connectionAcquisitionTimeoutInSec() != null) { Duration connAcqTimeout = Duration.ofSeconds(config.connectionAcquisitionTimeoutInSec()); builder.connectionAcquisitionTimeout(connAcqTimeout); } if (config.maxConcurrency() != null) { builder.maxConcurrency(config.maxConcurrency()); } return builder; } protected abstract void sendOneRequest(List<Double> latencies) throws Exception; protected abstract long contentLength() throws Exception; @Override public void run() { try { warmUp(); doRunBenchmark(); } catch (Exception e) { logger.error(() -> "Exception occurred", e); } finally { cleanup(); } } private void cleanup() { s3Client.close(); s3AsyncClient.close(); } private void warmUp() throws Exception { logger.info(() -> "Starting to warm up"); for (int i = 0; i < 3; i++) { sendOneRequest(new ArrayList<>()); Thread.sleep(500); } logger.info(() -> "Ending warm up"); } private void doRunBenchmark() throws Exception { List<Double> metrics = new ArrayList<>(); for (int i = 0; i < iteration; i++) { sendOneRequest(metrics); } printOutResult(metrics, "S3 Async client", contentLength()); } }
3,010
0
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/s3-benchmarks/src/main/java/software/amazon/awssdk/s3benchmarks/TransferManagerBenchmark.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.s3benchmarks; import java.util.function.Supplier; /** * Factory to create the benchmark */ @FunctionalInterface public interface TransferManagerBenchmark { /** * The benchmark method to run */ void run(); static TransferManagerBenchmark v2Download(TransferManagerBenchmarkConfig config) { return new TransferManagerDownloadBenchmark(config); } static TransferManagerBenchmark downloadDirectory(TransferManagerBenchmarkConfig config) { return new TransferManagerDownloadDirectoryBenchmark(config); } static TransferManagerBenchmark v2Upload(TransferManagerBenchmarkConfig config) { return new TransferManagerUploadBenchmark(config); } static TransferManagerBenchmark uploadDirectory(TransferManagerBenchmarkConfig config) { return new TransferManagerUploadDirectoryBenchmark(config); } static TransferManagerBenchmark copy(TransferManagerBenchmarkConfig config) { return new TransferManagerCopyBenchmark(config); } static TransferManagerBenchmark v1Download(TransferManagerBenchmarkConfig config) { return new V1TransferManagerDownloadBenchmark(config); } static TransferManagerBenchmark v1DownloadDirectory(TransferManagerBenchmarkConfig config) { return new V1TransferManagerDownloadDirectoryBenchmark(config); } static TransferManagerBenchmark v1Upload(TransferManagerBenchmarkConfig config) { return new V1TransferManagerUploadBenchmark(config); } static TransferManagerBenchmark v1UploadDirectory(TransferManagerBenchmarkConfig config) { return new V1TransferManagerUploadDirectoryBenchmark(config); } static TransferManagerBenchmark v1Copy(TransferManagerBenchmarkConfig config) { return new V1TransferManagerCopyBenchmark(config); } default <T> TimedResult<T> runWithTime(Supplier<T> toRun) { long start = System.currentTimeMillis(); T result = toRun.get(); long end = System.currentTimeMillis(); return new TimedResult<>(result, (end - start) / 1000.0); } final class TimedResult<T> { private final Double latency; private final T result; public TimedResult(T result, Double latency) { this.result = result; this.latency = latency; } public Double latency() { return latency; } public T result() { return result; } } }
3,011
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/EmptyPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.nio.ByteBuffer; import java.util.Optional; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; public class EmptyPublisher implements SdkHttpContentPublisher { @Override public void subscribe(Subscriber<? super ByteBuffer> subscriber) { subscriber.onSubscribe(new EmptySubscription(subscriber)); } @Override public Optional<Long> contentLength() { return Optional.of(0L); } private static class EmptySubscription implements Subscription { private final Subscriber subscriber; private volatile boolean done; EmptySubscription(Subscriber subscriber) { this.subscriber = subscriber; } @Override public void request(long l) { if (!done) { done = true; if (l <= 0) { this.subscriber.onError(new IllegalArgumentException("Demand must be positive")); } else { this.subscriber.onComplete(); } } } @Override public void cancel() { done = true; } } }
3,012
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/SimpleHttpContentPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.nio.ByteBuffer; import java.util.Optional; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; import software.amazon.awssdk.utils.IoUtils; /** * Implementation of {@link SdkHttpContentPublisher} that provides all it's data at once. Useful for * non streaming operations that are already marshalled into memory. */ @SdkInternalApi public final class SimpleHttpContentPublisher implements SdkHttpContentPublisher { private final ByteBuffer content; private final int length; public SimpleHttpContentPublisher(SdkHttpFullRequest request) { this.content = request.contentStreamProvider().map(p -> invokeSafely(() -> ByteBuffer.wrap(IoUtils.toByteArray(p.newStream())))) .orElseGet(() -> ByteBuffer.wrap(new byte[0])); this.length = content.remaining(); } public SimpleHttpContentPublisher(byte[] body) { this(ByteBuffer.wrap(body)); } public SimpleHttpContentPublisher(ByteBuffer byteBuffer) { this.content = byteBuffer; this.length = byteBuffer.remaining(); } @Override public Optional<Long> contentLength() { return Optional.of((long) length); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { s.onSubscribe(new SubscriptionImpl(s)); } private class SubscriptionImpl implements Subscription { private boolean running = true; private final Subscriber<? super ByteBuffer> s; private SubscriptionImpl(Subscriber<? super ByteBuffer> s) { this.s = s; } @Override public void request(long n) { if (running) { running = false; if (n <= 0) { s.onError(new IllegalArgumentException("Demand must be positive")); } else { s.onNext(content); s.onComplete(); } } } @Override public void cancel() { running = false; } } }
3,013
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/SdkAsyncHttpClientH1TestSuite.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE; import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE; import static io.netty.handler.codec.http.HttpHeaderValues.TEXT_PLAIN; import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.ServerSocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.util.SelfSignedCertificate; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; /** * A set of tests validating that the functionality implemented by a {@link SdkAsyncHttpClient} for HTTP/1 requests * * This is used by an HTTP plugin implementation by extending this class and implementing the abstract methods to provide this * suite with a testable HTTP client implementation. */ public abstract class SdkAsyncHttpClientH1TestSuite { private Server server; private SdkAsyncHttpClient client; protected abstract SdkAsyncHttpClient setupClient(); @BeforeEach public void setup() throws Exception { server = new Server(); server.init(); this.client = setupClient(); } @AfterEach public void teardown() throws InterruptedException { if (server != null) { server.shutdown(); } if (client != null) { client.close(); } server = null; } @Test public void connectionReceiveServerErrorStatusShouldNotReuseConnection() { server.return500OnFirstRequest = true; server.closeConnection = false; HttpTestUtils.sendGetRequest(server.port(), client).join(); HttpTestUtils.sendGetRequest(server.port(), client).join(); assertThat(server.channels.size()).isEqualTo(2); } @Test public void connectionReceiveOkStatusShouldReuseConnection() throws Exception { server.return500OnFirstRequest = false; server.closeConnection = false; HttpTestUtils.sendGetRequest(server.port(), client).join(); // The request-complete-future does not await the channel-release-future // Wait a small amount to allow the channel release to complete Thread.sleep(100); HttpTestUtils.sendGetRequest(server.port(), client).join(); assertThat(server.channels.size()).isEqualTo(1); } @Test public void connectionReceiveCloseHeaderShouldNotReuseConnection() throws InterruptedException { server.return500OnFirstRequest = false; server.closeConnection = true; HttpTestUtils.sendGetRequest(server.port(), client).join(); Thread.sleep(1000); HttpTestUtils.sendGetRequest(server.port(), client).join(); assertThat(server.channels.size()).isEqualTo(2); } @Test public void headRequestResponsesHaveNoPayload() { byte[] responseData = HttpTestUtils.sendHeadRequest(server.port(), client).join(); // The SDK core differentiates between NO data and ZERO bytes of data. Core expects it to be NO data, not ZERO bytes of // data for head requests. assertThat(responseData).isNull(); } @Test public void naughtyHeaderCharactersDoNotGetToServer() { String naughtyHeader = "foo\r\nbar"; assertThatThrownBy(() -> HttpTestUtils.sendRequest(client, SdkHttpFullRequest.builder() .uri(URI.create("https://localhost:" + server.port())) .method(SdkHttpMethod.POST) .appendHeader("h", naughtyHeader) .build()) .join()) .hasCauseInstanceOf(Exception.class); } @Test public void connectionsArePooledByHostAndPort() throws InterruptedException { HttpTestUtils.sendRequest(client, SdkHttpFullRequest.builder() .uri(URI.create("https://127.0.0.1:" + server.port() + "/foo?foo")) .method(SdkHttpMethod.GET) .build()) .join(); Thread.sleep(1_000); HttpTestUtils.sendRequest(client, SdkHttpFullRequest.builder() .uri(URI.create("https://127.0.0.1:" + server.port() + "/bar?bar")) .method(SdkHttpMethod.GET) .build()) .join(); assertThat(server.channels.size()).isEqualTo(1); } private static class Server extends ChannelInitializer<Channel> { private static final byte[] CONTENT = "helloworld".getBytes(StandardCharsets.UTF_8); private ServerBootstrap bootstrap; private ServerSocketChannel serverSock; private List<Channel> channels = new ArrayList<>(); private final NioEventLoopGroup group = new NioEventLoopGroup(); private SslContext sslCtx; private boolean return500OnFirstRequest; private boolean closeConnection; private volatile HttpRequest lastRequestReceived; public void init() throws Exception { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); bootstrap = new ServerBootstrap() .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.DEBUG)) .group(group) .childHandler(this); serverSock = (ServerSocketChannel) bootstrap.bind(0).sync().channel(); } public void shutdown() throws InterruptedException { group.shutdownGracefully().await(); serverSock.close(); } public int port() { return serverSock.localAddress().getPort(); } @Override protected void initChannel(Channel ch) { channels.add(ch); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(sslCtx.newHandler(ch.alloc())); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new BehaviorTestChannelHandler()); } private class BehaviorTestChannelHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { lastRequestReceived = (HttpRequest) msg; HttpResponseStatus status; if (ctx.channel().equals(channels.get(0)) && return500OnFirstRequest) { status = INTERNAL_SERVER_ERROR; } else { status = OK; } FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.wrappedBuffer(CONTENT)); response.headers() .set(CONTENT_TYPE, TEXT_PLAIN) .setInt(CONTENT_LENGTH, response.content().readableBytes()); if (closeConnection) { response.headers().set(CONNECTION, CLOSE); } ctx.writeAndFlush(response); } } } } }
3,014
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/RecordingNetworkTrafficListener.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; /** * Simple implementation of {@link WiremockNetworkTrafficListener} to record all requests received as a string for later * verification. */ public class RecordingNetworkTrafficListener implements WiremockNetworkTrafficListener { private final StringBuilder requests = new StringBuilder(); @Override public void opened(Socket socket) { } @Override public void incoming(Socket socket, ByteBuffer byteBuffer) { requests.append(StandardCharsets.UTF_8.decode(byteBuffer)); } @Override public void outgoing(Socket socket, ByteBuffer byteBuffer) { } @Override public void closed(Socket socket) { } public void reset() { requests.setLength(0); } public StringBuilder requests() { return requests; } }
3,015
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/HttpProxyTestSuite.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.net.URISyntaxException; import java.util.List; 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.http.proxy.ProxyConfigCommonTestData; import software.amazon.awssdk.http.proxy.TestProxySetting; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.StringUtils; public abstract class HttpProxyTestSuite { public static final String HTTP = "http"; public static final String HTTPS = "https"; private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); public static Stream<Arguments> proxyConfigurationSetting() { return ProxyConfigCommonTestData.proxyConfigurationSetting(); } static void setSystemProperties(List<Pair<String, String>> settingsPairs, String protocol) { settingsPairs.stream() .filter(p -> StringUtils.isNotBlank(p.left())) .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} -{0} useSystemProperty {4} useEnvironmentVariable {5} userSetProxy {3} then expected " + "is {6}") @MethodSource("proxyConfigurationSetting") void givenLocalSettingForHttpThenCorrectProxyConfig(String testCaseName, List<Pair<String, String>> systemSettingsPair, List<Pair<String, String>> envSystemSetting, TestProxySetting userSetProxySettings, Boolean useSystemProperty, Boolean useEnvironmentVariable, TestProxySetting expectedProxySettings) throws URISyntaxException { setSystemProperties(systemSettingsPair, HTTP); setEnvironmentProperties(envSystemSetting, HTTP); assertProxyConfiguration(userSetProxySettings, expectedProxySettings, useSystemProperty, useEnvironmentVariable, HTTP); } @ParameterizedTest(name = "{index} -{0} useSystemProperty {4} useEnvironmentVariable {5} userSetProxy {3} then expected " + "is {6}") @MethodSource("proxyConfigurationSetting") void givenLocalSettingForHttpsThenCorrectProxyConfig( String testCaseName, List<Pair<String, String>> systemSettingsPair, List<Pair<String, String>> envSystemSetting, TestProxySetting userSetProxySettings, Boolean useSystemProperty, Boolean useEnvironmentVariable, TestProxySetting expectedProxySettings) throws URISyntaxException { setSystemProperties(systemSettingsPair, HTTPS); setEnvironmentProperties(envSystemSetting, HTTPS); assertProxyConfiguration(userSetProxySettings, expectedProxySettings, useSystemProperty, useEnvironmentVariable, HTTPS); } protected abstract void assertProxyConfiguration(TestProxySetting userSetProxySettings, TestProxySetting expectedProxySettings, Boolean useSystemProperty, Boolean useEnvironmentVariable, String protocol) throws URISyntaxException; }
3,016
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/SdkHttpClientTestSuite.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.absent; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.common.FatalStartupException; import com.github.tomakehurst.wiremock.http.RequestMethod; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Random; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Logger; /** * A set of tests validating that the functionality implemented by a {@link SdkHttpClient}. * * This is used by an HTTP plugin implementation by extending this class and implementing the abstract methods to provide this * suite with a testable HTTP client implementation. */ @RunWith(MockitoJUnitRunner.class) public abstract class SdkHttpClientTestSuite { private static final Logger LOG = Logger.loggerFor(SdkHttpClientTestSuite.class); private static final ConnectionCountingTrafficListener CONNECTION_COUNTER = new ConnectionCountingTrafficListener(); @Rule public WireMockRule mockServer = createWireMockRule(); private final Random rng = new Random(); @Test public void supportsResponseCode200() throws Exception { testForResponseCode(HttpURLConnection.HTTP_OK); } @Test public void supportsResponseCode200Head() throws Exception { // HEAD is special due to closing of the connection immediately and streams are null testForResponseCode(HttpURLConnection.HTTP_FORBIDDEN, SdkHttpMethod.HEAD); } @Test public void supportsResponseCode202() throws Exception { testForResponseCode(HttpURLConnection.HTTP_ACCEPTED); } @Test public void supportsResponseCode403() throws Exception { testForResponseCode(HttpURLConnection.HTTP_FORBIDDEN); } @Test public void supportsResponseCode403Head() throws Exception { testForResponseCode(HttpURLConnection.HTTP_FORBIDDEN, SdkHttpMethod.HEAD); } @Test public void supportsResponseCode301() throws Exception { testForResponseCode(HttpURLConnection.HTTP_MOVED_PERM); } @Test public void supportsResponseCode302() throws Exception { testForResponseCode(HttpURLConnection.HTTP_MOVED_TEMP); } @Test public void supportsResponseCode500() throws Exception { testForResponseCode(HttpURLConnection.HTTP_INTERNAL_ERROR); } @Test public void validatesHttpsCertificateIssuer() throws Exception { SdkHttpClient client = createSdkHttpClient(); SdkHttpFullRequest request = mockSdkRequest("https://localhost:" + mockServer.httpsPort(), SdkHttpMethod.POST); assertThatThrownBy(client.prepareRequest(HttpExecuteRequest.builder().request(request).build())::call) .isInstanceOf(SSLHandshakeException.class); } @Test public void connectionPoolingWorks() throws Exception { int initialOpenedConnections = CONNECTION_COUNTER.openedConnections(); SdkHttpClientOptions httpClientOptions = new SdkHttpClientOptions(); httpClientOptions.trustAll(true); SdkHttpClient client = createSdkHttpClient(httpClientOptions); stubForMockRequest(200); for (int i = 0; i < 5; i++) { SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), SdkHttpMethod.POST); HttpExecuteResponse response = client.prepareRequest(HttpExecuteRequest.builder() .request(req) .contentStreamProvider(req.contentStreamProvider().orElse(null)) .build()) .call(); response.responseBody().ifPresent(IoUtils::drainInputStream); } assertThat(CONNECTION_COUNTER.openedConnections()).isEqualTo(initialOpenedConnections + 1); } @Test public void connectionsAreNotReusedOn5xxErrors() throws Exception { int initialOpenedConnections = CONNECTION_COUNTER.openedConnections(); SdkHttpClientOptions httpClientOptions = new SdkHttpClientOptions(); httpClientOptions.trustAll(true); SdkHttpClient client = createSdkHttpClient(httpClientOptions); stubForMockRequest(503); for (int i = 0; i < 5; i++) { SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), SdkHttpMethod.POST); HttpExecuteResponse response = client.prepareRequest(HttpExecuteRequest.builder() .request(req) .contentStreamProvider(req.contentStreamProvider().orElse(null)) .build()) .call(); response.responseBody().ifPresent(IoUtils::drainInputStream); } assertThat(CONNECTION_COUNTER.openedConnections()).isEqualTo(initialOpenedConnections + 5); } @Test public void testCustomTlsTrustManager() throws Exception { WireMockServer selfSignedServer = HttpTestUtils.createSelfSignedServer(); TrustManagerFactory managerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); managerFactory.init(HttpTestUtils.getSelfSignedKeyStore()); SdkHttpClientOptions httpClientOptions = new SdkHttpClientOptions(); httpClientOptions.tlsTrustManagersProvider(managerFactory::getTrustManagers); selfSignedServer.start(); try { SdkHttpClient client = createSdkHttpClient(httpClientOptions); SdkHttpFullRequest request = mockSdkRequest("https://localhost:" + selfSignedServer.httpsPort(), SdkHttpMethod.POST); client.prepareRequest(HttpExecuteRequest.builder().request(request).build()).call(); } finally { selfSignedServer.stop(); } } @Test public void testTrustAllWorks() throws Exception { SdkHttpClientOptions httpClientOptions = new SdkHttpClientOptions(); httpClientOptions.trustAll(true); testForResponseCodeUsingHttps(createSdkHttpClient(httpClientOptions), HttpURLConnection.HTTP_OK); } @Test public void testCustomTlsTrustManagerAndTrustAllFails() throws Exception { SdkHttpClientOptions httpClientOptions = new SdkHttpClientOptions(); httpClientOptions.tlsTrustManagersProvider(() -> new TrustManager[0]); httpClientOptions.trustAll(true); assertThatThrownBy(() -> createSdkHttpClient(httpClientOptions)).isInstanceOf(IllegalArgumentException.class); } protected void testForResponseCode(int returnCode) throws Exception { testForResponseCode(returnCode, SdkHttpMethod.POST); } private void testForResponseCode(int returnCode, SdkHttpMethod method) throws Exception { SdkHttpClient client = createSdkHttpClient(); stubForMockRequest(returnCode); SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), method); HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder() .request(req) .contentStreamProvider(req.contentStreamProvider() .orElse(null)) .build()) .call(); validateResponse(rsp, returnCode, method); } protected void testForResponseCodeUsingHttps(SdkHttpClient client, int returnCode) throws Exception { SdkHttpMethod sdkHttpMethod = SdkHttpMethod.POST; stubForMockRequest(returnCode); SdkHttpFullRequest req = mockSdkRequest("https://localhost:" + mockServer.httpsPort(), sdkHttpMethod); HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder() .request(req) .contentStreamProvider(req.contentStreamProvider() .orElse(null)) .build()) .call(); validateResponse(rsp, returnCode, sdkHttpMethod); } protected void stubForMockRequest(int returnCode) { ResponseDefinitionBuilder responseBuilder = aResponse().withStatus(returnCode) .withHeader("Some-Header", "With Value") .withBody("hello"); if (returnCode >= 300 && returnCode <= 399) { responseBuilder.withHeader("Location", "Some New Location"); } mockServer.stubFor(any(urlPathEqualTo("/")).willReturn(responseBuilder)); } private void validateResponse(HttpExecuteResponse response, int returnCode, SdkHttpMethod method) throws IOException { RequestMethod requestMethod = RequestMethod.fromString(method.name()); RequestPatternBuilder patternBuilder = RequestPatternBuilder.newRequestPattern(requestMethod, urlMatching("/")) .withHeader("Host", containing("localhost")) .withHeader("User-Agent", equalTo("hello-world!")); if (method == SdkHttpMethod.HEAD) { patternBuilder.withRequestBody(absent()); } else { patternBuilder.withRequestBody(equalTo("Body")); } mockServer.verify(1, patternBuilder); if (method == SdkHttpMethod.HEAD) { assertThat(response.responseBody()).isEmpty(); } else { assertThat(IoUtils.toUtf8String(response.responseBody().orElse(null))).isEqualTo("hello"); } assertThat(response.httpResponse().firstMatchingHeader("Some-Header")).contains("With Value"); assertThat(response.httpResponse().statusCode()).isEqualTo(returnCode); mockServer.resetMappings(); } protected SdkHttpFullRequest mockSdkRequest(String uriString, SdkHttpMethod method) { URI uri = URI.create(uriString); SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder() .uri(uri) .method(method) .putHeader("Host", uri.getHost()) .putHeader("User-Agent", "hello-world!"); if (method != SdkHttpMethod.HEAD) { requestBuilder.contentStreamProvider(() -> new ByteArrayInputStream("Body".getBytes(StandardCharsets.UTF_8))); } return requestBuilder.build(); } /** * {@link #createSdkHttpClient(SdkHttpClientOptions)} with default options. */ protected final SdkHttpClient createSdkHttpClient() { return createSdkHttpClient(new SdkHttpClientOptions()); } /** * Implemented by a child class to create an HTTP client to validate based on the provided options. */ protected abstract SdkHttpClient createSdkHttpClient(SdkHttpClientOptions options); /** * The options that should be considered when creating the client via {@link #createSdkHttpClient(SdkHttpClientOptions)}. */ protected static final class SdkHttpClientOptions { private TlsTrustManagersProvider tlsTrustManagersProvider = null; private boolean trustAll = false; public TlsTrustManagersProvider tlsTrustManagersProvider() { return tlsTrustManagersProvider; } public void tlsTrustManagersProvider(TlsTrustManagersProvider tlsTrustManagersProvider) { this.tlsTrustManagersProvider = tlsTrustManagersProvider; } public boolean trustAll() { return trustAll; } public void trustAll(boolean trustAll) { this.trustAll = trustAll; } } private WireMockRule createWireMockRule() { int maxAttempts = 5; for (int i = 0; i < maxAttempts; ++i) { try { return new WireMockRule(wireMockConfig().dynamicPort() .dynamicHttpsPort() .networkTrafficListener(CONNECTION_COUNTER)); } catch (FatalStartupException e) { int attemptNum = i + 1; LOG.debug(() -> "Was not able to start WireMock server. Attempt " + attemptNum, e); if (attemptNum != maxAttempts) { try { long sleepMillis = 1_000L + rng.nextInt(1_000); Thread.sleep(sleepMillis); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException("Backoff interrupted", ie); } } } } throw new RuntimeException("Unable to setup WireMock rule"); } }
3,017
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/ConnectionCountingTrafficListener.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import com.github.tomakehurst.wiremock.http.trafficlistener.WiremockNetworkTrafficListener; import java.io.ByteArrayOutputStream; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import software.amazon.awssdk.utils.BinaryUtils; public class ConnectionCountingTrafficListener implements WiremockNetworkTrafficListener { private final Map<Socket, ByteArrayOutputStream> sockets = new ConcurrentHashMap<>(); @Override public void opened(Socket socket) { sockets.put(socket, new ByteArrayOutputStream()); } @Override public void incoming(Socket socket, ByteBuffer bytes) { invokeSafely(() -> sockets.get(socket).write(BinaryUtils.copyBytesFrom(bytes.asReadOnlyBuffer()))); } @Override public void outgoing(Socket socket, ByteBuffer bytes) { } @Override public void closed(Socket socket) { } public int openedConnections() { int count = 0; for (ByteArrayOutputStream data : sockets.values()) { byte[] bytes = data.toByteArray(); try { if (new String(bytes, StandardCharsets.UTF_8).startsWith("POST /__admin/mappings")) { // Admin-related stuff, don't count it continue; } // Not admin-related stuff, so count it ++count; } catch (RuntimeException e) { // Could not decode, so it's not admin-related stuff (which uses JSON and can always be decoded) ++count; } } return count; } }
3,018
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/SdkHttpClientDefaultTestSuite.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.absent; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.http.RequestMethod; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.nio.charset.StandardCharsets; import javax.net.ssl.SSLHandshakeException; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.utils.IoUtils; /** * A set of tests validating that the functionality implemented by a {@link SdkHttpClient}. * * This is used by an HTTP plugin implementation by extending this class and implementing the abstract methods to provide this * suite with a testable HTTP client implementation. */ @RunWith(MockitoJUnitRunner.class) public abstract class SdkHttpClientDefaultTestSuite { @Rule public WireMockRule mockServer = new WireMockRule(wireMockConfig().dynamicPort().dynamicHttpsPort()); @Test public void supportsResponseCode200() throws Exception { testForResponseCode(HttpURLConnection.HTTP_OK); } @Test public void supportsResponseCode200Head() throws Exception { // HEAD is special due to closing of the connection immediately and streams are null testForResponseCode(HttpURLConnection.HTTP_FORBIDDEN, SdkHttpMethod.HEAD); } @Test public void supportsResponseCode202() throws Exception { testForResponseCode(HttpURLConnection.HTTP_ACCEPTED); } @Test public void supportsResponseCode403() throws Exception { testForResponseCode(HttpURLConnection.HTTP_FORBIDDEN); } @Test public void supportsResponseCode403Head() throws Exception { testForResponseCode(HttpURLConnection.HTTP_FORBIDDEN, SdkHttpMethod.HEAD); } @Test public void supportsResponseCode301() throws Exception { testForResponseCode(HttpURLConnection.HTTP_MOVED_PERM); } @Test public void supportsResponseCode302() throws Exception { testForResponseCode(HttpURLConnection.HTTP_MOVED_TEMP); } @Test public void supportsResponseCode500() throws Exception { testForResponseCode(HttpURLConnection.HTTP_INTERNAL_ERROR); } @Test public void validatesHttpsCertificateIssuer() throws Exception { SdkHttpClient client = createSdkHttpClient(); SdkHttpFullRequest request = mockSdkRequest("https://localhost:" + mockServer.httpsPort(), SdkHttpMethod.POST); assertThatThrownBy(client.prepareRequest(HttpExecuteRequest.builder().request(request).build())::call) .isInstanceOf(SSLHandshakeException.class); } private void testForResponseCode(int returnCode) throws Exception { testForResponseCode(returnCode, SdkHttpMethod.POST); } private void testForResponseCode(int returnCode, SdkHttpMethod method) throws Exception { SdkHttpClient client = createSdkHttpClient(); stubForMockRequest(returnCode); SdkHttpFullRequest req = mockSdkRequest("http://localhost:" + mockServer.port(), method); HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder() .request(req) .contentStreamProvider(req.contentStreamProvider() .orElse(null)) .build()) .call(); validateResponse(rsp, returnCode, method); } protected void testForResponseCodeUsingHttps(SdkHttpClient client, int returnCode) throws Exception { SdkHttpMethod sdkHttpMethod = SdkHttpMethod.POST; stubForMockRequest(returnCode); SdkHttpFullRequest req = mockSdkRequest("https://localhost:" + mockServer.httpsPort(), sdkHttpMethod); HttpExecuteResponse rsp = client.prepareRequest(HttpExecuteRequest.builder() .request(req) .contentStreamProvider(req.contentStreamProvider() .orElse(null)) .build()) .call(); validateResponse(rsp, returnCode, sdkHttpMethod); } private void stubForMockRequest(int returnCode) { ResponseDefinitionBuilder responseBuilder = aResponse().withStatus(returnCode) .withHeader("Some-Header", "With Value") .withBody("hello"); if (returnCode >= 300 && returnCode <= 399) { responseBuilder.withHeader("Location", "Some New Location"); } mockServer.stubFor(any(urlPathEqualTo("/")).willReturn(responseBuilder)); } private void validateResponse(HttpExecuteResponse response, int returnCode, SdkHttpMethod method) throws IOException { RequestMethod requestMethod = RequestMethod.fromString(method.name()); RequestPatternBuilder patternBuilder = RequestPatternBuilder.newRequestPattern(requestMethod, urlMatching("/")) .withHeader("Host", containing("localhost")) .withHeader("User-Agent", equalTo("hello-world!")); if (method == SdkHttpMethod.HEAD) { patternBuilder.withRequestBody(absent()); } else { patternBuilder.withRequestBody(equalTo("Body")); } mockServer.verify(1, patternBuilder); if (method == SdkHttpMethod.HEAD) { assertThat(response.responseBody()).isEmpty(); } else { assertThat(IoUtils.toUtf8String(response.responseBody().orElse(null))).isEqualTo("hello"); } assertThat(response.httpResponse().firstMatchingHeader("Some-Header")).contains("With Value"); assertThat(response.httpResponse().statusCode()).isEqualTo(returnCode); mockServer.resetMappings(); } private SdkHttpFullRequest mockSdkRequest(String uriString, SdkHttpMethod method) { URI uri = URI.create(uriString); SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder() .uri(uri) .method(method) .putHeader("Host", uri.getHost()) .putHeader("User-Agent", "hello-world!"); if (method != SdkHttpMethod.HEAD) { requestBuilder.contentStreamProvider(() -> new ByteArrayInputStream("Body".getBytes(StandardCharsets.UTF_8))); } return requestBuilder.build(); } /** * Implemented by a child class to create an HTTP client to validate, without any extra options. */ protected abstract SdkHttpClient createSdkHttpClient(); }
3,019
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/HttpTestUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static java.nio.charset.StandardCharsets.UTF_8; import static software.amazon.awssdk.utils.StringUtils.isBlank; import com.github.tomakehurst.wiremock.WireMockServer; import io.reactivex.Flowable; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URL; import java.nio.ByteBuffer; import java.security.KeyStore; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Stream; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; import software.amazon.awssdk.utils.BinaryUtils; public class HttpTestUtils { private HttpTestUtils() { } public static WireMockServer createSelfSignedServer() { URL selfSignedJks = SdkHttpClientTestSuite.class.getResource("/selfSigned.jks"); return new WireMockServer(wireMockConfig() .dynamicHttpsPort() .keystorePath(selfSignedJks.toString()) .keystorePassword("changeit") .keyManagerPassword("changeit") .keystoreType("jks") ); } public static KeyStore getSelfSignedKeyStore() throws Exception { URL selfSignedJks = SdkHttpClientTestSuite.class.getResource("/selfSigned.jks"); KeyStore keyStore = KeyStore.getInstance("jks"); try (InputStream stream = selfSignedJks.openStream()) { keyStore.load(stream, "changeit".toCharArray()); } return keyStore; } public static CompletableFuture<byte[]> sendGetRequest(int serverPort, SdkAsyncHttpClient client) { return sendRequest(serverPort, client, SdkHttpMethod.GET); } public static CompletableFuture<byte[]> sendHeadRequest(int serverPort, SdkAsyncHttpClient client) { return sendRequest(serverPort, client, SdkHttpMethod.HEAD); } private static CompletableFuture<byte[]> sendRequest(int serverPort, SdkAsyncHttpClient client, SdkHttpMethod httpMethod) { SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(httpMethod) .protocol("https") .host("127.0.0.1") .port(serverPort) .build(); return sendRequest(client, request); } public static CompletableFuture<byte[]> sendRequest(SdkAsyncHttpClient client, SdkHttpFullRequest request) { ByteArrayOutputStream responsePayload = new ByteArrayOutputStream(); AtomicBoolean responsePayloadReceived = new AtomicBoolean(false); return client.execute(AsyncExecuteRequest.builder() .responseHandler(new SdkAsyncHttpResponseHandler() { @Override public void onHeaders(SdkHttpResponse headers) { } @Override public void onStream(Publisher<ByteBuffer> stream) { Flowable.fromPublisher(stream).forEach(b -> { responsePayloadReceived.set(true); responsePayload.write(BinaryUtils.copyAllBytesFrom(b)); }); } @Override public void onError(Throwable error) { } }) .request(request) .requestContentPublisher(new EmptyPublisher()) .build()) .thenApply(v -> responsePayloadReceived.get() ? responsePayload.toByteArray() : null); } public static SdkHttpContentPublisher createProvider(String body) { Stream<ByteBuffer> chunks = splitStringBySize(body).stream() .map(chunk -> ByteBuffer.wrap(chunk.getBytes(UTF_8))); return new SdkHttpContentPublisher() { @Override public Optional<Long> contentLength() { return Optional.of(Long.valueOf(body.length())); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { chunks.forEach(s::onNext); s.onComplete(); } @Override public void cancel() { } }); } }; } public static Collection<String> splitStringBySize(String str) { if (isBlank(str)) { return Collections.emptyList(); } ArrayList<String> split = new ArrayList<>(); for (int i = 0; i <= str.length() / 1000; i++) { split.add(str.substring(i * 1000, Math.min((i + 1) * 1000, str.length()))); } return split; } }
3,020
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/RecordingResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Publisher; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import software.amazon.awssdk.http.async.SimpleSubscriber; import software.amazon.awssdk.metrics.MetricCollector; public final class RecordingResponseHandler implements SdkAsyncHttpResponseHandler { private final List<SdkHttpResponse> responses = new ArrayList<>(); private final StringBuilder bodyParts = new StringBuilder(); private final CompletableFuture<Void> completeFuture = new CompletableFuture<>(); private final MetricCollector collector = MetricCollector.create("test"); @Override public void onHeaders(SdkHttpResponse response) { responses.add(response); } @Override public void onStream(Publisher<ByteBuffer> publisher) { publisher.subscribe(new SimpleSubscriber(byteBuffer -> { byte[] b = new byte[byteBuffer.remaining()]; byteBuffer.duplicate().get(b); bodyParts.append(new String(b, StandardCharsets.UTF_8)); }) { @Override public void onError(Throwable t) { completeFuture.completeExceptionally(t); } @Override public void onComplete() { completeFuture.complete(null); } }); } @Override public void onError(Throwable error) { completeFuture.completeExceptionally(error); } public String fullResponseAsString() { return bodyParts.toString(); } public List<SdkHttpResponse> responses() { return responses; } public StringBuilder bodyParts() { return bodyParts; } public CompletableFuture<Void> completeFuture() { return completeFuture; } public MetricCollector collector() { return collector; } }
3,021
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/proxy/TestProxySetting.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.proxy; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; public class TestProxySetting { private Integer port = 0; private String host; private String userName; private String password; private Set<String> nonProxyHosts = new HashSet<>(); @Override public String toString() { return "TestProxySetting{" + "port=" + port + ", host='" + host + '\'' + ", userName='" + userName + '\'' + ", password='" + password + '\'' + ", nonProxyHosts=" + nonProxyHosts + '}' ; } public Integer getPort() { return port; } public String getHost() { return host; } public String getUserName() { return userName; } public String getPassword() { return password; } public Set<String> getNonProxyHosts() { return Collections.unmodifiableSet(nonProxyHosts); } public TestProxySetting port(Integer port) { this.port = port; return this; } public TestProxySetting host(String host) { this.host = host; return this; } public TestProxySetting userName(String userName) { this.userName = userName; return this; } public TestProxySetting password(String password) { this.password = password; return this; } public TestProxySetting nonProxyHost(String... nonProxyHosts) { this.nonProxyHosts = nonProxyHosts != null ? Arrays.stream(nonProxyHosts) .collect(Collectors.toSet()) : new HashSet<>(); return this; } }
3,022
0
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/test/http-client-tests/src/main/java/software/amazon/awssdk/http/proxy/ProxyConfigCommonTestData.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.proxy; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.stream.Stream; import org.junit.jupiter.params.provider.Arguments; import software.amazon.awssdk.utils.Pair; public final class ProxyConfigCommonTestData { public static final String SYSTEM_PROPERTY_HOST = "systemProperty.com"; public static final String SYSTEM_PROPERTY_PORT_NUMBER = "2222"; public static final String SYSTEM_PROPERTY_NON_PROXY = "systemPropertyNonProxy.com".toLowerCase(Locale.US); public static final String SYSTEM_PROPERTY_USER = "systemPropertyUserOne"; public static final String SYSTEM_PROPERTY_PASSWORD = "systemPropertyPassword"; public static final String ENV_VARIABLE_USER = "envUserOne"; public static final String ENV_VARIABLE_PASSWORD = "envPassword"; public static final String ENVIRONMENT_HOST = "environmentVariable.com".toLowerCase(Locale.US); public static final String ENVIRONMENT_VARIABLE_PORT_NUMBER = "3333"; public static final String ENVIRONMENT_VARIABLE_NON_PROXY = "environmentVariableNonProxy".toLowerCase(Locale.US); public static final String USER_HOST_ON_BUILDER = "proxyBuilder.com"; public static final int USER_PORT_NUMBER_ON_BUILDER = 9999; public static final String USER_USERNAME_ON_BUILDER = "proxyBuilderUser"; public static final String USER_PASSWORD_ON_BUILDER = "proxyBuilderPassword"; public static final String USER_NONPROXY_ON_BUILDER = "proxyBuilderNonProxy.com".toLowerCase(Locale.US); private ProxyConfigCommonTestData() { } public static Stream<Arguments> proxyConfigurationSetting() { return Stream.of( Arguments.of( "Provided system and environment variable when configured default setting then uses System property", systemPropertySettings(), environmentSettings(), new TestProxySetting(), null, null, getSystemPropertyProxySettings()), Arguments.of( "Provided system and environment variable when Host and port used from Builder then resolved Poxy " + "config uses User password from System setting", systemPropertySettings(), environmentSettings(), new TestProxySetting().host("localhost").port(80), null, null, getSystemPropertyProxySettings().host("localhost" ).port(80)), Arguments.of( "Provided system and environment variable when configured user setting then uses User provider setting", systemPropertySettings(), environmentSettings(), getTestProxySettings(), null, null, getTestProxySettings()), Arguments.of( "Provided: System property settings and environment variables are set. " + "When: useEnvironmentVariable is set to \true. And: useSystemProperty is left at its default value. Then: The" + " proxy configuration gets resolved to " + "use system properties ", systemPropertySettings(), environmentSettings(), new TestProxySetting(), null, true, getSystemPropertyProxySettings()), Arguments.of( "Provided: System property settings and environment variables are set. " + "When: useEnvironmentVariable is set to true. And: useSystemProperty is set to false. Then: " + "The proxy configuration gets resolved to use environment variable values", systemPropertySettings(), environmentSettings(), new TestProxySetting(), false, true, getEnvironmentVariableProxySettings()), // No System Property only Environment variable set Arguments.of( "Provided with no system property and valid environment variables, " + "when using the default proxy builder, the proxy configuration is resolved to use environment variables.", Collections.singletonList(Pair.of("", "")), environmentSettings(), new TestProxySetting(), null, null, getEnvironmentVariableProxySettings()), Arguments.of( "Provided with no system property and valid environment variables, when using the host," + "port on builder , the proxy configuration is resolved to username and password of environment variables.", Collections.singletonList(Pair.of("", "")), environmentSettings(), new TestProxySetting().host(USER_HOST_ON_BUILDER).port(USER_PORT_NUMBER_ON_BUILDER), null, true, getEnvironmentVariableProxySettings().host(USER_HOST_ON_BUILDER).port(USER_PORT_NUMBER_ON_BUILDER)), Arguments.of( "Provided with no system property and valid environment variables, when using the host,port on builder" + " , the proxy configuration is resolved to Builder values.", Collections.singletonList(Pair.of("", "")), environmentSettings(), getTestProxySettings(), null, null, getTestProxySettings()), Arguments.of( "Provided environment variable and No System Property when default ProxyConfig then uses environment " + "variable ", Collections.singletonList(Pair.of("", "")), environmentSettings(), new TestProxySetting(), null, true, getEnvironmentVariableProxySettings()), Arguments.of( "Provided only environment variable when useSytemProperty set to true " + "then proxy resolved to environment", Collections.singletonList(Pair.of("", "")), environmentSettings(), null, true, null, getEnvironmentVariableProxySettings()), Arguments.of( "Provided only environment variable when useEnvironmentVariable set to false then proxy resolved " + "to null", Collections.singletonList(Pair.of("", "")), environmentSettings(), new TestProxySetting(), null, true, getEnvironmentVariableProxySettings()), // Only System Property and no Environment variable Arguments.of( "Provided system and no environment variable when default ProxyConfig then used System Proxy config", systemPropertySettings(), Collections.singletonList(Pair.of("", "")), null, null, null, getSystemPropertyProxySettings()), Arguments.of( "Provided system and no environment variable when host from builder then Host is resolved from builder", systemPropertySettings(), Collections.singletonList(Pair.of("", "")), new TestProxySetting().port(USER_PORT_NUMBER_ON_BUILDER).host(USER_HOST_ON_BUILDER), null, null, getSystemPropertyProxySettings().host(USER_HOST_ON_BUILDER).port(USER_PORT_NUMBER_ON_BUILDER)), Arguments.of( "Provided system and no environment variable when user ProxyConfig on builder " + "then User Proxy resolved", systemPropertySettings(), Collections.singletonList(Pair.of("", "")), getTestProxySettings(), true, true, getTestProxySettings()), Arguments.of( "Provided system and no environment variable when useEnvironmentVariable then System property proxy resolved", systemPropertySettings(), Collections.singletonList(Pair.of("", "")), new TestProxySetting(), null, true, getSystemPropertyProxySettings()), Arguments.of( "Provided system and no environment variable " + "when useSystemProperty and useEnvironment set to false then resolved config is null ", systemPropertySettings(), Collections.singletonList(Pair.of("", "")), new TestProxySetting(), false, true, new TestProxySetting()), // when both system property and environment variable are null Arguments.of( "Provided no system property and no environment variable when default ProxyConfig " + "then no Proxy config resolved", Collections.singletonList(Pair.of("", "")), Collections.singletonList(Pair.of("", "")), new TestProxySetting(), null, null, new TestProxySetting()), Arguments.of( "Provided no system property and no environment variable when user ProxyConfig then user Proxy config resolved", Collections.singletonList(Pair.of("", "")), Collections.singletonList(Pair.of("", "")), new TestProxySetting().host(USER_HOST_ON_BUILDER).port(USER_PORT_NUMBER_ON_BUILDER), null, null, new TestProxySetting().host(USER_HOST_ON_BUILDER).port(USER_PORT_NUMBER_ON_BUILDER)), Arguments.of( "Provided no system property and no environment variable when user ProxyConfig " + "then user Proxy config resolved", Collections.singletonList(Pair.of("", "")), Collections.singletonList(Pair.of("", "")), getTestProxySettings(), null, null, getTestProxySettings()), Arguments.of( "Provided no system property and no environment variable when useSystemProperty and " + "useEnvironmentVariable set then resolved host is null ", Collections.singletonList(Pair.of("", "")), Collections.singletonList(Pair.of("", "")), null, true, true, new TestProxySetting()), // Incomplete Proxy setting in systemProperty and environment variable Arguments.of( "Given System property with No user name and Environment variable with user name " + "when Default proxy config then resolves proxy config with no user name same as System property", getSystemPropertiesWithNoUserName(), environmentSettingsWithNoPassword(), new TestProxySetting(), null, null, new TestProxySetting().host(SYSTEM_PROPERTY_HOST).port(Integer.parseInt(SYSTEM_PROPERTY_PORT_NUMBER)) .password(SYSTEM_PROPERTY_PASSWORD)), Arguments.of( "Given password in System property when Password present in system property " + "then proxy resolves to Builder password", getSystemPropertiesWithNoUserName(), environmentSettingsWithNoPassword(), new TestProxySetting().password("passwordFromBuilder"), null, null, getSystemPropertyProxySettings().password("passwordFromBuilder") .userName(null) .nonProxyHost(null)), Arguments.of( "Given partial System Property and partial Environment variables when Builder method with Host " + "and port only then Proxy config uses password from System property and no User name since System property" + " has none", getSystemPropertiesWithNoUserName(), environmentSettingsWithNoPassword(), new TestProxySetting().host(USER_HOST_ON_BUILDER).port(USER_PORT_NUMBER_ON_BUILDER), null, null, getSystemPropertyProxySettings().host(USER_HOST_ON_BUILDER) .port(USER_PORT_NUMBER_ON_BUILDER) .userName(null) .nonProxyHost(null)), Arguments.of( "Given System Property and Environment variables when valid empty Proxy config on Builder then " + "Proxy config resolves to Proxy on builder.", systemPropertySettings(), environmentSettings(), getTestProxySettings(), null, null, getTestProxySettings()), Arguments.of( "Given partial system property and partial environment variable when User " + "set useEnvironmentVariable to true and default System property then default system property gets used.", getSystemPropertiesWithNoUserName(), environmentSettingsWithNoPassword(), new TestProxySetting(), null, true, getSystemPropertyProxySettings().nonProxyHost(null) .userName(null)), Arguments.of( "Given partial system property and partial environment variable when User " + "set useEnvironmentVariable and explicitly sets useSystemProperty to fals then only environment variable is " + "resolved", getSystemPropertiesWithNoUserName(), environmentSettingsWithNoPassword(), new TestProxySetting(), false, true, getEnvironmentVariableProxySettings().password(null)) ); } private static List<Pair<String, String>> getSystemPropertiesWithNoUserName() { return Arrays.asList( Pair.of("%s.proxyHost", SYSTEM_PROPERTY_HOST), Pair.of("%s.proxyPort", SYSTEM_PROPERTY_PORT_NUMBER), Pair.of("%s.proxyPassword", SYSTEM_PROPERTY_PASSWORD)); } private static TestProxySetting getTestProxySettings() { return new TestProxySetting().host(USER_HOST_ON_BUILDER) .port(USER_PORT_NUMBER_ON_BUILDER) .userName(USER_USERNAME_ON_BUILDER) .password(USER_PASSWORD_ON_BUILDER) .nonProxyHost(USER_NONPROXY_ON_BUILDER); } private static TestProxySetting getSystemPropertyProxySettings() { return new TestProxySetting().host(SYSTEM_PROPERTY_HOST) .port(Integer.parseInt(SYSTEM_PROPERTY_PORT_NUMBER)) .userName(SYSTEM_PROPERTY_USER) .password(SYSTEM_PROPERTY_PASSWORD) .nonProxyHost(SYSTEM_PROPERTY_NON_PROXY); } private static TestProxySetting getEnvironmentVariableProxySettings() { return new TestProxySetting().host(ENVIRONMENT_HOST) .port(Integer.parseInt(ENVIRONMENT_VARIABLE_PORT_NUMBER)) .userName(ENV_VARIABLE_USER) .password(ENV_VARIABLE_PASSWORD) .nonProxyHost(ENVIRONMENT_VARIABLE_NON_PROXY); } private static List<Pair<String, String>> environmentSettings() { return Arrays.asList( Pair.of("%s_proxy", "http://" + ENV_VARIABLE_USER + ":" + ENV_VARIABLE_PASSWORD + "@" + ENVIRONMENT_HOST + ":" + ENVIRONMENT_VARIABLE_PORT_NUMBER + "/"), Pair.of("no_proxy", ENVIRONMENT_VARIABLE_NON_PROXY) ); } private static List<Pair<String, String>> environmentSettingsWithNoPassword() { return Arrays.asList( Pair.of("%s_proxy", "http://" + ENV_VARIABLE_USER + "@" + ENVIRONMENT_HOST + ":" + ENVIRONMENT_VARIABLE_PORT_NUMBER + "/"), Pair.of("no_proxy", ENVIRONMENT_VARIABLE_NON_PROXY) ); } private static List<Pair<String, String>> systemPropertySettings() { return Arrays.asList( Pair.of("%s.proxyHost", SYSTEM_PROPERTY_HOST), Pair.of("%s.proxyPort", SYSTEM_PROPERTY_PORT_NUMBER), Pair.of("http.nonProxyHosts", SYSTEM_PROPERTY_NON_PROXY), Pair.of("%s.proxyUser", SYSTEM_PROPERTY_USER), Pair.of("%s.proxyPassword", SYSTEM_PROPERTY_PASSWORD)); } }
3,023
0
Create_ds/aws-sdk-java-v2/test/region-testing/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/region-testing/src/test/java/software/amazon/awssdk/regiontesting/EndpointVariantsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regiontesting; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.regions.EndpointTag.DUALSTACK; import static software.amazon.awssdk.regions.EndpointTag.FIPS; import java.net.URI; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.regions.EndpointTag; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceEndpointKey; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.utils.Validate; @RunWith(Parameterized.class) public class EndpointVariantsTest { @Parameterized.Parameter public TestCase testCase; @Test public void resolvesCorrectEndpoint() { if (testCase instanceof SuccessCase) { URI endpoint = ServiceMetadata.of(testCase.service).endpointFor(testCase.endpointKey); assertThat(endpoint).isEqualTo(((SuccessCase) testCase).endpoint); } else { FailureCase failureCase = Validate.isInstanceOf(FailureCase.class, testCase, "Unknown case type %s.", getClass()); assertThatThrownBy(() -> ServiceMetadata.of(testCase.service).endpointFor(testCase.endpointKey)) .hasMessageContaining(failureCase.exceptionMessage); } } @Parameterized.Parameters(name = "{0}") public static Iterable<TestCase> testCases() { return Arrays.asList(new SuccessCase("default-pattern-service", "us-west-2", "default-pattern-service.us-west-2.amazonaws.com"), new SuccessCase("default-pattern-service", "us-west-2", "default-pattern-service-fips.us-west-2.amazonaws.com", FIPS), new SuccessCase("default-pattern-service", "af-south-1", "default-pattern-service.af-south-1.amazonaws.com"), new SuccessCase("default-pattern-service", "af-south-1", "default-pattern-service-fips.af-south-1.amazonaws.com", FIPS), new SuccessCase("global-service", "aws-global", "global-service.amazonaws.com"), new SuccessCase("global-service", "aws-global", "global-service-fips.amazonaws.com", FIPS), new SuccessCase("override-variant-service", "us-west-2", "override-variant-service.us-west-2.amazonaws.com"), new SuccessCase("override-variant-service", "us-west-2", "fips.override-variant-service.us-west-2.new.dns.suffix", FIPS), new SuccessCase("override-variant-service", "af-south-1", "override-variant-service.af-south-1.amazonaws.com"), new SuccessCase("override-variant-service", "af-south-1", "fips.override-variant-service.af-south-1.new.dns.suffix", FIPS), new SuccessCase("override-variant-dns-suffix-service", "us-west-2", "override-variant-dns-suffix-service.us-west-2.amazonaws.com"), new SuccessCase("override-variant-dns-suffix-service", "us-west-2", "override-variant-dns-suffix-service-fips.us-west-2.new.dns.suffix", FIPS), new SuccessCase("override-variant-dns-suffix-service", "af-south-1", "override-variant-dns-suffix-service.af-south-1.amazonaws.com"), new SuccessCase("override-variant-dns-suffix-service", "af-south-1", "override-variant-dns-suffix-service-fips.af-south-1.new.dns.suffix", FIPS), new SuccessCase("override-variant-hostname-service", "us-west-2", "override-variant-hostname-service.us-west-2.amazonaws.com"), new SuccessCase("override-variant-hostname-service", "us-west-2", "fips.override-variant-hostname-service.us-west-2.amazonaws.com", FIPS), new SuccessCase("override-variant-hostname-service", "af-south-1", "override-variant-hostname-service.af-south-1.amazonaws.com"), new SuccessCase("override-variant-hostname-service", "af-south-1", "fips.override-variant-hostname-service.af-south-1.amazonaws.com", FIPS), new SuccessCase("override-endpoint-variant-service", "us-west-2", "override-endpoint-variant-service.us-west-2.amazonaws.com"), new SuccessCase("override-endpoint-variant-service", "us-west-2", "fips.override-endpoint-variant-service.us-west-2.amazonaws.com", FIPS), new SuccessCase("override-endpoint-variant-service", "af-south-1", "override-endpoint-variant-service.af-south-1.amazonaws.com"), new SuccessCase("override-endpoint-variant-service", "af-south-1", "override-endpoint-variant-service-fips.af-south-1.amazonaws.com", FIPS), new SuccessCase("default-pattern-service", "us-west-2", "default-pattern-service.us-west-2.amazonaws.com"), new SuccessCase("default-pattern-service", "us-west-2", "default-pattern-service.us-west-2.api.aws", DUALSTACK), new SuccessCase("default-pattern-service", "af-south-1", "default-pattern-service.af-south-1.amazonaws.com"), new SuccessCase("default-pattern-service", "af-south-1", "default-pattern-service.af-south-1.api.aws", DUALSTACK), new SuccessCase("global-service", "aws-global", "global-service.amazonaws.com"), new SuccessCase("global-service", "aws-global", "global-service.api.aws", DUALSTACK), new SuccessCase("override-variant-service", "us-west-2", "override-variant-service.us-west-2.amazonaws.com"), new SuccessCase("override-variant-service", "us-west-2", "override-variant-service.dualstack.us-west-2.new.dns.suffix", DUALSTACK), new SuccessCase("override-variant-service", "af-south-1", "override-variant-service.af-south-1.amazonaws.com"), new SuccessCase("override-variant-service", "af-south-1", "override-variant-service.dualstack.af-south-1.new.dns.suffix", DUALSTACK), new SuccessCase("override-variant-dns-suffix-service", "us-west-2", "override-variant-dns-suffix-service.us-west-2.amazonaws.com"), new SuccessCase("override-variant-dns-suffix-service", "us-west-2", "override-variant-dns-suffix-service.us-west-2.new.dns.suffix", DUALSTACK), new SuccessCase("override-variant-dns-suffix-service", "af-south-1", "override-variant-dns-suffix-service.af-south-1.amazonaws.com"), new SuccessCase("override-variant-dns-suffix-service", "af-south-1", "override-variant-dns-suffix-service.af-south-1.new.dns.suffix", DUALSTACK), new SuccessCase("override-variant-hostname-service", "us-west-2", "override-variant-hostname-service.us-west-2.amazonaws.com"), new SuccessCase("override-variant-hostname-service", "us-west-2", "override-variant-hostname-service.dualstack.us-west-2.api.aws", DUALSTACK), new SuccessCase("override-variant-hostname-service", "af-south-1", "override-variant-hostname-service.af-south-1.amazonaws.com"), new SuccessCase("override-variant-hostname-service", "af-south-1", "override-variant-hostname-service.dualstack.af-south-1.api.aws", DUALSTACK), new SuccessCase("override-endpoint-variant-service", "us-west-2", "override-endpoint-variant-service.us-west-2.amazonaws.com"), new SuccessCase("override-endpoint-variant-service", "us-west-2", "override-endpoint-variant-service.dualstack.us-west-2.amazonaws.com", DUALSTACK), new SuccessCase("override-endpoint-variant-service", "af-south-1", "override-endpoint-variant-service.af-south-1.amazonaws.com"), new SuccessCase("override-endpoint-variant-service", "af-south-1", "override-endpoint-variant-service.af-south-1.api.aws", DUALSTACK), new SuccessCase("multi-variant-service", "us-west-2", "multi-variant-service.us-west-2.amazonaws.com"), new SuccessCase("multi-variant-service", "us-west-2", "multi-variant-service.dualstack.us-west-2.api.aws", DUALSTACK), new SuccessCase("multi-variant-service", "us-west-2", "fips.multi-variant-service.us-west-2.amazonaws.com", FIPS), new SuccessCase("multi-variant-service", "us-west-2", "fips.multi-variant-service.dualstack.us-west-2.new.dns.suffix", FIPS, DUALSTACK), new SuccessCase("multi-variant-service", "af-south-1", "multi-variant-service.af-south-1.amazonaws.com"), new SuccessCase("multi-variant-service", "af-south-1", "multi-variant-service.dualstack.af-south-1.api.aws", DUALSTACK), new SuccessCase("multi-variant-service", "af-south-1", "fips.multi-variant-service.af-south-1.amazonaws.com", FIPS), new SuccessCase("multi-variant-service", "af-south-1", "fips.multi-variant-service.dualstack.af-south-1.new.dns.suffix", FIPS, DUALSTACK), new FailureCase("some-service", "us-iso-east-1", "No endpoint known for [dualstack] in us-iso-east-1", DUALSTACK), new FailureCase("some-service", "us-iso-east-1", "No endpoint known for [fips] in us-iso-east-1", FIPS), new FailureCase("some-service", "us-iso-east-1", "No endpoint known for [fips, dualstack] in us-iso-east-1", FIPS, DUALSTACK), // These test case outcomes deviate from the other SDKs, because we ignore "global" services when a // non-global region is specified. We might consider changing this behavior, since the storm of // global services becoming regionalized is dying down. new SuccessCase("global-service", "foo", "global-service.foo.amazonaws.com"), new SuccessCase("global-service", "foo", "global-service-fips.foo.amazonaws.com", FIPS), new SuccessCase("global-service", "foo", "global-service.foo.amazonaws.com"), new SuccessCase("global-service", "foo", "global-service.foo.api.aws", DUALSTACK)); } public static class TestCase { private final String service; private final ServiceEndpointKey endpointKey; public TestCase(String service, String region, EndpointTag... tags) { this.service = service; this.endpointKey = ServiceEndpointKey.builder().region(Region.of(region)).tags(tags).build(); } } public static class SuccessCase extends TestCase { private final URI endpoint; public SuccessCase(String service, String region, String endpoint, EndpointTag... tags) { super(service, region, tags); this.endpoint = URI.create(endpoint); } @Override public String toString() { return "Positive Case: " + endpoint.toString(); } } private static class FailureCase extends TestCase { private final String exceptionMessage; public FailureCase(String service, String region, String exceptionMessage, EndpointTag... tags) { super(service, region, tags); this.exceptionMessage = exceptionMessage; } @Override public String toString() { return "Negative Case: " + exceptionMessage; } } }
3,024
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/TestRunner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests; /** * The main method will be invoked when you execute the test jar generated from * "mvn package -P test-jar" * * You can add the tests in the main method. * eg: * try { * S3AsyncStabilityTest s3AsyncStabilityTest = new S3AsyncStabilityTest(); * S3AsyncStabilityTest.setup(); * s3AsyncStabilityTest.putObject_getObject(); * } finally { * S3AsyncStabilityTest.cleanup(); * } */ public class TestRunner { public static void main(String... args) { } }
3,025
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/ExceptionCounter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests; import java.util.concurrent.atomic.AtomicInteger; public class ExceptionCounter { private final AtomicInteger serviceExceptionCount = new AtomicInteger(0); private final AtomicInteger ioExceptionCount = new AtomicInteger(0); private final AtomicInteger clientExceptionCount = new AtomicInteger(0); private final AtomicInteger unknownExceptionCount = new AtomicInteger(0); public void addServiceException() { serviceExceptionCount.getAndAdd(1); } public void addClientException() { clientExceptionCount.getAndAdd(1); } public void addUnknownException() { unknownExceptionCount.getAndAdd(1); } public void addIoException() { ioExceptionCount.getAndAdd(1); } public int serviceExceptionCount() { return serviceExceptionCount.get(); } public int ioExceptionCount() { return ioExceptionCount.get(); } public int clientExceptionCount() { return clientExceptionCount.get(); } public int unknownExceptionCount() { return unknownExceptionCount.get(); } }
3,026
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/TestResult.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests; /** * Model to store the test result */ public class TestResult { private final String testName; private final int totalRequestCount; private final int serviceExceptionCount; private final int ioExceptionCount; private final int clientExceptionCount; private final int unknownExceptionCount; private final int peakThreadCount; private final double heapMemoryAfterGCUsage; private TestResult(Builder builder) { this.testName = builder.testName; this.totalRequestCount = builder.totalRequestCount; this.serviceExceptionCount = builder.serviceExceptionCount; this.ioExceptionCount = builder.ioExceptionCount; this.clientExceptionCount = builder.clientExceptionCount; this.unknownExceptionCount = builder.unknownExceptionCount; this.heapMemoryAfterGCUsage = builder.heapMemoryAfterGCUsage; this.peakThreadCount = builder.peakThreadCount; } public static Builder builder() { return new Builder(); } public String testName() { return testName; } public int totalRequestCount() { return totalRequestCount; } public int serviceExceptionCount() { return serviceExceptionCount; } public int ioExceptionCount() { return ioExceptionCount; } public int clientExceptionCount() { return clientExceptionCount; } public int unknownExceptionCount() { return unknownExceptionCount; } public int peakThreadCount() { return peakThreadCount; } public double heapMemoryAfterGCUsage() { return heapMemoryAfterGCUsage; } @Override public String toString() { return "{" + "testName: '" + testName + '\'' + ", totalRequestCount: " + totalRequestCount + ", serviceExceptionCount: " + serviceExceptionCount + ", ioExceptionCount: " + ioExceptionCount + ", clientExceptionCount: " + clientExceptionCount + ", unknownExceptionCount: " + unknownExceptionCount + ", peakThreadCount: " + peakThreadCount + ", heapMemoryAfterGCUsage: " + heapMemoryAfterGCUsage + '}'; } public static class Builder { private String testName; private int totalRequestCount; private int serviceExceptionCount; private int ioExceptionCount; private int clientExceptionCount; private int unknownExceptionCount; private int peakThreadCount; private double heapMemoryAfterGCUsage; private Builder() { } public Builder testName(String testName) { this.testName = testName; return this; } public Builder totalRequestCount(int totalRequestCount) { this.totalRequestCount = totalRequestCount; return this; } public Builder serviceExceptionCount(int serviceExceptionCount) { this.serviceExceptionCount = serviceExceptionCount; return this; } public Builder ioExceptionCount(int ioExceptionCount) { this.ioExceptionCount = ioExceptionCount; return this; } public Builder clientExceptionCount(int clientExceptionCount) { this.clientExceptionCount = clientExceptionCount; return this; } public Builder unknownExceptionCount(int unknownExceptionCount) { this.unknownExceptionCount = unknownExceptionCount; return this; } public Builder peakThreadCount(int peakThreadCount) { this.peakThreadCount = peakThreadCount; return this; } public Builder heapMemoryAfterGCUsage(double heapMemoryAfterGCUsage) { this.heapMemoryAfterGCUsage = heapMemoryAfterGCUsage; return this; } public TestResult build() { return new TestResult(this); } } }
3,027
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/kinesis/KinesisStabilityTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.kinesis; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.function.IntFunction; import java.util.stream.Collectors; import org.apache.commons.lang3.RandomUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.kinesis.KinesisAsyncClient; import software.amazon.awssdk.services.kinesis.model.ConsumerStatus; import software.amazon.awssdk.services.kinesis.model.PutRecordRequest; import software.amazon.awssdk.services.kinesis.model.Record; import software.amazon.awssdk.services.kinesis.model.Shard; import software.amazon.awssdk.services.kinesis.model.ShardIteratorType; import software.amazon.awssdk.services.kinesis.model.StreamStatus; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardEvent; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardEventStream; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponse; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; import software.amazon.awssdk.stability.tests.utils.StabilityTestRunner; import software.amazon.awssdk.stability.tests.utils.TestEventStreamingResponseHandler; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.testutils.service.AwsTestBase; import software.amazon.awssdk.utils.Logger; /** * Stability Tests using Kinesis. * We can make one call to SubscribeToShard per second per registered consumer per shard * Limit: https://docs.aws.amazon.com/kinesis/latest/APIReference/API_SubscribeToShard.html */ public class KinesisStabilityTest extends AwsTestBase { private static final Logger log = Logger.loggerFor(KinesisStabilityTest.class.getSimpleName()); private static final int CONSUMER_COUNT = 4; private static final int SHARD_COUNT = 9; // one request per consumer/shard combination private static final int CONCURRENCY = CONSUMER_COUNT * SHARD_COUNT; private static final int MAX_CONCURRENCY = CONCURRENCY + 10; public static final String CONSUMER_PREFIX = "kinesisstabilitytestconsumer_"; private List<String> consumerArns; private List<String> shardIds; private List<SdkBytes> producedData; private KinesisAsyncClient asyncClient; private String streamName; private String streamARN; private ExecutorService waiterExecutorService; private ScheduledExecutorService producer; @BeforeEach public void setup() { streamName = "kinesisstabilitytest" + System.currentTimeMillis(); consumerArns = new ArrayList<>(CONSUMER_COUNT); shardIds = new ArrayList<>(SHARD_COUNT); producedData = new ArrayList<>(); asyncClient = KinesisAsyncClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .httpClientBuilder(NettyNioAsyncHttpClient.builder().maxConcurrency(MAX_CONCURRENCY)) .build(); asyncClient.createStream(r -> r.streamName(streamName) .shardCount(SHARD_COUNT)) .join(); waitForStreamToBeActive(); streamARN = asyncClient.describeStream(r -> r.streamName(streamName)).join() .streamDescription() .streamARN(); shardIds = asyncClient.listShards(r -> r.streamName(streamName)) .join() .shards().stream().map(Shard::shardId).collect(Collectors.toList()); waiterExecutorService = Executors.newFixedThreadPool(CONSUMER_COUNT); producer = Executors.newScheduledThreadPool(1); registerStreamConsumers(); waitForConsumersToBeActive(); } @AfterEach public void tearDown() { asyncClient.deleteStream(b -> b.streamName(streamName).enforceConsumerDeletion(true)).join(); waiterExecutorService.shutdown(); producer.shutdown(); asyncClient.close(); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void putRecords_subscribeToShard() { putRecords(); subscribeToShard(); } /** * We only have one run of subscribeToShard tests because it takes 5 minutes. */ private void subscribeToShard() { log.info(() -> "starting to test subscribeToShard to stream: " + streamName); List<CompletableFuture<?>> completableFutures = generateSubscribeToShardFutures(); StabilityTestRunner.newRunner() .testName("KinesisStabilityTest.subscribeToShard") .futures(completableFutures) .run(); } private void registerStreamConsumers() { log.info(() -> "Starting to register stream consumer " + streamARN); IntFunction<CompletableFuture<?>> futureFunction = i -> asyncClient.registerStreamConsumer(r -> r.streamARN(streamARN) .consumerName(CONSUMER_PREFIX + i)) .thenApply(b -> consumerArns.add(b.consumer().consumerARN())); StabilityTestRunner.newRunner() .requestCountPerRun(CONSUMER_COUNT) .totalRuns(1) .testName("KinesisStabilityTest.registerStreamConsumers") .futureFactory(futureFunction) .run(); } private void putRecords() { log.info(() -> "Starting to test putRecord"); producedData = new ArrayList<>(); SdkBytes data = SdkBytes.fromByteArray(RandomUtils.nextBytes(20)); IntFunction<CompletableFuture<?>> futureFunction = i -> asyncClient.putRecord(PutRecordRequest.builder() .streamName(streamName) .data(data) .partitionKey(UUID.randomUUID().toString()) .build()) .thenApply(b -> producedData.add(data)); StabilityTestRunner.newRunner() .requestCountPerRun(CONCURRENCY) .testName("KinesisStabilityTest.putRecords") .futureFactory(futureFunction) .run(); } /** * Generate request per consumer/shard combination * @return a lit of completablefutures */ private List<CompletableFuture<?>> generateSubscribeToShardFutures() { List<CompletableFuture<?>> completableFutures = new ArrayList<>(); for (int i = 0; i < CONSUMER_COUNT; i++) { final int consumerIndex = i; for (int j = 0; j < SHARD_COUNT; j++) { final int shardIndex = j; TestSubscribeToShardResponseHandler responseHandler = new TestSubscribeToShardResponseHandler(consumerIndex, shardIndex); CompletableFuture<Void> completableFuture = asyncClient.subscribeToShard(b -> b.shardId(shardIds.get(shardIndex)) .consumerARN(consumerArns.get(consumerIndex)) .startingPosition(s -> s.type(ShardIteratorType.TRIM_HORIZON)), responseHandler) .thenAccept(b -> { // Only verify data if all events have been received and the received data is not empty. // It is possible the received data is empty because there is no record at the position // event with TRIM_HORIZON. if (responseHandler.allEventsReceived && !responseHandler.receivedData.isEmpty()) { assertThat(producedData).as(responseHandler.id + " has not received all events" + ".").containsSequence(responseHandler.receivedData); } }); completableFutures.add(completableFuture); } } return completableFutures; } private void waitForStreamToBeActive() { Waiter.run(() -> asyncClient.describeStream(r -> r.streamName(streamName)) .join()) .until(b -> b.streamDescription().streamStatus().equals(StreamStatus.ACTIVE)) .orFailAfter(Duration.ofMinutes(5)); } private void waitForConsumersToBeActive() { CompletableFuture<?>[] completableFutures = consumerArns.stream() .map(a -> CompletableFuture.supplyAsync(() -> Waiter.run(() -> asyncClient.describeStreamConsumer(b -> b.consumerARN(a)) .join()) .until(b -> b.consumerDescription().consumerStatus().equals(ConsumerStatus.ACTIVE)) .orFailAfter(Duration.ofMinutes(5)), waiterExecutorService)) .toArray(CompletableFuture[]::new); CompletableFuture.allOf(completableFutures).join(); } private static class TestSubscribeToShardResponseHandler extends TestEventStreamingResponseHandler<SubscribeToShardResponse , SubscribeToShardEventStream> implements SubscribeToShardResponseHandler { private final List<SdkBytes> receivedData = new ArrayList<>(); private final String id; private volatile boolean allEventsReceived = false; TestSubscribeToShardResponseHandler(int consumerIndex, int shardIndex) { id = "consumer_" + consumerIndex + "_shard_" + shardIndex; } @Override public void onEventStream(SdkPublisher<SubscribeToShardEventStream> publisher) { publisher.filter(SubscribeToShardEvent.class) .subscribe(b -> { log.debug(() -> "sequenceNumber " + b.records() + "_" + id); receivedData.addAll(b.records().stream().map(Record::data).collect(Collectors.toList())); }); } @Override public void exceptionOccurred(Throwable throwable) { log.error(() -> "An exception was thrown from " + id, throwable); } @Override public void complete() { allEventsReceived = true; log.info(() -> "All events stream successfully " + id); } } }
3,028
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/cloudwatch/CloudWatchCrtAsyncStabilityTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.cloudwatch; import java.time.Duration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.crt.io.EventLoopGroup; import software.amazon.awssdk.crt.io.HostResolver; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient; import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; public class CloudWatchCrtAsyncStabilityTest extends CloudWatchBaseStabilityTest { private static String namespace; private static CloudWatchAsyncClient cloudWatchAsyncClient; @Override protected CloudWatchAsyncClient getTestClient() { return cloudWatchAsyncClient; } @Override protected String getNamespace() { return namespace; } @BeforeAll public static void setup() { namespace = "CloudWatchCrtAsyncStabilityTest" + System.currentTimeMillis(); SdkAsyncHttpClient.Builder crtClientBuilder = AwsCrtAsyncHttpClient.builder() .connectionMaxIdleTime(Duration.ofSeconds(5)); cloudWatchAsyncClient = CloudWatchAsyncClient.builder() .httpClientBuilder(crtClientBuilder) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b.apiCallTimeout(Duration.ofMinutes(10)) // Retry at test level .retryPolicy(RetryPolicy.none())) .build(); } @AfterAll public static void tearDown() { cloudWatchAsyncClient.close(); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void putMetrics_lowTpsLongInterval() { putMetrics(); } }
3,029
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/cloudwatch/CloudWatchNettyAsyncStabilityTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.cloudwatch; import java.time.Duration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; public class CloudWatchNettyAsyncStabilityTest extends CloudWatchBaseStabilityTest { private static String namespace; private static CloudWatchAsyncClient cloudWatchAsyncClient; @Override protected CloudWatchAsyncClient getTestClient() { return cloudWatchAsyncClient; } @Override protected String getNamespace() { return namespace; } @BeforeAll public static void setup() { namespace = "CloudWatchNettyAsyncStabilityTest" + System.currentTimeMillis(); cloudWatchAsyncClient = CloudWatchAsyncClient.builder() .httpClientBuilder(NettyNioAsyncHttpClient.builder().maxConcurrency(CONCURRENCY)) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b // Retry at test level .retryPolicy(RetryPolicy.none()) .apiCallTimeout(Duration.ofMinutes(1))) .build(); } @AfterAll public static void tearDown() { cloudWatchAsyncClient.close(); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void putMetrics_lowTpsLongInterval() { putMetrics(); } }
3,030
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/cloudwatch/CloudWatchBaseStabilityTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.cloudwatch; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.IntFunction; import org.apache.commons.lang3.RandomUtils; import software.amazon.awssdk.services.cloudwatch.CloudWatchAsyncClient; import software.amazon.awssdk.services.cloudwatch.model.MetricDatum; import software.amazon.awssdk.stability.tests.utils.StabilityTestRunner; import software.amazon.awssdk.testutils.service.AwsTestBase; public abstract class CloudWatchBaseStabilityTest extends AwsTestBase { protected static final int CONCURRENCY = 50; protected static final int TOTAL_RUNS = 3; protected abstract CloudWatchAsyncClient getTestClient(); protected abstract String getNamespace(); protected void putMetrics() { List<MetricDatum> metrics = new ArrayList<>(); for (int i = 0; i < 20 ; i++) { metrics.add(MetricDatum.builder() .metricName("test") .values(RandomUtils.nextDouble(1d, 1000d)) .build()); } IntFunction<CompletableFuture<?>> futureIntFunction = i -> getTestClient().putMetricData(b -> b.namespace(getNamespace()) .metricData(metrics)); runCloudWatchTest("putMetrics_lowTpsLongInterval", futureIntFunction); } private void runCloudWatchTest(String testName, IntFunction<CompletableFuture<?>> futureIntFunction) { StabilityTestRunner.newRunner() .testName("CloudWatchAsyncStabilityTest." + testName) .futureFactory(futureIntFunction) .totalRuns(TOTAL_RUNS) .requestCountPerRun(CONCURRENCY) .delaysBetweenEachRun(Duration.ofSeconds(6)) .run(); } }
3,031
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/s3/S3NettyAsyncStabilityTest.java
package software.amazon.awssdk.stability.tests.s3; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; import java.time.Duration; public class S3NettyAsyncStabilityTest extends S3BaseStabilityTest { private static String bucketName = "s3nettyasyncstabilitytests" + System.currentTimeMillis(); private static S3AsyncClient s3NettyClient; static { s3NettyClient = S3AsyncClient.builder() .httpClientBuilder(NettyNioAsyncHttpClient.builder() .maxConcurrency(CONCURRENCY)) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b.apiCallTimeout(Duration.ofMinutes(10)) // Retry at test level .retryPolicy(RetryPolicy.none())) .build(); } public S3NettyAsyncStabilityTest() { super(s3NettyClient); } @BeforeAll public static void setup() { s3NettyClient.createBucket(b -> b.bucket(bucketName)).join(); } @AfterAll public static void cleanup() { deleteBucketAndAllContents(s3NettyClient, bucketName); s3NettyClient.close(); } @Override protected String getTestBucketName() { return bucketName; } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void getBucketAcl_lowTpsLongInterval_Netty() { doGetBucketAcl_lowTpsLongInterval(); } }
3,032
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/s3/S3WithCrtAsyncHttpClientStabilityTest.java
package software.amazon.awssdk.stability.tests.s3; import java.time.Duration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; /** * Stability tests for {@link S3AsyncClient} using {@link AwsCrtAsyncHttpClient} */ public class S3WithCrtAsyncHttpClientStabilityTest extends S3BaseStabilityTest { private static String bucketName = "s3withcrtasyncclientstabilitytests" + System.currentTimeMillis(); private static S3AsyncClient s3CrtClient; static { int numThreads = Runtime.getRuntime().availableProcessors(); SdkAsyncHttpClient.Builder httpClientBuilder = AwsCrtAsyncHttpClient.builder() .connectionMaxIdleTime(Duration.ofSeconds(5)); s3CrtClient = S3AsyncClient.builder() .httpClientBuilder(httpClientBuilder) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b.apiCallTimeout(Duration.ofMinutes(10)) // Retry at test level .retryPolicy(RetryPolicy.none())) .build(); } public S3WithCrtAsyncHttpClientStabilityTest() { super(s3CrtClient); } @BeforeAll public static void setup() { s3CrtClient.createBucket(b -> b.bucket(bucketName)).join(); } @AfterAll public static void cleanup() { deleteBucketAndAllContents(s3CrtClient, bucketName); s3CrtClient.close(); } @Override protected String getTestBucketName() { return bucketName; } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void getBucketAcl_lowTpsLongInterval_Crt() { doGetBucketAcl_lowTpsLongInterval(); } }
3,033
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/s3/S3BaseStabilityTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.s3; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.IntFunction; import org.apache.commons.lang3.RandomStringUtils; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; import software.amazon.awssdk.services.s3.model.NoSuchBucketException; import software.amazon.awssdk.services.s3.model.NoSuchKeyException; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; import software.amazon.awssdk.stability.tests.utils.StabilityTestRunner; import software.amazon.awssdk.testutils.RandomTempFile; import software.amazon.awssdk.testutils.service.AwsTestBase; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Md5Utils; public abstract class S3BaseStabilityTest extends AwsTestBase { private static final Logger log = Logger.loggerFor(S3BaseStabilityTest.class); protected static final int CONCURRENCY = 100; protected static final int TOTAL_RUNS = 50; protected static final String LARGE_KEY_NAME = "2GB"; protected static S3Client s3ApacheClient; private final S3AsyncClient testClient; static { s3ApacheClient = S3Client.builder() .httpClientBuilder(ApacheHttpClient.builder() .maxConnections(CONCURRENCY)) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b.apiCallTimeout(Duration.ofMinutes(10))) .build(); } public S3BaseStabilityTest(S3AsyncClient testClient) { this.testClient = testClient; } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void largeObject_put_get_usingFile() { String md5Upload = uploadLargeObjectFromFile(); String md5Download = downloadLargeObjectToFile(); assertThat(md5Upload).isEqualTo(md5Download); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void putObject_getObject_highConcurrency() { putObject(); getObject(); } protected String computeKeyName(int i) { return "key_" + i; } protected abstract String getTestBucketName(); protected void doGetBucketAcl_lowTpsLongInterval() { IntFunction<CompletableFuture<?>> future = i -> testClient.getBucketAcl(b -> b.bucket(getTestBucketName())); String className = this.getClass().getSimpleName(); StabilityTestRunner.newRunner() .testName(className + ".getBucketAcl_lowTpsLongInterval") .futureFactory(future) .requestCountPerRun(10) .totalRuns(3) .delaysBetweenEachRun(Duration.ofSeconds(6)) .run(); } protected String downloadLargeObjectToFile() { File randomTempFile = RandomTempFile.randomUncreatedFile(); StabilityTestRunner.newRunner() .testName("S3AsyncStabilityTest.downloadLargeObjectToFile") .futures(testClient.getObject(b -> b.bucket(getTestBucketName()).key(LARGE_KEY_NAME), AsyncResponseTransformer.toFile(randomTempFile))) .run(); try { return Md5Utils.md5AsBase64(randomTempFile); } catch (IOException e) { throw new RuntimeException(e); } finally { randomTempFile.delete(); } } protected String uploadLargeObjectFromFile() { RandomTempFile file = null; try { file = new RandomTempFile((long) 2e+9); String md5 = Md5Utils.md5AsBase64(file); StabilityTestRunner.newRunner() .testName("S3AsyncStabilityTest.uploadLargeObjectFromFile") .futures(testClient.putObject(b -> b.bucket(getTestBucketName()).key(LARGE_KEY_NAME), AsyncRequestBody.fromFile(file))) .run(); return md5; } catch (IOException e) { throw new RuntimeException("fail to create test file", e); } finally { if (file != null) { file.delete(); } } } protected void putObject() { byte[] bytes = RandomStringUtils.randomAlphanumeric(10_000).getBytes(); IntFunction<CompletableFuture<?>> future = i -> { String keyName = computeKeyName(i); return testClient.putObject(b -> b.bucket(getTestBucketName()).key(keyName), AsyncRequestBody.fromBytes(bytes)); }; StabilityTestRunner.newRunner() .testName("S3AsyncStabilityTest.putObject") .futureFactory(future) .requestCountPerRun(CONCURRENCY) .totalRuns(TOTAL_RUNS) .delaysBetweenEachRun(Duration.ofMillis(100)) .run(); } protected void getObject() { IntFunction<CompletableFuture<?>> future = i -> { String keyName = computeKeyName(i); Path path = RandomTempFile.randomUncreatedFile().toPath(); return testClient.getObject(b -> b.bucket(getTestBucketName()).key(keyName), AsyncResponseTransformer.toFile(path)); }; StabilityTestRunner.newRunner() .testName("S3AsyncStabilityTest.getObject") .futureFactory(future) .requestCountPerRun(CONCURRENCY) .totalRuns(TOTAL_RUNS) .delaysBetweenEachRun(Duration.ofMillis(100)) .run(); } protected static void deleteBucketAndAllContents(S3AsyncClient client, String bucketName) { try { List<CompletableFuture<?>> futures = new ArrayList<>(); client.listObjectsV2Paginator(b -> b.bucket(bucketName)) .subscribe(r -> r.contents().forEach(s -> futures.add(client.deleteObject(o -> o.bucket(bucketName).key(s.key()))))) .join(); CompletableFuture<?>[] futureArray = futures.toArray(new CompletableFuture<?>[0]); CompletableFuture.allOf(futureArray).join(); client.deleteBucket(DeleteBucketRequest.builder().bucket(bucketName).build()).join(); } catch (Exception e) { log.error(() -> "Failed to delete bucket: " +bucketName); } } protected void verifyObjectExist(String bucketName, String keyName, long size) throws IOException { try { s3ApacheClient.headBucket(b -> b.bucket(bucketName)); } catch (NoSuchBucketException e) { log.info(() -> "NoSuchBucketException was thrown, staring to create the bucket"); s3ApacheClient.createBucket(b -> b.bucket(bucketName)); } try { s3ApacheClient.headObject(b -> b.key(keyName).bucket(bucketName)); } catch (NoSuchKeyException e) { log.info(() -> "NoSuchKeyException was thrown, starting to upload the object"); RandomTempFile file = new RandomTempFile(size); s3ApacheClient.putObject(b -> b.bucket(bucketName).key(keyName), RequestBody.fromFile(file)); file.delete(); } } }
3,034
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/s3/S3CrtAsyncClientStabilityTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.s3; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient; /** * Stability tests for {@link S3CrtAsyncClient} */ public class S3CrtAsyncClientStabilityTest extends S3BaseStabilityTest { private static final String BUCKET_NAME = "s3crtasyncclinetstabilitytests" + System.currentTimeMillis(); private static S3AsyncClient s3CrtAsyncClient; static { s3CrtAsyncClient = S3CrtAsyncClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); } public S3CrtAsyncClientStabilityTest() { super(s3CrtAsyncClient); } @BeforeAll public static void setup() { System.setProperty("aws.crt.debugnative", "true"); s3ApacheClient.createBucket(b -> b.bucket(BUCKET_NAME)); } @AfterAll public static void cleanup() { try (S3AsyncClient s3NettyClient = S3AsyncClient.builder() .httpClientBuilder(NettyNioAsyncHttpClient.builder() .maxConcurrency(CONCURRENCY)) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build()) { deleteBucketAndAllContents(s3NettyClient, BUCKET_NAME); } s3CrtAsyncClient.close(); s3ApacheClient.close(); CrtResource.waitForNoResources(); } @Override protected String getTestBucketName() { return BUCKET_NAME; } }
3,035
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/utils/RetryableTestExtension.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.utils; import static java.util.Spliterator.ORDERED; import static java.util.Spliterators.spliteratorUnknownSize; import static java.util.stream.StreamSupport.stream; import static org.junit.platform.commons.util.AnnotationUtils.findAnnotation; import static org.junit.platform.commons.util.AnnotationUtils.isAnnotated; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext.Namespace; import org.junit.jupiter.api.extension.ExtensionContextException; import org.junit.jupiter.api.extension.TestExecutionExceptionHandler; import org.junit.jupiter.api.extension.TestTemplateInvocationContext; import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider; import org.opentest4j.TestAbortedException; public class RetryableTestExtension implements TestTemplateInvocationContextProvider, TestExecutionExceptionHandler { private static final Namespace NAMESPACE = Namespace.create(RetryableTestExtension.class); @Override public boolean supportsTestTemplate(ExtensionContext extensionContext) { Method testMethod = extensionContext.getRequiredTestMethod(); return isAnnotated(testMethod, RetryableTest.class); } @Override public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(ExtensionContext context) { RetryExecutor executor = retryExecutor(context); return stream(spliteratorUnknownSize(executor, ORDERED), false); } @Override public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { if (!isRetryableException(context, throwable)) { throw throwable; } RetryExecutor retryExecutor = retryExecutor(context); retryExecutor.exceptionOccurred(throwable); } private RetryExecutor retryExecutor(ExtensionContext context) { Method method = context.getRequiredTestMethod(); ExtensionContext templateContext = context.getParent() .orElseThrow(() -> new IllegalStateException( "Extension context \"" + context + "\" should have a parent context.")); int maxRetries = maxRetries(context); return templateContext.getStore(NAMESPACE).getOrComputeIfAbsent(method.toString(), __ -> new RetryExecutor(maxRetries), RetryExecutor.class); } private boolean isRetryableException(ExtensionContext context, Throwable throwable) { return retryableException(context).isAssignableFrom(throwable.getClass()) || throwable instanceof TestAbortedException; } private int maxRetries(ExtensionContext context) { return retrieveAnnotation(context).maxRetries(); } private Class<? extends Throwable> retryableException(ExtensionContext context) { return retrieveAnnotation(context).retryableException(); } private RetryableTest retrieveAnnotation(ExtensionContext context) { return findAnnotation(context.getRequiredTestMethod(), RetryableTest.class) .orElseThrow(() -> new ExtensionContextException("@RetryableTest Annotation not found on method")); } private static final class RetryableTestsTemplateInvocationContext implements TestTemplateInvocationContext { private int maxRetries; private int numAttempt; RetryableTestsTemplateInvocationContext(int numAttempt, int maxRetries) { this.numAttempt = numAttempt; this.maxRetries = maxRetries; } } private static final class RetryExecutor implements Iterator<RetryableTestsTemplateInvocationContext> { private final int maxRetries; private int totalAttempts; private List<Throwable> throwables = new ArrayList<>(); RetryExecutor(int maxRetries) { this.maxRetries = maxRetries; } private void exceptionOccurred(Throwable throwable) { throwables.add(throwable); if (throwables.size() == maxRetries) { throw new AssertionError("All attempts failed. Last exception: ", throwable); } else { throw new TestAbortedException(String.format("Attempt %s failed of the retryable exception, going to retry the test", totalAttempts), throwable); } } @Override public boolean hasNext() { if (totalAttempts == 0) { return true; } boolean previousFailed = totalAttempts == throwables.size(); if (previousFailed && totalAttempts <= maxRetries - 1) { return true; } return false; } @Override public RetryableTestsTemplateInvocationContext next() { totalAttempts++; return new RetryableTestsTemplateInvocationContext(totalAttempts, maxRetries); } } }
3,036
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/utils/TestTranscribeStreamingSubscription.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.utils; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.transcribestreaming.model.AudioEvent; import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; public class TestTranscribeStreamingSubscription implements Subscription { private static final int CHUNK_SIZE_IN_BYTES = 1024; private ExecutorService executor = Executors.newFixedThreadPool(1); private AtomicLong demand = new AtomicLong(0); private final Subscriber<? super AudioStream> subscriber; private final InputStream inputStream; private volatile boolean done = false; public TestTranscribeStreamingSubscription(Subscriber<? super AudioStream> subscriber, InputStream inputStream) { this.subscriber = subscriber; this.inputStream = inputStream; } @Override public void request(long n) { if (done) { return; } if (n <= 0) { signalOnError(new IllegalArgumentException("Demand must be positive")); return; } demand.getAndAdd(n); executor.submit(() -> { try { do { ByteBuffer audioBuffer = getNextEvent(); if (audioBuffer.remaining() > 0) { AudioEvent audioEvent = audioEventFromBuffer(audioBuffer); subscriber.onNext(audioEvent); } else { subscriber.onComplete(); done = true; break; } } while (demand.decrementAndGet() > 0 && !done); } catch (Exception e) { signalOnError(e); } }); } @Override public void cancel() { executor.shutdown(); } private ByteBuffer getNextEvent() { ByteBuffer audioBuffer; byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES]; int len; try { len = inputStream.read(audioBytes); if (len <= 0) { audioBuffer = ByteBuffer.allocate(0); } else { audioBuffer = ByteBuffer.wrap(audioBytes, 0, len); } } catch (IOException e) { throw new UncheckedIOException(e); } return audioBuffer; } private AudioEvent audioEventFromBuffer(ByteBuffer bb) { return AudioEvent.builder() .audioChunk(SdkBytes.fromByteBuffer(bb)) .build(); } private void signalOnError(Throwable t) { if (!done) { subscriber.onError(t); done = true; } } }
3,037
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/utils/StabilityTestRunner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.utils; import static java.lang.management.MemoryType.HEAP; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.IntFunction; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.stability.tests.ExceptionCounter; import software.amazon.awssdk.stability.tests.TestResult; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * Stability tests runner. * * There are two ways to run the tests: * * - providing futureFactories requestCountPerRun and totalRuns. eg: * * StabilityTestRunner.newRunner() * .futureFactory(i -> CompletableFuture.runAsync(() -> LOGGER.info(() -> * "hello world " + i), executors)) * .testName("test") * .requestCountPerRun(10) * .delaysBetweenEachRun(Duration.ofMillis(1000)) * .totalRuns(5) * .run(); * * The tests runner will create futures from the factories and run the 10 requests per run for 5 runs with 1s delay between * each run. * * - providing futures, eg: * * StabilityTestRunner.newRunner() * .futures(futures) * .testName("test") * .run(); * The tests runner will run the given futures in one run. */ public class StabilityTestRunner { private static final Logger log = Logger.loggerFor(StabilityTestRunner.class); private static final double ALLOWED_FAILURE_RATIO = 0.05; private static final int TESTS_TIMEOUT_IN_MINUTES = 60; // The peak thread count might be different depending on the machine the tests are currently running on. // because of the internal thread pool used in AsynchronousFileChannel private static final int ALLOWED_PEAK_THREAD_COUNT = 90; private ThreadMXBean threadMXBean; private IntFunction<CompletableFuture<?>> futureFactory; private List<CompletableFuture<?>> futures; private String testName; private Duration delay = Duration.ZERO; private Integer requestCountPerRun; private Integer totalRuns = 1; private StabilityTestRunner() { threadMXBean = ManagementFactory.getThreadMXBean(); // Reset peak thread count for every test threadMXBean.resetPeakThreadCount(); } /** * Create a new test runner * * @return a new test runner */ public static StabilityTestRunner newRunner() { return new StabilityTestRunner(); } public StabilityTestRunner futureFactory(IntFunction<CompletableFuture<?>> futureFactory) { this.futureFactory = futureFactory; return this; } public StabilityTestRunner futures(List<CompletableFuture<?>> futures) { this.futures = futures; return this; } public StabilityTestRunner futures(CompletableFuture<?>... futures) { this.futures = Arrays.asList(futures); return this; } /** * The test name to generate the test report. * * @param testName the name of the report * @return StabilityTestRunner */ public StabilityTestRunner testName(String testName) { this.testName = testName; return this; } /** * @param delay delay between each run * @return StabilityTestRunner */ public StabilityTestRunner delaysBetweenEachRun(Duration delay) { this.delay = delay; return this; } /** * @param runs total runs * @return StabilityTestRunner */ public StabilityTestRunner totalRuns(Integer runs) { this.totalRuns = runs; return this; } /** * @param requestCountPerRun the number of request per run * @return StabilityTestRunner */ public StabilityTestRunner requestCountPerRun(Integer requestCountPerRun) { this.requestCountPerRun = requestCountPerRun; return this; } /** * Run the tests based on the parameters provided */ public void run() { validateParameters(); TestResult result; if (futureFactory != null) { result = runTestsFromFutureFunction(); } else { result = runTestsFromFutures(); } processResult(result); } private TestResult runTestsFromFutureFunction() { Validate.notNull(requestCountPerRun, "requestCountPerRun cannot be null"); Validate.notNull(totalRuns, "totalRuns cannot be null"); ExceptionCounter exceptionCounter = new ExceptionCounter(); int totalRequestNumber = requestCountPerRun * totalRuns; CompletableFuture[] completableFutures = new CompletableFuture[totalRequestNumber]; int runNumber = 0; while (runNumber < totalRequestNumber) { for (int i = runNumber; i < runNumber + requestCountPerRun; i++) { CompletableFuture<?> future = futureFactory.apply(i); completableFutures[i] = handleException(future, exceptionCounter); } int finalRunNumber = runNumber; log.debug(() -> "Finishing one run " + finalRunNumber); runNumber += requestCountPerRun; addDelayIfNeeded(); } return generateTestResult(totalRequestNumber, testName, exceptionCounter, completableFutures); } private double calculateHeapMemoryAfterGCUsage() { List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans(); long used = 0, max = 0; for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) { String name = memoryPoolMXBean.getName(); if (!name.contains("Eden")) { if (memoryPoolMXBean.getType().equals(HEAP)) { MemoryUsage memoryUsage = memoryPoolMXBean.getCollectionUsage(); used += memoryUsage.getUsed(); max += memoryUsage.getMax() == -1 ? 0 : memoryUsage.getMax(); } } } return used / (double) max; } private TestResult runTestsFromFutures() { ExceptionCounter exceptionCounter = new ExceptionCounter(); CompletableFuture[] completableFutures = futures.stream().map(b -> handleException(b, exceptionCounter)).toArray(CompletableFuture[]::new); return generateTestResult(futures.size(), testName, exceptionCounter, completableFutures); } private void validateParameters() { Validate.notNull(testName, "testName cannot be null"); Validate.isTrue(futureFactory == null || futures == null, "futureFactory and futures cannot be both configured"); } private void addDelayIfNeeded() { log.debug(() -> "Sleeping for " + delay.toMillis()); if (!delay.isZero()) { try { Thread.sleep(delay.toMillis()); } catch (InterruptedException e) { // Ignoring exception } } } /** * Handle the exceptions of executing the futures. * * @param future the future to be executed * @param exceptionCounter the exception counter * @return the completable future */ private static CompletableFuture<?> handleException(CompletableFuture<?> future, ExceptionCounter exceptionCounter) { return future.exceptionally(t -> { Throwable cause = t.getCause(); log.error(() -> "An exception was thrown ", t); if (cause instanceof SdkServiceException) { exceptionCounter.addServiceException(); } else if (isIOExceptionOrHasIOCause(cause)) { exceptionCounter.addIoException(); } else if (cause instanceof SdkClientException) { if (isIOExceptionOrHasIOCause(cause.getCause())) { exceptionCounter.addIoException(); } else { exceptionCounter.addClientException(); } } else { exceptionCounter.addUnknownException(); } return null; }); } private static boolean isIOExceptionOrHasIOCause(Throwable throwable) { if (throwable == null) { return false; } return throwable instanceof IOException || throwable.getCause() instanceof IOException; } private TestResult generateTestResult(int totalRequestNumber, String testName, ExceptionCounter exceptionCounter, CompletableFuture[] completableFutures) { try { CompletableFuture.allOf(completableFutures).get(TESTS_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException("Error occurred running the tests: " + testName, e); } catch (TimeoutException e) { throw new RuntimeException(String.format("Tests (%s) did not finish within %s minutes", testName, TESTS_TIMEOUT_IN_MINUTES)); } return TestResult.builder() .testName(testName) .clientExceptionCount(exceptionCounter.clientExceptionCount()) .serviceExceptionCount(exceptionCounter.serviceExceptionCount()) .ioExceptionCount(exceptionCounter.ioExceptionCount()) .totalRequestCount(totalRequestNumber) .unknownExceptionCount(exceptionCounter.unknownExceptionCount()) .peakThreadCount(threadMXBean.getPeakThreadCount()) .heapMemoryAfterGCUsage(calculateHeapMemoryAfterGCUsage()) .build(); } /** * Process the result. Throws exception if SdkClientExceptions were thrown or 5% requests failed of * SdkServiceException or IOException. * * @param testResult the result to process. */ private void processResult(TestResult testResult) { log.info(() -> "TestResult: " + testResult); int clientExceptionCount = testResult.clientExceptionCount(); int expectedExceptionCount = testResult.ioExceptionCount() + testResult.serviceExceptionCount(); int unknownExceptionCount = testResult.unknownExceptionCount(); double ratio = expectedExceptionCount / (double) testResult.totalRequestCount(); if (clientExceptionCount > 0) { String errorMessage = String.format("%s SdkClientExceptions were thrown, failing the tests", clientExceptionCount); log.error(() -> errorMessage); throw new AssertionError(errorMessage); } if (testResult.unknownExceptionCount() > 0) { String errorMessage = String.format("%s unknown exceptions were thrown, failing the tests", unknownExceptionCount); log.error(() -> errorMessage); throw new AssertionError(errorMessage); } if (ratio > ALLOWED_FAILURE_RATIO) { String errorMessage = String.format("More than %s percent requests (%s percent) failed of SdkServiceException " + "or IOException, failing the tests", ALLOWED_FAILURE_RATIO * 100, ratio * 100); throw new StabilityTestsRetryableException(errorMessage); } if (testResult.peakThreadCount() > ALLOWED_PEAK_THREAD_COUNT) { String errorMessage = String.format("The number of peak thread exceeds the allowed peakThread threshold %s", ALLOWED_PEAK_THREAD_COUNT); threadDump(testResult.testName()); throw new AssertionError(errorMessage); } } private void threadDump(String testName) { StringBuilder threadDump = new StringBuilder("\n============").append(testName) .append(" Thread Dump:=============\n"); ThreadInfo[] threadInfoList = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100); for (ThreadInfo threadInfo : threadInfoList) { threadDump.append('"'); threadDump.append(threadInfo.getThreadName()); threadDump.append("\":"); threadDump.append(threadInfo.getThreadState()); threadDump.append("\n"); } threadDump.append("=================================="); log.info(threadDump::toString); } }
3,038
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/utils/TestEventStreamingResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.utils; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.awscore.eventstream.EventStreamResponseHandler; import software.amazon.awssdk.utils.Logger; public abstract class TestEventStreamingResponseHandler<ResponseT extends AwsResponse, EventT> implements EventStreamResponseHandler<ResponseT, EventT> { private static final Logger log = Logger.loggerFor(TestEventStreamingResponseHandler.class.getSimpleName()); @Override public void responseReceived(ResponseT response) { String requestId = response.responseMetadata().requestId(); log.info(() -> "Received Initial response: " + requestId); } @Override public void complete() { log.info(() -> "All events stream successfully"); } @Override public void exceptionOccurred(Throwable throwable) { log.error(() -> "An exception was thrown " + throwable.getMessage(), throwable); } }
3,039
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/utils/StabilityTestsRunnerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.utils; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.utils.Logger; /** * Tests of the tests */ public class StabilityTestsRunnerTest { private static final Logger LOGGER = Logger.loggerFor("RunnerTest"); private static ExecutorService executors; @BeforeAll public static void setUp() { executors = Executors.newFixedThreadPool(10); } @AfterAll public static void tearDown() { executors.shutdown(); } @Test public void testUsingFutureFactory() { StabilityTestRunner.newRunner() .futureFactory(i -> CompletableFuture.runAsync(() -> LOGGER.debug(() -> "hello world " + i), executors)) .testName("test") .requestCountPerRun(10) .delaysBetweenEachRun(Duration.ofMillis(500)) .totalRuns(5) .run(); } @Test public void testUsingFutures() { List<CompletableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { int finalI = i; futures.add(CompletableFuture.runAsync(() -> LOGGER.debug(() -> "hello world " + finalI), executors)); } StabilityTestRunner.newRunner() .futures(futures) .testName("test") .run(); } @Test public void unexpectedExceptionThrown_shouldFailTests() { List<CompletableFuture<?>> futures = new ArrayList<>(); futures.add(CompletableFuture.runAsync(() -> { throw new RuntimeException("boom"); }, executors)); futures.add(CompletableFuture.runAsync(() -> LOGGER.debug(() -> "hello world "), executors)); assertThatThrownBy(() -> StabilityTestRunner.newRunner() .futures(futures) .testName("test") .run()).hasMessageContaining("unknown exceptions were thrown"); } @Test public void expectedExceptionThrownExceedsThreshold_shouldFailTests() { List<CompletableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { int finalI = i; if (i < 3) { futures.add(CompletableFuture.runAsync(() -> { throw SdkServiceException.builder().message("boom").build(); }, executors)); } else { futures.add(CompletableFuture.runAsync(() -> LOGGER.debug(() -> "hello world " + finalI), executors)); } } assertThatThrownBy(() -> StabilityTestRunner.newRunner() .futures(futures) .testName("test") .run()) .hasMessageContaining("failed of SdkServiceException or IOException"); } @Test public void expectedExceptionThrownNotExceedsThreshold_shouldSucceed() { List<CompletableFuture<?>> futures = new ArrayList<>(); futures.add(CompletableFuture.runAsync(() -> { throw SdkServiceException.builder().message("boom").build(); }, executors)); for (int i = 1; i < 20; i++) { futures.add(CompletableFuture.runAsync(() -> LOGGER.debug(() -> "hello world "), executors)); } StabilityTestRunner.newRunner() .futures(futures) .testName("test") .run(); } @Test public void sdkClientExceptionsThrown_shouldFail() { List<CompletableFuture<?>> futures = new ArrayList<>(); futures.add(CompletableFuture.runAsync(() -> { throw SdkClientException.builder().message("boom").build(); }, executors)); futures.add(CompletableFuture.runAsync(() -> LOGGER.debug(() -> "hello world "), executors)); assertThatThrownBy(() -> StabilityTestRunner.newRunner() .futures(futures) .testName("test") .run()).hasMessageContaining("SdkClientExceptions were thrown"); } }
3,040
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/utils/RetryableTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.utils; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.TestTemplate; import org.junit.jupiter.api.extension.ExtendWith; /** * Denotes that a method is a test template for a retryable test. */ @Target( {ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @TestTemplate @ExtendWith(RetryableTestExtension.class) public @interface RetryableTest { /** * Exception to retry * * @return Exception that handled */ Class<? extends Throwable> retryableException() default Throwable.class; /** * The maximum number of retries. * * @return the number of retries; must be greater than zero */ int maxRetries(); }
3,041
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/exceptions/StabilityTestsRetryableException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.exceptions; /** * Indicating the tests failure can be retried */ public class StabilityTestsRetryableException extends RuntimeException { public StabilityTestsRetryableException(String message) { super(message); } }
3,042
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/sqs/SqsCrtAsyncStabilityTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.sqs; import java.time.Duration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.crt.io.EventLoopGroup; import software.amazon.awssdk.crt.io.HostResolver; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient; import software.amazon.awssdk.services.sqs.SqsAsyncClient; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; public class SqsCrtAsyncStabilityTest extends SqsBaseStabilityTest { private static String queueName; private static String queueUrl; private static SqsAsyncClient sqsAsyncClient; @Override protected SqsAsyncClient getTestClient() { return sqsAsyncClient; } @Override protected String getQueueUrl() { return queueUrl; } @Override protected String getQueueName() { return queueName; } @BeforeAll public static void setup() { SdkAsyncHttpClient.Builder crtClientBuilder = AwsCrtAsyncHttpClient.builder() .connectionMaxIdleTime(Duration.ofSeconds(5)); sqsAsyncClient = SqsAsyncClient.builder() .httpClientBuilder(crtClientBuilder) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b.apiCallTimeout(Duration.ofMinutes(10)) // Retry at test level .retryPolicy(RetryPolicy.none())) .build(); queueName = "sqscrtasyncstabilitytests" + System.currentTimeMillis(); queueUrl = setup(sqsAsyncClient, queueName); } @AfterAll public static void tearDown() { tearDown(sqsAsyncClient, queueUrl); sqsAsyncClient.close(); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void sendMessage_receiveMessage() { sendMessage(); receiveMessage(); } }
3,043
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/sqs/SqsBaseStabilityTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.sqs; import java.time.Duration; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.IntFunction; import java.util.stream.Collectors; import org.apache.commons.lang3.RandomStringUtils; import software.amazon.awssdk.services.sqs.SqsAsyncClient; import software.amazon.awssdk.services.sqs.model.CreateQueueResponse; import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequestEntry; import software.amazon.awssdk.stability.tests.utils.StabilityTestRunner; import software.amazon.awssdk.testutils.service.AwsTestBase; import software.amazon.awssdk.utils.Logger; public abstract class SqsBaseStabilityTest extends AwsTestBase { private static final Logger log = Logger.loggerFor(SqsNettyAsyncStabilityTest.class); protected static final int CONCURRENCY = 100; protected static final int TOTAL_RUNS = 50; protected abstract SqsAsyncClient getTestClient(); protected abstract String getQueueUrl(); protected abstract String getQueueName(); protected static String setup(SqsAsyncClient client, String queueName) { CreateQueueResponse createQueueResponse = client.createQueue(b -> b.queueName(queueName)).join(); return createQueueResponse.queueUrl(); } protected static void tearDown(SqsAsyncClient client, String queueUrl) { if (queueUrl != null) { client.deleteQueue(b -> b.queueUrl(queueUrl)); } } protected void sendMessage() { log.info(() -> String.format("Starting testing sending messages to queue %s with queueUrl %s", getQueueName(), getQueueUrl())); String messageBody = RandomStringUtils.randomAscii(1000); IntFunction<CompletableFuture<?>> futureIntFunction = i -> getTestClient().sendMessage(b -> b.queueUrl(getQueueUrl()).messageBody(messageBody)); runSqsTests("sendMessage", futureIntFunction); } protected void receiveMessage() { log.info(() -> String.format("Starting testing receiving messages from queue %s with queueUrl %s", getQueueName(), getQueueUrl())); IntFunction<CompletableFuture<?>> futureIntFunction = i -> getTestClient().receiveMessage(b -> b.queueUrl(getQueueUrl())) .thenApply( r -> { List<DeleteMessageBatchRequestEntry> batchRequestEntries = r.messages().stream().map(m -> DeleteMessageBatchRequestEntry.builder().id(m.messageId()).receiptHandle(m.receiptHandle()).build()) .collect(Collectors.toList()); return getTestClient().deleteMessageBatch(b -> b.queueUrl(getQueueUrl()).entries(batchRequestEntries)); }); runSqsTests("receiveMessage", futureIntFunction); } private void runSqsTests(String testName, IntFunction<CompletableFuture<?>> futureIntFunction) { StabilityTestRunner.newRunner() .testName("SqsAsyncStabilityTest." + testName) .futureFactory(futureIntFunction) .totalRuns(TOTAL_RUNS) .requestCountPerRun(CONCURRENCY) .delaysBetweenEachRun(Duration.ofMillis(100)) .run(); } }
3,044
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/sqs/SqsNettyAsyncStabilityTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.sqs; import java.time.Duration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.sqs.SqsAsyncClient; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; public class SqsNettyAsyncStabilityTest extends SqsBaseStabilityTest { private static String queueName; private static String queueUrl; private static SqsAsyncClient sqsAsyncClient; @Override protected SqsAsyncClient getTestClient() { return sqsAsyncClient; } @Override protected String getQueueUrl() { return queueUrl; } @Override protected String getQueueName() { return queueName; } @BeforeAll public static void setup() { sqsAsyncClient = SqsAsyncClient.builder() .httpClientBuilder(NettyNioAsyncHttpClient.builder().maxConcurrency(CONCURRENCY)) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(b -> b.apiCallTimeout(Duration.ofMinutes(1))) .build(); queueName = "sqsnettyasyncstabilitytests" + System.currentTimeMillis(); queueUrl = setup(sqsAsyncClient, queueName); } @AfterAll public static void tearDown() { tearDown(sqsAsyncClient, queueUrl); sqsAsyncClient.close(); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void sendMessage_receiveMessage() { sendMessage(); receiveMessage(); } }
3,045
0
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests
Create_ds/aws-sdk-java-v2/test/stability-tests/src/it/java/software/amazon/awssdk/stability/tests/transcribestreaming/TranscribeStreamingStabilityTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.stability.tests.transcribestreaming; import java.io.InputStream; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.function.IntFunction; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient; import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; import software.amazon.awssdk.services.transcribestreaming.model.LanguageCode; import software.amazon.awssdk.services.transcribestreaming.model.MediaEncoding; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponse; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler; import software.amazon.awssdk.services.transcribestreaming.model.TranscriptEvent; import software.amazon.awssdk.services.transcribestreaming.model.TranscriptResultStream; import software.amazon.awssdk.stability.tests.exceptions.StabilityTestsRetryableException; import software.amazon.awssdk.stability.tests.utils.RetryableTest; import software.amazon.awssdk.stability.tests.utils.StabilityTestRunner; import software.amazon.awssdk.stability.tests.utils.TestEventStreamingResponseHandler; import software.amazon.awssdk.stability.tests.utils.TestTranscribeStreamingSubscription; import software.amazon.awssdk.testutils.service.AwsTestBase; import software.amazon.awssdk.utils.Logger; public class TranscribeStreamingStabilityTest extends AwsTestBase { private static final Logger log = Logger.loggerFor(TranscribeStreamingStabilityTest.class.getSimpleName()); public static final int CONCURRENCY = 2; public static final int TOTAL_RUNS = 1; private static TranscribeStreamingAsyncClient transcribeStreamingClient; private static InputStream audioFileInputStream; @BeforeAll public static void setup() { transcribeStreamingClient = TranscribeStreamingAsyncClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .httpClientBuilder(NettyNioAsyncHttpClient.builder() .connectionAcquisitionTimeout(Duration.ofSeconds(30)) .maxConcurrency(CONCURRENCY)) .build(); audioFileInputStream = getInputStream(); if (audioFileInputStream == null) { throw new RuntimeException("fail to get the audio input stream"); } } @AfterAll public static void tearDown() { transcribeStreamingClient.close(); } @RetryableTest(maxRetries = 3, retryableException = StabilityTestsRetryableException.class) public void startTranscription() { IntFunction<CompletableFuture<?>> futureIntFunction = i -> transcribeStreamingClient.startStreamTranscription(b -> b.mediaSampleRateHertz(8_000) .languageCode(LanguageCode.EN_US) .mediaEncoding(MediaEncoding.PCM), new AudioStreamPublisher(), new TestStartStreamTranscriptionResponseHandler()); StabilityTestRunner.newRunner() .futureFactory(futureIntFunction) .totalRuns(TOTAL_RUNS) .requestCountPerRun(CONCURRENCY) .testName("TranscribeStreamingStabilityTest.startTranscription") .run(); } private static InputStream getInputStream() { return TranscribeStreamingStabilityTest.class.getResourceAsStream("silence_8kHz.wav"); } private class AudioStreamPublisher implements Publisher<AudioStream> { @Override public void subscribe(Subscriber<? super AudioStream> s) { s.onSubscribe(new TestTranscribeStreamingSubscription(s, audioFileInputStream)); } } private static class TestStartStreamTranscriptionResponseHandler extends TestEventStreamingResponseHandler<StartStreamTranscriptionResponse, TranscriptResultStream> implements StartStreamTranscriptionResponseHandler { @Override public void onEventStream(SdkPublisher<TranscriptResultStream> publisher) { publisher .filter(TranscriptEvent.class) .subscribe(result -> log.debug(() -> "Record Batch - " + result.transcript().results())); } } }
3,046
0
Create_ds/aws-sdk-java-v2/codegen-maven-plugin/src/main/java/software/amazon/awssdk/codegen/maven
Create_ds/aws-sdk-java-v2/codegen-maven-plugin/src/main/java/software/amazon/awssdk/codegen/maven/plugin/GenerationMojo.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.codegen.maven.plugin; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.Optional; import java.util.stream.Stream; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import software.amazon.awssdk.codegen.C2jModels; import software.amazon.awssdk.codegen.CodeGenerator; import software.amazon.awssdk.codegen.internal.Utils; import software.amazon.awssdk.codegen.model.config.customization.CustomizationConfig; import software.amazon.awssdk.codegen.model.rules.endpoints.EndpointTestSuiteModel; import software.amazon.awssdk.codegen.model.service.EndpointRuleSetModel; import software.amazon.awssdk.codegen.model.service.Paginators; import software.amazon.awssdk.codegen.model.service.ServiceModel; import software.amazon.awssdk.codegen.model.service.Waiters; import software.amazon.awssdk.codegen.utils.ModelLoaderUtils; /** * The Maven mojo to generate Java client code using software.amazon.awssdk:codegen module. */ @Mojo(name = "generate") public class GenerationMojo extends AbstractMojo { private static final String MODEL_FILE = "service-2.json"; private static final String CUSTOMIZATION_CONFIG_FILE = "customization.config"; private static final String WAITERS_FILE = "waiters-2.json"; private static final String PAGINATORS_FILE = "paginators-1.json"; private static final String ENDPOINT_RULE_SET_FILE = "endpoint-rule-set.json"; private static final String ENDPOINT_TESTS_FILE = "endpoint-tests.json"; @Parameter(property = "codeGenResources", defaultValue = "${basedir}/src/main/resources/codegen-resources/") private File codeGenResources; @Parameter(property = "outputDirectory", defaultValue = "${project.build.directory}") private String outputDirectory; @Parameter(defaultValue = "false") private boolean writeIntermediateModel; @Parameter(defaultValue = "${project}", readonly = true) private MavenProject project; private Path sourcesDirectory; private Path resourcesDirectory; private Path testsDirectory; @Override public void execute() throws MojoExecutionException { this.sourcesDirectory = Paths.get(outputDirectory).resolve("generated-sources").resolve("sdk"); this.resourcesDirectory = Paths.get(outputDirectory).resolve("generated-resources").resolve("sdk-resources"); this.testsDirectory = Paths.get(outputDirectory).resolve("generated-test-sources").resolve("sdk-tests"); findModelRoots().forEach(p -> { Path modelRootPath = p.modelRoot; getLog().info("Loading from: " + modelRootPath.toString()); generateCode(C2jModels.builder() .customizationConfig(p.customizationConfig) .serviceModel(loadServiceModel(modelRootPath)) .waitersModel(loadWaiterModel(modelRootPath)) .paginatorsModel(loadPaginatorModel(modelRootPath)) .endpointRuleSetModel(loadEndpointRuleSetModel(modelRootPath)) .endpointTestSuiteModel(loadEndpointTestSuiteModel(modelRootPath)) .build()); }); project.addCompileSourceRoot(sourcesDirectory.toFile().getAbsolutePath()); project.addTestCompileSourceRoot(testsDirectory.toFile().getAbsolutePath()); } private Stream<ModelRoot> findModelRoots() throws MojoExecutionException { try { return Files.find(codeGenResources.toPath(), 10, this::isModelFile) .map(Path::getParent) .map(p -> new ModelRoot(p, loadCustomizationConfig(p))) .sorted(this::modelSharersLast); } catch (IOException e) { throw new MojoExecutionException("Failed to find '" + MODEL_FILE + "' files in " + codeGenResources, e); } } private int modelSharersLast(ModelRoot lhs, ModelRoot rhs) { return lhs.customizationConfig.getShareModelConfig() == null ? -1 : 1; } private boolean isModelFile(Path p, BasicFileAttributes a) { return p.toString().endsWith(MODEL_FILE); } private void generateCode(C2jModels models) { CodeGenerator.builder() .models(models) .sourcesDirectory(sourcesDirectory.toFile().getAbsolutePath()) .resourcesDirectory(resourcesDirectory.toFile().getAbsolutePath()) .testsDirectory(testsDirectory.toFile().getAbsolutePath()) .intermediateModelFileNamePrefix(intermediateModelFileNamePrefix(models)) .build() .execute(); } private String intermediateModelFileNamePrefix(C2jModels models) { return writeIntermediateModel ? Utils.getFileNamePrefix(models.serviceModel()) : null; } private CustomizationConfig loadCustomizationConfig(Path root) { return ModelLoaderUtils.loadOptionalModel(CustomizationConfig.class, root.resolve(CUSTOMIZATION_CONFIG_FILE).toFile(), true) .orElse(CustomizationConfig.create()); } private ServiceModel loadServiceModel(Path root) { return loadRequiredModel(ServiceModel.class, root.resolve(MODEL_FILE)); } private Waiters loadWaiterModel(Path root) { return loadOptionalModel(Waiters.class, root.resolve(WAITERS_FILE)).orElse(Waiters.none()); } private Paginators loadPaginatorModel(Path root) { return loadOptionalModel(Paginators.class, root.resolve(PAGINATORS_FILE)).orElse(Paginators.none()); } private EndpointRuleSetModel loadEndpointRuleSetModel(Path root) { return loadOptionalModel(EndpointRuleSetModel.class, root.resolve(ENDPOINT_RULE_SET_FILE)).orElse(null); } private EndpointTestSuiteModel loadEndpointTestSuiteModel(Path root) { return loadOptionalModel(EndpointTestSuiteModel.class, root.resolve(ENDPOINT_TESTS_FILE)).orElse(null); } /** * Load required model from the project resources. */ private <T> T loadRequiredModel(Class<T> clzz, Path location) { return ModelLoaderUtils.loadModel(clzz, location.toFile()); } /** * Load an optional model from the project resources. * * @return Model or empty optional if not present. */ private <T> Optional<T> loadOptionalModel(Class<T> clzz, Path location) { return ModelLoaderUtils.loadOptionalModel(clzz, location.toFile()); } private static class ModelRoot { private final Path modelRoot; private final CustomizationConfig customizationConfig; private ModelRoot(Path modelRoot, CustomizationConfig customizationConfig) { this.modelRoot = modelRoot; this.customizationConfig = customizationConfig; } } }
3,047
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/SdkHttpRequestResponseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; import java.util.AbstractMap; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; import org.junit.jupiter.api.Test; /** * Verify that {@link DefaultSdkHttpFullRequest} and {@link DefaultSdkHttpFullResponse} properly fulfill the contracts in their * interfaces. */ public class SdkHttpRequestResponseTest { @Test public void optionalValuesAreOptional() { assertThat(validRequest().contentStreamProvider()).isNotPresent(); assertThat(validResponse().content()).isNotPresent(); assertThat(validResponse().statusText()).isNotPresent(); } @Test public void requestHeaderMapsAreCopiedWhenModified() { assertRequestHeaderMapsAreCopied(b -> b.putHeader("foo", "bar")); assertRequestHeaderMapsAreCopied(b -> b.putHeader("foo", singletonList("bar"))); assertRequestHeaderMapsAreCopied(b -> b.appendHeader("foo", "bar")); assertRequestHeaderMapsAreCopied(b -> b.headers(emptyMap())); assertRequestHeaderMapsAreCopied(b -> b.clearHeaders()); assertRequestHeaderMapsAreCopied(b -> b.removeHeader("Accept")); } @Test public void requestQueryStringMapsAreCopiedWhenModified() { assertRequestQueryStringMapsAreCopied(b -> b.putRawQueryParameter("foo", "bar")); assertRequestQueryStringMapsAreCopied(b -> b.putRawQueryParameter("foo", singletonList("bar"))); assertRequestQueryStringMapsAreCopied(b -> b.appendRawQueryParameter("foo", "bar")); assertRequestQueryStringMapsAreCopied(b -> b.rawQueryParameters(emptyMap())); assertRequestQueryStringMapsAreCopied(b -> b.clearQueryParameters()); assertRequestQueryStringMapsAreCopied(b -> b.removeQueryParameter("Accept")); } @Test public void responseHeaderMapsAreCopiedWhenModified() { assertResponseHeaderMapsAreCopied(b -> b.putHeader("foo", "bar")); assertResponseHeaderMapsAreCopied(b -> b.putHeader("foo", singletonList("bar"))); assertResponseHeaderMapsAreCopied(b -> b.appendHeader("foo", "bar")); assertResponseHeaderMapsAreCopied(b -> b.headers(emptyMap())); assertResponseHeaderMapsAreCopied(b -> b.clearHeaders()); assertResponseHeaderMapsAreCopied(b -> b.removeHeader("Accept")); } private void assertRequestHeaderMapsAreCopied(Consumer<SdkHttpRequest.Builder> mutation) { SdkHttpFullRequest request = validRequestWithMaps(); Map<String, List<String>> originalQuery = new LinkedHashMap<>(request.headers()); SdkHttpFullRequest.Builder builder = request.toBuilder(); assertThat(request.headers()).isEqualTo(builder.headers()); builder.applyMutation(mutation); SdkHttpFullRequest request2 = builder.build(); assertThat(request.headers()).isEqualTo(originalQuery); assertThat(request.headers()).isNotEqualTo(request2.headers()); } private void assertRequestQueryStringMapsAreCopied(Consumer<SdkHttpRequest.Builder> mutation) { SdkHttpFullRequest request = validRequestWithMaps(); Map<String, List<String>> originalQuery = new LinkedHashMap<>(request.rawQueryParameters()); SdkHttpFullRequest.Builder builder = request.toBuilder(); assertThat(request.rawQueryParameters()).isEqualTo(builder.rawQueryParameters()); builder.applyMutation(mutation); SdkHttpFullRequest request2 = builder.build(); assertThat(request.rawQueryParameters()).isEqualTo(originalQuery); assertThat(request.rawQueryParameters()).isNotEqualTo(request2.rawQueryParameters()); } private void assertResponseHeaderMapsAreCopied(Consumer<SdkHttpResponse.Builder> mutation) { SdkHttpResponse response = validResponseWithMaps(); Map<String, List<String>> originalQuery = new LinkedHashMap<>(response.headers()); SdkHttpResponse.Builder builder = response.toBuilder(); assertThat(response.headers()).isEqualTo(builder.headers()); builder.applyMutation(mutation); SdkHttpResponse response2 = builder.build(); assertThat(response.headers()).isEqualTo(originalQuery); assertThat(response.headers()).isNotEqualTo(response2.headers()); } @Test public void headersAreUnmodifiable() { assertThatThrownBy(() -> validRequest().headers().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validResponse().headers().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validRequest().toBuilder().headers().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validResponse().toBuilder().headers().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validRequest().toBuilder().build().headers().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validResponse().toBuilder().build().headers().clear()).isInstanceOf(UnsupportedOperationException.class); } @Test public void queryStringsAreUnmodifiable() { assertThatThrownBy(() -> validRequest().rawQueryParameters().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validRequest().toBuilder().rawQueryParameters().clear()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> validRequest().toBuilder().build().rawQueryParameters().clear()).isInstanceOf(UnsupportedOperationException.class); } @Test public void uriConversionIsCorrect() { assertThat(normalizedUri(b -> b.protocol("http").host("localhost"))).isEqualTo("http://localhost"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80))).isEqualTo("http://localhost"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(8080))).isEqualTo("http://localhost:8080"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(443))).isEqualTo("http://localhost:443"); assertThat(normalizedUri(b -> b.protocol("https").host("localhost").port(443))).isEqualTo("https://localhost"); assertThat(normalizedUri(b -> b.protocol("https").host("localhost").port(8443))).isEqualTo("https://localhost:8443"); assertThat(normalizedUri(b -> b.protocol("https").host("localhost").port(80))).isEqualTo("https://localhost:80"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).encodedPath("foo"))) .isEqualTo("http://localhost/foo"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).encodedPath("/foo"))) .isEqualTo("http://localhost/foo"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).encodedPath("foo/"))) .isEqualTo("http://localhost/foo/"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).encodedPath("/foo/"))) .isEqualTo("http://localhost/foo/"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).putRawQueryParameter("foo", "bar "))) .isEqualTo("http://localhost?foo=bar%20"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).encodedPath("/foo").putRawQueryParameter("foo", "bar"))) .isEqualTo("http://localhost/foo?foo=bar"); assertThat(normalizedUri(b -> b.protocol("http").host("localhost").port(80).encodedPath("foo/").putRawQueryParameter("foo", "bar"))) .isEqualTo("http://localhost/foo/?foo=bar"); } private String normalizedUri(Consumer<SdkHttpRequest.Builder> builderMutator) { return validRequestBuilder().applyMutation(builderMutator).build().getUri().toString(); } @Test public void protocolNormalizationIsCorrect() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> normalizedProtocol(null)); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> normalizedProtocol("foo")); assertThat(normalizedProtocol("http")).isEqualTo("http"); assertThat(normalizedProtocol("https")).isEqualTo("https"); assertThat(normalizedProtocol("HtTp")).isEqualTo("http"); assertThat(normalizedProtocol("HtTpS")).isEqualTo("https"); } private String normalizedProtocol(String protocol) { return validRequestBuilder().protocol(protocol).build().protocol(); } @Test public void hostNormalizationIsCorrect() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> normalizedHost(null)); assertThat(normalizedHost("foo")).isEqualTo("foo"); } private String normalizedHost(String host) { return validRequestBuilder().host(host).build().host(); } @Test public void portNormalizationIsCorrect() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> normalizedPort("http", -2)); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> normalizedPort("https", -2)); assertThat(normalizedPort("http", -1)).isEqualTo(80); assertThat(normalizedPort("http", null)).isEqualTo(80); assertThat(normalizedPort("https", -1)).isEqualTo(443); assertThat(normalizedPort("https", null)).isEqualTo(443); assertThat(normalizedPort("http", 8080)).isEqualTo(8080); assertThat(normalizedPort("https", 8443)).isEqualTo(8443); } private int normalizedPort(String protocol, Integer port) { return validRequestBuilder().protocol(protocol).port(port).build().port(); } @Test public void requestPathNormalizationIsCorrect() { assertThat(normalizedPath(null)).isEqualTo(""); assertThat(normalizedPath("/")).isEqualTo("/"); assertThat(normalizedPath(" ")).isEqualTo("/ "); assertThat(normalizedPath(" /")).isEqualTo("/ /"); assertThat(normalizedPath("/ ")).isEqualTo("/ "); assertThat(normalizedPath("/ /")).isEqualTo("/ /"); assertThat(normalizedPath(" / ")).isEqualTo("/ / "); assertThat(normalizedPath("/Foo/")).isEqualTo("/Foo/"); assertThat(normalizedPath("Foo/")).isEqualTo("/Foo/"); assertThat(normalizedPath("Foo")).isEqualTo("/Foo"); assertThat(normalizedPath("/Foo/bar/")).isEqualTo("/Foo/bar/"); assertThat(normalizedPath("Foo/bar/")).isEqualTo("/Foo/bar/"); assertThat(normalizedPath("/Foo/bar")).isEqualTo("/Foo/bar"); assertThat(normalizedPath("Foo/bar")).isEqualTo("/Foo/bar"); assertThat(normalizedPath("%2F")).isEqualTo("/%2F"); } private String normalizedPath(String path) { return validRequestBuilder().encodedPath(path).build().encodedPath(); } @Test public void requestMethodNormalizationIsCorrect() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> normalizedMethod(null)); assertThat(normalizedMethod(SdkHttpMethod.POST)).isEqualTo(SdkHttpMethod.POST); } private SdkHttpMethod normalizedMethod(SdkHttpMethod method) { return validRequestBuilder().method(method).build().method(); } @Test public void requestQueryParamNormalizationIsCorrect() { headerOrQueryStringNormalizationIsCorrect(() -> new BuilderProxy() { private final SdkHttpRequest.Builder builder = validRequestBuilder(); @Override public BuilderProxy setValue(String key, String value) { builder.putRawQueryParameter(key, value); return this; } @Override public BuilderProxy appendValue(String key, String value) { builder.appendRawQueryParameter(key, value); return this; } @Override public BuilderProxy setValues(String key, List<String> values) { builder.putRawQueryParameter(key, values); return this; } @Override public BuilderProxy removeValue(String key) { builder.removeQueryParameter(key); return this; } @Override public BuilderProxy clearValues() { builder.clearQueryParameters(); return this; } @Override public BuilderProxy setMap(Map<String, List<String>> map) { builder.rawQueryParameters(map); return this; } @Override public Map<String, List<String>> getMap() { return builder.build().rawQueryParameters(); } }); } @Test public void requestHeaderNormalizationIsCorrect() { headerOrQueryStringNormalizationIsCorrect(() -> new BuilderProxy() { private final SdkHttpRequest.Builder builder = validRequestBuilder(); @Override public BuilderProxy setValue(String key, String value) { builder.putHeader(key, value); return this; } @Override public BuilderProxy appendValue(String key, String value) { builder.appendHeader(key, value); return this; } @Override public BuilderProxy setValues(String key, List<String> values) { builder.putHeader(key, values); return this; } @Override public BuilderProxy removeValue(String key) { builder.removeHeader(key); return this; } @Override public BuilderProxy clearValues() { builder.clearHeaders(); return this; } @Override public BuilderProxy setMap(Map<String, List<String>> map) { builder.headers(map); return this; } @Override public Map<String, List<String>> getMap() { return builder.build().headers(); } }); } @Test public void responseStatusCodeNormalizationIsCorrect() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> normalizedStatusCode(-1)); assertThat(normalizedStatusCode(200)).isEqualTo(200); } private int normalizedStatusCode(int statusCode) { return validResponseBuilder().statusCode(statusCode).build().statusCode(); } @Test public void responseHeaderNormalizationIsCorrect() { headerOrQueryStringNormalizationIsCorrect(() -> new BuilderProxy() { private final SdkHttpFullResponse.Builder builder = validResponseBuilder(); @Override public BuilderProxy setValue(String key, String value) { builder.putHeader(key, value); return this; } @Override public BuilderProxy appendValue(String key, String value) { builder.appendHeader(key, value); return this; } @Override public BuilderProxy setValues(String key, List<String> values) { builder.putHeader(key, values); return this; } @Override public BuilderProxy removeValue(String key) { builder.removeHeader(key); return this; } @Override public BuilderProxy clearValues() { builder.clearHeaders(); return this; } @Override public BuilderProxy setMap(Map<String, List<String>> map) { builder.headers(map); return this; } @Override public Map<String, List<String>> getMap() { return builder.build().headers(); } }); } @Test public void testSdkHttpFullRequestBuilderNoQueryParams() { URI uri = URI.create("https://github.com/aws/aws-sdk-java-v2/issues/2034"); final SdkHttpFullRequest sdkHttpFullRequest = SdkHttpFullRequest.builder().method(SdkHttpMethod.POST).uri(uri).build(); assertThat(sdkHttpFullRequest.getUri().getQuery()).isNullOrEmpty(); } @Test public void testSdkHttpFullRequestBuilderUriWithQueryParams() { URI uri = URI.create("https://github.com/aws/aws-sdk-java-v2/issues/2034?reqParam=1234&oParam=3456%26reqParam%3D5678"); final SdkHttpFullRequest sdkHttpFullRequest = SdkHttpFullRequest.builder().method(SdkHttpMethod.POST).uri(uri).build(); assertThat(sdkHttpFullRequest.getUri().getQuery()).contains("reqParam=1234", "oParam=3456&reqParam=5678"); } @Test public void testSdkHttpFullRequestBuilderUriWithQueryParamWithoutValue() { final String expected = "https://github.com/aws/aws-sdk-for-java-v2?foo"; URI myUri = URI.create(expected); SdkHttpFullRequest actual = SdkHttpFullRequest.builder().method(SdkHttpMethod.POST).uri(myUri).build(); assertThat(actual.getUri()).hasToString(expected); } @Test public void testSdkHttpRequestBuilderNoQueryParams() { URI uri = URI.create("https://github.com/aws/aws-sdk-java-v2/issues/2034"); final SdkHttpRequest sdkHttpRequest = SdkHttpRequest.builder().method(SdkHttpMethod.POST).uri(uri).build(); assertThat(sdkHttpRequest.getUri().getQuery()).isNullOrEmpty(); } @Test public void testSdkHttpRequestBuilderUriWithQueryParams() { URI uri = URI.create("https://github.com/aws/aws-sdk-java-v2/issues/2034?reqParam=1234&oParam=3456%26reqParam%3D5678"); final SdkHttpRequest sdkHttpRequest = SdkHttpRequest.builder().method(SdkHttpMethod.POST).uri(uri).build(); assertThat(sdkHttpRequest.getUri().getQuery()).contains("reqParam=1234", "oParam=3456&reqParam=5678"); } @Test public void testSdkHttpRequestBuilderUriWithQueryParamsIgnoreOtherQueryParams() { URI uri = URI.create("https://github.com/aws/aws-sdk-java-v2/issues/2034?reqParam=1234&oParam=3456%26reqParam%3D5678"); final SdkHttpRequest sdkHttpRequest = SdkHttpRequest.builder().method(SdkHttpMethod.POST).appendRawQueryParameter("clean", "up").uri(uri).build(); assertThat(sdkHttpRequest.getUri().getQuery()).contains("reqParam=1234", "oParam=3456&reqParam=5678") .doesNotContain("clean"); } @Test public void testSdkHttpRequestBuilderUriWithQueryParamWithoutValue() { final String expected = "https://github.com/aws/aws-sdk-for-java-v2?foo"; URI myUri = URI.create(expected); SdkHttpRequest actual = SdkHttpRequest.builder().method(SdkHttpMethod.POST).uri(myUri).build(); assertThat(actual.getUri()).hasToString(expected); } private interface BuilderProxy { BuilderProxy setValue(String key, String value); BuilderProxy appendValue(String key, String value); BuilderProxy setValues(String key, List<String> values); BuilderProxy removeValue(String key); BuilderProxy clearValues(); BuilderProxy setMap(Map<String, List<String>> map); Map<String, List<String>> getMap(); } private void headerOrQueryStringNormalizationIsCorrect(Supplier<BuilderProxy> builderFactory) { assertMapIsInitiallyEmpty(builderFactory); setValue_SetsSingleValueCorrectly(builderFactory); setValue_SettingMultipleKeysAppendsToMap(builderFactory); setValue_OverwritesExistingValue(builderFactory); setValues_SetsAllValuesCorrectly(builderFactory); setValue_OverwritesAllExistingValues(builderFactory); removeValue_OnlyRemovesThatKey(builderFactory); clearValues_RemovesAllExistingValues(builderFactory); setMap_OverwritesAllExistingValues(builderFactory); appendWithExistingValues_AddsValueToList(builderFactory); appendWithNoValues_AddsSingleElementToList(builderFactory); } private void assertMapIsInitiallyEmpty(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setMap(emptyMap()).getMap()).isEmpty(); } private void setValue_SetsSingleValueCorrectly(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValue("Foo", "Bar").getMap()).satisfies(params -> { assertThat(params).containsOnlyKeys("Foo"); assertThat(params.get("Foo")).containsExactly("Bar"); }); } private void setValue_SettingMultipleKeysAppendsToMap(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValue("Foo", "Bar").setValue("Foo2", "Bar2").getMap()).satisfies(params -> { assertThat(params).containsOnlyKeys("Foo", "Foo2"); assertThat(params.get("Foo")).containsExactly("Bar"); assertThat(params.get("Foo2")).containsExactly("Bar2"); }); } private void setValue_OverwritesExistingValue(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValue("Foo", "Bar").setValue("Foo", "Bar2").getMap()).satisfies(params -> { assertThat(params).containsOnlyKeys("Foo"); assertThat(params.get("Foo")).containsExactly("Bar2"); }); } private void setValues_SetsAllValuesCorrectly(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValues("Foo", Arrays.asList("Bar", "Baz")).getMap()).satisfies(params -> { assertThat(params).containsOnlyKeys("Foo"); assertThat(params.get("Foo")).containsExactly("Bar", "Baz"); }); } private void setValue_OverwritesAllExistingValues(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValues("Foo", Arrays.asList("Bar", "Baz")).setValue("Foo", "Bar").getMap()) .satisfies(params -> { assertThat(params).containsOnlyKeys("Foo"); assertThat(params.get("Foo")).containsExactly("Bar"); }); } private void removeValue_OnlyRemovesThatKey(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValues("Foo", Arrays.asList("Bar", "Baz")) .setValues("Foo2", Arrays.asList("Bar", "Baz")) .removeValue("Foo").getMap()) .satisfies(params -> { assertThat(params).doesNotContainKeys("Foo"); assertThat(params.get("Foo2")).containsExactly("Bar", "Baz"); }); } private void clearValues_RemovesAllExistingValues(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValues("Foo", Arrays.asList("Bar", "Baz")).clearValues().getMap()) .doesNotContainKeys("Foo"); } private void setMap_OverwritesAllExistingValues(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValues("Foo", Arrays.asList("Bar", "Baz")) .setMap(singletonMap("Foo2", singletonList("Baz2"))).getMap()) .satisfies(params -> { assertThat(params).containsOnlyKeys("Foo2"); assertThat(params.get("Foo2")).containsExactly("Baz2"); }); } private void appendWithExistingValues_AddsValueToList(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().setValues("Key", Arrays.asList("Foo", "Bar")) .appendValue("Key", "Baz").getMap()) .satisfies(params -> { assertThat(params).containsOnly(new AbstractMap.SimpleEntry<>("Key", Arrays.asList("Foo", "Bar", "Baz"))); }); } private void appendWithNoValues_AddsSingleElementToList(Supplier<BuilderProxy> builderFactory) { assertThat(builderFactory.get().appendValue("AppendNotExists", "Baz").getMap()) .satisfies(params -> { assertThat(params).containsOnly(new AbstractMap.SimpleEntry<>("AppendNotExists", Arrays.asList("Baz"))); }); } private SdkHttpFullRequest validRequestWithMaps() { return validRequestWithMapsBuilder().build(); } private SdkHttpFullRequest.Builder validRequestWithMapsBuilder() { return validRequestBuilder().putHeader("Accept", "*/*") .putRawQueryParameter("Accept", "*/*"); } private SdkHttpFullRequest validRequest() { return validRequestBuilder().build(); } private SdkHttpFullRequest.Builder validRequestBuilder() { return SdkHttpFullRequest.builder() .protocol("http") .host("localhost") .method(SdkHttpMethod.GET); } private SdkHttpResponse validResponseWithMaps() { return validResponseWithMapsBuilder().build(); } private SdkHttpResponse.Builder validResponseWithMapsBuilder() { return validResponseBuilder().putHeader("Accept", "*/*"); } private SdkHttpFullResponse validResponse() { return validResponseBuilder().build(); } private SdkHttpFullResponse.Builder validResponseBuilder() { return SdkHttpFullResponse.builder().statusCode(500); } }
3,048
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/TlsKeyManagersProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; public class TlsKeyManagersProviderTest { @Test public void noneProvider_returnsProviderThatReturnsNull() { assertThat(TlsKeyManagersProvider.noneProvider().keyManagers()).isNull(); } }
3,049
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/HttpStatusFamilyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; public class HttpStatusFamilyTest { @Test public void statusFamiliesAreMappedCorrectly() { assertThat(HttpStatusFamily.of(-1)).isEqualTo(HttpStatusFamily.OTHER); assertThat(HttpStatusFamily.of(HttpStatusCode.CONTINUE)).isEqualTo(HttpStatusFamily.INFORMATIONAL); assertThat(HttpStatusFamily.of(HttpStatusCode.OK)).isEqualTo(HttpStatusFamily.SUCCESSFUL); assertThat(HttpStatusFamily.of(HttpStatusCode.MOVED_PERMANENTLY)).isEqualTo(HttpStatusFamily.REDIRECTION); assertThat(HttpStatusFamily.of(HttpStatusCode.NOT_FOUND)).isEqualTo(HttpStatusFamily.CLIENT_ERROR); assertThat(HttpStatusFamily.of(HttpStatusCode.INTERNAL_SERVER_ERROR)).isEqualTo(HttpStatusFamily.SERVER_ERROR); } @Test public void matchingIsCorrect() { assertThat(HttpStatusFamily.SUCCESSFUL.isOneOf()).isFalse(); assertThat(HttpStatusFamily.SUCCESSFUL.isOneOf(null)).isFalse(); assertThat(HttpStatusFamily.SUCCESSFUL.isOneOf(HttpStatusFamily.CLIENT_ERROR)).isFalse(); assertThat(HttpStatusFamily.SUCCESSFUL.isOneOf(HttpStatusFamily.CLIENT_ERROR, HttpStatusFamily.SUCCESSFUL)).isTrue(); assertThat(HttpStatusFamily.SUCCESSFUL.isOneOf(HttpStatusFamily.SUCCESSFUL, HttpStatusFamily.CLIENT_ERROR)).isTrue(); assertThat(HttpStatusFamily.OTHER.isOneOf(HttpStatusFamily.values())).isTrue(); } }
3,050
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/SdkHttpExecutionAttributesTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.utils.AttributeMap; class SdkHttpExecutionAttributesTest { @Test void equalsAndHashcode() { AttributeMap one = AttributeMap.empty(); AttributeMap two = AttributeMap.builder().put(TestExecutionAttribute.TEST_KEY_FOO, "test").build(); EqualsVerifier.forClass(SdkHttpExecutionAttributes.class) .withNonnullFields("attributes") .withPrefabValues(AttributeMap.class, one, two) .verify(); } @Test void getAttribute_shouldReturnCorrectValue() { SdkHttpExecutionAttributes attributes = SdkHttpExecutionAttributes.builder() .put(TestExecutionAttribute.TEST_KEY_FOO, "test") .build(); assertThat(attributes.getAttribute(TestExecutionAttribute.TEST_KEY_FOO)).isEqualTo("test"); } private static final class TestExecutionAttribute<T> extends SdkHttpExecutionAttribute<T> { private static final TestExecutionAttribute<String> TEST_KEY_FOO = new TestExecutionAttribute<>(String.class); private TestExecutionAttribute(Class valueType) { super(valueType); } } }
3,051
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/ClientTlsAuthTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; abstract class ClientTlsAuthTestBase { protected static final String STORE_PASSWORD = "password"; protected static final String CLIENT_STORE_TYPE = "pkcs12"; protected static final String TEST_KEY_STORE = "/software/amazon/awssdk/http/server-keystore"; protected static final String CLIENT_KEY_STORE = "/software/amazon/awssdk/http/client1.p12"; protected static Path tempDir; protected static Path serverKeyStore; protected static Path clientKeyStore; @BeforeAll public static void setUp() throws IOException { tempDir = Files.createTempDirectory(ClientTlsAuthTestBase.class.getSimpleName()); copyCertsToTmpDir(); } @AfterAll public static void teardown() throws IOException { Files.deleteIfExists(serverKeyStore); Files.deleteIfExists(clientKeyStore); Files.deleteIfExists(tempDir); } private static void copyCertsToTmpDir() throws IOException { InputStream sksStream = ClientTlsAuthTestBase.class.getResourceAsStream(TEST_KEY_STORE); Path sks = copyToTmpDir(sksStream, "server-keystore"); InputStream cksStream = ClientTlsAuthTestBase.class.getResourceAsStream(CLIENT_KEY_STORE); Path cks = copyToTmpDir(cksStream, "client1.p12"); serverKeyStore = sks; clientKeyStore = cks; } private static Path copyToTmpDir(InputStream srcStream, String name) throws IOException { Path dst = tempDir.resolve(name); Files.copy(srcStream, dst); return dst; } }
3,052
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/FileStoreTlsKeyManagersProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.nio.file.Paths; import java.security.Security; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class FileStoreTlsKeyManagersProviderTest extends ClientTlsAuthTestBase { @BeforeClass public static void setUp() throws IOException { ClientTlsAuthTestBase.setUp(); } @AfterClass public static void teardown() throws IOException { ClientTlsAuthTestBase.teardown(); } @Test(expected = NullPointerException.class) public void storePathNull_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(null, CLIENT_STORE_TYPE, STORE_PASSWORD); } @Test(expected = NullPointerException.class) public void storeTypeNull_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, null, STORE_PASSWORD); } @Test(expected = IllegalArgumentException.class) public void storeTypeEmpty_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, "", STORE_PASSWORD); } @Test public void passwordNotGiven_doesNotThrowValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, null); } @Test public void paramsValid_createsKeyManager() { FileStoreTlsKeyManagersProvider provider = FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, STORE_PASSWORD); assertThat(provider.keyManagers()).hasSize(1); } @Test public void storeDoesNotExist_returnsNull() { FileStoreTlsKeyManagersProvider provider = FileStoreTlsKeyManagersProvider.create(Paths.get("does", "not", "exist"), CLIENT_STORE_TYPE, STORE_PASSWORD); assertThat(provider.keyManagers()).isNull(); } @Test public void invalidStoreType_returnsNull() { FileStoreTlsKeyManagersProvider provider = FileStoreTlsKeyManagersProvider.create(clientKeyStore, "invalid", STORE_PASSWORD); assertThat(provider.keyManagers()).isNull(); } @Test public void passwordIncorrect_returnsNull() { FileStoreTlsKeyManagersProvider provider = FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, "not correct password"); assertThat(provider.keyManagers()).isNull(); } @Test public void customKmfAlgorithmSetInProperty_usesAlgorithm() { FileStoreTlsKeyManagersProvider beforePropSetProvider = FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, STORE_PASSWORD); assertThat(beforePropSetProvider.keyManagers()).isNotNull(); String property = "ssl.KeyManagerFactory.algorithm"; String previousValue = Security.getProperty(property); Security.setProperty(property, "some-bogus-value"); try { FileStoreTlsKeyManagersProvider afterPropSetProvider = FileStoreTlsKeyManagersProvider.create( clientKeyStore, CLIENT_STORE_TYPE, STORE_PASSWORD); // This would otherwise be non-null if using the right algorithm, // i.e. not setting the algorithm property will cause the assertion // to fail assertThat(afterPropSetProvider.keyManagers()).isNull(); } finally { Security.setProperty(property, previousValue); } } }
3,053
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/SystemPropertyTlsKeyManagersProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE; import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE_PASSWORD; import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE_TYPE; import java.io.IOException; import java.nio.file.Paths; import java.security.Security; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; public class SystemPropertyTlsKeyManagersProviderTest extends ClientTlsAuthTestBase { private static final SystemPropertyTlsKeyManagersProvider PROVIDER = SystemPropertyTlsKeyManagersProvider.create(); @BeforeAll public static void setUp() throws IOException { ClientTlsAuthTestBase.setUp(); } @AfterEach public void methodTeardown() { System.clearProperty(SSL_KEY_STORE.property()); System.clearProperty(SSL_KEY_STORE_TYPE.property()); System.clearProperty(SSL_KEY_STORE_PASSWORD.property()); } @AfterAll public static void teardown() throws IOException { ClientTlsAuthTestBase.teardown(); } @Test public void propertiesNotSet_returnsNull() { assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void propertiesSet_createsKeyManager() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).hasSize(1); } @Test public void storeDoesNotExist_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), Paths.get("does", "not", "exist").toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void invalidStoreType_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), "invalid"); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void passwordIncorrect_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), "not correct password"); assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void customKmfAlgorithmSetInProperty_usesAlgorithm() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNotNull(); String property = "ssl.KeyManagerFactory.algorithm"; String previousValue = Security.getProperty(property); Security.setProperty(property, "some-bogus-value"); try { // This would otherwise be non-null if using the right algorithm, // i.e. not setting the algorithm property will cause the assertion // to fail assertThat(PROVIDER.keyManagers()).isNull(); } finally { Security.setProperty(property, previousValue); } } }
3,054
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/software/amazon/awssdk/internal
Create_ds/aws-sdk-java-v2/http-client-spi/src/test/java/software/amazon/awssdk/http/software/amazon/awssdk/internal/http/NoneTlsKeyManagersProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.software.amazon.awssdk.internal.http; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.internal.http.NoneTlsKeyManagersProvider; public class NoneTlsKeyManagersProviderTest { @Test public void getInstance_returnsNonNull() { assertThat(NoneTlsKeyManagersProvider.getInstance()).isNotNull(); } @Test public void keyManagers_returnsNull() { assertThat(NoneTlsKeyManagersProvider.getInstance().keyManagers()).isNull(); } @Test public void getInstance_returnsSingletonInstance() { NoneTlsKeyManagersProvider provider1 = NoneTlsKeyManagersProvider.getInstance(); NoneTlsKeyManagersProvider provider2 = NoneTlsKeyManagersProvider.getInstance(); assertThat(provider1 == provider2).isTrue(); } }
3,055
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/internal
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/internal/http/NoneTlsKeyManagersProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.internal.http; import javax.net.ssl.KeyManager; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.TlsKeyManagersProvider; /** * Simple implementation of {@link TlsKeyManagersProvider} that return a null array. * <p> * Use this provider if you don't want the client to present any certificates to the remote TLS host. */ @SdkInternalApi public final class NoneTlsKeyManagersProvider implements TlsKeyManagersProvider { private static final NoneTlsKeyManagersProvider INSTANCE = new NoneTlsKeyManagersProvider(); private NoneTlsKeyManagersProvider() { } @Override public KeyManager[] keyManagers() { return null; } public static NoneTlsKeyManagersProvider getInstance() { return INSTANCE; } }
3,056
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/internal
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/internal/http/AbstractFileStoreTlsKeyManagersProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.internal.http; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.TlsKeyManagersProvider; /** * Abstract {@link TlsKeyManagersProvider} that loads the key store from a * a given file path. * <p> * This uses {@link KeyManagerFactory#getDefaultAlgorithm()} to determine the * {@code KeyManagerFactory} algorithm to use. */ @SdkInternalApi public abstract class AbstractFileStoreTlsKeyManagersProvider implements TlsKeyManagersProvider { protected final KeyManager[] createKeyManagers(Path storePath, String storeType, char[] password) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, UnrecoverableKeyException { KeyStore ks = createKeyStore(storePath, storeType, password); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, password); return kmf.getKeyManagers(); } private KeyStore createKeyStore(Path storePath, String storeType, char[] password) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { KeyStore ks = KeyStore.getInstance(storeType); try (InputStream storeIs = Files.newInputStream(storePath)) { ks.load(storeIs, password); return ks; } } }
3,057
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/internal
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/internal/http/LowCopyListMap.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.internal.http; import static software.amazon.awssdk.utils.CollectionUtils.deepCopyMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.function.Supplier; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.Lazy; /** * A {@code Map<String, List<String>>} for headers and query strings in {@link SdkHttpRequest} and {@link SdkHttpResponse} that * avoids copying data during conversion between builders and buildables, unless data is modified. * * This is created via {@link #emptyHeaders()} or {@link #emptyQueryParameters()}. */ @SdkInternalApi public final class LowCopyListMap { private LowCopyListMap() { } /** * Create an empty {@link LowCopyListMap.ForBuilder} for header storage. */ public static LowCopyListMap.ForBuilder emptyHeaders() { return new LowCopyListMap.ForBuilder(() -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); } /** * Create an empty {@link LowCopyListMap.ForBuilder} for query parameter storage. */ public static LowCopyListMap.ForBuilder emptyQueryParameters() { return new LowCopyListMap.ForBuilder(LinkedHashMap::new); } @NotThreadSafe public static final class ForBuilder { /** * The constructor that can be used to create new, empty maps. */ private final Supplier<Map<String, List<String>>> mapConstructor; /** * Whether {@link #map} has been shared with a {@link ForBuildable}. If this is true, we need to make sure to copy the * map before we mutate it. */ private boolean mapIsShared = false; /** * The data stored in this low-copy list-map. */ private Map<String, List<String>> map; /** * Created from {@link LowCopyListMap#emptyHeaders()} or {@link LowCopyListMap#emptyQueryParameters()}. */ private ForBuilder(Supplier<Map<String, List<String>>> mapConstructor) { this.mapConstructor = mapConstructor; this.map = mapConstructor.get(); } /** * Created from {@link LowCopyListMap.ForBuildable#forBuilder()}. */ private ForBuilder(ForBuildable forBuildable) { this.mapConstructor = forBuildable.mapConstructor; this.map = forBuildable.map; this.mapIsShared = true; } public void clear() { this.map = mapConstructor.get(); this.mapIsShared = false; } public void setFromExternal(Map<String, List<String>> map) { this.map = deepCopyMap(map, mapConstructor); this.mapIsShared = false; } public Map<String, List<String>> forInternalWrite() { if (mapIsShared) { this.map = deepCopyMap(map, mapConstructor); this.mapIsShared = false; } return this.map; } public Map<String, List<String>> forInternalRead() { return this.map; } public ForBuildable forBuildable() { this.mapIsShared = true; return new ForBuildable(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ForBuilder that = (ForBuilder) o; return map.equals(that.map); } @Override public int hashCode() { return map.hashCode(); } } @ThreadSafe public static final class ForBuildable { /** * The constructor that can be used to create new, empty maps. */ private final Supplier<Map<String, List<String>>> mapConstructor; /** * An unmodifiable copy of {@link #map}, which is lazily initialized only when it is needed. */ private final Lazy<Map<String, List<String>>> deeplyUnmodifiableMap; /** * The data stored in this low-copy list-map. */ private final Map<String, List<String>> map; private ForBuildable(ForBuilder forBuilder) { this.mapConstructor = forBuilder.mapConstructor; this.map = forBuilder.map; this.deeplyUnmodifiableMap = new Lazy<>(() -> CollectionUtils.deepUnmodifiableMap(this.map, this.mapConstructor)); } public Map<String, List<String>> forExternalRead() { return deeplyUnmodifiableMap.getValue(); } public Map<String, List<String>> forInternalRead() { return map; } public ForBuilder forBuilder() { return new ForBuilder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ForBuildable that = (ForBuildable) o; return map.equals(that.map); } @Override public int hashCode() { return map.hashCode(); } } }
3,058
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/FileStoreTlsKeyManagersProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.nio.file.Path; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.internal.http.AbstractFileStoreTlsKeyManagersProvider; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * Implementation of {@link FileStoreTlsKeyManagersProvider} that loads a the * key store from a file. * <p> * This uses {@link KeyManagerFactory#getDefaultAlgorithm()} to determine the * {@code KeyManagerFactory} algorithm to use. */ @SdkPublicApi public final class FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { private static final Logger log = Logger.loggerFor(FileStoreTlsKeyManagersProvider.class); private final Path storePath; private final String storeType; private final char[] password; private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password) { this.storePath = Validate.paramNotNull(storePath, "storePath"); this.storeType = Validate.paramNotBlank(storeType, "storeType"); this.password = password; } @Override public KeyManager[] keyManagers() { try { return createKeyManagers(storePath, storeType, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from file %s", storePath), e); return null; } } public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } }
3,059
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpExecutionAttributes.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An immutable collection of {@link SdkHttpExecutionAttribute}s that can be configured on an {@link AsyncExecuteRequest} via * {@link AsyncExecuteRequest.Builder#httpExecutionAttributes(SdkHttpExecutionAttributes)} */ @SdkPublicApi public final class SdkHttpExecutionAttributes implements ToCopyableBuilder<SdkHttpExecutionAttributes.Builder, SdkHttpExecutionAttributes> { private final AttributeMap attributes; private SdkHttpExecutionAttributes(Builder builder) { this.attributes = builder.sdkHttpExecutionAttributes.build(); } /** * Retrieve the current value of the provided attribute in this collection of attributes. This will return null if the value * is not set. */ public <T> T getAttribute(SdkHttpExecutionAttribute<T> attribute) { return attributes.get(attribute); } public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return new Builder(attributes); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SdkHttpExecutionAttributes that = (SdkHttpExecutionAttributes) o; return Objects.equals(attributes, that.attributes); } @Override public int hashCode() { return attributes.hashCode(); } public static final class Builder implements CopyableBuilder<SdkHttpExecutionAttributes.Builder, SdkHttpExecutionAttributes> { private AttributeMap.Builder sdkHttpExecutionAttributes = AttributeMap.builder(); private Builder(AttributeMap attributes) { sdkHttpExecutionAttributes = attributes.toBuilder(); } private Builder() { } /** * Add a mapping between the provided key and value. */ public <T> SdkHttpExecutionAttributes.Builder put(SdkHttpExecutionAttribute<T> key, T value) { Validate.notNull(key, "Key to set must not be null."); sdkHttpExecutionAttributes.put(key, value); return this; } /** * Adds all the attributes from the map provided. */ public SdkHttpExecutionAttributes.Builder putAll(Map<? extends SdkHttpExecutionAttribute<?>, ?> attributes) { sdkHttpExecutionAttributes.putAll(attributes); return this; } @Override public SdkHttpExecutionAttributes build() { return new SdkHttpExecutionAttributes(this); } } }
3,060
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/TlsTrustManagersProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import javax.net.ssl.TrustManager; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Provider for the {@link TrustManager trust managers} to be used by the SDK when * creating the SSL context. Trust managers are used when the client is checking * if the remote host can be trusted. */ @SdkPublicApi @FunctionalInterface public interface TlsTrustManagersProvider { /** * @return The {@link TrustManager}s, or {@code null}. */ TrustManager[] trustManagers(); }
3,061
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SystemPropertyTlsKeyManagersProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE; import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE_PASSWORD; import static software.amazon.awssdk.utils.JavaSystemSetting.SSL_KEY_STORE_TYPE; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; import java.util.Optional; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.internal.http.AbstractFileStoreTlsKeyManagersProvider; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.internal.SystemSettingUtils; /** * Implementation of {@link TlsKeyManagersProvider} that gets the information * about the KeyStore to load from the system properties. * <p> * This provider checks the standard {@code javax.net.ssl.keyStore}, * {@code javax.net.ssl.keyStorePassword}, and * {@code javax.net.ssl.keyStoreType} properties defined by the * <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html">JSSE</a>. * <p> * This uses {@link KeyManagerFactory#getDefaultAlgorithm()} to determine the * {@code KeyManagerFactory} algorithm to use. */ @SdkPublicApi public final class SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { private static final Logger log = Logger.loggerFor(SystemPropertyTlsKeyManagersProvider.class); private SystemPropertyTlsKeyManagersProvider() { } @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } public static SystemPropertyTlsKeyManagersProvider create() { return new SystemPropertyTlsKeyManagersProvider(); } private static Optional<String> getKeyStore() { return SystemSettingUtils.resolveSetting(SSL_KEY_STORE); } private static String getKeyStoreType() { return SystemSettingUtils.resolveSetting(SSL_KEY_STORE_TYPE) .orElseGet(KeyStore::getDefaultType); } private static Optional<String> getKeyStorePassword() { return SystemSettingUtils.resolveSetting(SSL_KEY_STORE_PASSWORD); } }
3,062
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/HttpExecuteResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.io.InputStream; import java.util.Optional; import software.amazon.awssdk.annotations.SdkPublicApi; @SdkPublicApi public class HttpExecuteResponse { private final SdkHttpResponse response; private final Optional<AbortableInputStream> responseBody; private HttpExecuteResponse(BuilderImpl builder) { this.response = builder.response; this.responseBody = builder.responseBody; } /** * @return The HTTP response. */ public SdkHttpResponse httpResponse() { return response; } /** * /** Get the {@link AbortableInputStream} associated with this response. * * <p>Always close the "responseBody" input stream to release the underlying HTTP connection. * Even for error responses, the SDK creates an input stream for reading error data. It is essential to close the input stream * in the "responseBody" attribute for both success and error cases. * * @return An {@link Optional} containing the {@link AbortableInputStream} if available. */ public Optional<AbortableInputStream> responseBody() { return responseBody; } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * Set the HTTP response to be executed by the client. * * @param response The response. * @return This builder for method chaining. */ Builder response(SdkHttpResponse response); /** * Set the {@link InputStream} to be returned by the client. * @param inputStream The {@link InputStream} * @return This builder for method chaining */ Builder responseBody(AbortableInputStream inputStream); HttpExecuteResponse build(); } private static class BuilderImpl implements Builder { private SdkHttpResponse response; private Optional<AbortableInputStream> responseBody = Optional.empty(); @Override public Builder response(SdkHttpResponse response) { this.response = response; return this; } @Override public Builder responseBody(AbortableInputStream responseBody) { this.responseBody = Optional.ofNullable(responseBody); return this; } @Override public HttpExecuteResponse build() { return new HttpExecuteResponse(this); } } }
3,063
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/Http2Metric.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.metrics.MetricCategory; import software.amazon.awssdk.metrics.MetricLevel; import software.amazon.awssdk.metrics.SdkMetric; /** * Metrics collected by HTTP clients for HTTP/2 operations. See {@link HttpMetric} for metrics that are available on both HTTP/1 * and HTTP/2 operations. */ @SdkPublicApi public final class Http2Metric { /** * The local HTTP/2 window size in bytes for the stream that this request was executed on. * * <p>See https://http2.github.io/http2-spec/#FlowControl for more information on HTTP/2 window sizes. */ public static final SdkMetric<Integer> LOCAL_STREAM_WINDOW_SIZE_IN_BYTES = metric("LocalStreamWindowSize", Integer.class, MetricLevel.TRACE); /** * The remote HTTP/2 window size in bytes for the stream that this request was executed on. * * <p>See https://http2.github.io/http2-spec/#FlowControl for more information on HTTP/2 window sizes. */ public static final SdkMetric<Integer> REMOTE_STREAM_WINDOW_SIZE_IN_BYTES = metric("RemoteStreamWindowSize", Integer.class, MetricLevel.TRACE); private Http2Metric() { } private static <T> SdkMetric<T> metric(String name, Class<T> clzz, MetricLevel level) { return SdkMetric.create(name, clzz, level, MetricCategory.CORE, MetricCategory.HTTP_CLIENT); } }
3,064
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/DefaultSdkHttpFullRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.internal.http.LowCopyListMap; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * Internal implementation of {@link SdkHttpFullRequest}, buildable via {@link SdkHttpFullRequest#builder()}. Provided to HTTP * implementation to execute a request. */ @SdkInternalApi @Immutable final class DefaultSdkHttpFullRequest implements SdkHttpFullRequest { private final String protocol; private final String host; private final Integer port; private final String path; private final LowCopyListMap.ForBuildable queryParameters; private final LowCopyListMap.ForBuildable headers; private final SdkHttpMethod httpMethod; private final ContentStreamProvider contentStreamProvider; private DefaultSdkHttpFullRequest(Builder builder) { this.protocol = standardizeProtocol(builder.protocol); this.host = Validate.paramNotNull(builder.host, "host"); this.port = standardizePort(builder.port); this.path = standardizePath(builder.path); this.httpMethod = Validate.paramNotNull(builder.httpMethod, "method"); this.contentStreamProvider = builder.contentStreamProvider; this.queryParameters = builder.queryParameters.forBuildable(); this.headers = builder.headers.forBuildable(); } private String standardizeProtocol(String protocol) { Validate.paramNotNull(protocol, "protocol"); String standardizedProtocol = StringUtils.lowerCase(protocol); Validate.isTrue(standardizedProtocol.equals("http") || standardizedProtocol.equals("https"), "Protocol must be 'http' or 'https', but was %s", protocol); return standardizedProtocol; } private String standardizePath(String path) { if (StringUtils.isEmpty(path)) { return ""; } StringBuilder standardizedPath = new StringBuilder(); // Path must always start with '/' if (!path.startsWith("/")) { standardizedPath.append('/'); } standardizedPath.append(path); return standardizedPath.toString(); } private Integer standardizePort(Integer port) { Validate.isTrue(port == null || port >= -1, "Port must be positive (or null/-1 to indicate no port), but was '%s'", port); if (port != null && port == -1) { return null; } return port; } @Override public String protocol() { return protocol; } @Override public String host() { return host; } @Override public int port() { return Optional.ofNullable(port).orElseGet(() -> SdkHttpUtils.standardPort(protocol())); } @Override public Map<String, List<String>> headers() { return headers.forExternalRead(); } @Override public List<String> matchingHeaders(String header) { return unmodifiableList(headers.forInternalRead().getOrDefault(header, emptyList())); } @Override public Optional<String> firstMatchingHeader(String headerName) { List<String> headers = this.headers.forInternalRead().get(headerName); if (headers == null || headers.isEmpty()) { return Optional.empty(); } String header = headers.get(0); if (StringUtils.isEmpty(header)) { return Optional.empty(); } return Optional.of(header); } @Override public Optional<String> firstMatchingHeader(Collection<String> headersToFind) { for (String headerName : headersToFind) { Optional<String> header = firstMatchingHeader(headerName); if (header.isPresent()) { return header; } } return Optional.empty(); } @Override public void forEachHeader(BiConsumer<? super String, ? super List<String>> consumer) { headers.forInternalRead().forEach((k, v) -> consumer.accept(k, Collections.unmodifiableList(v))); } @Override public void forEachRawQueryParameter(BiConsumer<? super String, ? super List<String>> consumer) { queryParameters.forInternalRead().forEach((k, v) -> consumer.accept(k, Collections.unmodifiableList(v))); } @Override public int numHeaders() { return headers.forInternalRead().size(); } @Override public int numRawQueryParameters() { return queryParameters.forInternalRead().size(); } @Override public Optional<String> encodedQueryParameters() { return SdkHttpUtils.encodeAndFlattenQueryParameters(queryParameters.forInternalRead()); } @Override public Optional<String> encodedQueryParametersAsFormData() { return SdkHttpUtils.encodeAndFlattenFormData(queryParameters.forInternalRead()); } @Override public String encodedPath() { return path; } @Override public Map<String, List<String>> rawQueryParameters() { return queryParameters.forExternalRead(); } @Override public Optional<String> firstMatchingRawQueryParameter(String key) { List<String> values = queryParameters.forInternalRead().get(key); return values == null ? Optional.empty() : values.stream().findFirst(); } @Override public Optional<String> firstMatchingRawQueryParameter(Collection<String> keys) { for (String key : keys) { Optional<String> result = firstMatchingRawQueryParameter(key); if (result.isPresent()) { return result; } } return Optional.empty(); } @Override public List<String> firstMatchingRawQueryParameters(String key) { List<String> values = queryParameters.forInternalRead().get(key); return values == null ? emptyList() : unmodifiableList(values); } @Override public SdkHttpMethod method() { return httpMethod; } @Override public Optional<ContentStreamProvider> contentStreamProvider() { return Optional.ofNullable(contentStreamProvider); } @Override public SdkHttpFullRequest.Builder toBuilder() { return new Builder(this); } @Override public String toString() { return ToString.builder("DefaultSdkHttpFullRequest") .add("httpMethod", httpMethod) .add("protocol", protocol) .add("host", host) .add("port", port) .add("encodedPath", path) .add("headers", headers.forInternalRead().keySet()) .add("queryParameters", queryParameters.forInternalRead().keySet()) .build(); } /** * Builder for a {@link DefaultSdkHttpFullRequest}. */ static final class Builder implements SdkHttpFullRequest.Builder { private String protocol; private String host; private Integer port; private String path; private LowCopyListMap.ForBuilder queryParameters; private LowCopyListMap.ForBuilder headers; private SdkHttpMethod httpMethod; private ContentStreamProvider contentStreamProvider; Builder() { queryParameters = LowCopyListMap.emptyQueryParameters(); headers = LowCopyListMap.emptyHeaders(); } Builder(DefaultSdkHttpFullRequest request) { queryParameters = request.queryParameters.forBuilder(); headers = request.headers.forBuilder(); protocol = request.protocol; host = request.host; port = request.port; path = request.path; httpMethod = request.httpMethod; contentStreamProvider = request.contentStreamProvider; } @Override public String protocol() { return protocol; } @Override public SdkHttpFullRequest.Builder protocol(String protocol) { this.protocol = protocol; return this; } @Override public String host() { return host; } @Override public SdkHttpFullRequest.Builder host(String host) { this.host = host; return this; } @Override public Integer port() { return port; } @Override public SdkHttpFullRequest.Builder port(Integer port) { this.port = port; return this; } @Override public DefaultSdkHttpFullRequest.Builder encodedPath(String path) { this.path = path; return this; } @Override public String encodedPath() { return path; } @Override public DefaultSdkHttpFullRequest.Builder putRawQueryParameter(String paramName, List<String> paramValues) { this.queryParameters.forInternalWrite().put(paramName, new ArrayList<>(paramValues)); return this; } @Override public SdkHttpFullRequest.Builder appendRawQueryParameter(String paramName, String paramValue) { this.queryParameters.forInternalWrite().computeIfAbsent(paramName, k -> new ArrayList<>()).add(paramValue); return this; } @Override public DefaultSdkHttpFullRequest.Builder rawQueryParameters(Map<String, List<String>> queryParameters) { this.queryParameters.setFromExternal(queryParameters); return this; } @Override public Builder removeQueryParameter(String paramName) { this.queryParameters.forInternalWrite().remove(paramName); return this; } @Override public Builder clearQueryParameters() { this.queryParameters.forInternalWrite().clear(); return this; } @Override public Map<String, List<String>> rawQueryParameters() { return CollectionUtils.unmodifiableMapOfLists(queryParameters.forInternalRead()); } @Override public DefaultSdkHttpFullRequest.Builder method(SdkHttpMethod httpMethod) { this.httpMethod = httpMethod; return this; } @Override public SdkHttpMethod method() { return httpMethod; } @Override public DefaultSdkHttpFullRequest.Builder putHeader(String headerName, List<String> headerValues) { this.headers.forInternalWrite().put(headerName, new ArrayList<>(headerValues)); return this; } @Override public SdkHttpFullRequest.Builder appendHeader(String headerName, String headerValue) { this.headers.forInternalWrite().computeIfAbsent(headerName, k -> new ArrayList<>()).add(headerValue); return this; } @Override public DefaultSdkHttpFullRequest.Builder headers(Map<String, List<String>> headers) { this.headers.setFromExternal(headers); return this; } @Override public SdkHttpFullRequest.Builder removeHeader(String headerName) { this.headers.forInternalWrite().remove(headerName); return this; } @Override public SdkHttpFullRequest.Builder clearHeaders() { this.headers.clear(); return this; } @Override public Map<String, List<String>> headers() { return CollectionUtils.unmodifiableMapOfLists(this.headers.forInternalRead()); } @Override public List<String> matchingHeaders(String header) { return unmodifiableList(headers.forInternalRead().getOrDefault(header, emptyList())); } @Override public Optional<String> firstMatchingHeader(String headerName) { List<String> headers = this.headers.forInternalRead().get(headerName); if (headers == null || headers.isEmpty()) { return Optional.empty(); } String header = headers.get(0); if (StringUtils.isEmpty(header)) { return Optional.empty(); } return Optional.of(header); } @Override public Optional<String> firstMatchingHeader(Collection<String> headersToFind) { for (String headerName : headersToFind) { Optional<String> header = firstMatchingHeader(headerName); if (header.isPresent()) { return header; } } return Optional.empty(); } @Override public void forEachHeader(BiConsumer<? super String, ? super List<String>> consumer) { headers.forInternalRead().forEach((k, v) -> consumer.accept(k, unmodifiableList(v))); } @Override public void forEachRawQueryParameter(BiConsumer<? super String, ? super List<String>> consumer) { queryParameters.forInternalRead().forEach((k, v) -> consumer.accept(k, unmodifiableList(v))); } @Override public int numHeaders() { return headers.forInternalRead().size(); } @Override public int numRawQueryParameters() { return queryParameters.forInternalRead().size(); } @Override public Optional<String> encodedQueryParameters() { return SdkHttpUtils.encodeAndFlattenQueryParameters(queryParameters.forInternalRead()); } @Override public DefaultSdkHttpFullRequest.Builder contentStreamProvider(ContentStreamProvider contentStreamProvider) { this.contentStreamProvider = contentStreamProvider; return this; } @Override public ContentStreamProvider contentStreamProvider() { return contentStreamProvider; } @Override public SdkHttpFullRequest.Builder copy() { return build().toBuilder(); } @Override public SdkHttpFullRequest.Builder applyMutation(Consumer<SdkHttpRequest.Builder> mutator) { mutator.accept(this); return this; } @Override public DefaultSdkHttpFullRequest build() { return new DefaultSdkHttpFullRequest(this); } } }
3,065
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpHeaders.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BiConsumer; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * An immutable set of HTTP headers. {@link SdkHttpRequest} should be used for requests, and {@link SdkHttpResponse} should be * used for responses. */ @SdkPublicApi @Immutable public interface SdkHttpHeaders { /** * Returns a map of all HTTP headers in this message, sorted in case-insensitive order by their header name. * * <p>This will never be null. If there are no headers an empty map is returned.</p> * * @return An unmodifiable map of all headers in this message. */ Map<String, List<String>> headers(); /** * Perform a case-insensitive search for a particular header in this request, returning the first matching header, if one is * found. * * <p>This is useful for headers like 'Content-Type' or 'Content-Length' of which there is expected to be only one value * present.</p> * * <p>This is equivalent to invoking {@link SdkHttpUtils#firstMatchingHeader(Map, String)}</p>. * * @param header The header to search for (case insensitively). * @return The first header that matched the requested one, or empty if one was not found. */ default Optional<String> firstMatchingHeader(String header) { return SdkHttpUtils.firstMatchingHeader(headers(), header); } default Optional<String> firstMatchingHeader(Collection<String> headersToFind) { return SdkHttpUtils.firstMatchingHeaderFromCollection(headers(), headersToFind); } default List<String> matchingHeaders(String header) { return SdkHttpUtils.allMatchingHeaders(headers(), header).collect(Collectors.toList()); } default void forEachHeader(BiConsumer<? super String, ? super List<String>> consumer) { headers().forEach(consumer); } default int numHeaders() { return headers().size(); } }
3,066
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/Protocol.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; public enum Protocol { HTTP1_1, HTTP2 }
3,067
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpFullRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static java.util.Collections.singletonList; import java.net.URI; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * An immutable HTTP request with a possible HTTP body. * * <p>All implementations of this interface MUST be immutable. Instead of implementing this interface, consider using * {@link #builder()} to create an instance.</p> */ @SdkPublicApi @Immutable public interface SdkHttpFullRequest extends SdkHttpRequest { /** * @return Builder instance to construct a {@link DefaultSdkHttpFullRequest}. */ static SdkHttpFullRequest.Builder builder() { return new DefaultSdkHttpFullRequest.Builder(); } @Override SdkHttpFullRequest.Builder toBuilder(); /** * @return The optional {@link ContentStreamProvider} for this request. */ Optional<ContentStreamProvider> contentStreamProvider(); /** * A mutable builder for {@link SdkHttpFullRequest}. An instance of this can be created using * {@link SdkHttpFullRequest#builder()}. */ interface Builder extends SdkHttpRequest.Builder { /** * Convenience method to set the {@link #protocol()}, {@link #host()}, {@link #port()}, * {@link #encodedPath()} and extracts query parameters from a {@link URI} object. * * @param uri URI containing protocol, host, port and path. * @return This builder for method chaining. */ @Override default Builder uri(URI uri) { Builder builder = this.protocol(uri.getScheme()) .host(uri.getHost()) .port(uri.getPort()) .encodedPath(SdkHttpUtils.appendUri(uri.getRawPath(), encodedPath())); if (uri.getRawQuery() != null) { builder.clearQueryParameters(); SdkHttpUtils.uriParams(uri) .forEach(this::putRawQueryParameter); } return builder; } /** * The protocol, exactly as it was configured with {@link #protocol(String)}. */ @Override String protocol(); /** * Configure a {@link SdkHttpRequest#protocol()} to be used in the created HTTP request. This is not validated until the * http request is created. */ @Override Builder protocol(String protocol); /** * The host, exactly as it was configured with {@link #host(String)}. */ @Override String host(); /** * Configure a {@link SdkHttpRequest#host()} to be used in the created HTTP request. This is not validated until the * http request is created. */ @Override Builder host(String host); /** * The port, exactly as it was configured with {@link #port(Integer)}. */ @Override Integer port(); /** * Configure a {@link SdkHttpRequest#port()} to be used in the created HTTP request. This is not validated until the * http request is created. In order to simplify mapping from a {@link URI}, "-1" will be treated as "null" when the http * request is created. */ @Override Builder port(Integer port); /** * The path, exactly as it was configured with {@link #encodedPath(String)}. */ @Override String encodedPath(); /** * Configure an {@link SdkHttpRequest#encodedPath()} to be used in the created HTTP request. This is not validated * until the http request is created. This path MUST be URL encoded. * * <p>Justification of requirements: The path must be encoded when it is configured, because there is no way for the HTTP * implementation to distinguish a "/" that is part of a resource name that should be encoded as "%2F" from a "/" that is * part of the actual path.</p> */ @Override Builder encodedPath(String path); /** * The query parameters, exactly as they were configured with {@link #rawQueryParameters(Map)}, * {@link #putRawQueryParameter(String, String)} and {@link #putRawQueryParameter(String, List)}. */ @Override Map<String, List<String>> rawQueryParameters(); /** * Add a single un-encoded query parameter to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this parameter name in the builder.</p> * * @param paramName The name of the query parameter to add * @param paramValue The un-encoded value for the query parameter. */ @Override default Builder putRawQueryParameter(String paramName, String paramValue) { return putRawQueryParameter(paramName, singletonList(paramValue)); } /** * Add a single un-encoded query parameter to be included in the created HTTP request. * * <p>This will <b>ADD</b> the value to any existing values already configured with this parameter name in * the builder.</p> * * @param paramName The name of the query parameter to add * @param paramValue The un-encoded value for the query parameter. */ @Override Builder appendRawQueryParameter(String paramName, String paramValue); /** * Add a single un-encoded query parameter with multiple values to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this parameter name in the builder.</p> * * @param paramName The name of the query parameter to add * @param paramValues The un-encoded values for the query parameter. */ @Override Builder putRawQueryParameter(String paramName, List<String> paramValues); /** * Configure an {@link SdkHttpRequest#rawQueryParameters()} to be used in the created HTTP request. This is not validated * until the http request is created. This overrides any values currently configured in the builder. The query parameters * MUST NOT be URL encoded. * * <p>Justification of requirements: The query parameters must not be encoded when they are configured because some HTTP * implementations perform this encoding automatically.</p> */ @Override Builder rawQueryParameters(Map<String, List<String>> queryParameters); /** * Remove all values for the requested query parameter from this builder. */ @Override Builder removeQueryParameter(String paramName); /** * Removes all query parameters from this builder. */ @Override Builder clearQueryParameters(); /** * The path, exactly as it was configured with {@link #method(SdkHttpMethod)}. */ @Override SdkHttpMethod method(); /** * Configure an {@link SdkHttpRequest#method()} to be used in the created HTTP request. This is not validated * until the http request is created. */ @Override Builder method(SdkHttpMethod httpMethod); /** * The query parameters, exactly as they were configured with {@link #headers(Map)}, * {@link #putHeader(String, String)} and {@link #putHeader(String, List)}. */ @Override Map<String, List<String>> headers(); /** * Add a single header to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add (eg. "Host") * @param headerValue The value for the header */ @Override default Builder putHeader(String headerName, String headerValue) { return putHeader(headerName, singletonList(headerValue)); } /** * Add a single header with multiple values to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add * @param headerValues The values for the header */ @Override Builder putHeader(String headerName, List<String> headerValues); /** * Add a single header to be included in the created HTTP request. * * <p>This will <b>ADD</b> the value to any existing values already configured with this header name in * the builder.</p> * * @param headerName The name of the header to add * @param headerValue The value for the header */ @Override Builder appendHeader(String headerName, String headerValue); /** * Configure an {@link SdkHttpRequest#headers()} to be used in the created HTTP request. This is not validated * until the http request is created. This overrides any values currently configured in the builder. */ @Override Builder headers(Map<String, List<String>> headers); /** * Remove all values for the requested header from this builder. */ @Override Builder removeHeader(String headerName); /** * Removes all headers from this builder. */ @Override Builder clearHeaders(); /** * Set the {@link ContentStreamProvider} for this request. * * @param contentStreamProvider The ContentStreamProvider. * @return This object for method chaining. */ Builder contentStreamProvider(ContentStreamProvider contentStreamProvider); /** * @return The {@link ContentStreamProvider} for this request. */ ContentStreamProvider contentStreamProvider(); @Override SdkHttpFullRequest.Builder copy(); @Override SdkHttpFullRequest.Builder applyMutation(Consumer<SdkHttpRequest.Builder> mutator); @Override SdkHttpFullRequest build(); } }
3,068
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Interface to take a representation of an HTTP request, make an HTTP call, and return a representation of an HTTP response. * * <p>Implementations MUST be thread safe.</p> */ @Immutable @ThreadSafe @SdkPublicApi public interface SdkHttpClient extends SdkAutoCloseable { /** * Create a {@link ExecutableHttpRequest} that can be used to execute the HTTP request. * * @param request Representation of an HTTP request. * @return Task that can execute an HTTP request and can be aborted. */ ExecutableHttpRequest prepareRequest(HttpExecuteRequest request); /** * Each HTTP client implementation should return a well-formed client name * that allows requests to be identifiable back to the client that made the request. * The client name should include the backing implementation as well as the Sync or Async * to identify the transmission type of the request. Client names should only include * alphanumeric characters. Examples of well formed client names include, ApacheSync, for * requests using Apache's synchronous http client or NettyNioAsync for Netty's asynchronous * http client. * * @return String containing the name of the client */ default String clientName() { return "UNKNOWN"; } /** * Interface for creating an {@link SdkHttpClient} with service specific defaults applied. */ @FunctionalInterface interface Builder<T extends SdkHttpClient.Builder<T>> extends SdkBuilder<T, SdkHttpClient> { /** * Create a {@link SdkHttpClient} with global defaults applied. This is useful for reusing an HTTP client across multiple * services. */ @Override default SdkHttpClient build() { return buildWithDefaults(AttributeMap.empty()); } /** * Create an {@link SdkHttpClient} with service specific defaults and defaults from {@code DefaultsMode} applied. * Applying service defaults is optional and some options may not be supported by a particular implementation. * * @param serviceDefaults Service specific defaults. Keys will be one of the constants defined in * {@link SdkHttpConfigurationOption}. * @return Created client */ SdkHttpClient buildWithDefaults(AttributeMap serviceDefaults); } }
3,069
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/AbortableInputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static software.amazon.awssdk.utils.Validate.paramNotNull; import java.io.ByteArrayInputStream; import java.io.FilterInputStream; import java.io.InputStream; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; /** * Input stream that can be aborted. Abort typically means to destroy underlying HTTP connection * without reading more data. This may be desirable when the cost of reading the rest of the data * exceeds that of establishing a new connection. */ @SdkProtectedApi public final class AbortableInputStream extends FilterInputStream implements Abortable { private final Abortable abortable; private AbortableInputStream(InputStream delegate, Abortable abortable) { super(paramNotNull(delegate, "delegate")); this.abortable = paramNotNull(abortable, "abortable"); } /** * Creates an instance of {@link AbortableInputStream}. * * @param delegate the delegated input stream * @param abortable the abortable * @return a new instance of AbortableInputStream */ public static AbortableInputStream create(InputStream delegate, Abortable abortable) { return new AbortableInputStream(delegate, abortable); } /** * Creates an instance of {@link AbortableInputStream} that ignores abort. * * @param delegate the delegated input stream * @return a new instance of AbortableInputStream */ public static AbortableInputStream create(InputStream delegate) { if (delegate instanceof Abortable) { return new AbortableInputStream(delegate, (Abortable) delegate); } return new AbortableInputStream(delegate, () -> { }); } public static AbortableInputStream createEmpty() { return create(new ByteArrayInputStream(new byte[0])); } @Override public void abort() { abortable.abort(); } /** * Access the underlying delegate stream, for testing purposes. */ @SdkTestInternalApi public InputStream delegate() { return in; } }
3,070
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpMethod.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.util.Locale; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Enum for available HTTP methods. */ @SdkProtectedApi public enum SdkHttpMethod { GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS,; /** * @param value Raw string representing value of enum * @return HttpMethodName enum or null if value is not present. * @throws IllegalArgumentException If value does not represent a known enum value. */ public static SdkHttpMethod fromValue(String value) { if (value == null || value.isEmpty()) { return null; } String upperCaseValue = value.toUpperCase(Locale.ENGLISH); return Stream.of(values()) .filter(h -> h.name().equals(upperCaseValue)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Unsupported HTTP method name " + value)); } }
3,071
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/ContentStreamProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.io.InputStream; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Provides the content stream of a request. * <p> * Each call to to the {@link #newStream()} method must result in a stream whose position is at the beginning of the content. * Implementations may return a new stream or the same stream for each call. If returning a new stream, the implementation * must ensure to {@code close()} and free any resources acquired by the previous stream. The last stream returned by {@link * #newStream()}} will be closed by the SDK. * */ @SdkPublicApi @FunctionalInterface public interface ContentStreamProvider { /** * @return The content stream. */ InputStream newStream(); }
3,072
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/HttpStatusCode.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Constants for common HTTP status codes. */ @SdkProtectedApi public final class HttpStatusCode { // --- 1xx Informational --- public static final int CONTINUE = 100; // --- 2xx Success --- public static final int OK = 200; public static final int CREATED = 201; public static final int ACCEPTED = 202; public static final int NON_AUTHORITATIVE_INFORMATION = 203; public static final int NO_CONTENT = 204; public static final int RESET_CONTENT = 205; public static final int PARTIAL_CONTENT = 206; // --- 3xx Redirection --- public static final int MOVED_PERMANENTLY = 301; public static final int MOVED_TEMPORARILY = 302; public static final int TEMPORARY_REDIRECT = 307; // --- 4xx Client Error --- public static final int BAD_REQUEST = 400; public static final int UNAUTHORIZED = 401; public static final int FORBIDDEN = 403; public static final int NOT_FOUND = 404; public static final int METHOD_NOT_ALLOWED = 405; public static final int NOT_ACCEPTABLE = 406; public static final int REQUEST_TIMEOUT = 408; public static final int REQUEST_TOO_LONG = 413; public static final int THROTTLING = 429; // --- 5xx Server Error --- public static final int INTERNAL_SERVER_ERROR = 500; public static final int BAD_GATEWAY = 502; public static final int SERVICE_UNAVAILABLE = 503; public static final int GATEWAY_TIMEOUT = 504; private HttpStatusCode() { } }
3,073
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpService.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * Service Provider interface for HTTP implementations. The core uses {@link java.util.ServiceLoader} to find appropriate * HTTP implementations on the classpath. HTTP implementations that wish to be discovered by the default HTTP provider chain * should implement this interface and declare that implementation as a service in the * META-INF/service/software.amazon.awssdk.http.SdkHttpService resource. See * <a href="https://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html">Service Loader</a> for more * information. * * <p> * This interface is simply a factory for {@link SdkHttpClient.Builder}. Implementations must be thread safe. * </p> */ @ThreadSafe @SdkPublicApi public interface SdkHttpService { /** * @return An {@link SdkHttpClient.Builder} capable of creating {@link SdkHttpClient} instances. This factory should be thread * safe. */ SdkHttpClient.Builder createHttpClientBuilder(); }
3,074
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkRequestContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Container for extra dependencies needed during execution of a request. */ @SdkProtectedApi public class SdkRequestContext { private final boolean isFullDuplex; private SdkRequestContext(Builder builder) { this.isFullDuplex = builder.isFullDuplex; } /** * @return Builder instance to construct a {@link SdkRequestContext}. */ @SdkInternalApi public static Builder builder() { return new Builder(); } /** * Option to indicate if the request is for a full duplex operation ie., request and response are sent/received at the same * time. * This can be used to set http configuration like ReadTimeouts as soon as request has begin sending data instead of * waiting for the entire request to be sent. * * @return True if the operation this request belongs to is full duplex. Otherwise false. */ public boolean fullDuplex() { return isFullDuplex; } /** * Builder for a {@link SdkRequestContext}. */ @SdkInternalApi public static final class Builder { private boolean isFullDuplex; private Builder() { } public boolean fullDuplex() { return isFullDuplex; } public Builder fullDuplex(boolean fullDuplex) { isFullDuplex = fullDuplex; return this; } /** * @return An immutable {@link SdkRequestContext} object. */ public SdkRequestContext build() { return new SdkRequestContext(this); } } }
3,075
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/HttpExecuteRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.util.Optional; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.metrics.MetricCollector; /** * Request object containing the parameters necessary to make a synchronous HTTP request. * * @see SdkHttpClient */ @SdkPublicApi public final class HttpExecuteRequest { private final SdkHttpRequest request; private final Optional<ContentStreamProvider> contentStreamProvider; private final MetricCollector metricCollector; private HttpExecuteRequest(BuilderImpl builder) { this.request = builder.request; this.contentStreamProvider = builder.contentStreamProvider; this.metricCollector = builder.metricCollector; } /** * @return The HTTP request. */ public SdkHttpRequest httpRequest() { return request; } /** * @return The {@link ContentStreamProvider}. */ public Optional<ContentStreamProvider> contentStreamProvider() { return contentStreamProvider; } /** * @return The {@link MetricCollector}. */ public Optional<MetricCollector> metricCollector() { return Optional.ofNullable(metricCollector); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * Set the HTTP request to be executed by the client. * * @param request The request. * @return This builder for method chaining. */ Builder request(SdkHttpRequest request); /** * Set the {@link ContentStreamProvider} to be executed by the client. * @param contentStreamProvider The content stream provider * @return This builder for method chaining */ Builder contentStreamProvider(ContentStreamProvider contentStreamProvider); /** * Set the {@link MetricCollector} to be used by the HTTP client to * report metrics collected for this request. * * @param metricCollector The metric collector. * @return This builder for method chaining. */ Builder metricCollector(MetricCollector metricCollector); HttpExecuteRequest build(); } private static class BuilderImpl implements Builder { private SdkHttpRequest request; private Optional<ContentStreamProvider> contentStreamProvider = Optional.empty(); private MetricCollector metricCollector; @Override public Builder request(SdkHttpRequest request) { this.request = request; return this; } @Override public Builder contentStreamProvider(ContentStreamProvider contentStreamProvider) { this.contentStreamProvider = Optional.ofNullable(contentStreamProvider); return this; } @Override public Builder metricCollector(MetricCollector metricCollector) { this.metricCollector = metricCollector; return this; } @Override public HttpExecuteRequest build() { return new HttpExecuteRequest(this); } } }
3,076
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkCancellationException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Exception thrown when the response subscription is cancelled. */ @SdkPublicApi public final class SdkCancellationException extends RuntimeException { public SdkCancellationException(String message) { super(message); } }
3,077
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpFullResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static java.util.Collections.singletonList; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * An immutable HTTP response with a possible HTTP body. * * <p>All implementations of this interface MUST be immutable. Instead of implementing this interface, consider using * {@link #builder()} to create an instance.</p> */ @SdkProtectedApi @Immutable public interface SdkHttpFullResponse extends SdkHttpResponse { /** * @return Builder instance to construct a {@link DefaultSdkHttpFullResponse}. */ static Builder builder() { return new DefaultSdkHttpFullResponse.Builder(); } @Override Builder toBuilder(); /** * Returns the optional stream containing the payload data returned by the service. Note: an {@link AbortableInputStream} * is returned instead of an {@link InputStream}. This allows the stream to be aborted before all content is read, which * usually means destroying the underlying HTTP connection. This may be implemented differently in other HTTP implementations. * * <p>When the response does not include payload data, this will return {@link Optional#empty()}.</p> * * @return The optional stream containing the payload data included in this response, or empty if there is no payload. */ Optional<AbortableInputStream> content(); /** * Builder for a {@link DefaultSdkHttpFullResponse}. */ interface Builder extends SdkHttpResponse.Builder { /** * The status text, exactly as it was configured with {@link #statusText(String)}. */ @Override String statusText(); /** * Configure an {@link SdkHttpResponse#statusText()} to be used in the created HTTP response. This is not validated * until the http response is created. */ @Override Builder statusText(String statusText); /** * The status text, exactly as it was configured with {@link #statusCode(int)}. */ @Override int statusCode(); /** * Configure an {@link SdkHttpResponse#statusCode()} to be used in the created HTTP response. This is not validated * until the http response is created. */ @Override Builder statusCode(int statusCode); /** * The query parameters, exactly as they were configured with {@link #headers(Map)}, * {@link #putHeader(String, String)} and {@link #putHeader(String, List)}. */ @Override Map<String, List<String>> headers(); /** * Add a single header to be included in the created HTTP response. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add (eg. "Host") * @param headerValue The value for the header */ @Override default Builder putHeader(String headerName, String headerValue) { return putHeader(headerName, singletonList(headerValue)); } /** * Add a single header with multiple values to be included in the created HTTP response. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add * @param headerValues The values for the header */ @Override Builder putHeader(String headerName, List<String> headerValues); /** * Add a single header to be included in the created HTTP request. * * <p>This will <b>ADD</b> the value to any existing values already configured with this header name in * the builder.</p> * * @param headerName The name of the header to add * @param headerValue The value for the header */ @Override Builder appendHeader(String headerName, String headerValue); /** * Configure an {@link SdkHttpResponse#headers()} to be used in the created HTTP response. This is not validated * until the http response is created. This overrides any values currently configured in the builder. */ @Override Builder headers(Map<String, List<String>> headers); /** * Remove all values for the requested header from this builder. */ @Override Builder removeHeader(String headerName); /** * Removes all headers from this builder. */ @Override Builder clearHeaders(); /** * The content, exactly as it was configured with {@link #content(AbortableInputStream)}. */ AbortableInputStream content(); /** * Configure an {@link SdkHttpFullResponse#content()} to be used in the HTTP response. This is not validated until * the http response is created. * * <p>Implementers should implement the abort method on the input stream to drop all remaining content with the service. * This is usually done by closing the service connection.</p> */ Builder content(AbortableInputStream content); @Override SdkHttpFullResponse build(); } }
3,078
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/DefaultSdkHttpFullResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableList; import static software.amazon.awssdk.utils.CollectionUtils.unmodifiableMapOfLists; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.BiConsumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.internal.http.LowCopyListMap; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; /** * Internal implementation of {@link SdkHttpFullResponse}, buildable via {@link SdkHttpFullResponse#builder()}. Returned by HTTP * implementation to represent a service response. */ @SdkInternalApi @Immutable class DefaultSdkHttpFullResponse implements SdkHttpFullResponse { private static final long serialVersionUID = 1; private final String statusText; private final int statusCode; private final transient AbortableInputStream content; private transient LowCopyListMap.ForBuildable headers; private DefaultSdkHttpFullResponse(Builder builder) { this.statusCode = Validate.isNotNegative(builder.statusCode, "Status code must not be negative."); this.statusText = builder.statusText; this.content = builder.content; this.headers = builder.headers.forBuildable(); } @Override public Map<String, List<String>> headers() { return headers.forExternalRead(); } @Override public List<String> matchingHeaders(String header) { return unmodifiableList(headers.forInternalRead().getOrDefault(header, emptyList())); } @Override public Optional<String> firstMatchingHeader(String headerName) { List<String> headers = this.headers.forInternalRead().get(headerName); if (headers == null || headers.isEmpty()) { return Optional.empty(); } String header = headers.get(0); if (StringUtils.isEmpty(header)) { return Optional.empty(); } return Optional.of(header); } @Override public Optional<String> firstMatchingHeader(Collection<String> headersToFind) { for (String headerName : headersToFind) { Optional<String> header = firstMatchingHeader(headerName); if (header.isPresent()) { return header; } } return Optional.empty(); } @Override public void forEachHeader(BiConsumer<? super String, ? super List<String>> consumer) { this.headers.forInternalRead().forEach((k, v) -> consumer.accept(k, unmodifiableList(v))); } @Override public int numHeaders() { return this.headers.forInternalRead().size(); } @Override public Optional<AbortableInputStream> content() { return Optional.ofNullable(content); } @Override public Optional<String> statusText() { return Optional.ofNullable(statusText); } @Override public int statusCode() { return statusCode; } @Override public SdkHttpFullResponse.Builder toBuilder() { return new Builder(this); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); headers = LowCopyListMap.emptyHeaders().forBuildable(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultSdkHttpFullResponse that = (DefaultSdkHttpFullResponse) o; return (statusCode == that.statusCode) && Objects.equals(statusText, that.statusText) && Objects.equals(headers, that.headers); } @Override public int hashCode() { int result = statusText != null ? statusText.hashCode() : 0; result = 31 * result + statusCode; result = 31 * result + Objects.hashCode(headers); return result; } /** * Builder for a {@link DefaultSdkHttpFullResponse}. */ static final class Builder implements SdkHttpFullResponse.Builder { private String statusText; private int statusCode; private AbortableInputStream content; private LowCopyListMap.ForBuilder headers; Builder() { headers = LowCopyListMap.emptyHeaders(); } private Builder(DefaultSdkHttpFullResponse defaultSdkHttpFullResponse) { statusText = defaultSdkHttpFullResponse.statusText; statusCode = defaultSdkHttpFullResponse.statusCode; content = defaultSdkHttpFullResponse.content; headers = defaultSdkHttpFullResponse.headers.forBuilder(); } @Override public String statusText() { return statusText; } @Override public Builder statusText(String statusText) { this.statusText = statusText; return this; } @Override public int statusCode() { return statusCode; } @Override public Builder statusCode(int statusCode) { this.statusCode = statusCode; return this; } @Override public AbortableInputStream content() { return content; } @Override public Builder content(AbortableInputStream content) { this.content = content; return this; } @Override public Builder putHeader(String headerName, List<String> headerValues) { Validate.paramNotNull(headerName, "headerName"); Validate.paramNotNull(headerValues, "headerValues"); this.headers.forInternalWrite().put(headerName, new ArrayList<>(headerValues)); return this; } @Override public SdkHttpFullResponse.Builder appendHeader(String headerName, String headerValue) { Validate.paramNotNull(headerName, "headerName"); Validate.paramNotNull(headerValue, "headerValue"); this.headers.forInternalWrite().computeIfAbsent(headerName, k -> new ArrayList<>()).add(headerValue); return this; } @Override public Builder headers(Map<String, List<String>> headers) { Validate.paramNotNull(headers, "headers"); this.headers.setFromExternal(headers); return this; } @Override public Builder removeHeader(String headerName) { this.headers.forInternalWrite().remove(headerName); return this; } @Override public Builder clearHeaders() { this.headers.clear(); return this; } @Override public Map<String, List<String>> headers() { return unmodifiableMapOfLists(this.headers.forInternalRead()); } @Override public List<String> matchingHeaders(String header) { return unmodifiableList(headers.forInternalRead().getOrDefault(header, emptyList())); } @Override public Optional<String> firstMatchingHeader(String headerName) { List<String> headers = this.headers.forInternalRead().get(headerName); if (headers == null || headers.isEmpty()) { return Optional.empty(); } String header = headers.get(0); if (StringUtils.isEmpty(header)) { return Optional.empty(); } return Optional.of(header); } @Override public Optional<String> firstMatchingHeader(Collection<String> headersToFind) { for (String headerName : headersToFind) { Optional<String> header = firstMatchingHeader(headerName); if (header.isPresent()) { return header; } } return Optional.empty(); } @Override public void forEachHeader(BiConsumer<? super String, ? super List<String>> consumer) { headers.forInternalRead().forEach((k, v) -> consumer.accept(k, unmodifiableList(v))); } @Override public int numHeaders() { return headers.forInternalRead().size(); } /** * @return An immutable {@link DefaultSdkHttpFullResponse} object. */ @Override public SdkHttpFullResponse build() { return new DefaultSdkHttpFullResponse(this); } } }
3,079
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/TlsKeyManagersProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import javax.net.ssl.KeyManager; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.internal.http.NoneTlsKeyManagersProvider; /** * Provider for the {@link KeyManager key managers} to be used by the SDK when * creating the SSL context. Key managers are used when the client is required * to authenticate with the remote TLS peer, such as an HTTP proxy. */ @SdkPublicApi @FunctionalInterface public interface TlsKeyManagersProvider { /** * @return The {@link KeyManager}s, or {@code null}. */ KeyManager[] keyManagers(); /** * @return A provider that returns a {@code null} array of {@link KeyManager}s. */ static TlsKeyManagersProvider noneProvider() { return NoneTlsKeyManagersProvider.getInstance(); } }
3,080
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/HttpStatusFamily.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * The set of HTTP status families defined by the standard. A code can be converted to its family with {@link #of(int)}. */ @SdkProtectedApi public enum HttpStatusFamily { /** * 1xx response family. */ INFORMATIONAL, /** * 2xx response family. */ SUCCESSFUL, /** * 3xx response family. */ REDIRECTION, /** * 4xx response family. */ CLIENT_ERROR, /** * 5xx response family. */ SERVER_ERROR, /** * The family for any status code outside of the range 100-599. */ OTHER; /** * Retrieve the HTTP status family for the given HTTP status code. */ public static HttpStatusFamily of(int httpStatusCode) { switch (httpStatusCode / 100) { case 1: return INFORMATIONAL; case 2: return SUCCESSFUL; case 3: return REDIRECTION; case 4: return CLIENT_ERROR; case 5: return SERVER_ERROR; default: return OTHER; } } /** * Determine whether this HTTP status family is in the list of provided families. * * @param families The list of families to check against this family. * @return True if any of the families in the list match this one. */ public boolean isOneOf(HttpStatusFamily... families) { return families != null && Stream.of(families).anyMatch(family -> family == this); } }
3,081
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/ExecutableHttpRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.io.IOException; import java.util.concurrent.Callable; import software.amazon.awssdk.annotations.SdkPublicApi; /** * An HTTP request that can be invoked by {@link #call()}. Once invoked, the HTTP call can be cancelled via {@link #abort()}, * which should release the thread that has invoked {@link #call()} as soon as possible. */ @SdkPublicApi public interface ExecutableHttpRequest extends Callable<HttpExecuteResponse>, Abortable { @Override HttpExecuteResponse call() throws IOException; }
3,082
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/Abortable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * An Abortable task. */ @SdkProtectedApi public interface Abortable { /** * Aborts the execution of the task. Multiple calls to abort or calling abort an already aborted task * should return without error. */ void abort(); }
3,083
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpExecutionAttribute.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.utils.AttributeMap; /** * An attribute attached to a particular HTTP request execution, stored in {@link SdkHttpExecutionAttributes}. It can be * configured on an {@link AsyncExecuteRequest} via * {@link AsyncExecuteRequest.Builder#putHttpExecutionAttribute(SdkHttpExecutionAttribute, * Object)} * * @param <T> The type of data associated with this attribute. */ @SdkPublicApi public abstract class SdkHttpExecutionAttribute<T> extends AttributeMap.Key<T> { protected SdkHttpExecutionAttribute(Class<T> valueType) { super(valueType); } protected SdkHttpExecutionAttribute(UnsafeValueType unsafeValueType) { super(unsafeValueType); } }
3,084
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import java.net.URI; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BiConsumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * An immutable HTTP request without access to the request body. {@link SdkHttpFullRequest} should be used when access to a * request body stream is required. */ @SdkProtectedApi @Immutable public interface SdkHttpRequest extends SdkHttpHeaders, ToCopyableBuilder<SdkHttpRequest.Builder, SdkHttpRequest> { /** * @return Builder instance to construct a {@link DefaultSdkHttpFullRequest}. */ static Builder builder() { return new DefaultSdkHttpFullRequest.Builder(); } /** * Returns the protocol that should be used for HTTP communication. * * <p>This will always be "https" or "http" (lowercase).</p> * * @return Either "http" or "https" depending on which protocol should be used. */ String protocol(); /** * Returns the host that should be communicated with. * * <p>This will never be null.</p> * * @return The host to which the request should be sent. */ String host(); /** * The port that should be used for HTTP communication. If this was not configured when the request was created, it will be * derived from the protocol. For "http" it would be 80, and for "https" it would be 443. * * <p>Important Note: AWS signing DOES NOT include the port when the request is signed if the default port for the protocol is * being used. When sending requests via http over port 80 or via https over port 443, the URI or host header MUST NOT include * the port or a signature error will be raised from the service for signed requests. HTTP plugin implementers are encouraged * to use the {@link #getUri()} method for generating the URI to use for communicating with AWS to ensure the URI used in the * request matches the URI used during signing.</p> * * @return The port that should be used for HTTP communication. */ int port(); /** * Returns the URL-encoded path that should be used in the HTTP request. * * <p>If a path is configured, the path will always start with '/' and may or may not end with '/', depending on what the * service might expect. If a path is not configured, this will always return empty-string (ie. ""). Note that '/' is also a * valid path.</p> * * @return The path to the resource being requested. */ String encodedPath(); /** * Returns a map of all non-URL encoded parameters in this request. HTTP plugins can use * {@link SdkHttpUtils#encodeQueryParameters(Map)} to encode parameters into map-form, or * {@link SdkHttpUtils#encodeAndFlattenQueryParameters(Map)} to encode the parameters into uri-formatted string form. * * <p>This will never be null. If there are no parameters an empty map is returned.</p> * * @return An unmodifiable map of all non-encoded parameters in this request. */ Map<String, List<String>> rawQueryParameters(); default Optional<String> firstMatchingRawQueryParameter(String key) { List<String> values = rawQueryParameters().get(key); return values == null ? Optional.empty() : values.stream().findFirst(); } default Optional<String> firstMatchingRawQueryParameter(Collection<String> keys) { for (String key : keys) { Optional<String> result = firstMatchingRawQueryParameter(key); if (result.isPresent()) { return result; } } return Optional.empty(); } default List<String> firstMatchingRawQueryParameters(String key) { List<String> values = rawQueryParameters().get(key); return values == null ? emptyList() : values; } default void forEachRawQueryParameter(BiConsumer<? super String, ? super List<String>> consumer) { rawQueryParameters().forEach(consumer); } default int numRawQueryParameters() { return rawQueryParameters().size(); } default Optional<String> encodedQueryParameters() { return SdkHttpUtils.encodeAndFlattenQueryParameters(rawQueryParameters()); } default Optional<String> encodedQueryParametersAsFormData() { return SdkHttpUtils.encodeAndFlattenFormData(rawQueryParameters()); } /** * Convert this HTTP request's protocol, host, port, path and query string into a properly-encoded URI string that matches the * URI string used for AWS request signing. * * <p>The URI's port will be missing (-1) when the {@link #port()} is the default port for the {@link #protocol()}. (80 for * http and 443 for https). This is to reflect the fact that request signature does not include the port.</p> * * @return The URI for this request, formatted in the same way the AWS HTTP request signer uses the URI in the signature. */ default URI getUri() { // We can't create a URI by simply passing the query parameters into the URI constructor that takes a query string, // because URI will re-encode them. Because we want to encode them using our encoder, we have to build the URI // ourselves and pass it to the single-argument URI constructor that doesn't perform the encoding. String encodedQueryString = encodedQueryParameters().map(value -> "?" + value).orElse(""); // Do not include the port in the URI when using the default port for the protocol. String portString = SdkHttpUtils.isUsingStandardPort(protocol(), port()) ? "" : ":" + port(); return URI.create(protocol() + "://" + host() + portString + encodedPath() + encodedQueryString); } /** * Returns the HTTP method (GET, POST, etc) to use when sending this request. * * <p>This will never be null.</p> * * @return The HTTP method to use when sending this request. */ SdkHttpMethod method(); /** * A mutable builder for {@link SdkHttpFullRequest}. An instance of this can be created using * {@link SdkHttpFullRequest#builder()}. */ interface Builder extends CopyableBuilder<Builder, SdkHttpRequest>, SdkHttpHeaders { /** * Convenience method to set the {@link #protocol()}, {@link #host()}, {@link #port()}, * {@link #encodedPath()} and extracts query parameters from a {@link URI} object. * * @param uri URI containing protocol, host, port and path. * @return This builder for method chaining. */ default Builder uri(URI uri) { Builder builder = this.protocol(uri.getScheme()) .host(uri.getHost()) .port(uri.getPort()) .encodedPath(SdkHttpUtils.appendUri(uri.getRawPath(), encodedPath())); if (uri.getRawQuery() != null) { builder.clearQueryParameters(); SdkHttpUtils.uriParams(uri) .forEach(this::putRawQueryParameter); } return builder; } /** * The protocol, exactly as it was configured with {@link #protocol(String)}. */ String protocol(); /** * Configure a {@link SdkHttpRequest#protocol()} to be used in the created HTTP request. This is not validated until the * http request is created. */ Builder protocol(String protocol); /** * The host, exactly as it was configured with {@link #host(String)}. */ String host(); /** * Configure a {@link SdkHttpRequest#host()} to be used in the created HTTP request. This is not validated until the * http request is created. */ Builder host(String host); /** * The port, exactly as it was configured with {@link #port(Integer)}. */ Integer port(); /** * Configure a {@link SdkHttpRequest#port()} to be used in the created HTTP request. This is not validated until the * http request is created. In order to simplify mapping from a {@link URI}, "-1" will be treated as "null" when the http * request is created. */ Builder port(Integer port); /** * The path, exactly as it was configured with {@link #encodedPath(String)}. */ String encodedPath(); /** * Configure an {@link SdkHttpRequest#encodedPath()} to be used in the created HTTP request. This is not validated * until the http request is created. This path MUST be URL encoded. * * <p>Justification of requirements: The path must be encoded when it is configured, because there is no way for the HTTP * implementation to distinguish a "/" that is part of a resource name that should be encoded as "%2F" from a "/" that is * part of the actual path.</p> */ Builder encodedPath(String path); /** * The query parameters, exactly as they were configured with {@link #rawQueryParameters(Map)}, * {@link #putRawQueryParameter(String, String)} and {@link #putRawQueryParameter(String, List)}. */ Map<String, List<String>> rawQueryParameters(); /** * Add a single un-encoded query parameter to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this parameter name in the builder.</p> * * @param paramName The name of the query parameter to add * @param paramValue The un-encoded value for the query parameter. */ default Builder putRawQueryParameter(String paramName, String paramValue) { return putRawQueryParameter(paramName, singletonList(paramValue)); } /** * Add a single un-encoded query parameter to be included in the created HTTP request. * * <p>This will <b>ADD</b> the value to any existing values already configured with this parameter name in * the builder.</p> * * @param paramName The name of the query parameter to add * @param paramValue The un-encoded value for the query parameter. */ Builder appendRawQueryParameter(String paramName, String paramValue); /** * Add a single un-encoded query parameter with multiple values to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this parameter name in the builder.</p> * * @param paramName The name of the query parameter to add * @param paramValues The un-encoded values for the query parameter. */ Builder putRawQueryParameter(String paramName, List<String> paramValues); /** * Configure an {@link SdkHttpRequest#rawQueryParameters()} to be used in the created HTTP request. This is not validated * until the http request is created. This overrides any values currently configured in the builder. The query parameters * MUST NOT be URL encoded. * * <p>Justification of requirements: The query parameters must not be encoded when they are configured because some HTTP * implementations perform this encoding automatically.</p> */ Builder rawQueryParameters(Map<String, List<String>> queryParameters); /** * Remove all values for the requested query parameter from this builder. */ Builder removeQueryParameter(String paramName); /** * Removes all query parameters from this builder. */ Builder clearQueryParameters(); default void forEachRawQueryParameter(BiConsumer<? super String, ? super List<String>> consumer) { rawQueryParameters().forEach(consumer); } default int numRawQueryParameters() { return rawQueryParameters().size(); } default Optional<String> encodedQueryParameters() { return SdkHttpUtils.encodeAndFlattenQueryParameters(rawQueryParameters()); } /** * The path, exactly as it was configured with {@link #method(SdkHttpMethod)}. */ SdkHttpMethod method(); /** * Configure an {@link SdkHttpRequest#method()} to be used in the created HTTP request. This is not validated * until the http request is created. */ Builder method(SdkHttpMethod httpMethod); /** * The query parameters, exactly as they were configured with {@link #headers(Map)}, * {@link #putHeader(String, String)} and {@link #putHeader(String, List)}. */ Map<String, List<String>> headers(); /** * Add a single header to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add (eg. "Host") * @param headerValue The value for the header */ default Builder putHeader(String headerName, String headerValue) { return putHeader(headerName, singletonList(headerValue)); } /** * Add a single header with multiple values to be included in the created HTTP request. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add * @param headerValues The values for the header */ Builder putHeader(String headerName, List<String> headerValues); /** * Add a single header to be included in the created HTTP request. * * <p>This will <b>ADD</b> the value to any existing values already configured with this header name in * the builder.</p> * * @param headerName The name of the header to add * @param headerValue The value for the header */ Builder appendHeader(String headerName, String headerValue); /** * Configure an {@link SdkHttpRequest#headers()} to be used in the created HTTP request. This is not validated * until the http request is created. This overrides any values currently configured in the builder. */ Builder headers(Map<String, List<String>> headers); /** * Remove all values for the requested header from this builder. */ Builder removeHeader(String headerName); /** * Removes all headers from this builder. */ Builder clearHeaders(); } }
3,085
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import static java.util.Collections.singletonList; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An immutable HTTP response without access to the response body. {@link SdkHttpFullResponse} should be used when access to a * response body stream is required. */ @SdkPublicApi @Immutable public interface SdkHttpResponse extends ToCopyableBuilder<SdkHttpResponse.Builder, SdkHttpResponse>, SdkHttpHeaders, Serializable { /** * @return Builder instance to construct a {@link DefaultSdkHttpFullResponse}. */ static SdkHttpFullResponse.Builder builder() { return new DefaultSdkHttpFullResponse.Builder(); } /** * Returns the HTTP status text returned by the service. * * <p>If this was not provided by the service, empty will be returned.</p> */ Optional<String> statusText(); /** * Returns the HTTP status code (eg. 200, 404, etc.) returned by the service. * * <p>This will always be positive.</p> */ int statusCode(); /** * If we get back any 2xx status code, then we know we should treat the service call as successful. */ default boolean isSuccessful() { return HttpStatusFamily.of(statusCode()) == HttpStatusFamily.SUCCESSFUL; } /** * Builder for a {@link DefaultSdkHttpFullResponse}. */ interface Builder extends CopyableBuilder<Builder, SdkHttpResponse>, SdkHttpHeaders { /** * The status text, exactly as it was configured with {@link #statusText(String)}. */ String statusText(); /** * Configure an {@link SdkHttpResponse#statusText()} to be used in the created HTTP response. This is not validated * until the http response is created. */ Builder statusText(String statusText); /** * The status text, exactly as it was configured with {@link #statusCode(int)}. */ int statusCode(); /** * Configure an {@link SdkHttpResponse#statusCode()} to be used in the created HTTP response. This is not validated * until the http response is created. */ Builder statusCode(int statusCode); /** * The HTTP headers, exactly as they were configured with {@link #headers(Map)}, * {@link #putHeader(String, String)} and {@link #putHeader(String, List)}. */ Map<String, List<String>> headers(); /** * Add a single header to be included in the created HTTP response. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add (eg. "Host") * @param headerValue The value for the header */ default Builder putHeader(String headerName, String headerValue) { return putHeader(headerName, singletonList(headerValue)); } /** * Add a single header with multiple values to be included in the created HTTP response. * * <p>This completely <b>OVERRIDES</b> any values already configured with this header name in the builder.</p> * * @param headerName The name of the header to add * @param headerValues The values for the header */ Builder putHeader(String headerName, List<String> headerValues); /** * Add a single header to be included in the created HTTP request. * * <p>This will <b>ADD</b> the value to any existing values already configured with this header name in * the builder.</p> * * @param headerName The name of the header to add * @param headerValue The value for the header */ Builder appendHeader(String headerName, String headerValue); /** * Configure an {@link SdkHttpResponse#headers()} to be used in the created HTTP response. This is not validated * until the http response is created. This overrides any values currently configured in the builder. */ Builder headers(Map<String, List<String>> headers); /** * Remove all values for the requested header from this builder. */ Builder removeHeader(String headerName); /** * Removes all headers from this builder. */ Builder clearHeaders(); } }
3,086
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/Header.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Constants for commonly used HTTP headers. */ @SdkProtectedApi public final class Header { public static final String CONTENT_LENGTH = "Content-Length"; public static final String CONTENT_TYPE = "Content-Type"; public static final String CONTENT_MD5 = "Content-MD5"; public static final String TRANSFER_ENCODING = "Transfer-Encoding"; public static final String CHUNKED = "chunked"; public static final String HOST = "Host"; public static final String CONNECTION = "Connection"; public static final String KEEP_ALIVE_VALUE = "keep-alive"; public static final String ACCEPT = "Accept"; private Header() { } }
3,087
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/SdkHttpConfigurationOption.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.time.Duration; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.AttributeMap; /** * Type safe key for an HTTP related configuration option. These options are used for service specific configuration * and are treated as hints for the underlying HTTP implementation for better defaults. If an implementation does not support * a particular option, they are free to ignore it. * * @param <T> Type of option * @see AttributeMap */ @SdkProtectedApi public final class SdkHttpConfigurationOption<T> extends AttributeMap.Key<T> { /** * Timeout for each read to the underlying socket. */ public static final SdkHttpConfigurationOption<Duration> READ_TIMEOUT = new SdkHttpConfigurationOption<>("ReadTimeout", Duration.class); /** * Timeout for each write to the underlying socket. */ public static final SdkHttpConfigurationOption<Duration> WRITE_TIMEOUT = new SdkHttpConfigurationOption<>("WriteTimeout", Duration.class); /** * Timeout for establishing a connection to a remote service. */ public static final SdkHttpConfigurationOption<Duration> CONNECTION_TIMEOUT = new SdkHttpConfigurationOption<>("ConnectionTimeout", Duration.class); /** * Timeout for acquiring an already-established connection from a connection pool to a remote service. */ public static final SdkHttpConfigurationOption<Duration> CONNECTION_ACQUIRE_TIMEOUT = new SdkHttpConfigurationOption<>("ConnectionAcquireTimeout", Duration.class); /** * Timeout after which an idle connection should be closed. */ public static final SdkHttpConfigurationOption<Duration> CONNECTION_MAX_IDLE_TIMEOUT = new SdkHttpConfigurationOption<>("ConnectionMaxIdleTimeout", Duration.class); /** * Timeout after which a connection should be closed, regardless of whether it is idle. Zero indicates an infinite amount * of time. */ public static final SdkHttpConfigurationOption<Duration> CONNECTION_TIME_TO_LIVE = new SdkHttpConfigurationOption<>("ConnectionTimeToLive", Duration.class); /** * Maximum number of connections allowed in a connection pool. */ public static final SdkHttpConfigurationOption<Integer> MAX_CONNECTIONS = new SdkHttpConfigurationOption<>("MaxConnections", Integer.class); /** * HTTP protocol to use. */ public static final SdkHttpConfigurationOption<Protocol> PROTOCOL = new SdkHttpConfigurationOption<>("Protocol", Protocol.class); /** * Maximum number of requests allowed to wait for a connection. */ public static final SdkHttpConfigurationOption<Integer> MAX_PENDING_CONNECTION_ACQUIRES = new SdkHttpConfigurationOption<>("MaxConnectionAcquires", Integer.class); /** * Whether idle connection should be removed after the {@link #CONNECTION_MAX_IDLE_TIMEOUT} has passed. */ public static final SdkHttpConfigurationOption<Boolean> REAP_IDLE_CONNECTIONS = new SdkHttpConfigurationOption<>("ReapIdleConnections", Boolean.class); /** * Whether to enable or disable TCP KeepAlive. * <p> * When enabled, the actual KeepAlive mechanism is dependent on the Operating System and therefore additional TCP KeepAlive * values (like timeout, number of packets, etc) must be configured via the Operating System (sysctl on Linux/Mac, and * Registry values on Windows). */ public static final SdkHttpConfigurationOption<Boolean> TCP_KEEPALIVE = new SdkHttpConfigurationOption<>("TcpKeepalive", Boolean.class); /** * The {@link TlsKeyManagersProvider} that will be used by the HTTP client when authenticating with a * TLS host. */ public static final SdkHttpConfigurationOption<TlsKeyManagersProvider> TLS_KEY_MANAGERS_PROVIDER = new SdkHttpConfigurationOption<>("TlsKeyManagersProvider", TlsKeyManagersProvider.class); /** * Option to disable SSL cert validation and SSL host name verification. By default, this option is off. * Only enable this option for testing purposes. */ public static final SdkHttpConfigurationOption<Boolean> TRUST_ALL_CERTIFICATES = new SdkHttpConfigurationOption<>("TrustAllCertificates", Boolean.class); /** * The {@link TlsTrustManagersProvider} that will be used by the HTTP client when authenticating with a * TLS host. */ public static final SdkHttpConfigurationOption<TlsTrustManagersProvider> TLS_TRUST_MANAGERS_PROVIDER = new SdkHttpConfigurationOption<>("TlsTrustManagersProvider", TlsTrustManagersProvider.class); /** * The maximum amount of time that a TLS handshake is allowed to take from the time the CLIENT HELLO * message is sent to the time the client and server have fully negotiated ciphers and exchanged keys. * * <p> * If not specified, the default value will be the same as the resolved {@link #CONNECTION_TIMEOUT}. */ public static final SdkHttpConfigurationOption<Duration> TLS_NEGOTIATION_TIMEOUT = new SdkHttpConfigurationOption<>("TlsNegotiationTimeout", Duration.class); private static final Duration DEFAULT_SOCKET_READ_TIMEOUT = Duration.ofSeconds(30); private static final Duration DEFAULT_SOCKET_WRITE_TIMEOUT = Duration.ofSeconds(30); private static final Duration DEFAULT_CONNECTION_TIMEOUT = Duration.ofSeconds(2); private static final Duration DEFAULT_CONNECTION_ACQUIRE_TIMEOUT = Duration.ofSeconds(10); private static final Duration DEFAULT_CONNECTION_MAX_IDLE_TIMEOUT = Duration.ofSeconds(60); private static final Duration DEFAULT_CONNECTION_TIME_TO_LIVE = Duration.ZERO; /** * 5 seconds = 3 seconds (RTO for 2 packets loss) + 2 seconds (startup latency and RTT buffer) */ private static final Duration DEFAULT_TLS_NEGOTIATION_TIMEOUT = Duration.ofSeconds(5); private static final Boolean DEFAULT_REAP_IDLE_CONNECTIONS = Boolean.TRUE; private static final int DEFAULT_MAX_CONNECTIONS = 50; private static final int DEFAULT_MAX_CONNECTION_ACQUIRES = 10_000; private static final Boolean DEFAULT_TCP_KEEPALIVE = Boolean.FALSE; private static final Boolean DEFAULT_TRUST_ALL_CERTIFICATES = Boolean.FALSE; private static final Protocol DEFAULT_PROTOCOL = Protocol.HTTP1_1; private static final TlsTrustManagersProvider DEFAULT_TLS_TRUST_MANAGERS_PROVIDER = null; private static final TlsKeyManagersProvider DEFAULT_TLS_KEY_MANAGERS_PROVIDER = SystemPropertyTlsKeyManagersProvider.create(); public static final AttributeMap GLOBAL_HTTP_DEFAULTS = AttributeMap .builder() .put(READ_TIMEOUT, DEFAULT_SOCKET_READ_TIMEOUT) .put(WRITE_TIMEOUT, DEFAULT_SOCKET_WRITE_TIMEOUT) .put(CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT) .put(CONNECTION_ACQUIRE_TIMEOUT, DEFAULT_CONNECTION_ACQUIRE_TIMEOUT) .put(CONNECTION_MAX_IDLE_TIMEOUT, DEFAULT_CONNECTION_MAX_IDLE_TIMEOUT) .put(CONNECTION_TIME_TO_LIVE, DEFAULT_CONNECTION_TIME_TO_LIVE) .put(MAX_CONNECTIONS, DEFAULT_MAX_CONNECTIONS) .put(MAX_PENDING_CONNECTION_ACQUIRES, DEFAULT_MAX_CONNECTION_ACQUIRES) .put(PROTOCOL, DEFAULT_PROTOCOL) .put(TRUST_ALL_CERTIFICATES, DEFAULT_TRUST_ALL_CERTIFICATES) .put(REAP_IDLE_CONNECTIONS, DEFAULT_REAP_IDLE_CONNECTIONS) .put(TCP_KEEPALIVE, DEFAULT_TCP_KEEPALIVE) .put(TLS_KEY_MANAGERS_PROVIDER, DEFAULT_TLS_KEY_MANAGERS_PROVIDER) .put(TLS_TRUST_MANAGERS_PROVIDER, DEFAULT_TLS_TRUST_MANAGERS_PROVIDER) .put(TLS_NEGOTIATION_TIMEOUT, DEFAULT_TLS_NEGOTIATION_TIMEOUT) .build(); private final String name; private SdkHttpConfigurationOption(String name, Class<T> clzz) { super(clzz); this.name = name; } /** * Note that the name is mainly used for debugging purposes. Two option key objects with the same name do not represent * the same option. Option keys are compared by reference when obtaining a value from an {@link AttributeMap}. * * @return Name of this option key. */ public String name() { return name; } @Override public String toString() { return name; } }
3,088
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/HttpMetric.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http; import java.time.Duration; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.metrics.MetricCategory; import software.amazon.awssdk.metrics.MetricLevel; import software.amazon.awssdk.metrics.SdkMetric; /** * Metrics collected by HTTP clients for HTTP/1 and HTTP/2 operations. See {@link Http2Metric} for metrics that are only available * on HTTP/2 operations. */ @SdkPublicApi public final class HttpMetric { /** * The name of the HTTP client. */ public static final SdkMetric<String> HTTP_CLIENT_NAME = metric("HttpClientName", String.class, MetricLevel.INFO); /** * The maximum number of concurrent requests that is supported by the HTTP client. * * <p>For HTTP/1 operations, this is equal to the maximum number of TCP connections that can be be pooled by the HTTP client. * For HTTP/2 operations, this is equal to the maximum number of streams that can be pooled by the HTTP client. * * <p>Note: Depending on the HTTP client, this is either a value for all endpoints served by the HTTP client, or a value * that applies only to the specific endpoint/host used in the request. For 'apache-http-client', this value is * for the entire HTTP client. For 'netty-nio-client', this value is per-endpoint. In all cases, this value is scoped to an * individual HTTP client instance, and does not include concurrency that may be available in other HTTP clients running * within the same JVM. */ public static final SdkMetric<Integer> MAX_CONCURRENCY = metric("MaxConcurrency", Integer.class, MetricLevel.INFO); /** * The number of additional concurrent requests that can be supported by the HTTP client without needing to establish * additional connections to the target server. * * <p>For HTTP/1 operations, this is equal to the number of TCP connections that have been established with the service, * but are currently idle/unused. For HTTP/2 operations, this is equal to the number of streams that are currently * idle/unused. * * <p>Note: Depending on the HTTP client, this is either a value for all endpoints served by the HTTP client, or a value * that applies only to the specific endpoint/host used in the request. For 'apache-http-client', this value is * for the entire HTTP client. For 'netty-nio-client', this value is per-endpoint. In all cases, this value is scoped to an * individual HTTP client instance, and does not include concurrency that may be available in other HTTP clients running * within the same JVM. */ public static final SdkMetric<Integer> AVAILABLE_CONCURRENCY = metric("AvailableConcurrency", Integer.class, MetricLevel.INFO); /** * The number of requests that are currently being executed by the HTTP client. * * <p>For HTTP/1 operations, this is equal to the number of TCP connections currently in active communication with the service * (excluding idle connections). For HTTP/2 operations, this is equal to the number of HTTP streams currently in active * communication with the service (excluding idle stream capacity). * * <p>Note: Depending on the HTTP client, this is either a value for all endpoints served by the HTTP client, or a value * that applies only to the specific endpoint/host used in the request. For 'apache-http-client', this value is * for the entire HTTP client. For 'netty-nio-client', this value is per-endpoint. In all cases, this value is scoped to an * individual HTTP client instance, and does not include concurrency that may be available in other HTTP clients running * within the same JVM. */ public static final SdkMetric<Integer> LEASED_CONCURRENCY = metric("LeasedConcurrency", Integer.class, MetricLevel.INFO); /** * The number of requests that are awaiting concurrency to be made available from the HTTP client. * * <p>For HTTP/1 operations, this is equal to the number of requests currently blocked, waiting for a TCP connection to be * established or returned from the connection pool. For HTTP/2 operations, this is equal to the number of requests currently * blocked, waiting for a new stream (and possibly a new HTTP/2 connection) from the connection pool. * * <p>Note: Depending on the HTTP client, this is either a value for all endpoints served by the HTTP client, or a value * that applies only to the specific endpoint/host used in the request. For 'apache-http-client', this value is * for the entire HTTP client. For 'netty-nio-client', this value is per-endpoint. In all cases, this value is scoped to an * individual HTTP client instance, and does not include concurrency that may be available in other HTTP clients running * within the same JVM. */ public static final SdkMetric<Integer> PENDING_CONCURRENCY_ACQUIRES = metric("PendingConcurrencyAcquires", Integer.class, MetricLevel.INFO); /** * The status code of the HTTP response. * * <p> * This is reported by the SDK core, and should not be reported by an individual HTTP client implementation. */ public static final SdkMetric<Integer> HTTP_STATUS_CODE = metric("HttpStatusCode", Integer.class, MetricLevel.TRACE); /** * The time taken to acquire a channel from the connection pool. * * <p>For HTTP/1 operations, a channel is equivalent to a TCP connection. For HTTP/2 operations, a channel is equivalent to * an HTTP/2 stream channel. For both protocols, the time to acquire a new channel may include the following: * <ol> * <li>Awaiting a concurrency permit, as restricted by the client's max concurrency configuration.</li> * <li>The time to establish a new connection, depending on whether an existing connection is available in the pool or * not.</li> * <li>The time taken to perform a TLS handshake/negotiation, if TLS is enabled.</li> * </ol> */ public static final SdkMetric<Duration> CONCURRENCY_ACQUIRE_DURATION = metric("ConcurrencyAcquireDuration", Duration.class, MetricLevel.INFO); private HttpMetric() { } private static <T> SdkMetric<T> metric(String name, Class<T> clzz, MetricLevel level) { return SdkMetric.create(name, clzz, level, MetricCategory.CORE, MetricCategory.HTTP_CLIENT); } }
3,089
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/SdkHttpContentPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.async; import java.nio.ByteBuffer; import java.util.Optional; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkPublicApi; /** * A {@link Publisher} of HTTP content data that allows streaming operations for asynchronous HTTP clients. */ @SdkPublicApi public interface SdkHttpContentPublisher extends Publisher<ByteBuffer> { /** * @return The content length of the data being produced. */ Optional<Long> contentLength(); }
3,090
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/AsyncExecuteRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.async; import java.util.Optional; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.SdkHttpExecutionAttribute; import software.amazon.awssdk.http.SdkHttpExecutionAttributes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.utils.Validate; /** * Request object containing the parameters necessary to make an asynchronous HTTP request. * * @see SdkAsyncHttpClient */ @SdkPublicApi public final class AsyncExecuteRequest { private final SdkHttpRequest request; private final SdkHttpContentPublisher requestContentPublisher; private final SdkAsyncHttpResponseHandler responseHandler; private final MetricCollector metricCollector; private final boolean isFullDuplex; private final SdkHttpExecutionAttributes sdkHttpExecutionAttributes; private AsyncExecuteRequest(BuilderImpl builder) { this.request = builder.request; this.requestContentPublisher = builder.requestContentPublisher; this.responseHandler = builder.responseHandler; this.metricCollector = builder.metricCollector; this.isFullDuplex = builder.isFullDuplex; this.sdkHttpExecutionAttributes = builder.executionAttributesBuilder.build(); } /** * @return The HTTP request. */ public SdkHttpRequest request() { return request; } /** * @return The publisher of request body. */ public SdkHttpContentPublisher requestContentPublisher() { return requestContentPublisher; } /** * @return The response handler. */ public SdkAsyncHttpResponseHandler responseHandler() { return responseHandler; } /** * @return The {@link MetricCollector}. */ public Optional<MetricCollector> metricCollector() { return Optional.ofNullable(metricCollector); } /** * @return True if the operation this request belongs to is full duplex. Otherwise false. */ public boolean fullDuplex() { return isFullDuplex; } /** * @return the SDK HTTP execution attributes associated with this request */ public SdkHttpExecutionAttributes httpExecutionAttributes() { return sdkHttpExecutionAttributes; } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * Set the HTTP request to be executed by the client. * * @param request The request. * @return This builder for method chaining. */ Builder request(SdkHttpRequest request); /** * Set the publisher of the request content. * * @param requestContentPublisher The publisher. * @return This builder for method chaining. */ Builder requestContentPublisher(SdkHttpContentPublisher requestContentPublisher); /** * Set the response handler for the resposne. * * @param responseHandler The response handler. * @return This builder for method chaining. */ Builder responseHandler(SdkAsyncHttpResponseHandler responseHandler); /** * Set the {@link MetricCollector} to be used by the HTTP client to * report metrics collected for this request. * * @param metricCollector The metric collector. * @return This builder for method chaining. */ Builder metricCollector(MetricCollector metricCollector); /** * Option to indicate if the request is for a full duplex operation ie., request and response are sent/received at * the same time. * <p> * This can be used to set http configuration like ReadTimeouts as soon as request has begin sending data instead of * waiting for the entire request to be sent. * * @return True if the operation this request belongs to is full duplex. Otherwise false. */ Builder fullDuplex(boolean fullDuplex); /** * Put an HTTP execution attribute into to the collection of HTTP execution attributes for this request * * @param attribute The execution attribute object * @param value The value of the execution attribute. */ <T> Builder putHttpExecutionAttribute(SdkHttpExecutionAttribute<T> attribute, T value); /** * Sets the additional HTTP execution attributes collection for this request. * <p> * This will override the attributes configured through * {@link #putHttpExecutionAttribute(SdkHttpExecutionAttribute, Object)} * * @param executionAttributes Execution attributes map for this request. * @return This object for method chaining. */ Builder httpExecutionAttributes(SdkHttpExecutionAttributes executionAttributes); AsyncExecuteRequest build(); } private static class BuilderImpl implements Builder { private SdkHttpRequest request; private SdkHttpContentPublisher requestContentPublisher; private SdkAsyncHttpResponseHandler responseHandler; private MetricCollector metricCollector; private boolean isFullDuplex; private SdkHttpExecutionAttributes.Builder executionAttributesBuilder = SdkHttpExecutionAttributes.builder(); @Override public Builder request(SdkHttpRequest request) { this.request = request; return this; } @Override public Builder requestContentPublisher(SdkHttpContentPublisher requestContentPublisher) { this.requestContentPublisher = requestContentPublisher; return this; } @Override public Builder responseHandler(SdkAsyncHttpResponseHandler responseHandler) { this.responseHandler = responseHandler; return this; } @Override public Builder metricCollector(MetricCollector metricCollector) { this.metricCollector = metricCollector; return this; } @Override public Builder fullDuplex(boolean fullDuplex) { isFullDuplex = fullDuplex; return this; } @Override public <T> Builder putHttpExecutionAttribute(SdkHttpExecutionAttribute<T> attribute, T value) { this.executionAttributesBuilder.put(attribute, value); return this; } @Override public Builder httpExecutionAttributes(SdkHttpExecutionAttributes executionAttributes) { Validate.paramNotNull(executionAttributes, "executionAttributes"); this.executionAttributesBuilder = executionAttributes.toBuilder(); return this; } @Override public AsyncExecuteRequest build() { return new AsyncExecuteRequest(this); } } }
3,091
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/SdkHttpResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.async; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.http.SdkHttpResponse; /** * Responsible for handling asynchronous http responses * * @param <T> Type of result returned in {@link #complete()}. May be {@link Void}. */ @SdkProtectedApi public interface SdkHttpResponseHandler<T> { /** * Called when the initial response with headers is received. * * @param response the {@link SdkHttpResponse} */ void headersReceived(SdkHttpResponse response); /** * Called when the HTTP client is ready to start sending data to the response handler. Implementations * must subscribe to the {@link Publisher} and request data via a {@link org.reactivestreams.Subscription} as * they can handle it. * * <p> * If at any time the subscriber wishes to stop receiving data, it may call {@link Subscription#cancel()}. This * will be treated as a failure of the response and the {@link #exceptionOccurred(Throwable)} callback will be invoked. * </p> */ void onStream(Publisher<ByteBuffer> publisher); /** * Called when an exception occurs during the request/response. * * This is a terminal method call, no other method invocations should be expected * on the {@link SdkHttpResponseHandler} after this point. * * @param throwable the exception that occurred. */ void exceptionOccurred(Throwable throwable); /** * Called when all parts of the response have been received. * * This is a terminal method call, no other method invocations should be expected * on the {@link SdkHttpResponseHandler} after this point. * * @return Transformed result. */ T complete(); }
3,092
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/SdkAsyncHttpClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.async; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Interface to take a representation of an HTTP request, asynchronously make an HTTP call, and return a representation of an * HTTP response. * * <p>Implementations MUST be thread safe.</p> */ @Immutable @ThreadSafe @SdkPublicApi public interface SdkAsyncHttpClient extends SdkAutoCloseable { /** * Execute the request. * * @param request The request object. * * @return The future holding the result of the request execution. Upon success execution of the request, the future is * completed with {@code null}, otherwise it is completed exceptionally. */ CompletableFuture<Void> execute(AsyncExecuteRequest request); /** * Each HTTP client implementation should return a well-formed client name * that allows requests to be identifiable back to the client that made the request. * The client name should include the backing implementation as well as the Sync or Async * to identify the transmission type of the request. Client names should only include * alphanumeric characters. Examples of well formed client names include, Apache, for * requests using Apache's http client or NettyNio for Netty's http client. * * @return String containing the name of the client */ default String clientName() { return "UNKNOWN"; } @FunctionalInterface interface Builder<T extends SdkAsyncHttpClient.Builder<T>> extends SdkBuilder<T, SdkAsyncHttpClient> { /** * Create a {@link SdkAsyncHttpClient} with global defaults applied. This is useful for reusing an HTTP client across * multiple services. */ @Override default SdkAsyncHttpClient build() { return buildWithDefaults(AttributeMap.empty()); } /** * Create an {@link SdkAsyncHttpClient} with service specific defaults applied. Applying service defaults is optional * and some options may not be supported by a particular implementation. * * @param serviceDefaults Service specific defaults. Keys will be one of the constants defined in {@link * SdkHttpConfigurationOption}. * @return Created client */ SdkAsyncHttpClient buildWithDefaults(AttributeMap serviceDefaults); } }
3,093
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/SdkAsyncHttpService.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.async; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * Service Provider interface for Async HTTP implementations. The core uses {@link java.util.ServiceLoader} to find appropriate * HTTP implementations on the classpath. HTTP implementations that wish to be discovered by the default HTTP provider chain * should implement this interface and declare that implementation as a service in the * META-INF/service/software.amazon.awssdk.http.async.SdkAsyncHttpService resource. See * <a href="https://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html">Service Loader</a> for more * information. * * <p> * This interface is simply a factory for {@link SdkAsyncHttpClient.Builder}. Implementations must be thread safe. * </p> */ @ThreadSafe @SdkPublicApi public interface SdkAsyncHttpService { /** * @return An {@link SdkAsyncHttpClient.Builder} capable of creating {@link SdkAsyncHttpClient} instances. This factory should * be thread safe. */ SdkAsyncHttpClient.Builder createAsyncHttpClientFactory(); }
3,094
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/SdkAsyncHttpResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.async; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.SdkHttpResponse; /** * Handles asynchronous HTTP responses. */ @SdkPublicApi public interface SdkAsyncHttpResponseHandler { /** * Called when the headers have been received. * * @param headers The headers. */ void onHeaders(SdkHttpResponse headers); /** * Called when the streaming body is ready. * <p> * This method is always called. If the response does not have a body, then the publisher will complete the subscription * without signalling any elements. * * @param stream The streaming body. */ void onStream(Publisher<ByteBuffer> stream); /** * Called when there is an error making the request or receiving the response. If the error is encountered while * streaming the body, then the error is also delivered to the {@link org.reactivestreams.Subscriber}. * * @param error The error. */ void onError(Throwable error); }
3,095
0
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http
Create_ds/aws-sdk-java-v2/http-client-spi/src/main/java/software/amazon/awssdk/http/async/SimpleSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.async; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Simple subscriber that does no backpressure and doesn't care about errors or completion. */ @SdkProtectedApi public class SimpleSubscriber implements Subscriber<ByteBuffer> { private final Consumer<ByteBuffer> consumer; private final AtomicReference<Subscription> subscription = new AtomicReference<>(); public SimpleSubscriber(Consumer<ByteBuffer> consumer) { this.consumer = consumer; } @Override public void onSubscribe(Subscription s) { // As per rule 1.9 we must throw NullPointerException if the subscriber parameter is null if (s == null) { throw new NullPointerException("Subscription MUST NOT be null."); } if (subscription.get() == null) { if (subscription.compareAndSet(null, s)) { s.request(Long.MAX_VALUE); } else { onSubscribe(s); // lost race, retry (will cancel in the else branch below) } } else { try { s.cancel(); // Cancel the additional subscription } catch (final Throwable t) { // Subscription.cancel is not allowed to throw an exception, according to rule 3.15 (new IllegalStateException(s + " violated the Reactive Streams rule 3.15 by throwing an exception from cancel.", t)) .printStackTrace(System.err); } } } @Override public void onNext(ByteBuffer byteBuffer) { // Rule 2.13, null arguments must be failed on eagerly if (byteBuffer == null) { throw new NullPointerException("Element passed to onNext MUST NOT be null."); } consumer.accept(byteBuffer); } @Override public void onError(Throwable t) { if (t == null) { throw new NullPointerException("Throwable passed to onError MUST NOT be null."); } // else, ignore } @Override public void onComplete() { // ignore } }
3,096
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/service-metadata-provider.java
package software.amazon.awssdk.regions; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.servicemetadata.A4bServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AccessAnalyzerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AccountServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AcmPcaServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AcmServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AirflowServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AmplifyServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AmplifybackendServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiDetectiveServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiEcrPublicServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiEcrServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiElasticInferenceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiFleethubIotServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiMediatailorServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiPricingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApiSagemakerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApigatewayServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AppIntegrationsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AppflowServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApplicationAutoscalingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApplicationinsightsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AppmeshServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApprunnerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Appstream2ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AppsyncServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ApsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AthenaServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AuditmanagerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AutoscalingPlansServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.AutoscalingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.BackupServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.BatchServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.BraketServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.BudgetsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ChimeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Cloud9ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CloudcontrolapiServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ClouddirectoryServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CloudformationServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CloudfrontServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CloudhsmServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Cloudhsmv2ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CloudsearchServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CloudtrailServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodeartifactServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodebuildServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodecommitServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodedeployServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodeguruProfilerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodeguruReviewerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodepipelineServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodestarConnectionsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodestarNotificationsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CodestarServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CognitoIdentityServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CognitoIdpServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CognitoSyncServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ComprehendServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ComprehendmedicalServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ComputeOptimizerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ConfigServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ConnectServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ConnectparticipantServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ContactLensServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.CurServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DataIotServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DataJobsIotServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DataMediastoreServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DatabrewServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DataexchangeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DatapipelineServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DatasyncServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DaxServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DeeplensServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DevicefarmServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DevicesIot1clickServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DirectconnectServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DiscoveryServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DlmServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DmsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DocdbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.DynamodbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EbsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Ec2ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EcsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EdgeSagemakerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EksServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ElasticacheServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ElasticbeanstalkServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ElasticfilesystemServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ElasticloadbalancingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ElasticmapreduceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ElastictranscoderServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EmailServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EmrContainersServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EnhancedS3ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EntitlementMarketplaceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.EventsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ExecuteApiServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.FinspaceApiServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.FinspaceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.FirehoseServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.FmsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ForecastServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ForecastqueryServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.FrauddetectorServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.FsxServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GameliftServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GlacierServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GlueServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GrafanaServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GreengrassServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GroundstationServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.GuarddutyServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.HealthServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.HealthlakeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.HoneycodeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IamServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IdentityChimeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IdentitystoreServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ImportexportServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.InspectorServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotanalyticsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotdeviceadvisorServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IoteventsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IoteventsdataServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotsecuredtunnelingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotsitewiseServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotthingsgraphServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IotwirelessServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.IvsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KafkaServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KafkaconnectServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KendraServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KinesisServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KinesisanalyticsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KinesisvideoServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.KmsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LakeformationServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LambdaServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LicenseManagerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LightsailServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LogsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LookoutequipmentServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LookoutmetricsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.LookoutvisionServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MachinelearningServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Macie2ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MacieServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ManagedblockchainServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MarketplacecommerceanalyticsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MediaconnectServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MediaconvertServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MedialiveServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MediapackageServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MediapackageVodServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MediastoreServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MemorydbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MessagingChimeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MeteringMarketplaceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MghServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MgnServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MigrationhubStrategyServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MobileanalyticsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ModelsLexServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ModelsV2LexServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MonitoringServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MqServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.MturkRequesterServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.NeptuneServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.NetworkFirewallServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.NetworkmanagerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.NimbleServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.OidcServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.OperatorServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.OpsworksCmServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.OpsworksServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.OrganizationsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.OutpostsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.PersonalizeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.PiServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.PinpointServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.PinpointSmsVoiceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.PollyServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.PortalSsoServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ProfileServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ProjectsIot1clickServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.QldbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.QuicksightServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RamServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RdsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RdsdataserviceServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RedshiftServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RekognitionServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ResourceGroupsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RobomakerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Route53RecoveryControlConfigServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Route53ServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Route53domainsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.Route53resolverServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RuntimeLexServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RuntimeSagemakerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.RuntimeV2LexServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.S3ControlServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.S3OutpostsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SavingsplansServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SchemasServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SdbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SecretsmanagerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SecurityhubServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ServerlessrepoServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ServicecatalogAppregistryServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ServicecatalogServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ServicediscoveryServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ServicequotasServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SessionQldbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ShieldServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SignerServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SmsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SmsVoicePinpointServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SnowDeviceManagementServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SnowballServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SnsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SqsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SsmIncidentsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SsmServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.StatesServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.StoragegatewayServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.StreamsDynamodbServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.StsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SupportServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SwfServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.SyntheticsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TaggingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TextractServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TimestreamQueryServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TimestreamWriteServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TranscribeServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TranscribestreamingServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TransferServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.TranslateServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.ValkyrieServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.VoiceidServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.WafRegionalServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.WafServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.WisdomServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.WorkdocsServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.WorkmailServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.WorkspacesServiceMetadata; import software.amazon.awssdk.regions.servicemetadata.XrayServiceMetadata; import software.amazon.awssdk.utils.ImmutableMap; @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public final class GeneratedServiceMetadataProvider implements ServiceMetadataProvider { private static final Map<String, ServiceMetadata> SERVICE_METADATA = ImmutableMap.<String, ServiceMetadata> builder() .put("a4b", new A4bServiceMetadata()).put("access-analyzer", new AccessAnalyzerServiceMetadata()) .put("account", new AccountServiceMetadata()).put("acm", new AcmServiceMetadata()) .put("acm-pca", new AcmPcaServiceMetadata()).put("airflow", new AirflowServiceMetadata()) .put("amplify", new AmplifyServiceMetadata()).put("amplifybackend", new AmplifybackendServiceMetadata()) .put("api.detective", new ApiDetectiveServiceMetadata()).put("api.ecr", new ApiEcrServiceMetadata()) .put("api.ecr-public", new ApiEcrPublicServiceMetadata()) .put("api.elastic-inference", new ApiElasticInferenceServiceMetadata()) .put("api.fleethub.iot", new ApiFleethubIotServiceMetadata()) .put("api.mediatailor", new ApiMediatailorServiceMetadata()).put("api.pricing", new ApiPricingServiceMetadata()) .put("api.sagemaker", new ApiSagemakerServiceMetadata()).put("apigateway", new ApigatewayServiceMetadata()) .put("app-integrations", new AppIntegrationsServiceMetadata()).put("appflow", new AppflowServiceMetadata()) .put("application-autoscaling", new ApplicationAutoscalingServiceMetadata()) .put("applicationinsights", new ApplicationinsightsServiceMetadata()).put("appmesh", new AppmeshServiceMetadata()) .put("apprunner", new ApprunnerServiceMetadata()).put("appstream2", new Appstream2ServiceMetadata()) .put("appsync", new AppsyncServiceMetadata()).put("aps", new ApsServiceMetadata()) .put("athena", new AthenaServiceMetadata()).put("auditmanager", new AuditmanagerServiceMetadata()) .put("autoscaling", new AutoscalingServiceMetadata()).put("autoscaling-plans", new AutoscalingPlansServiceMetadata()) .put("backup", new BackupServiceMetadata()).put("batch", new BatchServiceMetadata()) .put("braket", new BraketServiceMetadata()).put("budgets", new BudgetsServiceMetadata()) .put("ce", new CeServiceMetadata()).put("chime", new ChimeServiceMetadata()) .put("cloud9", new Cloud9ServiceMetadata()).put("cloudcontrolapi", new CloudcontrolapiServiceMetadata()) .put("clouddirectory", new ClouddirectoryServiceMetadata()) .put("cloudformation", new CloudformationServiceMetadata()).put("cloudfront", new CloudfrontServiceMetadata()) .put("cloudhsm", new CloudhsmServiceMetadata()).put("cloudhsmv2", new Cloudhsmv2ServiceMetadata()) .put("cloudsearch", new CloudsearchServiceMetadata()).put("cloudtrail", new CloudtrailServiceMetadata()) .put("codeartifact", new CodeartifactServiceMetadata()).put("codebuild", new CodebuildServiceMetadata()) .put("codecommit", new CodecommitServiceMetadata()).put("codedeploy", new CodedeployServiceMetadata()) .put("codeguru-profiler", new CodeguruProfilerServiceMetadata()) .put("codeguru-reviewer", new CodeguruReviewerServiceMetadata()) .put("codepipeline", new CodepipelineServiceMetadata()).put("codestar", new CodestarServiceMetadata()) .put("codestar-connections", new CodestarConnectionsServiceMetadata()) .put("codestar-notifications", new CodestarNotificationsServiceMetadata()) .put("cognito-identity", new CognitoIdentityServiceMetadata()).put("cognito-idp", new CognitoIdpServiceMetadata()) .put("cognito-sync", new CognitoSyncServiceMetadata()).put("comprehend", new ComprehendServiceMetadata()) .put("comprehendmedical", new ComprehendmedicalServiceMetadata()) .put("compute-optimizer", new ComputeOptimizerServiceMetadata()).put("config", new ConfigServiceMetadata()) .put("connect", new ConnectServiceMetadata()).put("connectparticipant", new ConnectparticipantServiceMetadata()) .put("contact-lens", new ContactLensServiceMetadata()).put("cur", new CurServiceMetadata()) .put("data.iot", new DataIotServiceMetadata()).put("data.jobs.iot", new DataJobsIotServiceMetadata()) .put("data.mediastore", new DataMediastoreServiceMetadata()).put("databrew", new DatabrewServiceMetadata()) .put("dataexchange", new DataexchangeServiceMetadata()).put("datapipeline", new DatapipelineServiceMetadata()) .put("datasync", new DatasyncServiceMetadata()).put("dax", new DaxServiceMetadata()) .put("deeplens", new DeeplensServiceMetadata()).put("devicefarm", new DevicefarmServiceMetadata()) .put("devices.iot1click", new DevicesIot1clickServiceMetadata()) .put("directconnect", new DirectconnectServiceMetadata()).put("discovery", new DiscoveryServiceMetadata()) .put("dlm", new DlmServiceMetadata()).put("dms", new DmsServiceMetadata()).put("docdb", new DocdbServiceMetadata()) .put("ds", new DsServiceMetadata()).put("dynamodb", new DynamodbServiceMetadata()) .put("ebs", new EbsServiceMetadata()).put("ec2", new Ec2ServiceMetadata()).put("ecs", new EcsServiceMetadata()) .put("edge.sagemaker", new EdgeSagemakerServiceMetadata()).put("eks", new EksServiceMetadata()) .put("elasticache", new ElasticacheServiceMetadata()).put("elasticbeanstalk", new ElasticbeanstalkServiceMetadata()) .put("elasticfilesystem", new ElasticfilesystemServiceMetadata()) .put("elasticloadbalancing", new ElasticloadbalancingServiceMetadata()) .put("elasticmapreduce", new ElasticmapreduceServiceMetadata()) .put("elastictranscoder", new ElastictranscoderServiceMetadata()).put("email", new EmailServiceMetadata()) .put("emr-containers", new EmrContainersServiceMetadata()) .put("entitlement.marketplace", new EntitlementMarketplaceServiceMetadata()).put("es", new EsServiceMetadata()) .put("events", new EventsServiceMetadata()).put("execute-api", new ExecuteApiServiceMetadata()) .put("finspace", new FinspaceServiceMetadata()).put("finspace-api", new FinspaceApiServiceMetadata()) .put("firehose", new FirehoseServiceMetadata()).put("fms", new FmsServiceMetadata()) .put("forecast", new ForecastServiceMetadata()).put("forecastquery", new ForecastqueryServiceMetadata()) .put("frauddetector", new FrauddetectorServiceMetadata()).put("fsx", new FsxServiceMetadata()) .put("gamelift", new GameliftServiceMetadata()).put("glacier", new GlacierServiceMetadata()) .put("glue", new GlueServiceMetadata()).put("grafana", new GrafanaServiceMetadata()) .put("greengrass", new GreengrassServiceMetadata()).put("groundstation", new GroundstationServiceMetadata()) .put("guardduty", new GuarddutyServiceMetadata()).put("health", new HealthServiceMetadata()) .put("healthlake", new HealthlakeServiceMetadata()).put("honeycode", new HoneycodeServiceMetadata()) .put("iam", new IamServiceMetadata()).put("identity-chime", new IdentityChimeServiceMetadata()) .put("identitystore", new IdentitystoreServiceMetadata()).put("importexport", new ImportexportServiceMetadata()) .put("inspector", new InspectorServiceMetadata()).put("iot", new IotServiceMetadata()) .put("iotanalytics", new IotanalyticsServiceMetadata()) .put("iotdeviceadvisor", new IotdeviceadvisorServiceMetadata()).put("iotevents", new IoteventsServiceMetadata()) .put("ioteventsdata", new IoteventsdataServiceMetadata()) .put("iotsecuredtunneling", new IotsecuredtunnelingServiceMetadata()) .put("iotsitewise", new IotsitewiseServiceMetadata()).put("iotthingsgraph", new IotthingsgraphServiceMetadata()) .put("iotwireless", new IotwirelessServiceMetadata()).put("ivs", new IvsServiceMetadata()) .put("kafka", new KafkaServiceMetadata()).put("kafkaconnect", new KafkaconnectServiceMetadata()) .put("kendra", new KendraServiceMetadata()).put("kinesis", new KinesisServiceMetadata()) .put("kinesisanalytics", new KinesisanalyticsServiceMetadata()) .put("kinesisvideo", new KinesisvideoServiceMetadata()).put("kms", new KmsServiceMetadata()) .put("lakeformation", new LakeformationServiceMetadata()).put("lambda", new LambdaServiceMetadata()) .put("license-manager", new LicenseManagerServiceMetadata()).put("lightsail", new LightsailServiceMetadata()) .put("logs", new LogsServiceMetadata()).put("lookoutequipment", new LookoutequipmentServiceMetadata()) .put("lookoutmetrics", new LookoutmetricsServiceMetadata()).put("lookoutvision", new LookoutvisionServiceMetadata()) .put("machinelearning", new MachinelearningServiceMetadata()).put("macie", new MacieServiceMetadata()) .put("macie2", new Macie2ServiceMetadata()).put("managedblockchain", new ManagedblockchainServiceMetadata()) .put("marketplacecommerceanalytics", new MarketplacecommerceanalyticsServiceMetadata()) .put("mediaconnect", new MediaconnectServiceMetadata()).put("mediaconvert", new MediaconvertServiceMetadata()) .put("medialive", new MedialiveServiceMetadata()).put("mediapackage", new MediapackageServiceMetadata()) .put("mediapackage-vod", new MediapackageVodServiceMetadata()).put("mediastore", new MediastoreServiceMetadata()) .put("memorydb", new MemorydbServiceMetadata()).put("messaging-chime", new MessagingChimeServiceMetadata()) .put("metering.marketplace", new MeteringMarketplaceServiceMetadata()).put("mgh", new MghServiceMetadata()) .put("mgn", new MgnServiceMetadata()).put("migrationhub-strategy", new MigrationhubStrategyServiceMetadata()) .put("mobileanalytics", new MobileanalyticsServiceMetadata()).put("models-v2-lex", new ModelsV2LexServiceMetadata()) .put("models.lex", new ModelsLexServiceMetadata()).put("monitoring", new MonitoringServiceMetadata()) .put("mq", new MqServiceMetadata()).put("mturk-requester", new MturkRequesterServiceMetadata()) .put("neptune", new NeptuneServiceMetadata()).put("network-firewall", new NetworkFirewallServiceMetadata()) .put("networkmanager", new NetworkmanagerServiceMetadata()).put("nimble", new NimbleServiceMetadata()) .put("oidc", new OidcServiceMetadata()).put("opsworks", new OpsworksServiceMetadata()) .put("opsworks-cm", new OpsworksCmServiceMetadata()).put("organizations", new OrganizationsServiceMetadata()) .put("outposts", new OutpostsServiceMetadata()).put("personalize", new PersonalizeServiceMetadata()) .put("pi", new PiServiceMetadata()).put("pinpoint", new PinpointServiceMetadata()) .put("pinpoint-sms-voice", new PinpointSmsVoiceServiceMetadata()).put("polly", new PollyServiceMetadata()) .put("portal.sso", new PortalSsoServiceMetadata()).put("profile", new ProfileServiceMetadata()) .put("projects.iot1click", new ProjectsIot1clickServiceMetadata()).put("qldb", new QldbServiceMetadata()) .put("quicksight", new QuicksightServiceMetadata()).put("ram", new RamServiceMetadata()) .put("rds", new RdsServiceMetadata()).put("rdsdataservice", new RdsdataserviceServiceMetadata()) .put("redshift", new RedshiftServiceMetadata()).put("rekognition", new RekognitionServiceMetadata()) .put("resource-groups", new ResourceGroupsServiceMetadata()).put("robomaker", new RobomakerServiceMetadata()) .put("route53", new Route53ServiceMetadata()) .put("route53-recovery-control-config", new Route53RecoveryControlConfigServiceMetadata()) .put("route53domains", new Route53domainsServiceMetadata()) .put("route53resolver", new Route53resolverServiceMetadata()) .put("runtime-v2-lex", new RuntimeV2LexServiceMetadata()).put("runtime.lex", new RuntimeLexServiceMetadata()) .put("runtime.sagemaker", new RuntimeSagemakerServiceMetadata()).put("s3", new EnhancedS3ServiceMetadata()) .put("s3-control", new S3ControlServiceMetadata()).put("s3-outposts", new S3OutpostsServiceMetadata()) .put("savingsplans", new SavingsplansServiceMetadata()).put("schemas", new SchemasServiceMetadata()) .put("sdb", new SdbServiceMetadata()).put("secretsmanager", new SecretsmanagerServiceMetadata()) .put("securityhub", new SecurityhubServiceMetadata()).put("serverlessrepo", new ServerlessrepoServiceMetadata()) .put("servicecatalog", new ServicecatalogServiceMetadata()) .put("servicecatalog-appregistry", new ServicecatalogAppregistryServiceMetadata()) .put("servicediscovery", new ServicediscoveryServiceMetadata()) .put("servicequotas", new ServicequotasServiceMetadata()).put("session.qldb", new SessionQldbServiceMetadata()) .put("shield", new ShieldServiceMetadata()).put("signer", new SignerServiceMetadata()) .put("sms", new SmsServiceMetadata()).put("sms-voice.pinpoint", new SmsVoicePinpointServiceMetadata()) .put("snow-device-management", new SnowDeviceManagementServiceMetadata()) .put("snowball", new SnowballServiceMetadata()).put("sns", new SnsServiceMetadata()) .put("sqs", new SqsServiceMetadata()).put("ssm", new SsmServiceMetadata()) .put("ssm-incidents", new SsmIncidentsServiceMetadata()).put("states", new StatesServiceMetadata()) .put("storagegateway", new StoragegatewayServiceMetadata()) .put("streams.dynamodb", new StreamsDynamodbServiceMetadata()).put("sts", new StsServiceMetadata()) .put("support", new SupportServiceMetadata()).put("swf", new SwfServiceMetadata()) .put("synthetics", new SyntheticsServiceMetadata()).put("tagging", new TaggingServiceMetadata()) .put("textract", new TextractServiceMetadata()).put("timestream.query", new TimestreamQueryServiceMetadata()) .put("timestream.write", new TimestreamWriteServiceMetadata()).put("transcribe", new TranscribeServiceMetadata()) .put("transcribestreaming", new TranscribestreamingServiceMetadata()).put("transfer", new TransferServiceMetadata()) .put("translate", new TranslateServiceMetadata()).put("valkyrie", new ValkyrieServiceMetadata()) .put("voiceid", new VoiceidServiceMetadata()).put("waf", new WafServiceMetadata()) .put("waf-regional", new WafRegionalServiceMetadata()).put("wisdom", new WisdomServiceMetadata()) .put("workdocs", new WorkdocsServiceMetadata()).put("workmail", new WorkmailServiceMetadata()) .put("workspaces", new WorkspacesServiceMetadata()).put("xray", new XrayServiceMetadata()) .put("operator", new OperatorServiceMetadata()).build(); public ServiceMetadata serviceMetadata(String endpointPrefix) { return SERVICE_METADATA.get(endpointPrefix); } }
3,097
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/partition-metadata-provider.java
package software.amazon.awssdk.regions; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.partitionmetadata.AwsCnPartitionMetadata; import software.amazon.awssdk.regions.partitionmetadata.AwsIsoBPartitionMetadata; import software.amazon.awssdk.regions.partitionmetadata.AwsIsoPartitionMetadata; import software.amazon.awssdk.regions.partitionmetadata.AwsPartitionMetadata; import software.amazon.awssdk.regions.partitionmetadata.AwsUsGovPartitionMetadata; import software.amazon.awssdk.utils.ImmutableMap; @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public final class GeneratedPartitionMetadataProvider implements PartitionMetadataProvider { private static final Map<String, PartitionMetadata> PARTITION_METADATA = ImmutableMap.<String, PartitionMetadata> builder() .put("aws", new AwsPartitionMetadata()).put("aws-cn", new AwsCnPartitionMetadata()) .put("aws-us-gov", new AwsUsGovPartitionMetadata()).put("aws-iso", new AwsIsoPartitionMetadata()) .put("aws-iso-b", new AwsIsoBPartitionMetadata()).build(); public PartitionMetadata partitionMetadata(String partition) { return PARTITION_METADATA.get(partition); } public PartitionMetadata partitionMetadata(Region region) { return PARTITION_METADATA.values().stream().filter(p -> region.id().matches(p.regionRegex())).findFirst() .orElse(new AwsPartitionMetadata()); } }
3,098
0
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite
Create_ds/aws-sdk-java-v2/codegen-lite/src/test/resources/software/amazon/awssdk/codegen/lite/regions/sts-service-metadata.java
package software.amazon.awssdk.regions.servicemetadata; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Generated; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.EndpointTag; import software.amazon.awssdk.regions.PartitionEndpointKey; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceEndpointKey; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.regions.ServicePartitionMetadata; import software.amazon.awssdk.regions.internal.DefaultServicePartitionMetadata; import software.amazon.awssdk.regions.internal.util.ServiceMetadataUtils; import software.amazon.awssdk.utils.ImmutableMap; import software.amazon.awssdk.utils.Pair; @Generated("software.amazon.awssdk:codegen") @SdkPublicApi public final class StsServiceMetadata implements ServiceMetadata { private static final String ENDPOINT_PREFIX = "sts"; private static final List<Region> REGIONS = Collections.unmodifiableList(Arrays.asList(Region.of("af-south-1"), Region.of("ap-east-1"), Region.of("ap-northeast-1"), Region.of("ap-northeast-2"), Region.of("ap-northeast-3"), Region.of("ap-south-1"), Region.of("ap-southeast-1"), Region.of("ap-southeast-2"), Region.of("aws-global"), Region.of("ca-central-1"), Region.of("eu-central-1"), Region.of("eu-north-1"), Region.of("eu-south-1"), Region.of("eu-west-1"), Region.of("eu-west-2"), Region.of("eu-west-3"), Region.of("me-south-1"), Region.of("sa-east-1"), Region.of("us-east-1"), Region.of("us-east-1-fips"), Region.of("us-east-2"), Region.of("us-east-2-fips"), Region.of("us-west-1"), Region.of("us-west-1-fips"), Region.of("us-west-2"), Region.of("us-west-2-fips"), Region.of("cn-north-1"), Region.of("cn-northwest-1"), Region.of("us-gov-east-1"), Region.of("us-gov-east-1-fips"), Region.of("us-gov-west-1"), Region.of("us-gov-west-1-fips"), Region.of("us-iso-east-1"), Region.of("us-iso-west-1"), Region.of("us-isob-east-1"))); private static final List<ServicePartitionMetadata> PARTITIONS = Collections.unmodifiableList(Arrays.asList( new DefaultServicePartitionMetadata("aws", null), new DefaultServicePartitionMetadata("aws-cn", null), new DefaultServicePartitionMetadata("aws-us-gov", null), new DefaultServicePartitionMetadata("aws-iso", null), new DefaultServicePartitionMetadata("aws-iso-b", null))); private static final Map<ServiceEndpointKey, String> SIGNING_REGIONS_BY_REGION = ImmutableMap .<ServiceEndpointKey, String> builder() .put(ServiceEndpointKey.builder().region(Region.of("aws-global")).build(), "us-east-1") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1-fips")).build(), "us-east-1") .put(ServiceEndpointKey.builder().region(Region.of("us-east-2-fips")).build(), "us-east-2") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1-fips")).build(), "us-west-1") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2-fips")).build(), "us-west-2") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-east-1-fips")).build(), "us-gov-east-1") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-west-1-fips")).build(), "us-gov-west-1").build(); private static final Map<Pair<String, PartitionEndpointKey>, String> SIGNING_REGIONS_BY_PARTITION = ImmutableMap .<Pair<String, PartitionEndpointKey>, String> builder().build(); private static final Map<ServiceEndpointKey, String> DNS_SUFFIXES_BY_REGION = ImmutableMap .<ServiceEndpointKey, String> builder().build(); private static final Map<Pair<String, PartitionEndpointKey>, String> DNS_SUFFIXES_BY_PARTITION = ImmutableMap .<Pair<String, PartitionEndpointKey>, String> builder().build(); private static final Map<ServiceEndpointKey, String> HOSTNAMES_BY_REGION = ImmutableMap .<ServiceEndpointKey, String> builder() .put(ServiceEndpointKey.builder().region(Region.of("aws-global")).build(), "sts.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1")).tags(EndpointTag.of("fips")).build(), "sts-fips.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-1-fips")).build(), "sts-fips.us-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-2")).tags(EndpointTag.of("fips")).build(), "sts-fips.us-east-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-east-2-fips")).build(), "sts-fips.us-east-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1")).tags(EndpointTag.of("fips")).build(), "sts-fips.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-1-fips")).build(), "sts-fips.us-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2")).tags(EndpointTag.of("fips")).build(), "sts-fips.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-west-2-fips")).build(), "sts-fips.us-west-2.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-east-1")).tags(EndpointTag.of("fips")).build(), "sts.us-gov-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-east-1-fips")).build(), "sts.us-gov-east-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-west-1")).tags(EndpointTag.of("fips")).build(), "sts.us-gov-west-1.amazonaws.com") .put(ServiceEndpointKey.builder().region(Region.of("us-gov-west-1-fips")).build(), "sts.us-gov-west-1.amazonaws.com") .build(); private static final Map<Pair<String, PartitionEndpointKey>, String> HOSTNAMES_BY_PARTITION = ImmutableMap .<Pair<String, PartitionEndpointKey>, String> builder() .put(Pair.of("aws-us-gov", PartitionEndpointKey.builder().tags(EndpointTag.of("fips")).build()), "sts.{region}.{dnsSuffix}").build(); @Override public List<Region> regions() { return REGIONS; } @Override public List<ServicePartitionMetadata> servicePartitions() { return PARTITIONS; } @Override public URI endpointFor(ServiceEndpointKey key) { return ServiceMetadataUtils.endpointFor(ServiceMetadataUtils.hostname(key, HOSTNAMES_BY_REGION, HOSTNAMES_BY_PARTITION), ENDPOINT_PREFIX, key.region().id(), ServiceMetadataUtils.dnsSuffix(key, DNS_SUFFIXES_BY_REGION, DNS_SUFFIXES_BY_PARTITION)); } @Override public Region signingRegion(ServiceEndpointKey key) { return ServiceMetadataUtils.signingRegion(key, SIGNING_REGIONS_BY_REGION, SIGNING_REGIONS_BY_PARTITION); } }
3,099