AWS SDK for Java (v2) With Wasabi

Prev Next

How do I use AWS SDK for Java (v2) with Wasabi?

AWS SDK for Java has been certified for use with Wasabi. 

To use the Java SDK v2, execute the following steps:

1) Install Java and Maven, referring to this guide.

2) Follow the guide Using the SDK with Apache Maven and add the required dependencies in the pom.xml file.

<?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> <!-- Updated 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> 
            <version>2.27.21</version>  
        </dependency> 

        <dependency> 
            <groupId>software.amazon.awssdk</groupId> 
            <artifactId>iam</artifactId> 
            <version>2.27.21</version>  
        </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> 

3) Configure additional AWS CLI profile for Wasabi account using the Wasabi keys (optional).

In this example, we have set the profile name as "wasabi" in the "~/.aws/credentials" file. To help our customers use this SDK with Wasabi, we have provided examples for both IAM and S3. This example shows: 

Other examples can be referred from the AWS documentation.

Important: This example discusses the use of Wasabi's us-east-1 storage region. To use other Wasabi storage regions, please use the appropriate Wasabi service URL as described in this article.

Setting the Credentials

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; 
import software.amazon.awssdk.regions.Region; 
import software.amazon.awssdk.services.iam.IamClient; 
import software.amazon.awssdk.core.exception.SdkException; 

public class GeneralConnection { 

    public static void main(String[] args) { 

        final String iamEndpoint = "https://iam.wasabisys.com";  // IAM Endpoint URL 
        final Region region = Region.US_EAST_1;  

        String profileName = "your-profile-name";  // Profile name  

        try { 
            ProfileCredentialsProvider credentialsProvider = ProfileCredentialsProvider.create(profileName); 
            credentialsProvider.resolveCredentials(); 
            IamClient iamClient = IamClient.builder() 
                    .endpointOverride(java.net.URI.create(iamEndpoint)) 
                    .region(region) 
                    .credentialsProvider(credentialsProvider) 
                    .build(); 

            System.out.println("Successfully connected to Wasabi IAM using profile: " + profileName); 
        } catch (SdkException e) { 
            String errorMessage = e.getMessage(); 

            if (errorMessage.contains("Profile file contained no credentials")) { 
                System.err.println("Error: The profile '" + profileName + "' is missing credentials."); 
            } else if (errorMessage.contains("InvalidAccessKeyId")) { 
                System.err.println("Error: The provided credentials for profile '" + profileName + "' are invalid."); 
            } else { 
                System.err.println("Error occurred: " + errorMessage); 
            } 
        } catch (Exception e) { 
            System.err.println("An unexpected error occurred: " + e.getMessage()); 
        } 
    } 
} 

Connecting to IAM and S3 Endpoints

IAM

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; 
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; 
import software.amazon.awssdk.regions.Region; 
import software.amazon.awssdk.services.iam.IamClient; 
import software.amazon.awssdk.services.iam.model.ListUsersRequest; 
import software.amazon.awssdk.services.iam.model.ListUsersResponse; 

import java.net.URI; 

public class IAMConnectionTest { 

    public static void main(String[] args) { 
        String accessKey = "your-access-key"; // Replace with your access key 
        String secretKey = "your-secret-key"; // Replace with your secret key 
        String region = "us-east-1"; // IAM region us-east-1 
        String endpointUrl = "https://iam.wasabisys.com"; // IAM endpoint URL 

        IamClient iamClient = IamClient.builder() 
                .region(Region.of(region)) 
                .credentialsProvider(StaticCredentialsProvider.create( 
                        AwsBasicCredentials.create(accessKey, secretKey))) 
                .endpointOverride(URI.create(endpointUrl)) 
                .build(); 

        try { 
            ListUsersResponse response = iamClient.listUsers(ListUsersRequest.builder().maxItems(5).build()); 
            System.out.println("Successfully connected to IAM! Users:"); 
            response.users().forEach(user -> System.out.println(user.userName())); 
        } catch (Exception e) { 
            System.err.println("Error occurred while connecting to IAM: " + e.getMessage()); 
            e.printStackTrace(); 
        } finally { 
            iamClient.close(); 
        } 
    } 
} 

S3

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; 
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; 
import software.amazon.awssdk.regions.Region; 
import software.amazon.awssdk.services.s3.S3Client; 

