Object Storage Service (OSS) では、オブジェクトタグを設定してオブジェクトを分類できます。 ライフサイクルルールを設定し、タグに基づいてオブジェクトへのアクセスを制御できます。
使用上の注意
オブジェクトのタグ付けを設定する前に、この機能に精通していることを確認してください。 詳細については、「オブジェクトのタグ付け」をご参照ください。
このトピックでは、中国 (杭州) リージョンのパブリックエンドポイントを使用します。 OSSと同じリージョンにある他のAlibaba CloudサービスからOSSにアクセスする場合は、内部エンドポイントを使用します。 OSSリージョンとエンドポイントの詳細については、「リージョン、エンドポイント、オープンポート」をご参照ください。
このトピックでは、アクセス資格情報は環境変数から取得します。 アクセス資格情報の設定方法の詳細については、「アクセス資格情報の設定」をご参照ください。
このトピックでは、OSSエンドポイントを使用してOSSClientインスタンスを作成します。 カスタムドメイン名またはSecurity Token Service (STS) を使用してOSSClientインスタンスを作成する場合は、「OSSClientインスタンスの作成」をご参照ください。
OSS SDK for Java 3.5.0以降のみがオブジェクトタグ付けをサポートしています。
オブジェクトにタグを追加するには、
oss:PutObjectTagging
権限が必要です。 詳細については、「RAMユーザーへのカスタムポリシーのアタッチ」をご参照ください。
オブジェクトをアップロードするときにオブジェクトにタグを追加する
次の例では、単純アップロード、マルチパートアップロード、追加アップロード、および再開可能アップロードを使用してオブジェクトをアップロードするときに、オブジェクトにタグを追加する方法について説明します。
シンプルアップロードを使用してオブジェクトをアップロードするときにオブジェクトにタグを追加する
次のサンプルコードでは、単純アップロードを使用してオブジェクトをアップロードするときに、オブジェクトにタグを追加する方法の例を示します。
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.*; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Map; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. String objectName = "exampledir/exampleobject.txt"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { Map<String, String> tags = new HashMap<String, String>(); // Specify the key and value of the object tags. For example, set the key to owner and value to John. tags.put("owner", "John"); tags.put("type", "document"); // Configure the tags in the HTTP header. ObjectMetadata metadata = new ObjectMetadata(); metadata.setObjectTagging(tags); // Upload the object and add the tags to the object. String content = "<yourtContent>"; ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()), metadata); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
マルチパートアップロードを使用してオブジェクトをアップロードするときにオブジェクトにタグを追加する
次のサンプルコードは、マルチパートアップロードを使用してオブジェクトをアップロードするときに、オブジェクトにタグを追加する方法の例を示しています。
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.*; import java.io.*; import java.util.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. String objectName = "exampledir/exampleobject.txt"; // Specify the full path of the local file that you want to upload. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs. String localFile = "D:\\localpath\\examplefile.txt"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { /* Step 1: Initiate a multipart upload task. */ // Configure the tags in the HTTP header. Map<String, String> tags = new HashMap<String, String>(); // Specify the key and value of the object tags. For example, set the key to owner and value to John. tags.put("owner", "John"); tags.put("type", "document"); ObjectMetadata metadata = new ObjectMetadata(); metadata.setObjectTagging(tags); // Initiate an InitiateMultipartUploadRequest request and add the tags to the object. InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName, metadata); InitiateMultipartUploadResult result = ossClient.initiateMultipartUpload(request); // Obtain the upload ID. The upload ID uniquely identifies the multipart upload task. The upload ID can be used to query or cancel the multipart upload task. String uploadId = result.getUploadId(); /* Step 2: Upload parts. */ // partETags is a set of PartETags. A PartETag consists of the part number and ETag of an uploaded part. List<PartETag> partETags = new ArrayList<PartETag>(); // Calculate the total number of parts. final long partSize = 1 x 1024 x 1024L; // Set the part size to 1 MB. final File sampleFile = new File(localFile); long fileLength = sampleFile.length(); int partCount = (int) (fileLength / partSize); if (fileLength % partSize != 0) { partCount++; } // Upload all parts. for (int i = 0; i < partCount; i++) { long startPos = i * partSize; long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize; InputStream instream = null; try { instream = new FileInputStream(sampleFile); // Skip the parts that are uploaded. instream.skip(startPos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } UploadPartRequest uploadPartRequest = new UploadPartRequest(); uploadPartRequest.setBucketName(bucketName); uploadPartRequest.setKey(objectName); uploadPartRequest.setUploadId(uploadId); uploadPartRequest.setInputStream(instream); // Specify the part size. Each part except the last part must be equal to or greater than 100 KB in size. uploadPartRequest.setPartSize(curPartSize); // Specify part numbers. Each part requires a part number. The part number ranges from 1 to 10000. If you specify a part number that exceeds this range, OSS returns the InvalidArgument error code. uploadPartRequest.setPartNumber( i + 1); // Parts are not necessarily uploaded in order and can be uploaded from different OSS clients. OSS sorts the parts based on the part numbers and combines the parts into a complete object. UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest); // After you upload a part, OSS returns a PartETag. The PartETag is stored in partETags. partETags.add(uploadPartResult.getPartETag()); } /* Step 3: Complete multipart upload. */ // The PartETags stored in partEtags are sorted in ascending order by part numbers. Collections.sort(partETags, new Comparator<PartETag>() { public int compare(PartETag p1, PartETag p2) { return p1.getPartNumber() - p2.getPartNumber(); } }); // Provide all valid PartETags when you perform this operation. OSS verifies the validity of all parts one by one after it receives PartETags. After all parts are verified, OSS combines the parts into a complete object. CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags); ossClient.completeMultipartUpload(completeMultipartUploadRequest); // View the tags added to the object. TagSet tagSet = ossClient.getObjectTagging(bucketName, objectName); Map<String, String> getTags = tagSet.getAllTags(); System.out.println("object tagging: "+ getTags.toString()); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
追加アップロードを使用してオブジェクトをアップロードするときにオブジェクトにタグを追加する
次のサンプルコードは、追加アップロードを使用してオブジェクトをアップロードするときに、オブジェクトにタグを追加する方法の例を示しています。
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.*; import java.io.*; import java.util.*; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. String objectName = "exampledir/exampleobject.txt"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { String content1 = "Hello OSS A \n"; String content2 = "Hello OSS B \n"; String content3 = "Hello OSS C \n"; Map<String, String> tags = new HashMap<String, String>(); // Specify the key and value of the object tags. For example, set the key to owner and value to John. tags.put("owner", "John"); tags.put("type", "document"); ObjectMetadata meta = new ObjectMetadata(); // Configure tags for the object. meta.setObjectTagging(tags); // Specify the type of content that you want to upload. meta.setContentType("text/plain"); // Configure parameters by using AppendObjectRequest. AppendObjectRequest appendObjectRequest = new AppendObjectRequest(bucketName, objectName, new ByteArrayInputStream(content1.getBytes()), meta); // Configure a parameter by using AppendObjectRequest. //appendObjectRequest.setBucketName(bucketName); //appendObjectRequest.setKey(objectName); // Configure the type of the content that you want to append. Two types are supported: InputStream and File. In this example, the type is set to InputStream. //appendObjectRequest.setInputStream(new ByteArrayInputStream(content1.getBytes())); // Configure the type of the content that you want to append. Two types are supported: InputStream and File. In this example, the type is set to File. // Specify the full path of the local file that you want to upload. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs. //appendObjectRequest.setFile(new File("D:\\localpath\\examplefile.txt")); // Specify the metadata of the object. You can specify the metadata only when you perform the first append operation on the object. //appendObjectRequest.setMetadata(meta); // Perform the first append operation. Only the tags configured when the object is appended for the first time are added to the object. // Configure the position from which the append operation starts. appendObjectRequest.setPosition(0L); AppendObjectResult appendObjectResult = ossClient.appendObject(appendObjectRequest); // Calculate the CRC-64 of the object. The value is calculated based on the ECMA-182 specification. System.out.println(appendObjectResult.getObjectCRC()); // Perform the second append operation. // NextPosition specifies the position from which the next append operation starts, which is the length of the object. appendObjectRequest.setPosition(appendObjectResult.getNextPosition()); appendObjectRequest.setInputStream(new ByteArrayInputStream(content2.getBytes())); appendObjectResult = ossClient.appendObject(appendObjectRequest); // Perform the third append operation. appendObjectRequest.setPosition(appendObjectResult.getNextPosition()); appendObjectRequest.setInputStream(new ByteArrayInputStream(content3.getBytes())); appendObjectResult = ossClient.appendObject(appendObjectRequest); // View the tags added to the uploaded object. TagSet tagSet = ossClient.getObjectTagging(bucketName, objectName); Map<String, String> getTags = tagSet.getAllTags(); System.out.println("object tagging: "+ getTags.toString()); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
再開可能アップロードを使用してオブジェクトをアップロードするときにオブジェクトにタグを追加する
次のサンプルコードは、再開可能アップロードを使用してオブジェクトをアップロードするときに、オブジェクトにタグを追加する方法の例を示しています。
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.*; import java.util.*; public class Demo { public static void main(String[] args) throws Throwable { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. String objectName = "exampledir/exampleobject.txt"; // Specify the full path of the local file that you want to upload. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs. String localFile = "D:\\localpath\\examplefile.txt"; // Specify the checkpoint file that records the upload progress of each part. The name of the checkpoint file must contain the .ucp extension and be in the same path as the local file specified by localFile. // After the local file is uploaded to OSS, the checkpoint file is deleted. String yourCheckpointFile = "D:\\localpath\\uploadfile.ucp"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Configure the tags that you want to add to the object. Map<String, String> tags = new HashMap<String, String>(); // Specify the key and value of the object tags. For example, set the key to owner and value to John. tags.put("owner", "John"); tags.put("type", "document"); ObjectMetadata meta = new ObjectMetadata(); // Specify the type of content that you want to upload. meta.setContentType("text/plain"); // Add the tags to the object. meta.setObjectTagging(tags); // Configure parameters by using UploadFileRequest. UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName,objectName); // Configure a parameter by using UploadFileRequest. // Specify the name of the bucket. //uploadFileRequest.setBucketName(bucketName); // Specify the full path of the object. Do not include the bucket name in the full path. //uploadFileRequest.setKey(objectName); // Specify the name of the local file that you want to upload. uploadFileRequest.setUploadFile(localFile); // Specify the number of threads for the resumable upload task. Default value: 1. uploadFileRequest.setTaskNum(5); // Specify the size of each part. Valid values: 100 KB to 5 GB. The default size of each part is calculated based on the following formula: Default size of each part = Object size/10,000. uploadFileRequest.setPartSize(1 * 1024 * 1024); // Enable resumable upload. By default, resumable upload is disabled. uploadFileRequest.setEnableCheckpoint(true); // Specify the checkpoint file that records the upload progress of each part. If you enable resumable upload, you must configure this parameter. The checkpoint file stores the upload progress. If a part fails to be uploaded, OSS can resume the upload of the part based on the progress information recorded in the checkpoint file. After the local file is uploaded to OSS, the checkpoint file is deleted. By default, the checkpoint file shares the same directory (uploadFile.ucp) as the local file that you want to upload. uploadFileRequest.setCheckpointFile(yourCheckpointFile); // Configure object metadata. uploadFileRequest.setObjectMetadata(meta); // Configure a callback after the object is uploaded. The parameter type is Callback. //uploadFileRequest.setCallback("yourCallbackEvent"); // Start the resumable upload task and configure the tags that you want to add to the object. ossClient.uploadFile(uploadFileRequest); // View the tags added to the uploaded object. TagSet tagSet = ossClient.getObjectTagging(bucketName, objectName); Map<String, String> getTags = tagSet.getAllTags(); System.out.println("object tagging: "+ getTags.toString()); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
既存のオブジェクトへのタグの追加またはタグの変更
既存のオブジェクトにタグがない場合、またはオブジェクトのタグが要件を満たしていない場合は、オブジェクトのタグを追加または変更できます。
次のサンプルコードは、既存のオブジェクトのタグを追加または変更する方法の例を示しています。
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import java.util.*;
public class Demo {
public static void main(String[] args) throws Throwable {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
String objectName = "exampledir/exampleobject.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
Map<String, String> tags = new HashMap<String, String>();
// Specify the key and value of the object tags. For example, set the key to owner and value to John.
tags.put("owner", "John");
tags.put("type", "document");
// Add tags to the object.
ossClient.setObjectTagging(bucketName, objectName, tags);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
オブジェクトの特定のバージョンのタグを追加または変更する
バケットのバージョン管理が有効になっている場合、オブジェクトのバージョンIDを指定することで、バケット内のオブジェクトの特定のバージョンにタグを追加したり、タグを変更したりできます。
次のサンプルコードでは、特定のバージョンのオブジェクトにタグを追加またはタグを変更する方法の例を示します。
バージョンIDの取得方法の詳細については、「オブジェクトのリスト」をご参照ください。
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.SetObjectTaggingRequest;
import java.util.*;
public class Demo {
public static void main(String[] args) throws Throwable {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
String objectName = "exampledir/exampleobject.txt";
// Specify the version ID of the object. Example: CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****.
String versionId = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
Map<String, String> tags = new HashMap<String, String>(1);
// Specify the key and value of the object tags. For example, set the key to owner and value to John.
tags.put("owner", "John");
tags.put("type", "document");
SetObjectTaggingRequest setObjectTaggingRequest = new SetObjectTaggingRequest(bucketName, objectName, tags);
setObjectTaggingRequest.setVersionId(versionId);
ossClient.setObjectTagging(setObjectTaggingRequest);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
オブジェクトをコピーするときにオブジェクトにタグを追加する
次のいずれかの方法を使用して、オブジェクトをコピーするときにオブジェクトのタグ付けを設定できます。
コピー: ソースオブジェクトのタグがコピー先オブジェクトにコピーされます。
置換: ターゲットオブジェクトには、ソースオブジェクトのタグではなく、リクエストで指定されたタグがあります。
次の例では、シンプルコピーモードで1 GB未満のオブジェクトに、マルチパートコピーモードで1 GBを超えるオブジェクトにタグを追加する方法について説明します。
シンプルコピーモードでオブジェクトをコピーするときにオブジェクトにタグを追加する
次のサンプルコードは、シンプルコピーモードでオブジェクトをコピーするときに、1 GB未満のオブジェクトにタグを追加する方法の例を示しています。
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.internal.OSSHeaders; import com.aliyun.oss.model.CopyObjectRequest; import com.aliyun.oss.model.CopyObjectResult; import com.aliyun.oss.model.TagSet; import java.util.*; public class Demo { public static void main(String[] args) throws Throwable { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the source bucket. Example: srcexamplebucket. String sourceBucketName = "srcexamplebucket"; // Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcexampledir/exampleobject.txt. String sourceObjectName = "srcexampledir/exampleobject.txt"; // Specify the name of the destination bucket. Example: destexamplebucket. String destinationBucketName = "destexamplebucket"; // Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destexampledir/exampleobject.txt. String destinationObjectName = "destexampledir/exampleobject.txt"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Create CopyObjectRequest. CopyObjectRequest copyObjectRequest = new CopyObjectRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName); // Configure the tags that you want to add to the destination object. If the headers are not configured, the tags of the source object are added to the destination object by default. Map<String, String> headers = new HashMap<String, String>(); headers.put(OSSHeaders.COPY_OBJECT_TAGGING_DIRECTIVE, "REPLACE"); headers.put(OSSHeaders.OSS_TAGGING, "key1=value1&key2=value2"); copyObjectRequest.setHeaders(headers); // Copy the source object. CopyObjectResult result = ossClient.copyObject(copyObjectRequest); System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified()); // View the tags added to the destination object. TagSet tagSet = ossClient.getObjectTagging(destinationBucketName, destinationObjectName); Map<String, String> getTags = tagSet.getAllTags(); System.out.println("dest object tagging: "+ getTags.toString()); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
マルチパートコピーモードでオブジェクトをコピーするときにオブジェクトにタグを追加する
次のサンプルコードは、マルチパートコピーモードでオブジェクトをコピーするときに、1 GBを超えるオブジェクトにタグを追加する方法の例を示しています。
import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.*; import java.util.*; public class Demo { public static void main(String[] args) throws Throwable { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the source bucket. Example: srcexamplebucket. String sourceBucketName = "srcexamplebucket"; // Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcexampledir/exampleobject.txt. String sourceObjectName = "srcexampledir/exampleobject.txt"; // Specify the name of the destination bucket. Example: destexamplebucket. String destinationBucketName = "destexamplebucket"; // Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destexampledir/exampleobject.txt. String destinationObjectName = "destexampledir/exampleobject.txt"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { ObjectMetadata objectMetadata = ossClient.getObjectMetadata(sourceBucketName, sourceObjectName); // Query the size of the source object. long contentLength = objectMetadata.getContentLength(); // Set the part size to 10 MB. long partSize = 1024 * 1024 * 10; // Calculate the total number of parts. int partCount = (int) (contentLength / partSize); if (contentLength % partSize != 0) { partCount++; } System.out.println("total part count:" + partCount); // Configure the tags in the HTTP header. Map<String, String> tags2 = new HashMap<String, String>(); // Specify the key and value of the object tags. For example, set the key to owner and the value to Lily. tags2.put("owner", "Lily"); tags2.put("type", "document"); ObjectMetadata metadata = new ObjectMetadata(); metadata.setObjectTagging(tags2); // Initiate a multipart copy task and configure the tags that you want to add to the destination object. InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(destinationBucketName, destinationObjectName, metadata); InitiateMultipartUploadResult initiateMultipartUploadResult = ossClient.initiateMultipartUpload(initiateMultipartUploadRequest); String uploadId = initiateMultipartUploadResult.getUploadId(); // Start the multipart copy task. List<PartETag> partETags = new ArrayList<PartETag>(); for (int i = 0; i < partCount; i++) { // Calculate the size of each part. long skipBytes = partSize * i; long size = partSize < contentLength - skipBytes ? partSize : contentLength - skipBytes; // Create UploadPartCopyRequest. You can specify conditions by using UploadPartCopyRequest. UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName); uploadPartCopyRequest.setUploadId(uploadId); uploadPartCopyRequest.setPartSize(size); uploadPartCopyRequest.setBeginIndex(skipBytes); uploadPartCopyRequest.setPartNumber(i + 1); UploadPartCopyResult uploadPartCopyResult = ossClient.uploadPartCopy(uploadPartCopyRequest); // Store the returned PartETags in partETags. partETags.add(uploadPartCopyResult.getPartETag()); } // Complete the multipart copy task. CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest( destinationBucketName, destinationObjectName, uploadId, partETags); CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest); System.out.println("versionId: "+completeMultipartUploadResult.getVersionId()); // View the tags of the source object. TagSet tagSet = ossClient.getObjectTagging(sourceBucketName, sourceObjectName); Map<String, String> getTags = tagSet.getAllTags(); System.out.println("src object tagging: "+ getTags.toString()); // View the tags added to the destination object. tagSet = ossClient.getObjectTagging(destinationBucketName, destinationObjectName); getTags = tagSet.getAllTags(); System.out.println("dest object tagging: "+ getTags.toString()); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
シンボリックリンクにタグを追加する
次のサンプルコードは、シンボリックリンクにタグを追加する方法の例を示しています。
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.*;
public class Demo {
public static void main(String[] args) throws Throwable {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the symbolic link. Example: shortcut/myobject.txt.
String symLink = "shortcut/myobject.txt";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
String destinationObjectName = "exampledir/exampleobject.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Configure the tags that you want to add to the symbolic link.
Map<String, String> tags = new HashMap<String, String>();
// Specify the key and value of the object tags. For example, set the key to owner and value to John.
tags.put("owner", "John");
tags.put("type", "document");
// Configure metadata for the uploaded object.
ObjectMetadata metadata = new ObjectMetadata();
metadata.setObjectTagging(tags);
// Create CreateSymlinkRequest.
CreateSymlinkRequest createSymlinkRequest = new CreateSymlinkRequest(bucketName, symLink, destinationObjectName);
// Configure metadata.
createSymlinkRequest.setMetadata(metadata);
// Create the symbolic link.
ossClient.createSymlink(createSymlinkRequest);
// View the tags added to the symbolic link.
TagSet tagSet = ossClient.getObjectTagging(bucketName, symLink);
Map<String, String> getTags = tagSet.getAllTags();
System.out.println("symLink tagging: "+ getTags.toString());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
関連ドキュメント
オブジェクトのタグ付けの設定に使用される完全なサンプルコードについては、『GitHub』をご参照ください。
オブジェクトのタグ付けを設定するために呼び出すことができるAPI操作の詳細については、「PutObjectTagging」をご参照ください。