SkilVaultSign inStart free

Catalogue / aws-java-sdk2-client-guide

aws-java-sdk2-client-guide

Older skill: source not recordedSignedSets up AWS SDK for Java 2.x the right way: dependency imports, credential providers, HTTP transports, call deadlines, retry budgets, client lifecycle, metrics, and bounded S3/DynamoDB operations, with isolated emulator verification. Use when the user says "add the AWS SDK to my Java project", "conf…
---
name: aws-java-sdk2-client-guide
description: >-
  Sets up AWS SDK for Java 2.x the right way: dependency imports, credential
  providers, HTTP transports, call deadlines, retry budgets, client lifecycle,
  metrics, and bounded S3/DynamoDB operations, with isolated emulator verification.
  Use when the user says "add the AWS SDK to my Java project", "configure S3 or
  DynamoDB clients", "fix AWS credentials in Java", "set SDK timeouts or retries",
  or "review our AWS client setup". Not for creating or mutating cloud resources,
  signing in to AWS, or installing dependencies without approval.
---

Own cloud clients, budgets and failure semantics

Core principles:

  • Keep configuration, authentication, transport, service requests, and lifecycle separate.
  • Reuse thread-safe service clients for the application's lifetime; close owned streams and shared transports at the correct ownership boundary.
  • Building a client authorizes nothing — a client builder is not permission to call the cloud.

Confirmation

  • Reading supplied local code and installed contracts needs no extra approval within the stated request.
  • Before credential resolution, sign-in, AWS/metadata/emulator calls, resource mutation, installation, container startup, metrics export, environment changes, or file writes beyond the stated scope, confirm: account/region/endpoint, resources, operation, data sent, cost, rollback.
  • Do not re-ask for unchanged, already authorized scope.
  • Default credential resolution may contact web-identity/SSO/container/instance services — building an approved client must never become an accidental production test.

Establish the project contract

Discover before coding:

  • Java runtime, build system, installed SDK version.
  • Synchronous or asynchronous workload; which services; deployment identity.
  • Deadlines, concurrency, streaming sizes, proxy/TLS requirements, telemetry destination.

SDK 2.x notes:

  • Packages, request builders, credentials, and lifecycle differ from 1.x — migrate call and exception semantics, don't swap imports blindly.
  • Service modules (s3, dynamodb, …) are explicit dependencies, not runtime discovery.

Versioning rules:

  • Pick an approved BOM version from the project lock or dependency cache; the examples use the property aws.sdk.version, never a stale “latest”.
  • Check Java minimums, retry strategy APIs, and native TLS compatibility against that actual release.
  • These examples were validated without network documentation — compile against the approved local dependency contract before deploying. SDK/Spring/emulator/native-TLS integrations stay unverified where their runtimes are absent.

Credentials and identity

  • The type is AwsCredentialsProvider — no invented generic CredentialsProvider exists.
  • The default chain generally checks: system properties → environment variables → web-identity configuration → shared profiles → container credentials → instance profile. Profiles may themselves involve SSO, roles, or processes.
  • Inspect installed behavior; never read secret files to discover credentials.
  • Region resolution is separate and should be explicit when scope matters; an endpoint override does not replace signing-region requirements.

Provider selection:

  • Environment/system-property/profile providers: deliberate, when required.
  • Deployments: web identity or workload IAM roles, with approved temporary credentials and rotation.
  • Human development: SSO-backed profiles.
  • Static credentials: only for explicitly isolated synthetic emulator tests — never real literals in source or logs.
  • Session credentials need their token; basic access keys are not equivalent.
  • Least privilege, encrypted TLS, audit policy, and rotation need a reviewed operational plan.

SSO workflow:

  1. Obtain the organization-provided account, role, start URL, and session region.
  2. Configure the chosen profile only with authorization.
  3. An approved aws sso login --profile PROFILE plus a caller-identity check contacts services — it is not offline validation.
  4. Prefer the profile provider plus installed sso/ssooidc modules; never assume an invented provider class or builder method.

Dependencies and alternatives

  • Resolve the version property from approved project configuration before any build.
  • Add only the service modules actually used: s3, dynamodb, lambda, ec2, rds are distinct modules — sdk-core alone provides none of their clients.
  • CloudWatch publishing needs its module plus an approved destination.
  • URLConnection and Netty are alternatives/extensions, not mandatory for a synchronous S3-only application.

Maven fragment:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>software.amazon.awssdk</groupId><artifactId>bom</artifactId>
      <version>${aws.sdk.version}</version><type>pom</type><scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
<dependencies>
  <dependency><groupId>software.amazon.awssdk</groupId><artifactId>s3</artifactId></dependency>
  <dependency><groupId>software.amazon.awssdk</groupId><artifactId>dynamodb</artifactId></dependency>
  <dependency><groupId>software.amazon.awssdk</groupId><artifactId>apache-client</artifactId></dependency>
  <dependency><groupId>software.amazon.awssdk</groupId><artifactId>netty-nio-client</artifactId></dependency>
  <dependency><groupId>software.amazon.awssdk</groupId><artifactId>url-connection-client</artifactId></dependency>
  <dependency><groupId>software.amazon.awssdk</groupId><artifactId>cloudwatch-metric-publisher</artifactId></dependency>
