### Initialize SsoTokenProvider Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/tokenauth/README.md Example of building an SsoTokenProvider instance. ```java SsoTokenProvider ssoTokenProvider = SsoTokenProvider.builder() .startUrl("https://d-abc123.awsapps.com/start") .build(); ``` -------------------------------- ### Build the project Source: https://github.com/aws/aws-sdk-java-v2/blob/master/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/README.md Use Maven to clean and install the project dependencies and build the artifact. ```bash mvn clean install ``` -------------------------------- ### Configure Client with TokenProvider Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/tokenauth/README.md Example of setting a token provider chain on a service client builder. ```java SdkTokenProviderChain TOKEN_PROVIDER_CHAIN = DefaultSdkTokenProvderChain.create(); ServiceClient.builder() .region(REGION) .tokenProvider(TOKEN_PROVIDER_CHAIN) .build(); ``` -------------------------------- ### DefaultCredentialsProvider Initialization Example Source: https://github.com/aws/aws-sdk-java-v2/wiki/Favor-Static-Factory-Methods-Over-Constructors Demonstrates how to create instances of DefaultCredentialsProvider using both the `create()` static factory method and the `builder().build()` pattern. ```java public class DefaultCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { private static final DefaultCredentialsProvider DEFAULT_CREDENTIALS_PROVIDER = new DefaultCredentialsProvider(builder()); private DefaultCredentialsProvider(Builder builder) { this.providerChain = createChain(builder); } public static DefaultCredentialsProvider create() { return DEFAULT_CREDENTIALS_PROVIDER; } public static Builder builder() { return new Builder(); } public static final class Builder { // ... } // ... } // There are two ways to create new instance DefaultCredentialsProvider defaultCredentialsProvider1 = DefaultCredentialsProvider.create(); DefaultCredentialsProvider defaultCredentialsProvider2 = DefaultCredentialsProvider.builder().build; ``` -------------------------------- ### Create StaticTokenProvider Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/tokenauth/README.md Example of creating a provider that returns a static token. ```java StaticTokenProvider provider = StaticTokenProvider.create(bearerToken); ``` -------------------------------- ### Implement CloudWatchSdkMetricPublisherService Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/metrics/Design.md Example implementation of the SdkMetricPublisherService interface to enable CloudWatchMetricPublisher globally. ```java package software.amazon.awssdk.metrics.publishers.cloudwatch; public final class CloudWatchSdkMetricPublisherService implements SdkMetricPublisherService { @Override public MetricPublisher createMetricPublisher() { return CloudWatchMetricPublisher.create(); } } ``` -------------------------------- ### Class Documentation Example with Code Snippet Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/guidelines/javadoc-guidelines.md Example of Javadoc for a public API class, including a description, usage example with `@snippet`, and relevant `@see` tags. Favors external snippets for clarity. ```java /** * A high-level library for uploading and downloading objects to and from Amazon S3. * This can be created using the static {@link #builder()} method. * *

S3TransferManager provides a simplified API for efficient transfers between a local environment * and S3. It handles multipart uploads/downloads, concurrent transfers, progress tracking, and * automatic retries. * *

See {@link S3TransferManagerBuilder} for information on configuring an S3TransferManager. * *

