Manage versioning (Java SDK V2)

Updated at:

Manage the versioning state of a bucket by using OSS Java SDK V2 to call the PutBucketVersioning and GetBucketVersioning operations.

Prerequisites

  • OSS Java SDK V2 is installed. If you use Maven, add the following dependency to the pom.xml file: com.aliyun:alibabacloud-oss-v2.

  • Access credentials are configured by using environment variables. The sample code in this topic uses EnvironmentVariableCredentialsProvider to read credentials from the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

Permissions

By default, an Alibaba Cloud account has full permissions. However, the RAM users or RAM roles of the Alibaba Cloud account have no permissions. The Alibaba Cloud account or an account administrator must grant the required permissions to the RAM users or RAM roles.

API

Action

Description

PutBucketVersioning

oss:PutBucketVersioning

Sets or queries the versioning state of a bucket.

Sample code

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.OSSClientBuilder;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.models.*;

public class BucketVersioningSample {
    public static void main(String[] args) throws Exception {
        String region = "cn-hangzhou";
        String bucket = "examplebucket";

        CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
        OSSClientBuilder clientBuilder = OSSClient.newBuilder()
                .credentialsProvider(provider)
                .region(region);

        try (OSSClient client = clientBuilder.build()) {
            // Enable versioning
            VersioningConfiguration versioningConfig = VersioningConfiguration.newBuilder()
                    .status("Enabled")
                    .build();

            PutBucketVersioningResult putResult = client.putBucketVersioning(
                    PutBucketVersioningRequest.newBuilder()
                            .bucket(bucket)
                            .versioningConfiguration(versioningConfig)
                            .build());

            System.out.printf("PutBucketVersioning status code:%d%n", putResult.statusCode());

            // Query the versioning state
            GetBucketVersioningResult getResult = client.getBucketVersioning(
                    GetBucketVersioningRequest.newBuilder()
                            .bucket(bucket)
                            .build());

            System.out.printf("Versioning status: %s%n",
                    getResult.versioningConfiguration().status());

        } catch (Exception e) {
            System.out.printf("error:%n%s", e);
        }
    }
}

References