</dependencies>

Gradle equivalent — align SDK modules through a platform, never per-module versions. Optional native TLS needs a compatible approved Netty/tcnative platform and version, not an old fixed number:

def sdkVersion = providers.gradleProperty('awsSdkVersion').get()
dependencies {
    implementation platform("software.amazon.awssdk:bom:${sdkVersion}")
    implementation 'software.amazon.awssdk:s3'
    implementation 'software.amazon.awssdk:dynamodb'
    implementation 'software.amazon.awssdk:apache-client'
    implementation 'software.amazon.awssdk:netty-nio-client'
    implementation 'software.amazon.awssdk:url-connection-client'
    implementation 'software.amazon.awssdk:cloudwatch-metric-publisher'
}

Complete original client and operation modules

These Java 17-style modules build a small rehearsal-notes archive example:

  • Every helper is implemented here in full; nothing invokes a cloud service on construction (beyond a credential/transport provider's eventual authorized behavior).
  • Use them only after local compilation against the chosen SDK contract.

`CallBudget.java` validates deadlines and pool bounds. Derive values from application measurements — the example copies no universal throughput numbers.

package rehearsal.cloud;
import java.time.Duration;
public record CallBudget(Duration total, Duration attempt, Duration connect,
                         Duration io, int concurrency) {
    public CallBudget {
        for (Duration value : new Duration[] {total, attempt, connect, io})
            if (value == null || value.isNegative() || value.isZero())
                throw new IllegalArgumentException("Positive deadlines required");
        if (attempt.compareTo(total) >= 0 || connect.compareTo(attempt) >= 0
                || io.compareTo(attempt) >= 0 || concurrency <= 0)
            throw new IllegalArgumentException("Deadline hierarchy or concurrency invalid");
    }
}

`CloudClients.java` owns its provider, HTTP transport, and service clients:

  • A caller-owned .httpClient(...) is closed by this owner after all clients; a transport given via .httpClientBuilder(...) follows the SDK's managed ownership instead.
  • Never close a transport another service client still uses.
package rehearsal.cloud;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
public final class CloudClients implements AutoCloseable {
    private final DefaultCredentialsProvider credentials;
    private final SdkHttpClient transport;
    private final S3Client s3;
    private final DynamoDbClient dynamo;
    public CloudClients(String region, CallBudget budget) {
        if (region == null || region.isBlank()) throw new IllegalArgumentException("Region required");
        credentials = DefaultCredentialsProvider.builder().build();
        transport = ApacheHttpClient.builder().maxConnections(budget.concurrency())
            .connectionTimeout(budget.connect()).socketTimeout(budget.io()).build();
        var overrides = ClientOverrideConfiguration.builder().apiCallTimeout(budget.total())
            .apiCallAttemptTimeout(budget.attempt()).build();
        S3Client builtS3 = null;
        try {
            builtS3 = S3Client.builder().region(Region.of(region)).credentialsProvider(credentials)
                .overrideConfiguration(overrides).httpClient(transport).build();
            dynamo = DynamoDbClient.builder().region(Region.of(region)).credentialsProvider(credentials)
                .overrideConfiguration(overrides).httpClient(transport).build();
            s3 = builtS3;
        } catch (RuntimeException failure) {
            if (builtS3 != null) builtS3.close();
            transport.close(); credentials.close(); throw failure;
        }
    }
    public S3Client s3() { return s3; }
    public DynamoDbClient dynamo() { return dynamo; }
    @Override public void close() {
        try { dynamo.close(); }
        finally { try { s3.close(); }
            finally { try { transport.close(); } finally { credentials.close(); } } }
    }
}

Known limitation of that constructor: transport creation sits outside its cleanup block, so a provider or transport builder failure needs ownership review if the chosen provider allocates eagerly. A production factory should track every successful allocation and clean up all of them on failure — do not present this as proven fault coverage.

`NoteArchive.java` provides upload, bounded streaming download, and paged key traversal:

  • Bucket/prefix scope must be authorized externally; having a client establishes no object ownership.
  • The size bound limits allocation without trusting object metadata.
package rehearsal.cloud;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.function.Consumer;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
public final class NoteArchive {
    private final S3Client client;
    public NoteArchive(S3Client client) { this.client = java.util.Objects.requireNonNull(client); }
    public String upload(String bucket, String approvedKey, byte[] text) {
        var request = PutObjectRequest.builder().bucket(bucket).key(approvedKey)
            .contentType("text/plain; charset=utf-8").build();
        return client.putObject(request, RequestBody.fromBytes(text)).eTag();
    }
    public byte[] download(String bucket, String approvedKey, int maximumBytes) throws IOException {
        if (maximumBytes <= 0) throw new IllegalArgumentException("Positive bound required");
        var request = GetObjectRequest.builder().bucket(bucket).key(approvedKey).build();
        try (var response = client.getObject(request); var buffer = new ByteArrayOutputStream()) {
            byte[] chunk = new byte[4096]; int count;
            while ((count = response.read(chunk)) != -1) {
                if ((long) buffer.size() + count > maximumBytes) {

Preview shortened. The full SKILL.md is in the pack.