Example usage: * {@snippet : * S3TransferManager transferManager = S3TransferManager.builder() * .s3ClientConfiguration(b -> b.credentialsProvider(credentialsProvider) * .region(Region.US_WEST_2)) * .build(); * * // Upload a file * UploadFileRequest uploadRequest = UploadFileRequest.builder() * .putObjectRequest(req -> req.bucket("bucket").key("key")) * .source(Paths.get("file.txt")) * .build(); * * FileUpload upload = transferManager.uploadFile(uploadRequest); * CompletedFileUpload uploadResult = upload.completionFuture().join(); * } * * @see S3TransferManagerBuilder */ @SdkPublicApi public interface S3TransferManager extends SdkAutoCloseable { ``` -------------------------------- ### Deploy the application Source: https://github.com/aws/aws-sdk-java-v2/blob/master/archetypes/archetype-lambda/src/test/resources/projects/apachehttpclient/reference/README.md Deploy the serverless application to AWS using the guided SAM deployment process. ```bash sam deploy --guided ``` -------------------------------- ### Example Usage of TransferListener Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/services/s3/transfermanager/listener/README.md An example demonstrating how to use the `TransferListener` to update a progress bar based on the percentage of bytes transferred. ```APIDOC ## Example Usage of TransferListener ### Description This example illustrates how to implement the `TransferListener` interface to monitor transfer progress and update a UI element, such as a progress bar. It specifically shows how to use the `bytesTransferred` callback to get the percentage of the transfer completed. ### Code Example ```java @Override public void bytesTransferred(Context.BytesTransferred context) { context.transferProgress().percentageTransferred().ifPresent(this::updateProgressBar); } ``` ### Explanation The `bytesTransferred` method is invoked as data is transferred. Inside this method, `context.transferProgress().percentageTransferred()` retrieves an `OptionalDouble` representing the completion percentage. If the percentage is present (i.e., the total transfer size is known), the `updateProgressBar` method is called with that value. ``` -------------------------------- ### Install Graph Script Dependencies Source: https://github.com/aws/aws-sdk-java-v2/blob/master/test/s3-benchmarks/README.md Install the necessary Python packages for generating benchmark graphs. ```bash pip install plotly ``` ```bash pip install kaleido ``` -------------------------------- ### Configure SSO Profile Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/tokenauth/README.md Example configuration for an SSO profile in the shared SDK configuration file. ```ini [profile sono] sso_start_url = https://sono.aws sso_region = us-east-1 ``` -------------------------------- ### Method Documentation Example with Code Snippet Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/guidelines/javadoc-guidelines.md Example of Javadoc for a public API method, detailing its purpose, usage with `@snippet`, parameters, return value, and potential exceptions. The snippet demonstrates API usage. ```java /** * Uploads a file from a specified path to an S3 bucket. * *

This method handles large files efficiently by using multipart uploads when appropriate. * Progress can be tracked through the returned {@link FileUpload} object. * *

Example: * {@snippet : * UploadFileRequest request = UploadFileRequest.builder() * .putObjectRequest(r -> r.bucket("bucket-name").key("key")) * .source(Paths.get("my-file.txt")) * .build(); * * FileUpload upload = transferManager.uploadFile(request); * CompletedFileUpload completedUpload = upload.completionFuture().join(); * } * * @param request Object containing the bucket, key, and file path for the upload * @return A {@link FileUpload} object to track the upload and access the result * @throws S3Exception If any errors occur during the S3 operation * @throws SdkClientException If any client-side errors occur * @throws IOException If the file cannot be read */ FileUpload uploadFile(UploadFileRequest request); ``` -------------------------------- ### Static Factory Method vs. Constructor Example Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/guidelines/FavorStaticFactoryMethods.md Illustrates the difference in readability between using a static factory method with a descriptive name and a standard constructor. ```java FoobarProvider defaultProvider = FoobarProvider.defaultFoobarProvider(); ``` ```java FoobarProvider defaultProvider = new FoobarProvider(); ``` -------------------------------- ### Execute Presigned Request with DynamoDbClient Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/presigners/README.md Conceptual example demonstrating how a presigned request might be executed using a service client. ```Java DynamoDbClient dynamo = DynamoDbClient.create(); PresignedPutItemRequest presignedRequest = dynamo.presigner().presignPutItem(...); PutItemResponse response = dynamo.putItem(presignedRequest); ``` -------------------------------- ### Transcribe startStreamTranscription with Reactive Streams Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/event-streaming/alternate-syntax/README.md Example demonstrating how to use the Transcribe streaming client with RxJava for handling audio input and transcription output. ```Java try (TranscribeStreamingAsyncClient client = TranscribeStreamingAsyncClient.create(); // Create the connection to transcribe and send the initial request message RunningStartStreamTranscription transcription = client.startStreamTranscription(r -> r.languageCode(LanguageCode.EN_US) .mediaEncoding(MediaEncoding.PCM) .mediaSampleRateHertz(16_000))) { // Use RxJava to create the audio stream to be transcribed Publisher audioPublisher = Bytes.from(audioFile) .map(SdkBytes::fromByteArray) .map(bytes -> AudioEvent.builder().audioChunk(bytes).build()) .cast(AudioStream.class); // Begin sending the audio data to transcribe, asynchronously transcription.writeAll(audioPublisher); // Get a publisher for the transcription Publisher transcriptionPublisher = transcription.responseEventPublisher(); // Use RxJava to log the transcription Flowable.fromPublisher(transcriptionPublisher) .filter(e -> e instanceof TranscriptEvent) .cast(TranscriptEvent.class) .forEach(e -> System.out.println(e.transcript().results())); // Wait for the operation to complete transcription.completionFuture().join(); } ``` -------------------------------- ### Implement ProgressListener Callback (v1) Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/services/s3/transfermanager/listener/README.md Example implementation of a progress listener callback for updating a progress bar. ```java @Override public void progressChanged(ProgressEvent e) { double pct = e.getBytesTransferred() * 100.0 / e.getBytes(); eraseProgressBar(); printProgressBar(pct); } ``` -------------------------------- ### Run unit tests with Maven Source: https://github.com/aws/aws-sdk-java-v2/wiki/Working-on-the-SDK Executes the unit test suite during the standard Maven install lifecycle. ```sh # runs the unit tests mvn install ``` -------------------------------- ### Static Factory Method vs Constructor Example Source: https://github.com/aws/aws-sdk-java-v2/wiki/Favor-Static-Factory-Methods-Over-Constructors Illustrates the difference in readability between using a static factory method with a meaningful name and a standard constructor. ```java // With static factory method, giving a hint that a foobar provider with default settings is being created. FoobarProvider defaultProvider = FoobarProvider.defaultFoobarProvider(); // With constructor FoobarProvider defaultProvider = new FoobarProvider(); ``` -------------------------------- ### Run Mock Tests with Maven Source: https://github.com/aws/aws-sdk-java-v2/blob/master/test/module-path-tests/README.md Execute mock tests for XML/JSON protocol sync/async clients using mock HTTP clients. Ensure Maven is installed and the project is built. ```bash mvn clean package mvn exec:exec -P mock-tests ``` -------------------------------- ### Transcribe startStreamTranscription without Reactive Streams Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/event-streaming/alternate-syntax/README.md Example demonstrating how to use the Transcribe streaming client using standard Java IO and asynchronous read callbacks. ```Java try (TranscribeStreamingAsyncClient client = TranscribeStreamingAsyncClient.create(); // Create the connection to transcribe and send the initial request message RunningStartStreamTranscription transcription = client.startStreamTranscription(r -> r.languageCode(LanguageCode.EN_US) .mediaEncoding(MediaEncoding.PCM) .mediaSampleRateHertz(16_000))) { // Asynchronously log response transcription events, as we receive them transcription.readAll(TranscriptEvent.class, e -> System.out.println(e.transcript().results())); // Read from our audio file, 4 KB at a time try (InputStream reader = Files.newInputStream(audioFile)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = reader.read(buffer)) != -1) { if (bytesRead > 0) { // Write the 4 KB we read to transcribe, and wait for the write to complete ``` -------------------------------- ### Run Integration Tests with Maven Source: https://github.com/aws/aws-sdk-java-v2/blob/master/test/module-path-tests/README.md Execute integration tests for service clients using UrlConnectionHttpClient, ApacheHttpClient, and NettyNioAsyncHttpClient. Ensure Maven is installed and the project is built. ```bash mvn clean package mvn exec:exec -P integ-tests ``` -------------------------------- ### Build Native Image with Maven Source: https://github.com/aws/aws-sdk-java-v2/blob/master/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/README.md Command to build a native image of the Maven project using GraalVM. Requires 'native-image' to be installed. ```bash mvn clean package -P native-image ``` -------------------------------- ### Record Business Metrics in HttpChecksumStage Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/guidelines/business-metrics-guidelines.md This example demonstrates recording business metrics after a checksum feature has been finalized within the HttpChecksumStage. This ensures metrics are associated with confirmed feature usage. ```java // Example from HttpChecksumStage - showing where business metrics are recorded @Override public SdkHttpFullRequest.Builder execute(SdkHttpFullRequest.Builder request, RequestExecutionContext context) throws Exception { // ... feature resolution logic ... SdkHttpFullRequest.Builder result = processChecksum(request, context); // Record business metrics after feature is finalized recordChecksumBusinessMetrics(context.executionAttributes()); return result; } ``` -------------------------------- ### Build and Execute Commands Source: https://github.com/aws/aws-sdk-java-v2/blob/master/archetypes/archetype-app-quickstart/src/test/resources/projects/urlhttpclient/reference/README.md Commands for building the project, creating a native image, and executing the resulting binary. ```bash mvn clean package ``` ```bash mvn clean package -P native-image ``` ```bash target/test-apache-artifact ``` -------------------------------- ### Quick Build All Modules (Linux) Source: https://github.com/aws/aws-sdk-java-v2/blob/master/README.md Builds all modules of the SDK from source on Linux, skipping tests and checks for a faster build. ```shell ./mvnw clean install -P quick ``` -------------------------------- ### Instantiate Sync and Async Batch Managers from Existing Clients Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/batch-manager/Design.md Demonstrates how to obtain sync and async batch managers from existing SqsClient and SqsAsyncClient instances, respectively. ```java // Sync Batch Manager SqsClient sqs = SqsClient.create(); SqsBatchManager sqsBatch = sqs.batchManager(); // Async Batch Manager SqsAsyncClient sqsAsync = SqsAsyncClient.create(); SqsAsyncBatchManager sqsAsyncBatch = sqsAsync.batchManager(); ``` -------------------------------- ### Initialize Client Configuration Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/LaunchChangelog.md Comparison of client configuration initialization between SDK versions. ```java ClientConfiguration clientConfig = new ClientConfiguration() ``` ```java ClientOverrideConfiguration.Builder overrideConfig = ClientOverrideConfiguration.builder() ``` -------------------------------- ### Define AttributeValue structure Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/tagged-unions/README.md Example of the existing structure for a tagged union in DynamoDB. ```java class AttributeValue { private String s; private String n; private SdkBytes b; private List ss; private List ns; private List bs; // ... } ``` -------------------------------- ### Build SDK Standard Benchmarks Source: https://github.com/aws/aws-sdk-java-v2/blob/master/test/sdk-standard-benchmarks/README.md Builds the SDK standard benchmarks and all upstream dependencies. Only needed on the first build or after upstream changes. ```bash mvn clean install -P quick -pl :sdk-standard-benchmarks --am ``` -------------------------------- ### Define Waiter Interface Methods Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/waiters/README.md Example of default interface methods for waiter operations. ```Java default CompletableFuture> waitUntilTableExists(Consumer describeTableRequest) { return waitUntilTableExists(DescribeTableRequest.builder().applyMutation(describeTableRequest).build()); } // other waiter operations omitted // ... interface Builder { Builder client(DynamoDbAsyncClient client); Builder scheduledExecutorService(ScheduledExecutorService executorService); Builder overrideConfiguration(WaiterOverrideConfiguration overrideConfiguration); DynamoDbAsyncWaiter build(); } } ``` -------------------------------- ### Build All Modules (Windows) Source: https://github.com/aws/aws-sdk-java-v2/blob/master/README.md Builds all modules of the SDK from source on Windows using the Maven wrapper. ```shell ./mvnw.cmd clean install ``` -------------------------------- ### Build Project with Maven Source: https://github.com/aws/aws-sdk-java-v2/blob/master/archetypes/archetype-app-quickstart/src/test/resources/projects/apachehttpclient/reference/README.md Standard command to clean and package the Maven project. ```bash mvn clean package ``` -------------------------------- ### Build and Execute Native Image Tests Source: https://github.com/aws/aws-sdk-java-v2/blob/master/test/sdk-native-image-test/README.md Commands to compile the project, build the native image, and execute the resulting binary. ```bash mvn clean install -pl :sdk-native-image-test -P quick --am mvn clean install -pl :bom-internal,:bom cd test/sdk-native-image-test # build the image mvn clean package -P native-image # execute the image target/sdk-native-image-test ``` -------------------------------- ### HTTP Bearer Authorization Request Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/tokenauth/README.md Example of an HTTP request using the Bearer authorization header. ```http GET /resource HTTP/1.1 Host: server.example.com Authorization: Bearer mF_9.B5f-4.1JqM ``` -------------------------------- ### Configure Asynchronous DynamoDbAsyncClient Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/LaunchChangelog.md Demonstrates setting up an asynchronous DynamoDB client using NettyNioAsyncHttpClient, ClientOverrideConfiguration, and ClientAsyncConfiguration. ```Java NettyNioAsyncHttpClient.Builder httpClientBuilder = NettyNioAsyncHttpClient.builder(); ClientOverrideConfiguration.Builder overrideConfig = ClientOverrideConfiguration.builder(); ClientAsyncConfiguration.Builder asyncConfig = ClientAsyncConfiguration.builder(); DynamoDbAsyncClient client = DynamoDbAsyncClient.builder() .httpClientBuilder(httpClientBuilder) .overrideConfiguration(overrideConfig.build()) .asyncConfiguration(asyncConfig.build()) .build(); ``` -------------------------------- ### Build Module Locally for Development Source: https://github.com/aws/aws-sdk-java-v2/blob/master/v2-migration/README.md Execute this command to build the module locally, including specific sub-modules, for fast development cycles. The '-P quick --am' flags optimize the build process. ```bash mvn clean install -pl :bom-internal,:bom,:v2-migration -P quick --am ``` -------------------------------- ### GET /header(String name) Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/guidelines/javadoc-guidelines.md Retrieves the value of a specified header. This method is marked as deprecated. ```APIDOC ## GET header(String name) ### Description Returns the value of the specified header. This method provides direct access to the header value. ### Parameters #### Path Parameters - **name** (String) - Required - The name of the header ### Note This method is @Deprecated. Use firstMatchingHeader(String) instead, as it properly handles headers with multiple values. ``` -------------------------------- ### Generate Project via Maven Archetype Source: https://github.com/aws/aws-sdk-java-v2/blob/master/archetypes/archetype-app-quickstart/README.md Use these commands to bootstrap a new project. Interactive mode prompts for configuration, while batch mode allows defining parameters directly. ```bash mvn archetype:generate \ -DarchetypeGroupId=software.amazon.awssdk \ -DarchetypeArtifactId=archetype-app-quickstart \ -DarchetypeVersion=2.x ``` ```bash mvn archetype:generate \ -DarchetypeGroupId=software.amazon.awssdk \ -DarchetypeArtifactId=archetype-app-quickstart \ -DarchetypeVersion=2.x \ -DgroupId=com.test \ -DnativeImage=true \ -DhttpClient=apache-client \ -DartifactId=sample-project \ -Dservice=s3 \ -DinteractiveMode=false \ -DcredentialProvider=default ``` -------------------------------- ### Build SDK Standard Benchmarks (Subsequent Builds) Source: https://github.com/aws/aws-sdk-java-v2/blob/master/test/sdk-standard-benchmarks/README.md Builds the SDK standard benchmarks after the initial build. Upstream dependencies are not rebuilt. ```bash mvn install -P quick -pl :sdk-standard-benchmarks ``` -------------------------------- ### Instantiate Sync and Async Batch Managers using Builders Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/batch-manager/Design.md Shows how to create sync and async batch managers using their respective builders, allowing for configuration overrides. ```java // Sync Batch Manager SqsBatchManager sqsBatch = SqsBatchManager.builder() .client(client) .overrideConfiguration(newConfig) .build(); // Async Batch Manager SqsAsyncBatchManager sqsBatch = SqsAsyncBatchManager.builder() .client(asyncClient) .overrideConfiguration(newConfig) .build(); ``` -------------------------------- ### Implement progress update in TransferListener Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/services/s3/transfermanager/listener/README.md Example of updating a progress bar using the percentageTransferred method within a TransferListener. ```java @Override public void bytesTransferred(Context.BytesTransferred context) { context.transferProgress().percentageTransferred().ifPresent(this::updateProgressBar); } ``` -------------------------------- ### Define PresignedUrlDownloadRequest Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/presignedURL-Get/Design.md The request object used for presigned URL GET operations, containing the URL and optional range. ```java /** * Request object for presigned URL GET operations. */ @SdkPublicApi @ThreadSafe public final class PresignedUrlDownloadRequest implements ToCopyableBuilder { private final URL presignedUrl; private final String range; // Standard getters: presignedUrl(), range() // Standard builder methods: builder(), toBuilder() // Standard Builder class with presignedUrl(), range() setter methods } ``` -------------------------------- ### Perform Async Pre-signed URL Download Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/presignedURL-Get/Design.md Configure a download request and execute it using the extension. ```java // Create presigned URL request PresignedUrlDownloadRequest request = PresignedUrlDownloadRequest.builder() .presignedUrl(presignedUrl) .range("range=0-1024") .build(); // Async usage S3AsyncClient s3Client = S3AsyncClient.create(); AsyncPresignedUrlExtension presignedUrlExtension = s3Client.presignedUrlExtension(); CompletableFuture response = presignedUrlExtension.getObject(request, AsyncResponseTransformer.toBytes()); ``` -------------------------------- ### Handle CompletableFuture results Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/guidelines/async-programming-guidelines.md Prefer non-blocking callbacks over blocking methods like get() to maintain asynchronous execution flow. ```java // Avoid when possible - blocks the current thread String result = future.get(); // Better - use callbacks future.thenAccept(result -> processResult(result)); ``` -------------------------------- ### DefaultCredentialsProvider Initialization Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/guidelines/FavorStaticFactoryMethods.md Demonstrates the implementation of static factory methods `create()` and `builder()` for initializing DefaultCredentialsProvider. Use `create()` for a default instance and `builder()` for custom configurations. ```java public class DefaultCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { private static final DefaultCredentialsProvider DEFAULT_CREDENTIALS_PROVIDER = new DefaultCredentialsProvider(builder()); private DefaultCredentialsProvider(Builder builder) { this.providerChain = createChain(builder); } public static DefaultCredentialsProvider create() { return DEFAULT_CREDENTIALS_PROVIDER; } public static Builder builder() { return new Builder(); } public static final class Builder { // ... } // ... } ``` ```java DefaultCredentialsProvider defaultCredentialsProvider1 = DefaultCredentialsProvider.create(); ``` ```java DefaultCredentialsProvider defaultCredentialsProvider2 = DefaultCredentialsProvider.builder().build; ``` -------------------------------- ### Configure Synchronous DynamoDbClient Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/LaunchChangelog.md Demonstrates setting up a synchronous DynamoDB client using ApacheHttpClient and ClientOverrideConfiguration. ```Java ProxyConfiguration.Builder proxyConfig = ProxyConfiguration.builder(); ApacheHttpClient.Builder httpClientBuilder = ApacheHttpClient.builder() .proxyConfiguration(proxyConfig.build()); ClientOverrideConfiguration.Builder overrideConfig = ClientOverrideConfiguration.builder(); DynamoDbClient client = DynamoDbClient.builder() .httpClientBuilder(httpClientBuilder) .overrideConfiguration(overrideConfig.build()) .build(); ``` -------------------------------- ### Example Cross-Language Output JSON Structure Source: https://github.com/aws/aws-sdk-java-v2/blob/master/test/sdk-standard-benchmarks/README.md Illustrates the structure of the output JSON produced by the JmhResultConverter, used for cross-language benchmark comparisons. ```json { "metadata": { "lang": "Java", "software": [["smithy-java", "TODO"], ["AWS SDK for Java", "TODO"]], "os": "TODO", "instance": "TODO", "precision": "-9" }, "serde_benchmarks": [ { "id": "awsJson1_0_GetItemInput_Baseline", "n": 5, "mean": 1234, "p50": 1200, "p90": 1500, "p95": 1600, "p99": 1800, "std_dev": 150 } ] } ``` -------------------------------- ### Build All Modules (Linux) Source: https://github.com/aws/aws-sdk-java-v2/blob/master/README.md Builds all modules of the SDK from source on Linux using Maven wrapper. ```shell ./mvnw clean install ``` -------------------------------- ### Run All Benchmarks with Custom Iterations Source: https://github.com/aws/aws-sdk-java-v2/blob/master/test/http-client-benchmarks/README.md Executes all benchmarks with specified warmup, measurement iterations, and fork count. ```bash java -jar target/http-client-benchmarks.jar -wi 3 -i 3 -f 1 ``` -------------------------------- ### Configure AtomicCounter Extension Source: https://github.com/aws/aws-sdk-java-v2/blob/master/services-custom/dynamodb-enhanced/README.md Tag a Long attribute with @DynamoDbAtomicCounter to enable automatic incrementing. Counters start at 0 and increment by 1 by default. ```java @DynamoDbAtomicCounter public Long getCounter() {...}; public void setCounter(Long counter) {...}; ``` ```java .addAttribute(Integer.class, a -> a.name("counter") .getter(Customer::getCounter) .setter(Customer::setCounter) // Apply the 'atomicCounter' tag to the attribute with start and increment values .tags(atomicCounter(10L, 5L)) ``` -------------------------------- ### Build Benchmark Module Source: https://github.com/aws/aws-sdk-java-v2/blob/master/test/http-client-benchmarks/README.md Builds the benchmark module using Maven. ```bash mvn clean install -P quick -pl :http-client-benchmarks --am ``` -------------------------------- ### Javadoc Formatting Example Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/guidelines/javadoc-guidelines.md Demonstrates the correct use of `

` tags for paragraphs in Javadoc. The first paragraph does not use a `

` tag, while subsequent paragraphs do. ```java /** * First paragraph with no

tag. * *

Second paragraph starts with a

tag. * *

Third paragraph also starts with a

tag. */ ``` -------------------------------- ### Presign GetObject using Option 2 (Core Input Shape) Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/presigners/README.md Shows the alternative approach using a parameterized core input shape, which results in smaller jar sizes but less intuitive builder patterns. ```Java s3.presignGetObject(PresignRequest.builder(GetObjectRequest.builder().bucket("bucket").key("key").build()) .signatureDuration(Duration.ofMinutes(15)) .build()); ``` ```Java s3.presignGetObject(GetObjectRequest.builder().bucket("bucket").key("key").build(), r -> r.signatureDuration(Duration.ofMinutes(15))); ``` -------------------------------- ### Get Table with Enhanced Client Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/services/dynamodb/high-level-library/UpdateExpression.md Shows how to obtain a DynamoDbTable instance from the configured enhanced client, ready for operations using the defined schema and extensions. ```java DynamoDbTable table = enhancedClient.table("some-table-name"), TableSchema.fromClass(SomeRecord.class)); ``` -------------------------------- ### Run S3 Benchmark Harness Source: https://github.com/aws/aws-sdk-java-v2/blob/master/test/s3-benchmarks/README.md Build the benchmark JAR and execute download or upload operations with specified parameters. ```bash # Build the JAR mvn clean install -pl :s3-benchmarks -P quick --am # download java -jar s3-benchmarks.jar --bucket=bucket --key=key -file=/path/to/destionfile/ --operation=download --partSizeInMB=20 --maxThroughput=100.0 # upload java -jar s3-benchmarks.jar --bucket=bucket --key=key -file=/path/to/sourcefile/ --operation=upload --partSizeInMB=20 --maxThroughput=100.0 ``` -------------------------------- ### Run All Benchmarks with Executable JAR Source: https://github.com/aws/aws-sdk-java-v2/blob/master/test/sdk-benchmarks/README.md Execute all benchmarks with specified warmup and measurement iterations. Adjust iteration counts for reliability. ```bash java -jar target/benchmarks.jar -wi 3 -i 3 -f 1 ``` -------------------------------- ### Start Stream Transcription with Reconnects (Option 1) Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/event-streaming/reconnect/README.md This method enables automatic reconnects for streaming operations. Use this when you want transparent reconnection handling for network errors. ```Java try (TranscribeStreamingAsyncClient client = TranscribeStreamingAsyncClient.create()) { // ... // Current method (behavior is unchanged) client.startStreamTranscription(audioMetadata, audioStream, responseHandler); // New method that transparently reconnects on network errors (name to be bikeshed) client.startStreamTranscriptionWithReconnects(audioMetadata, audioStream, responseHandler); // ... } ``` -------------------------------- ### Configure Client Extensions Source: https://github.com/aws/aws-sdk-java-v2/blob/master/services-custom/dynamodb-enhanced/README.md Load custom extensions during client initialization; order of specification determines execution sequence. ```java DynamoDbEnhancedClientExtension versionedRecordExtension = VersionedRecordExtension.builder().build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(dynamoDbClient) .extensions(versionedRecordExtension, verifyChecksumExtension) .build(); ``` -------------------------------- ### DynamoDB Waiter Instantiation Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/waiters/README.md Demonstrates how to instantiate DynamoDB waiters, both synchronous and asynchronous, using a service client or a waiter builder. ```APIDOC ## Instantiation This class can be instantiated from an existing service client or builder - from an existing service client ```Java // sync waiter DynamoDbClient dynamo = DynamoDbClient.create(); DynamoDbWaiter dynamoWaiter = dynamo.waiter(); // async waiter DynamoDbClient dynamoAsync = DynamoDbAsyncClient.create(); DynamoDbAsyncWaiter dynamoAsyncWaiter = dynamoAsync.waiter(); ``` - from waiter builder ```java // sync waiter DynamodbWaiter waiter = DynamoDbWaiter.builder() .client(client) .overrideConfiguration(p -> p.maxAttempts(10)) .build(); // async waiter DynamoDbAsyncWaiter asyncWaiter = DynamoDbAsyncWaiter.builder() .client(asyncClient) .overrideConfiguration(p -> p.maxAttempts(10)) .build(); ``` ``` -------------------------------- ### Start Stream Transcription with Default Reconnects (Option 2) Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/event-streaming/reconnect/README.md The default behavior for streaming operations is to transparently reconnect on network errors. This code shows the standard client usage. ```Java // Current method is updated to transparently reconnect on network errors try (TranscribeStreamingAsyncClient client = TranscribeStreamingAsyncClient.create()) { // ... client.startStreamTranscription(audioMetadata, audioStream, responseHandler); // ... } ``` -------------------------------- ### Run Benchmarks via Maven Exec Source: https://github.com/aws/aws-sdk-java-v2/blob/master/test/http-client-benchmarks/README.md Invokes the UnifiedBenchmarkRunner main method using Maven. ```bash mvn clean install -P quick -pl :http-client-benchmarks --am mvn clean install -pl :bom-internal cd test/http-client-benchmarks mvn exec:exec ``` -------------------------------- ### Configure and Run Generic Waiter Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/waiters/README.md Use the generic Waiter builder to define custom success, failure, and retry conditions, and polling configurations. This example shows synchronous and asynchronous execution. ```java Waiter waiter = Waiter.builder(DescribeTableResponse.class) .addAcceptor(WaiterAcceptor.successAcceptor(r -> r.table().tableStatus().equals(TableStatus.ACTIVE))) .addAcceptor(WaiterAcceptor.retryAcceptor(t -> t instanceof ResourceNotFoundException)) .addAcceptor(WaiterAcceptor.errorAcceptor(t -> t instanceof InternalServerErrorException)) .overrideConfiguration(p -> p.maxAttemps(20).backoffStrategy(BackoffStrategy.defaultStrategy())) .build(); // run synchronously WaiterResponse response = waiter.run(() -> client.describeTable(describeTableRequest)); // run asynchronously CompletableFuture> responseFuture = waiter.runAsync(() -> asyncClient.describeTable(describeTableRequest)); ``` -------------------------------- ### Start Stream Transcription with Disabled Reconnects (Option 2) Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/event-streaming/reconnect/README.md To disable automatic reconnects, use the client builder to override the configuration and set the reconnect policy to none. This is useful for specific use-cases that require explicit control over session management. ```Java // New client configuration option can be used to configure reconnect behavior try (TranscribeStreamingAsyncClient client = TranscribeStreamingAsyncClient.builder() .overrideConfiguration(c -> c.reconnectPolicy(ReconnectPolicy.none())) .build()) { // ... client.startStreamTranscription(audioMetadata, audioStream, responseHandler); // ... } ``` -------------------------------- ### Compare Batching Implementation Options Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/design/core/batch-manager/Design.md Comparison of different architectural approaches for implementing batching features in the SDK. ```java SqsAsyncClient sqsAsync = SqsAsyncClient.builder().build(); // Option 1 sqsAsync.automaticSendMessageBatch(message1); sqsAsync.automaticSendMessageBatch(message1); // Option 2 SqsAsyncBatchManager batchManager = SqsAsyncBatchManager .builder() .client(sqsAsync) .build() batchManager.sendMessage(message1); batchManager.sendMessage(message2); // Option 3 SqsAsyncBatchManager batchManager = SqsAsyncBatchManager.batchManager() batchManager.sendMessage(message1); batchManager.sendMessage(message2); ``` -------------------------------- ### Configure HTTP Client Builders Source: https://github.com/aws/aws-sdk-java-v2/blob/master/docs/LaunchChangelog.md Initialize builders for Apache (Sync) or Netty (Async) HTTP clients. ```java ApacheHttpClient.Builder httpClientBuilder = ApacheHttpClient.builder() ``` ```java NettyNioAsyncHttpClient.Builder httpClientBuilder = NettyNioAsyncHttpClient.builder() ``` -------------------------------- ### Define Collection Configuration Methods Source: https://github.com/aws/aws-sdk-java-v2/wiki/Client-Configuration Demonstrates the required pattern for collection fields, including plural naming and singular 'add' methods for individual items. ```Java public interface Builder { Builder options(List options); Builder addOption(String option); Builder headers(Map headers); Builder addHeader(String key, String value); } ``` -------------------------------- ### Run Specific Benchmark with Executable JAR Source: https://github.com/aws/aws-sdk-java-v2/blob/master/test/sdk-benchmarks/README.md Use this command to execute a single benchmark class. Ensure the JAR is built first. ```bash mvn clean install -P quick -pl :sdk-benchmarks --am # Run specific benchmark java -jar target/benchmarks.jar ApacheHttpClientBenchmark ```