import java.net.URI; 

public class s3Connection { 

    public static void main(String[] args) { 
        String accessKey = "your-access-key"; // Replace with your access key 
        String secretKey = "your-secret-access-key"; // Replace with your secret key 
        String region = "us-east-1"; // Replace with your region 
        String endpointUrl = "https://s3.wasabisys.com"; // Specify the endpoint URL associated with your bucket region 

        S3Client s3Client = S3Client.builder() 
                .region(Region.of(region))   
                .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))) 
                .endpointOverride(URI.create(endpointUrl))  
                .build(); 

        System.out.println("Successfully connected to Wasabi S3!"); 
        s3Client.close(); 
    } 
} 

Creating a User Using IAM

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;  
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;  
import software.amazon.awssdk.core.waiters.WaiterResponse;  
import software.amazon.awssdk.services.iam.IamClient;  
import software.amazon.awssdk.services.iam.model.CreateUserRequest;  
import software.amazon.awssdk.services.iam.model.CreateUserResponse;  
import software.amazon.awssdk.services.iam.model.IamException;  
import software.amazon.awssdk.regions.Region;  
import software.amazon.awssdk.services.iam.waiters.IamWaiter;  
import software.amazon.awssdk.services.iam.model.GetUserRequest;  
import software.amazon.awssdk.services.iam.model.GetUserResponse;  
import java.net.URI;  

public class CreateUser {  
    public static void main(String[] args) {  

        String username = "your-yser-name"; // Replace with your desired username  
        String accessKey = "your-access-key"; // Replace with your AWS Access Key  
        String secretKey = "your-secret-key";  // Replace with your AWS Secret Key  
        Region region = Region.of("us-east-1");    // region 
        URI endpoint = URI.create("https://iam.wasabisys.com");  // IAM Endpoint URL 
        IamClient iamClient = IamClient.builder()  
                .region(region)  
                .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey)))  
                .endpointOverride(endpoint)    
                .build();  

        String result = createIAMUser(iamClient, username);  
        System.out.println("Successfully created user: " + result);  
        iamClient.close();  
    }  

public static String createIAMUser(IamClient iam, String username) {  
        try {  
            IamWaiter iamWaiter = iam.waiter();  
            CreateUserRequest createUserRequest = CreateUserRequest.builder()  
                    .userName(username)  
                    .build();  


            CreateUserResponse createUserResponse = iam.createUser(createUserRequest);  
            System.out.println("User creation response: " + createUserResponse.user().userName());  
            GetUserRequest getUserRequest = GetUserRequest.builder()  
                    .userName(createUserResponse.user().userName())  
                    .build();  
            WaiterResponse<GetUserResponse> waitUntilUserExists = iam.waiter().waitUntilUserExists(getUserRequest);  
            waitUntilUserExists.matched().response().ifPresent(user -> System.out.println("User exists: " + user.user().userName()));  

           return createUserResponse.user().userName();  

         } catch (IamException e) {  

            System.err.println("Error occurred: " + e.awsErrorDetails().errorMessage());  
            System.exit(1);  
        }  
        return "";  
    }  
} 

Creating a Bucket

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; 
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; 
import software.amazon.awssdk.regions.Region; 
import software.amazon.awssdk.services.s3.S3Client; 
import software.amazon.awssdk.services.s3.model.CreateBucketRequest; 
import software.amazon.awssdk.services.s3.model.HeadBucketRequest; 
import software.amazon.awssdk.services.s3.model.S3Exception; 
import java.net.URI; 

public class CreateBucket { 
    public static void main(String[] args) { 
        String accessKey = "your-access-key";   // Replace with your access key 
        String secretKey = "your-secret-key";   // Replace with your secret key 
        Region region = Region.of("us-east-1");  // Use the correct bucket region  
        String endpointUrl = "https://s3.us-east-1.wasabisys.com";  // Use the appropriate Endpoint URL accoring to your bucket region 

        S3Client s3Client = S3Client.builder() 
                .region(region) 
                .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))) 
                .endpointOverride(URI.create(endpointUrl)) 
                .build(); 

        String bucketName = "your-bucket-name"; //please enter the bucket name 
        createBucket(s3Client, bucketName); 
        s3Client.close(); 
} 

private static void createBucket(S3Client s3Client, String bucketName) { 
        try { 
            s3Client.createBucket(CreateBucketRequest.builder().bucket(bucketName).build()); 
            System.out.println("Bucket " + bucketName + " created successfully."); 
            s3Client.waiter().waitUntilBucketExists(HeadBucketRequest.builder().bucket(bucketName).build()); 
            System.out.println(bucketName + " is ready."); 
        } catch (S3Exception e) { 
            System.err.println("Error creating bucket: " + e.awsErrorDetails().errorMessage()); 
            System.exit(1); 
        } 
    } 
} 

Uploading an Object to the Bucket

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; 
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; 
import software.amazon.awssdk.services.s3.model.PutObjectRequest; 
import software.amazon.awssdk.services.s3.model.PutObjectResponse; 
import software.amazon.awssdk.core.async.AsyncRequestBody; 
import software.amazon.awssdk.services.s3.S3AsyncClient; 
import software.amazon.awssdk.regions.Region; 

import java.nio.file.Paths; 
import java.util.concurrent.CompletableFuture; 

public class UploadObject { 

    private final S3AsyncClient s3AsyncClient; 

    public UploadObject(String accessKey, String secretKey, String region, String endpointUrl) { 
        try { 
            this.s3AsyncClient = S3AsyncClient.builder() 
                    .region(Region.of(region)) 
                    .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))) 
                    .endpointOverride(java.net.URI.create(endpointUrl)) 
                    .build(); 
            System.out.println("S3AsyncClient initialized successfully."); 
        } catch (Exception e) { 
            System.err.println("Error initializing S3AsyncClient: " + e.getMessage()); 
            throw new RuntimeException("Failed to initialize S3 client", e); 
        } 
    } 
  
    public CompletableFuture<PutObjectResponse> uploadLocalFileAsync(String bucketName, String key, String objectPath) { 

        PutObjectRequest objectRequest = PutObjectRequest.builder() 
                .bucket(bucketName) 
                .key(key) 
                .build(); 

        CompletableFuture<PutObjectResponse> uploadFuture = s3AsyncClient.putObject(objectRequest, AsyncRequestBody.fromFile(Paths.get(objectPath))) 
                .exceptionally(ex -> { 
                    System.err.println("Failed to upload file to S3: " + ex.getMessage()); 
                    return null;   
                }); 

        uploadFuture.thenAccept(response -> { 
            if (response != null) { 
                System.out.println("Successfully uploaded the file to S3."); 
            } else { 
                System.err.println("Upload failed"); 
            } 
        }); 
        return uploadFuture; 
    } 

    public static void main(String[] args) { 

        String accessKey = "your-access-key"; // Replace with your access key 
        String secretKey = "your-secret-access-key"; // Replace with your secret key 
        String region = "us-east-1";  // Your bucket region 
        String endpointUrl = "https://s3.wasabisys.com";  // Endpoint URL for Wasabi S3, please change this to your appropriate bucket regin endpointURL 
        String bucketName = "bucket-name"; // your bucket name 
        String key = "your-object-prefix";  // The key (name) for the uploaded file in S3 
        String objectPath = "path-to-the-objectkey/file-name";  // Local file path , for example /Users/user-name/desktop/file-name 

        UploadObject uploadObject = new UploadObject(accessKey, secretKey, region, endpointUrl); 

        CompletableFuture<PutObjectResponse> uploadFuture = uploadObject.uploadLocalFileAsync(bucketName, key, objectPath); 

        try { 
            uploadFuture.get();  

        } catch (Exception e) { 

            System.err.println("Error occurred during the upload: " + e.getMessage()); 

        } finally { 

            try { 
                System.out.println("Closing S3 client..."); 
                uploadObject.s3AsyncClient.close(); 
                System.out.println("S3 client closed successfully."); 
            } catch (Exception e) { 
                System.err.println("Error closing S3 client: " + e.getMessage()); 
            } 
        } 
    } 
} 

Downloading an Object From the Bucket

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; 
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; 
import software.amazon.awssdk.services.s3.S3AsyncClient; 
import software.amazon.awssdk.services.s3.model.GetObjectRequest; 
import software.amazon.awssdk.services.s3.model.S3Exception; 
import software.amazon.awssdk.regions.Region; 
import software.amazon.awssdk.core.async.AsyncResponseTransformer; 

