Get started with the AWS SDK for Java 2.x

The AWS SDK for Java 2.x provides Java APIs for Amazon Web Services (AWS). Using the SDK, you can build Java applications that work with Amazon S3, Amazon EC2, DynamoDB, and more.

This tutorial shows you how you can use Apache Maven to define dependencies for the AWS SDK for Java Programming Questions and then write code that connects to Amazon S3 to upload a file.

Step 1: Set up for this tutorial

Follow these steps to set up for this tutorial:

  • Create an AWS account
  • Create an IAM user
  • Install Java and Apache Maven
  • Configure credentials

Create an AWS account

After you activate your new AWS account, follow the instructions in Creating your first IAM admin user and group in the IAM User Guide. Use this account instead of the root account when accessing the AWS Console. For more information

Create an IAM user

To create an IAM user with a programmatic access key and the required permissions for this tutorial

  1. Sign in to the IAM console
  2. In the navigation pane on the left, choose Users. Then choose Add user.
  3. Enter TestSDK as the User name and select the Programmatic access checkbox. Choose Next: Permissions.
  4. Under Set permissions, select Attach existing policies directly.
  5. In the list of policies, select the checkbox for the AmazonS3FullAccess policy. Choose Next: Tags.
  6. Choose Next: Review. Then choose Create user
  7. On the Success screen, choose Download .csv.
  8. The downloaded file contains the Access Key ID and the Secret Access Key for this tutorial. Treat your Secret Access Key as a password; save in a trusted location and do not share it.

Install Java and Apache Maven

  • For Java, use Oracle Java SE Development Kit , Amazon Corretto, Red Hat OpenJDK, or AdoptOpenJDK.
  • For Maven, go to https://maven.apache.org/.

Configure credentials

To configure credentials

  1. In a text editor, create a new file with the following code:

[default] aws_access_key_id = YOUR_AWS_ACCESS_KEY_ID aws_secret_access_key = YOUR_AWS_SECRET_ACCESS_KEY

  1. In the text file you just created, replace YOUR_AWS_ACCESS_KEY with your unique AWS access key ID, and replace YOUR_AWS_SECRET_ACCESS_KEY with your unique AWS secret access key.
  2. Save the file without a file extension. Refer to the following table for the correct location and file name based on your operating system.
  3. Operating systemFile name
  4. Windows
  5. C:\Users\<yourUserName>\.aws\credentials
  6. Linux, macOS, Unix
  7. ~/.aws/credentials

Step 2: Create the project

To create the Maven project

  1. Open a terminal or command prompt window and navigate to a directory of your choice, for example, your Desktop or Home folder.
  2. Use the following command to create a new directory called myapp with a project configuration file (pom.xml) and a basic Java class.
  • mvn -B archetype:generate \ -DarchetypeGroupId=org.apache.maven.archetypes \ -DgroupId=com.example.myapp \ -DartifactId=myapp

To configure your project with dependencies for the AWS SDK for Java and Amazon S3, and to use Java 1.8

  • In the folder myapp that you created in the previous procedure, open the pom.xml file. Replace its contents with the following code, and then save your changes.
  • <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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <groupId>com.example.myapp</groupId> <artifactId>myapp</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>myapp</name> <dependencyManagement> <dependencies> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>bom</artifactId> <version>2.15.15</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>s3</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build> </project>

The dependencyManagement section contains a dependency to the AWS SDK for Java and the dependencies section has a dependency for Amazon S3. The Apache Maven Compiler Plugin is configured in the build section to use Java 1.8.

Step 3: Write the code

The example class below creates a service client for Amazon S3 and then uses it to upload a text file. To create a service client for Amazon S3, instantiate an S3Client object using the static factory method builder. To upload a file to Amazon S3, first build a PutObjectRequest object, supplying a bucket name and a key name. Then, call the S3Client’s putObject method, with a RequestBody that contains the object content and the PutObjectRequest object.

To create the Java class for this tutorial

  1. In your project folder myapp, navigate to the directory src/main/java/com/example/myapp. Open the App.java file.
  2. Replace its contents with the following code and save the file.
  • package com.example.myapp; import java.io.IOException;
  • import software.amazon.awssdk.core.sync.RequestBody;
  • import software.amazon.awssdk.regions.Region;
  • importsoftware.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
  • 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;
  • import software.amazon.awssdk.services.s3.S3Client;
  • public class App { public static void main(String[] args) throws IOException { Region region = Region.US_WEST_2;
  • S3Client s3 = S3Client.builder().region(region).build(); String bucket = "bucket" + System.currentTimeMillis(); String key = "key"; tutorialSetup(s3, bucket, region); System.out.println("Uploading object..."); s3.putObject(PutObjectRequest.builder().bucket(bucket).key(key) .build(), RequestBody.fromString("Testing with the AWS SDK for Java")); System.out.println("Upload complete"); System.out.printf("%n"); cleanUp(s3, bucket, key); System.out.println("Closing the connection to Amazon S3"); s3.close(); System.out.println("Connection closed"); System.out.println("Exiting..."); } public static void tutorialSetup(S3Client s3Client, String bucketName, Region region) { try { s3Client.createBucket(CreateBucketRequest .builder() .bucket(bucketName) .createBucketConfiguration( CreateBucketConfiguration.builder() .locationConstraint(region.id()) .build()) .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

To build the project using Maven

  1. Open a terminal or command prompt window and navigate to your project directory myapp.
  2. Use the following command to build your project:
  • mvn package

To run the application

  1. Open a terminal or command prompt window and navigate to your project directory myapp.
  2. Use the following command to run the application.
  • mvn exec:java -Dexec.mainClass="com.example.myapp.App"

When you run the application, it uploads a new a text file to a new bucket in Amazon S3. Afterward, it will also delete the file and bucket.

To see the file in the Amazon S3 console after it uploads

  1. In App.java, comment out the line cleanUp(s3, bucket, key); and save the file.
  2. Rebuild the project by running mvn package.
  3. Upload the file by running mvn exec:java -Dexec.mainClass="com.example.myapp.App" again.
  4. Sign in to the S3 console to view the new file in the newly-created bucket.

After you view the file, clean up test resources by deleting the object and then deleting the bucket.

Success!

Help Freshers is the best Job portal and free Online web site for learning programming skills easily to achieve your dream job and start your career like a pro.