Set object tags with versioning (Java SDK V2)

Updated at:

This topic describes how to set tags for a specific version of an object in a versioned bucket by using OSS Java SDK V2.

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 examples in this topic use 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. RAM users and RAM roles have no permissions by default. The Alibaba Cloud account owner or an administrator must grant the required permissions.

API

Actions

Description

PutObjectTagging

oss:PutObjectTagging

Sets tags for a specific object version.

Sample code

Set tags for a specific object version

The following code adds or modifies tags for a specific version of an object:

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.*;
import java.util.Arrays;

public class PutObjectTaggingVersionSample {
    public static void main(String[] args) throws Exception {
        String region = "cn-hangzhou";
        String bucket = "examplebucket";
        String key = "exampleobject";
        String versionId = "CAEQMxiBgIDU0YWNkBYiIGRhY2U5ZjYxYzU5NDk5MGFhZjM5Zjg5ZTk5ZDU1";

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

        try (OSSClient client = clientBuilder.build()) {
            Tagging tagging = Tagging.newBuilder()
                    .tagSet(TagSet.newBuilder()
                            .tags(Arrays.asList(
                                    Tag.newBuilder().key("env").value("production").build(),
                                    Tag.newBuilder().key("team").value("storage").build()))
                            .build())
                    .build();

            PutObjectTaggingResult result = client.putObjectTagging(
                    PutObjectTaggingRequest.newBuilder()
                            .bucket(bucket)
                            .key(key)
                            .versionId(versionId)
                            .tagging(tagging)
                            .build());

            System.out.printf("status code:%d, request id:%s%n",
                    result.statusCode(), result.requestId());
        } catch (Exception e) {
            System.out.printf("error:%n%s", e);
        }
    }
}

References