import java.nio.file.Path; 
import java.net.URI;   
import java.util.concurrent.CompletableFuture; 

public class DownloadObjectAsync { 

    public static void main(String[] args) { 

        String region = "us-east-1";  // Replace with your region 
        String accessKey = "your-access-key";  // Replace with your access key 
        String secretKey = "your-secret-key";  // Replace with your secret key 
        String endpointUrl = "https://s3.wasabisys.com";  // Replace with your endpoint URL depending upon the bucket region 
        String bucketName = "bucket-name";  // Replace with your bucket name 
        String objectKey = "your-object-prefix";  // Object key in bucket 
        String downloadPath = "your-local-path";  // Local download path 

        S3AsyncClient s3AsyncClient = S3AsyncClient.builder() 
                .region(Region.of(region)) 
                .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))) 
                .endpointOverride(URI.create(endpointUrl))   
                .build(); 

        GetObjectRequest getObjectRequest = GetObjectRequest.builder() 
                .bucket(bucketName) 
                .key(objectKey) 
                .build(); 

        CompletableFuture<Void> future = s3AsyncClient.getObject(getObjectRequest, 
                AsyncResponseTransformer.toFile(Path.of(downloadPath)))   
                .thenRun(() -> { 
                    System.out.println("Successfully downloaded object to: " + downloadPath); 
                }) 
                .exceptionally(ex -> { 
                    if (ex instanceof S3Exception) { 
                        S3Exception s3Ex = (S3Exception) ex; 
                        System.err.println("S3 Error: " + s3Ex.awsErrorDetails().errorMessage()); 
                    } else { 
                        System.err.println("Unexpected error: " + ex.getMessage()); 
                    } 
                    ex.printStackTrace(); 
                    return null; 
                }) 
                .whenComplete((resp, ex) -> { 
                    System.out.println("Download operation completed."); 
                    if (s3AsyncClient != null) { 
                        s3AsyncClient.close(); 
                        System.out.println("S3AsyncClient closed."); 
                    } 
                }); 

        future.join();   
    } 
} 

Deleting the Object From the Bucket

import software.amazon.awssdk.services.s3.S3AsyncClient; 
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; 
import software.amazon.awssdk.services.s3.model.DeleteObjectResponse; 
import software.amazon.awssdk.regions.Region; 
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; 
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; 
import java.net.URI; 
import java.util.concurrent.CompletableFuture; 

public class DeleteObjectExample { 

    public CompletableFuture<Void> deleteObjectFromBucketAsync(S3AsyncClient s3AsyncClient, String bucketName, String key) { 
        DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder() 
            .bucket(bucketName)  
            .key(key)           
            .build();             

        CompletableFuture<DeleteObjectResponse> response = s3AsyncClient.deleteObject(deleteObjectRequest); 

        return response.whenComplete((deleteRes, ex) -> { 
            if (deleteRes != null) { 
                System.out.println(key + " was successfully deleted."); 
            } else { 
                System.err.println("Error deleting object: " + ex.getMessage()); 
                throw new RuntimeException("An error occurred during the deletion of the object.", ex); 
            } 
        }).thenApply(r -> null);  
    } 
    public static void main(String[] args) { 
        String accessKey = "your-access-key"; // Replace with your access key 
        String secretKey = "your-secret-key"; // Replace with your secret key 
        String bucketName = "bucket-name"; // Replace with your bucket name 
        String objectKey = "your-object-prefix";  

        Region region = Region.of("us-east-1"); // Replace with your region 
        URI endpoint = URI.create("https://s3.wasabisys.com"); //Enter the endpoint URL associated with your bucket region 
        S3AsyncClient s3AsyncClient = S3AsyncClient.builder() 
            .region(region) 
            .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))) 
            .endpointOverride(endpoint)   
            .build(); 

        DeleteObjectExample deleteExample = new DeleteObjectExample(); 
        CompletableFuture<Void> deleteFuture = deleteExample.deleteObjectFromBucketAsync(s3AsyncClient, bucketName, objectKey); 

        deleteFuture.join();   
        s3AsyncClient.close(); 
    } 
}