Expert AWS Development
上QQ阅读APP看书,第一时间看更新

AWS SDK for Java using Gradle

Please perform the following steps to include AWS SDK for Java using Gradle:

  1. Assuming that you have already installed Gradle in your machine, create a new folder called java-gradle-demo or any other name. Go to this folder and copy the following files:
    • The gradle folder: Contains necessary files for the wrapper
    • build.gradle: Gradle build file
    • gradlew: Gradle startup script for Unix
    • gradlew.bat: Gradle startup script for Windows:
  1. Now execute the following command:
gradlew.bat

After completing this execution, you can see the .gradle folder.

  1. Now you need to update your build.gradlew file to connect with AWS:
apply plugin: 'java'
apply plugin: 'application'

mainClassName="com.packt.example.S3GradleExample"
repositories {
mavenCentral()
}
dependencies {
compile 'com.amazonaws:aws-java-sdk:1.9.6'
}
  1. Let's create a S3GradleExample.java file under the com.packt.example folder. This is the same file as S3MavenExample.java:
package com.packt.example;
import java.util.UUID;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
public class S3GradleExample {
public static void main(String[] args) {
AmazonS3 s3 = new AmazonS3Client();
Region s3Region = Region.getRegion(Regions.AP_SOUTHEAST_1);
s3.setRegion(s3Region);
String bucketName = "s3-gradle-bucket-" + UUID.randomUUID();
System.out.println("Amazon S3 will create/delete bucket");
// Create a new bucket
System.out.println("Creating bucket " + bucketName + "\n");
s3.createBucket(bucketName);
// Delete a bucket.
System.out.println("Deleting bucket " + bucketName + "\n");
s3.deleteBucket(bucketName);
}
}
  1. After creating the Java file, execute the following command:
gradlew clean build run

It will create and delete the bucket as per the specified regions: