

# Getting started with the AWS SDK for Java 2.x
<a name="get-started"></a>

The sections in this topic walk you through the essential steps to begin building Java applications that connect to AWS service. The sections cover setting up your development environment with Java and build tools like Maven or Gradle, configuring secure authentication to AWS, and creating your first working application through a hands-on tutorial. This beginner-friendly topic serves as your entry point to AWS development with Java, providing the foundation you'll need before exploring more advanced features.

**Contents**
+ [

# Setting up the AWS SDK for Java 2.x
](setup.md)
  + [

## Setup overview
](setup.md#setup-overview)
  + [

# Install Java and a build tool to work with the AWS SDK for Java 2.x
](setup-java-buildtool.md)
  + [

# Set up an Apache Maven project that uses the AWS SDK for Java 2.x
](setup-project-maven.md)
    + [

## Prerequisites
](setup-project-maven.md#prerequisitesmaven)
    + [

## Create a Maven project
](setup-project-maven.md#create-maven-project)
    + [

## Configure the Java compiler for Maven
](setup-project-maven.md#configure-maven-compiler)
    + [

## Declare the SDK as a dependency
](setup-project-maven.md#sdk-as-dependency)
    + [

## Set dependencies for SDK modules
](setup-project-maven.md#modules-dependencies)
      + [

### Build the entire SDK into your project
](setup-project-maven.md#build-the-entire-sdk-into-your-project)
    + [

## Build your project
](setup-project-maven.md#build-project)
  + [

# Set up a Gradle project that uses the AWS SDK for Java 2.x
](setup-project-gradle.md)
  + [

# Set up a GraalVM Native Image project that uses the AWS SDK for Java 2.x
](setup-project-graalvm.md)
    + [

## Prerequisites
](setup-project-graalvm.md#setup-graalvmnativeimage-prereq)
    + [

## Create a project using the archetype
](setup-project-graalvm.md#setup-graalvmnativeimage-project)
    + [

## Build a native image
](setup-project-graalvm.md#build-graalvmnativeimage-project)
+ [

# Authenticating with AWS using the AWS SDK for Java 2.x
](get-started-auth.md)
  + [

## Set up for authentication
](get-started-auth.md#setup-auth)
    + [

### 1. Local development using short-term credentials
](get-started-auth.md#setup-login)
    + [

### 2. Setup for single sign-on access for the SDK
](get-started-auth.md#setup-credentials)
    + [

### 3. Sign in using the AWS CLI
](get-started-auth.md#setup-login-sso)
  + [

## Additional authentication options
](get-started-auth.md#setup-additional)
+ [

# Creating a simple application using the AWS SDK for Java 2.x
](get-started-tutorial.md)
  + [

## Step 1: Set up for this tutorial
](get-started-tutorial.md#get-started-setup)
  + [

## Step 2: Create the project
](get-started-tutorial.md#get-started-projectsetup)
  + [

## Step 3: Write the code
](get-started-tutorial.md#get-started-code)
  + [

## Step 4: Build and run the application
](get-started-tutorial.md#get-started-run)
    + [

### Success
](get-started-tutorial.md#get-started-success)
    + [

### Cleanup
](get-started-tutorial.md#cleanup)
  + [

## Next steps
](get-started-tutorial.md#get-started-next)

# Setting up the AWS SDK for Java 2.x
<a name="setup"></a>

This section provides information about how to set up your development environment and projects to use the AWS SDK for Java 2.x.

## Setup overview
<a name="setup-overview"></a>

To successfully develop applications that access AWS services using the AWS SDK for Java, the following conditions are required:
+ The Java SDK must have access to credentials to [authenticate requests](get-started-auth.md#setup-auth) on your behalf.
+ The [permissions of the IAM role](https://docs.aws.amazon.com/singlesignon/latest/userguide/permissionsetsconcept.html) configured for the SDK must allow access to the AWS services that your application requires. The permissions associated with the **PowerUserAccess** AWS managed policy are sufficient for most development needs.
+ A development environment with the following elements:
  + [Shared configuration files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) that are set up in at least one of the following ways:
    + The `config` file contains [IAM Identity Center single sign-on settings](get-started-auth.md#setup-credentials) so that the SDK can get AWS credentials.
    + The `credentials` file contains temporary credentials.
  + An [installation of Java 8](setup-java-buildtool.md) or later.
  + A [build automation tool ](setup-java-buildtool.md)such as [Maven](https://maven.apache.org/download.cgi) or [Gradle](https://gradle.org/install/).
  + A text editor to work with code.
  + (Optional, but recommended) An IDE (integrated development environment) such as [IntelliJ IDEA](https://www.jetbrains.com/idea/download/#section=windows), [Eclipse](https://www.eclipse.org/ide/), or [NetBeans](https://netbeans.apache.org/front/main/download/index.html).

    If you use IntelliJ IDEA, you can also add the [AWS Toolkit for IntelliJ IDEA](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) to integrate AWS services directly into the IDE to help you streamline development.
+ An active AWS access portal session when you are ready to run your application. You use the AWS Command Line Interface to [initiate the sign-in process](get-started-auth.md#setup-login-sso) to IAM Identity Center's AWS access portal.

**Important**  
The instructions in this setup section assume that you or organization uses IAM Identity Center. If your organization uses an external identity provider that works independently of IAM Identity Center, find out how you can get temporary credentials for the SDK for Java to use. Follow [these instructions](credentials-temporary.md#credentials-temporary-from-portal) to add temporary credentials to the `~/.aws/credentials` file.  
If your identity provider adds temporary credentials automatically to the `~/.aws/credentials` file, make sure that the profile name is `[default]` so that you do not need to provide a profile name to the SDK or AWS CLI.

# Install Java and a build tool to work with the AWS SDK for Java 2.x
<a name="setup-java-buildtool"></a>

You need the following Java development environment requirements to work with SDK for Java 2.x:
+ Java 8 or later. The AWS SDK for Java works with the [Oracle Java SE Development Kit](https://www.oracle.com/java/technologies/downloads/) and with distributions of Open Java Development Kit (OpenJDK) such as [Amazon Corretto](https://aws.amazon.com/corretto/), [Red Hat OpenJDK](https://developers.redhat.com/products/openjdk/overview), and [Adoptium](https://adoptium.net/).
+ A Maven-compatible build tools such as Apache Maven, Apache Ant with Ivy, Gradle, or IntelliJ.
  + For information about how to install and use Maven, see [https://maven.apache.org/](https://maven.apache.org/).
  + For information about how to install and use Apache Ivy, see [https://ant.apache.org/ivy/](https://ant.apache.org/ivy/).
  + For information about how to install and use Gradle, see [https://gradle.org/](https://gradle.org/).
  + For information about how to install and use IntelliJ IDEA, see [https://www.jetbrains.com/idea/](https://www.jetbrains.com/idea/).

# Set up an Apache Maven project that uses the AWS SDK for Java 2.x
<a name="setup-project-maven"></a>

You can use [Apache Maven](https://maven.apache.org/) to set up and build AWS SDK for Java 2.x projects, or to [build the SDK itself](https://github.com/aws/aws-sdk-java-v2/tree/master#building-from-source).

## Prerequisites
<a name="prerequisitesmaven"></a>

To use the SDK for Java 2.x with Maven, you need the following:
+ Java *8.0 or later*. You can download the latest Java SE Development Kit software from [http://www.oracle.com/technetwork/java/javase/downloads/](https://www.oracle.com/java/technologies/downloads/). The SDK for Java 2.x also works with [OpenJDK](https://openjdk.org/) and Amazon Corretto, a distribution of the Open Java Development Kit (OpenJDK). Download the latest OpenJDK version from [https://openjdk.java.net/install/index.html](https://openjdk.org/install/index.html). Download the latest Amazon Corretto 8 or Amazon Corretto 11 version from [the Corretto page](https://aws.amazon.com/corretto/).
+  *Apache Maven*. If you need to install Maven, go to [http://maven.apache.org/](https://maven.apache.org/) to download and install it.

## Create a Maven project
<a name="create-maven-project"></a>

To create a Maven project from the command line, run the following command from a terminal or command prompt window````.

```
mvn -B archetype:generate \
 -DarchetypeGroupId=software.amazon.awssdk \
 -DarchetypeArtifactId=archetype-lambda -Dservice=s3 -Dregion=US_WEST_2 \
 -DarchetypeVersion=2.X.X \
 -DgroupId=com.example.myapp \
 -DartifactId=myapp
```

**Note**  
Replace *com.example.myapp* with the full package namespace of your application. Also replace *myapp* with your project name. This becomes the name of the directory for your project.  
To use the latest version of the archetype, replace *2.X.X* with the [latest from Maven central](https://central.sonatype.com/artifact/software.amazon.awssdk/archetype-lambda).

This command creates a Maven project using the archetype templating toolkit. The archetype generates the scaffolding for an AWS Lambda function handler project . This project archetype is preconfigured to compile with Java SE 8 and includes a dependency to the version of the SDK for Java 2.x specified with `-DarchetypeVersion`.

For more information about creating and configuring Maven projects, see the [Maven Getting Started Guide](https://maven.apache.org/guides/getting-started/).

## Configure the Java compiler for Maven
<a name="configure-maven-compiler"></a>

If you created your project using the AWS Lambda project archetype as described previously, the configuration of the Java compiler is already done for you.

To verify that this configuration is present, start by opening the `pom.xml` file from the project folder you created (for example, `myapp`) when you executed the previous command. Look on lines 11 and 12 to see the Java compiler version setting for this Maven project, and the required inclusion of the Maven compiler plugin on lines 71-75.

```
<project>
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>${maven.compiler.plugin.version}</version>
      </plugin>
    </plugins>
  </build>
</project>
```

If you create your project with a different archetype or by using another method, you must ensure that the Maven compiler plugin is part of the build and that its source and target properties are both set to **1.8** in the `pom.xml` file.

See the previous snippet for one way to configure these required settings.

Alternatively, you can configure the compiler configuration inline with the plugin declaration, as follows.

```
<project>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
```

## Declare the SDK as a dependency
<a name="sdk-as-dependency"></a>

To use the AWS SDK for Java in your project, you need to declare it as a dependency in your project’s `pom.xml` file.

If you created your project using the project archetype as described previously, the latest version of the SDK is already configured as a dependency in your project. 

The archetype generates a BOM (bill of materials) artifact dependency for the `software.amazon.awssdk` group id. With a BOM, you do not have to specify the maven version for individual artifact dependencies that share the same group id.

If you created your Maven project in a different way, configure the latest version of the SDK for your project by ensuring that the `pom.xml` file contains the following.

```
<project>
  <properties>
    <aws.java.sdk.version>2.X.X</aws.java.sdk.version>
  </properties>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>software.amazon.awssdk</groupId>
        <artifactId>bom</artifactId>
        <version>${aws.java.sdk.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
</project>
```

**Note**  
Replace *2.X.X* in the `pom.xml` file with the [latest version of the AWS SDK for Java 2.x](https://central.sonatype.com/artifact/software.amazon.awssdk/bom).

## Set dependencies for SDK modules
<a name="modules-dependencies"></a>

Now that you have configured the SDK, you can add dependencies for one or more of the AWS SDK for Java modules to use in your project.

Although you can specify the version number for each component, you don’t need to because you already declared the SDK version in the `dependencyManagement` section using the bill of materials artifact. To load a different version of a given module, specify a version number for its dependency.

If you created your project using the project archetype as described previously, your project is already configured with multiple dependencies. These include dependences for AWS Lambda function handlers and Amazon S3, as follows.

```
<project>
    <dependencies>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>s3</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>software.amazon.awssdk</groupId>
                    <artifactId>netty-nio-client</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>software.amazon.awssdk</groupId>
                    <artifactId>apache-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>url-connection-client</artifactId>
        </dependency>

        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-lambda-java-core</artifactId>
            <version>${aws.lambda.java.version}</version>
        </dependency>
    </dependencies>
</project>
```

**Note**  
In the `pom.xml` example above, the dependencies are from different `groupId`s. The `s3` dependency is from `software.amazon.awssdk`, whereas the `aws-lambda-java-core` dependency is from `com.amazonaws`. The BOM dependency management configuration affects artifacts for `software.amazon.awssdk`, so a version is needed for the `aws-lambda-java-core` artifact.  
For the development of *Lambda function handlers* using the SDK for Java 2.x, `aws-lambda-java-core` is the correct dependency. However, if your application needs to manage Lambda resources, using operations such as `listFunctions`, `deleteFunction`, `invokeFunction`, and `createFunction`, your application requires the following dependency.   

```
<groupId>software.amazon.awssdk</groupId>
<artifactId>lambda</artifactId>
```

**Note**  
The `s3` dependency excludes the the `netty-nio-client` and `apache-client` transitive dependencies. In place of either of those HTTP clients, the archetype includes the `url-connection-client` dependency, which helps [reduce the startup latency for AWS Lambda functions](lambda-optimize-starttime.md#lambda-quick-url).

Add the modules to your project for the AWS service and features you need for your project. The modules (dependencies) that are managed by the AWS SDK for Java BOM are listed on the [Maven central repository](https://central.sonatype.com/artifact/software.amazon.awssdk/bom).

**Note**  
You can look at the `pom.xml` file from a code example to determine which dependencies you need for your project. For example, if you’re interested in the dependencies for the DynamoDB service, see [this example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/da520cb4436f8567a90b6f73f77232fd590a50bf/javav2/example_code/dynamodb/pom.xml) from the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2) on GitHub. (Look for the `pom.xml` file under [/javav2/example\$1code/dynamodb](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb).)

### Build the entire SDK into your project
<a name="build-the-entire-sdk-into-your-project"></a>

To optimize your application, we strongly recommend that you pull in only the components you need instead of the entire SDK. However, to build the entire AWS SDK for Java into your project, declare it in your `pom.xml` file, as follows.

```
<project>
  <dependencies>
    <dependency>
      <groupId>software.amazon.awssdk</groupId>
      <artifactId>aws-sdk-java</artifactId>
      <version>2.X.X</version>
    </dependency>
  </dependencies>
</project>
```

## Build your project
<a name="build-project"></a>

After you configure the `pom.xml` file, you can use Maven to build your project.

To build your Maven project from the command line, open a terminal or command prompt window, navigate to your project directory (for example, `myapp`), enter or paste the following command, then press Enter or Return.

```
mvn package
```

This creates a single `.jar` file (JAR) in the `target` directory (for example, `myapp/target`). This JAR contains all of the SDK modules you specified as dependencies in your `pom.xml` file.

# Set up a Gradle project that uses the AWS SDK for Java 2.x
<a name="setup-project-gradle"></a>

You can use [Gradle](https://gradle.org/) to set up and build AWS SDK for Java 2.x projects. 

The initial steps in the following example come from [Gradle's Getting Started guide](https://docs.gradle.org/current/samples/sample_building_java_applications.html) for version 8.4. If you use a different version, your results may differ slightly.

**To create a Java application with Gradle (command line)**

1. Create a directory to hold your project. In this example, `demo` is the directory name.

1. Inside the `demo` directory, execute the `gradle init` command and supply the values highlighted in red as shown in the following command line output. For the walk through, we choose Kotlin as the build script DSL language, but a complete example for Groovy is also shown at the end of this topic.

   ```
   > gradle init
   Starting a Gradle Daemon (subsequent builds will be faster)
   
   Select type of project to generate:
   1: basic
   2: application
   3: library
   4: Gradle plugin
   Enter selection (default: basic) [1..4] 2
   
   Select implementation language:
   1: C++
   2: Groovy
   3: Java
   4: Kotlin
   5: Scala
   6: Swift
   Enter selection (default: Java) [1..6] 3
   
   Generate multiple subprojects for application? (default: no) [yes, no] no
   Select build script DSL:
   1: Kotlin
   2: Groovy
   Enter selection (default: Kotlin) [1..2] <Enter>
   
   Select test framework:
   1: JUnit 4
   2: TestNG
   3: Spock
   4: JUnit Jupiter
   Enter selection (default: JUnit Jupiter) [1..4] 4
   
   Project name (default: demo): <Enter>
   Source package (default: demo): <Enter>
   Enter target version of Java (min. 7) (default: 11): <Enter>
   Generate build using new APIs and behavior (some features may change in the next minor release)? (default: no) [yes, no] <Enter>
   
   > Task :init
   To learn more about Gradle by exploring our Samples at https://docs.gradle.org/8.4/samples/sample_building_java_applications.html
   
   BUILD SUCCESSFUL in 3m 43s
   2 actionable tasks: 2 executed
   ```

1. After the `init` task completes, the `demo` directory contains the following tree structure. We take a closer look at the main build file, `build.gradle.kts` (highlighted in red), in the next section.

   ```
   ├── app
   │   ├── build.gradle.kts
   │   └── src
   │       ├── main
   │       │   ├── java
   │       │   │   └── demo
   │       │   │       └── App.java
   │       │   └── resources
   │       └── test
   │           ├── java
   │           │   └── demo
   │           │       └── AppTest.java
   │           └── resources
   ├── gradle
   │   └── wrapper
   │       ├── gradle-wrapper.jar
   │       └── gradle-wrapper.properties
   ├── gradlew
   ├── gradlew.bat
   └── settings.gradle.kts
   ```

   The `build.gradle.kts` file contains the following scaffolded content.

   ```
   /*
    * This file was generated by the Gradle 'init' task.
    *
    * This generated file contains a sample Java application project to get you started.
    * For more details on building Java & JVM projects, please refer to https://docs.gradle.org/8.4/userguide/building_java_projects.html in the Gradle documentation.
    */
   
   plugins {
       // Apply the application plugin to add support for building a CLI application in Java.
       application
   }
   
   repositories {
       // Use Maven Central for resolving dependencies.
       mavenCentral()
   }
   
   dependencies {
       // Use JUnit Jupiter for testing.
       testImplementation("org.junit.jupiter:junit-jupiter:5.9.3")
   
       testRuntimeOnly("org.junit.platform:junit-platform-launcher")
   
       // This dependency is used by the application.
       implementation("com.google.guava:guava:33.3.0-jre")
   }
   
   // Apply a specific Java toolchain to ease working on different environments.
   java {
       toolchain {
           languageVersion.set(JavaLanguageVersion.of(11))
       }
   }
   
   application {
       // Define the main class for the application.
       mainClass.set("demo.App")
   }
   
   tasks.named<Test>("test") {
       // Use JUnit Platform for unit tests.
       useJUnitPlatform()
   }
   ```

1. Use the scaffolded Gradle build file as the basis for your AWS project.

   1. To manage SDK dependencies for your Gradle project, add the Maven bill of materials (BOM) for the AWS SDK for Java 2.x to the `dependencies` section of the `build.gradle.kts` file.

      ```
      ...
      dependencies {
          implementation(platform("software.amazon.awssdk:bom:2.27.21"))
          // With the bom declared, you specify individual SDK dependencies without a version.
       ...
      }
      ...
      ```
**Note**  
In this example build file, replace *2.27.21* with the latest version of the SDK for Java 2.x. Find the latest version available in [Maven central repository](https://central.sonatype.com/artifact/software.amazon.awssdk/bom/versions).

   1. Specify the SDK modules your application needs in the `dependencies` section. As an example, the following adds a dependency on Amazon Simple Storage Service. 

      ```
      ...
      dependencies {    
          implementation(platform("software.amazon.awssdk:bom:2.27.21"))
          implementation("software.amazon.awssdk:s3")
       ...
      }
      ...
      ```

      Gradle automatically resolves the correct version of declared dependencies by using the information from the BOM.

The following examples show complete Gradle build files in both the Kotlin and Groovy DSLs. The build file contains dependencies for Amazon S3, authentication, logging, and testing. The source and target version of Java is version 11.

------
#### [ Kotlin DSL (build.gradle.kts) ]

```
/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java application project to get you started.
 * For more details on building Java & JVM projects, please refer to https://docs.gradle.org/8.4/userguide/building_java_projects.html in the Gradle documentation.
 */

plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    application
}

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    implementation(platform("software.amazon.awssdk:bom:2.20.56"))
    implementation("software.amazon.awssdk:s3")
    implementation("software.amazon.awssdk:sso")
    implementation("software.amazon.awssdk:ssooidc")
    implementation(platform("org.apache.logging.log4j:log4j-bom:2.20.0"))
    implementation("org.apache.logging.log4j:log4j-slf4j2-impl")
    implementation("org.apache.logging.log4j:log4j-1.2-api")
    testImplementation(platform("org.junit:junit-bom:5.10.0"))
    testImplementation("org.junit.jupiter:junit-jupiter")
}

// Apply a specific Java toolchain to ease working on different environments.
java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(11))
    }
}

application {
    // Define the main class for the application.
    mainClass.set("demo.App")
}

tasks.named<Test>("test") {
    // Use JUnit Platform for unit tests.
    useJUnitPlatform()
}
```

------
#### [ Groovy DSL (build.gradle) ]

```
/*
 * This file was generated by the Gradle 'init' task.
 *
 * This generated file contains a sample Java application project to get you started.
 * For more details on building Java & JVM projects, please refer to https://docs.gradle.org/8.4/userguide/building_java_projects.html in the Gradle documentation.
 */

plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    id 'application'
}

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    implementation platform('software.amazon.awssdk:bom:2.27.21')
    implementation 'software.amazon.awssdk:s3'
    implementation 'software.amazon.awssdk:sso'
    implementation 'software.amazon.awssdk:ssooidc'
    implementation platform('org.apache.logging.log4j:log4j-bom:2.20.0')
    implementation 'org.apache.logging.log4j:log4j-slf4j2-impl'
    implementation 'org.apache.logging.log4j:log4j-1.2-api'
    testImplementation platform('org.junit:junit-bom:5.10.0')
    testImplementation 'org.junit.jupiter:junit-jupiter'
}

// Apply a specific Java toolchain to ease working on different environments.
java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(11)
    }
}

application {
    // Define the main class for the application.
    mainClass = 'demo_groovy.App'
}

tasks.named('test') {
    // Use JUnit Platform for unit tests.
    useJUnitPlatform()
}
```

------

For next steps, see the Getting Started guide on the Gradle website for instructions on how to [build and run a Gradle application](https://docs.gradle.org/current/samples/sample_building_java_applications.html#run_the_application).

# Set up a GraalVM Native Image project that uses the AWS SDK for Java 2.x
<a name="setup-project-graalvm"></a>

With versions 2.16.1 and later, the AWS SDK for Java 2.x provides out-of-the-box support for GraalVM Native Image applications. Use the `archetype-app-quickstart` Maven archetype to set up a project with built-in native image support.

## Prerequisites
<a name="setup-graalvmnativeimage-prereq"></a>
+ Complete the steps in [Setting up the AWS SDK for Java 2.x](setup.md).
+ Install [GraalVM Native Image](https://www.graalvm.org/reference-manual/native-image/#install-native-image).

## Create a project using the archetype
<a name="setup-graalvmnativeimage-project"></a>

To create a Maven project with built-in native image support, in a terminal or command prompt window, use the following command.

**Note**  
Replace `com.example.mynativeimageapp` with the full package namespace of your application. Also replace `mynativeimageapp` with your project name. This becomes the name of the directory for your project.

```
mvn archetype:generate \
    -DarchetypeGroupId=software.amazon.awssdk \
    -DarchetypeArtifactId=archetype-app-quickstart \
    -DarchetypeVersion=2.27.21\
    -DnativeImage=true \
    -DhttpClient=apache-client \
    -Dservice=s3 \
    -DgroupId=com.example.mynativeimageapp \
    -DartifactId=mynativeimageapp \
    -DinteractiveMode=false
```

This command creates a Maven project configured with dependencies for the AWS SDK for Java, Amazon S3, and the `ApacheHttpClient` HTTP client. It also includes a dependency for the [GraalVM Native Image Maven plugin](https://graalvm.github.io/native-build-tools/latest/index.html), so that you can build native images using Maven.

To include dependencies for a different Amazon Web Services, set the value of the `-Dservice` parameter to the artifact ID of that service. Examples include `dynamodb`, `comprehend`, and `pinpoint`. For a complete list of artifact IDs, see the list of managed dependencies for [software.amazon.awssdk on Maven Central](https://mvnrepository.com/artifact/software.amazon.awssdk/bom/latest).

To use an asynchronous HTTP client, set the `-DhttpClient` parameter to `netty-nio-client`. To use `UrlConnectionHttpClient` as the synchronous HTTP client instead of `apache-client`, set the `-DhttpClient` parameter to `url-connection-client`.

## Build a native image
<a name="build-graalvmnativeimage-project"></a>

After you create the project, run the following command from your project directory, for example, `mynativeimageapp`:

```
mvn package -P native-image
```

This creates a native image application in the `target` directory, for example, `target/mynativeimageapp`.

# Authenticating with AWS using the AWS SDK for Java 2.x
<a name="get-started-auth"></a>

 You must establish how the AWS SDK for Java 2.x authenticates with AWS when you develop with AWS services. The SDK manages credential discovery, signature creation, and credential refreshing completely behind the scenes, letting you focus on your application logic.

## Set up for authentication
<a name="setup-auth"></a>

The [Authentication and access](https://docs.aws.amazon.com/sdkref/latest/guide/access.html) topic in the AWS SDKs and Tools Reference Guide describes the different authentication approaches.

For local development the recommended approach is to use short-term credentials by logging into the AWS CLI with your console login credentials. Recommended if you use root, IAM users, or federation with IAM for AWS account access. Follow the instructions at [Access credentials for interactive development work using AWS SDK for Java 2.x](credentials-temporary.md).

After following the instructions in AWS SDKs and Tools Reference Guide, your system should be set up to allow the SDK to sign requests:

### 1. Local development using short-term credentials
<a name="setup-login"></a>

For local development the recommended approach is to use short-term credentials by logging into the AWS CLI with your console login credentials. Recommended if you use root, IAM users, or federation with IAM for AWS account access. 

For instructions, see [Using credentials providers in the AWS SDK for Java 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials-temporary.html).

### 2. Setup for single sign-on access for the SDK
<a name="setup-credentials"></a>

After you complete Step 2 in the [programmatic access section](https://docs.aws.amazon.com/sdkref/latest/guide/access-sso.html#idcGettingStarted) so that the SDK can use IAM Identity Center authentication, your system should contain the following elements.
+ The AWS CLI, which you use to start an [AWS access portal session](#setup-login-sso) before you run your application.
+ An `~/.aws/config` file that contains a [default profile](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html#file-format-profile). The SDK for Java uses the profile's SSO token provider configuration to acquire credentials before sending requests to AWS. The `sso_role_name` value, which is an IAM role connected to an IAM Identity Center permission set, should allow access to the AWS services used in your application.

  The following sample `config` file shows a default profile set up with SSO token provider configuration. The profile's `sso_session` setting refers to the named `sso-session` section. The `sso-session` section contains settings to initiate an AWS access portal session.

  ```
  [default]
  sso_session = my-sso
  sso_account_id = 111122223333
  sso_role_name = SampleRole
  region = us-east-1
  output = json
  
  [sso-session my-sso]
  sso_region = us-east-1
  sso_start_url = https://provided-domain.awsapps.com/start
  sso_registration_scopes = sso:account:access
  ```

For more details about the settings used in the SSO token provider configuration, see [SSO token provider configuration](https://docs.aws.amazon.com/sdkref/latest/guide/feature-sso-credentials.html#sso-token-config) in the AWS SDKs and Tools Reference Guide.

If your development environment is not set up for programmatic access as previously shown, follow [Step 2 in the SDKs Reference Guide](https://docs.aws.amazon.com/sdkref/latest/guide/access-sso.html#idcGettingStarted).

### 3. Sign in using the AWS CLI
<a name="setup-login-sso"></a>

Before running an application that accesses AWS services, you need an active AWS access portal session in order for the SDK to use IAM Identity Center authentication to resolve credentials. Run the following command in the AWS CLI to sign in to the AWS access portal.

```
aws sso login
```

Since you have a default profile setup, you do not need to call the command with a `--profile` option. If your SSO token provider configuration is using a named profile, the command is `aws sso login --profile named-profile`.

To test if you already have an active session, run the following AWS CLI command.

```
aws sts get-caller-identity
```

The response to this command should report the IAM Identity Center account and permission set configured in the shared `config` file.

**Note**  
If you already have an active AWS access portal session and run `aws sso login`, you will not be required to provide credentials.   
However, you will see a dialog that requests permission for `botocore` to access your information. `botocore` is the foundation for the AWS CLI .   
Select **Allow** to authorize access to your information for the AWS CLI and SDK for Java.

## Additional authentication options
<a name="setup-additional"></a>

For more options on authentication for the SDK, such as the use of profiles and environment variables, see the [configuration](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html) chapter in the AWS SDKs and Tools Reference Guide.

# Creating a simple application using the AWS SDK for Java 2.x
<a name="get-started-tutorial"></a>

This tutorial shows you how to use [Apache Maven](https://maven.apache.org/) to define dependencies for the SDK for Java 2.x and then write code that connects to Amazon S3 to upload a file.

Follow these steps to complete this tutorial:
+  [Step 1: Set up for this tutorial](#get-started-setup) 
+  [Step 2: Create the project](#get-started-projectsetup) 
+  [Step 3: Write the code](#get-started-code) 
+  [Step 4: Build and run the application](#get-started-run) 

## Step 1: Set up for this tutorial
<a name="get-started-setup"></a>

Before you begin this tutorial, you need the following:
+ Permission to access Amazon S3
+ A Java development environment that is configured to access AWS services using single sign-on to the AWS IAM Identity Center

Use the instructions in [Setup overview](setup.md#setup-overview) to get set up for this tutorial. After you have [configured your development environment with single sign-on access](get-started-auth.md#setup-credentials) for the Java SDK and you have an [active AWS access portal session](get-started-auth.md#setup-login-sso), continue with Step 2 of this tutorial.

## Step 2: Create the project
<a name="get-started-projectsetup"></a>

To create the project for this tutorial, you run a Maven command that prompts you for input on how to configure the project. After all input is entered and confirmed, Maven finishes building out the project by creating a `pom.xml` and creates stub Java files.

1. Open a terminal or command prompt window and navigate to a directory of your choice, for example, your `Desktop` or `Home` folder.

1. Enter the following command at the terminal and press `Enter`.

   ```
   mvn archetype:generate \
     -DarchetypeGroupId=software.amazon.awssdk \
     -DarchetypeArtifactId=archetype-app-quickstart \
     -DarchetypeVersion=2.27.21
   ```

1. Enter the value listed in the second column for each prompt.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started-tutorial.html)

1. After the last value is entered, Maven lists the choices you made. Confirm by entering *`Y`* or re-enter values by entering *`N`*.

Maven creates the project folder named `getstarted` based on the `artifactId` value that you entered. Inside the `getstarted` folder, find a `README.md` file that you can review, a `pom.xml` file, and a `src` directory.

Maven builds the following directory tree.

```
getstarted
├── README.md
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── org
    │   │       └── example
    │   │           ├── App.java
    │   │           ├── DependencyFactory.java
    │   │           └── Handler.java
    │   └── resources
    │       └── simplelogger.properties
    └── test
        └── java
            └── org
                └── example
                    └── HandlerTest.java

10 directories, 7 files
```

The following shows the contents of the `pom.xml` project file.

### `pom.xml`
<a name="projectsetup-collapse2"></a>

The `dependencyManagement` section contains a dependency to the AWS SDK for Java 2.x and the `dependencies` section has a dependency for Amazon S3. The project uses Java 1.8 because of the `1.8` value in the `maven.compiler.source` and `maven.compiler.target` properties.

```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>getstarted</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.shade.plugin.version>3.2.1</maven.shade.plugin.version>
        <maven.compiler.plugin.version>3.6.1</maven.compiler.plugin.version>
        <exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
        <aws.java.sdk.version>2.27.21</aws.java.sdk.version> <-------- SDK version picked up from archetype version.
        <slf4j.version>1.7.28</slf4j.version>
        <junit5.version>5.8.1</junit5.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>software.amazon.awssdk</groupId>
                <artifactId>bom</artifactId>
                <version>${aws.java.sdk.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>s3</artifactId>  <-------- S3 dependency
            <exclusions>
                <exclusion>
                    <groupId>software.amazon.awssdk</groupId>
                    <artifactId>netty-nio-client</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>software.amazon.awssdk</groupId>
                    <artifactId>apache-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>sso</artifactId> <-------- Required for identity center authentication.
        </dependency>

        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>ssooidc</artifactId> <-------- Required for identity center authentication.
        </dependency>

        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>apache-client</artifactId> <-------- HTTP client specified.
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <!-- Needed to adapt Apache Commons Logging used by Apache HTTP Client to Slf4j to avoid
        ClassNotFoundException: org.apache.commons.logging.impl.LogFactoryImpl during runtime -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <!-- Test Dependencies -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>${junit5.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
            </plugin>
        </plugins>
    </build>

</project>
```

## Step 3: Write the code
<a name="get-started-code"></a>

The following code shows the `App` class created by Maven. The `main` method is the entry point into the application, which creates an instance of the `Handler` class and then calls its `sendRequest` method.

### `App` class
<a name="projectsetup-collapse2"></a>

```
package org.example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App {
    private static final Logger logger = LoggerFactory.getLogger(App.class);

    public static void main(String... args) {
        logger.info("Application starts");

        Handler handler = new Handler();
        handler.sendRequest();

        logger.info("Application ends");
    }
}
```

The `DependencyFactory` class created by Maven contains the `s3Client` factory method that builds and returns an [https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html) instance. The `S3Client` instance uses an instance of the Apache-based HTTP client. This is because you specified `apache-client` when Maven prompted you for which HTTP client to use.

The `DependencyFactory` is shown in the following code.

### `DependencyFactory` class
<a name="code-collapse2"></a>

```
package org.example;

import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.s3.S3Client;

/**
 * The module containing all dependencies required by the {@link Handler}.
 */
public class DependencyFactory {

    private DependencyFactory() {}

    /**
     * @return an instance of S3Client
     */
    public static S3Client s3Client() {
        return S3Client.builder()
                       .httpClientBuilder(ApacheHttpClient.builder())
                       .build();
    }
}
```

The `Handler` class contains the main logic of your program. When an instance of `Handler` is created in the `App` class, the `DependencyFactory` furnishes the `S3Client` service client. Your code uses the `S3Client` instance to call the Amazon S3 service.

Maven generates the following `Handler` class with a `TODO` comment. The next step in the tutorial replaces the *`TODO`* with code.

### `Handler` class, Maven-generated
<a name="code-collapsible3"></a>

```
package org.example;

import software.amazon.awssdk.services.s3.S3Client;


public class Handler {
    private final S3Client s3Client;

    public Handler() {
        s3Client = DependencyFactory.s3Client();
    }

    public void sendRequest() {
        // TODO: invoking the api calls using s3Client.
    }
}
```

To fill in the logic, replace the entire contents of the `Handler` class with the following code. The `sendRequest` method is filled in and the necessary imports are added.

### `Handler` class, implemented
<a name="code-collapse4"></a>

The code first creates a new S3 bucket with the last part of the name generated using `System.currentTimeMillis()` in order to make the bucket name unique.

After creating the bucket in the `createBucket()` method, the program uploads an object using the [https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html#putObject(software.amazon.awssdk.services.s3.model.PutObjectRequest,software.amazon.awssdk.core.sync.RequestBody)](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html#putObject(software.amazon.awssdk.services.s3.model.PutObjectRequest,software.amazon.awssdk.core.sync.RequestBody)) method of `S3Client`. The contents of the object is a simple string created with the `RequestBody.fromString` method.

Finally, the program deletes the object followed by the bucket in the `cleanUp` method.

```
package org.example;

import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;


public class Handler {
    private final S3Client s3Client;

    public Handler() {
        s3Client = DependencyFactory.s3Client();
    }

    public void sendRequest() {
        String bucket = "bucket" + System.currentTimeMillis();
        String key = "key";

        createBucket(s3Client, bucket);

        System.out.println("Uploading object...");

        s3Client.putObject(PutObjectRequest.builder().bucket(bucket).key(key)
                        .build(),
                RequestBody.fromString("Testing with the {sdk-java}"));

        System.out.println("Upload complete");
        System.out.printf("%n");

        cleanUp(s3Client, bucket, key);

        System.out.println("Closing the connection to {S3}");
        s3Client.close();
        System.out.println("Connection closed");
        System.out.println("Exiting...");
    }

    public static void createBucket(S3Client s3Client, String bucketName) {
        try {
            s3Client.createBucket(CreateBucketRequest
                    .builder()
                    .bucket(bucketName)
                    .build());
            System.out.println("Creating bucket: " + bucketName);
            s3Client.waiter().waitUntilBucketExists(HeadBucketRequest.builder()
                    .bucket(bucketName)
                    .build());
            System.out.println(bucketName + " is ready.");
            System.out.printf("%n");
        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void cleanUp(S3Client s3Client, String bucketName, String keyName) {
        System.out.println("Cleaning up...");
        try {
            System.out.println("Deleting object: " + keyName);
            DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder().bucket(bucketName).key(keyName).build();
            s3Client.deleteObject(deleteObjectRequest);
            System.out.println(keyName + " has been deleted.");
            System.out.println("Deleting bucket: " + bucketName);
            DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder().bucket(bucketName).build();
            s3Client.deleteBucket(deleteBucketRequest);
            System.out.println(bucketName + " has been deleted.");
            System.out.printf("%n");
        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Cleanup complete");
        System.out.printf("%n");
    }
}
```

## Step 4: Build and run the application
<a name="get-started-run"></a>

After the project is created and contains the complete `Handler` class, build and run the application. 

1. Make sure that you have an active IAM Identity Center session. To do so, run the AWS Command Line Interface command `aws sts get-caller-identity` and check the response. If you don't have an active session, see [this section](get-started-auth.md#setup-login-sso) for instructions.

1. Open a terminal or command prompt window and navigate to your project directory `getstarted`.

1. Use the following command to build your project:

   ```
   mvn clean package
   ```

1. Use the following command to run the application.

   ```
   mvn exec:java -Dexec.mainClass="org.example.App"
   ```

To view the new bucket and object that the program creates, perform the following steps.

1. In `Handler.java`, comment out the line `cleanUp(s3Client, bucket, key)` in the `sendRequest` method and save the file.

1. Rebuild the project by running `mvn clean package`.

1. Rerun `mvn exec:java -Dexec.mainClass="org.example.App"` to upload the text object once more.

1. Sign in to [the S3 console](https://console.aws.amazon.com/s3/) to view the new object in the newly created bucket.

After you view the file, delete the object, and then delete the bucket.

### Success
<a name="get-started-success"></a>

If your Maven project built and ran without error, then congratulations\$1 You have successfully built your first Java application using the SDK for Java 2.x.

### Cleanup
<a name="cleanup"></a>

To clean up the resources you created during this tutorial, do the following:
+ If you haven't done so already, in [the S3 console](https://console.aws.amazon.com/s3/), delete any objects and any buckets created when you ran the application.
+ Delete the project folder (`getstarted`).

## Next steps
<a name="get-started-next"></a>

Now that you have the basics down, you can learn about the following:
+  [Working with Amazon S3](examples-s3.md) 
+  [Working with other Amazon Web Services](work-with-services.md), such as [DynamoDB](examples-dynamodb.md), [Amazon EC2](examples-ec2.md), and [various database services](examples-databases.md) 
+  [Use the SDK](using.md) 
+  [Security for the AWS SDK for Java](security.md) **