すべてのプロダクト
Search
ドキュメントセンター

Object Storage Service:バケット在庫

最終更新日:Oct 28, 2024

このトピックでは、バケットのインベントリを作成する方法と、バケットに設定されたインベントリを照会、一覧表示、および削除する方法について説明します。

使用上の注意

  • このトピックでは、中国 (杭州) リージョンのパブリックエンドポイントを使用します。 OSSと同じリージョンにある他のAlibaba CloudサービスからOSSにアクセスする場合は、内部エンドポイントを使用します。 OSSリージョンとエンドポイントの詳細については、「リージョン、エンドポイント、オープンポート」をご参照ください。

  • このトピックでは、アクセス資格情報は環境変数から取得します。 アクセス資格情報の設定方法の詳細については、「アクセス資格情報の設定」をご参照ください。

  • このトピックでは、OSSエンドポイントを使用してOSSClientインスタンスを作成します。 カスタムドメイン名またはSecurity Token Service (STS) を使用してOSSClientインスタンスを作成する場合は、「OSSClientインスタンスの作成」をご参照ください。

  • バケットのインベントリを作成、表示、一覧表示、および削除する権限があることを確認します。 デフォルトでは、バケット所有者に上記の操作を実行する権限があります。 上記の操作を実行する権限がない場合は、バケットの所有者に権限を付与するよう依頼してください。

  • バケットには最大1,000のインベントリを設定できます。

  • インベントリを構成するソースバケットは、インベントリリストが保存されているターゲットバケットと同じリージョンにデプロイする必要があります。

バケットのインベントリを作成する

次のコードは、バケットのインベントリを作成する方法の例を示しています。

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.ArrayList;
import java.util.List;

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 name of the bucket in which you want to store the generated inventory lists. 
        String destBucketName ="yourDestinationBucketName";
        // Specify the account ID granted by the bucket owner. 
        String accountId ="yourDestinationBucketAccountId";
        // Specify the name of the RAM role that is granted the permissions to read all objects in the bucket for which you want to configure the inventory and the permissions to write data to the bucket in which you want to store the generated inventory lists. 
        String roleArn ="yourDestinationBucketRoleArn";
        // 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 an inventory. 
            InventoryConfiguration inventoryConfiguration = new InventoryConfiguration();

            // Specify the inventory name. 
            String inventoryId = "testid";
            inventoryConfiguration.setInventoryId(inventoryId);

            // Specify the object attributes that are included in inventory lists. 
            List<String> fields = new ArrayList<String>();
            fields.add(InventoryOptionalFields.Size);
            fields.add(InventoryOptionalFields.LastModifiedDate);
            fields.add(InventoryOptionalFields.IsMultipartUploaded);
            fields.add(InventoryOptionalFields.StorageClass);
            fields.add(InventoryOptionalFields.ETag);
            fields.add(InventoryOptionalFields.EncryptionStatus);
            inventoryConfiguration.setOptionalFields(fields);

            // Specify whether to generate inventory lists on a daily or weekly basis. The following code provides an example on how to generate the inventory lists on a weekly basis. Weekly indicates that the inventory lists are generated once a week and Daily indicates that the inventory lists are generated once a day. 
            inventoryConfiguration.setSchedule(new InventorySchedule().withFrequency(InventoryFrequency.Weekly));

            // Specify that the inventory lists include only the current version of objects. If you set the InventoryIncludedObjectVersions parameter to All, all versions of objects are included in the inventory lists. This configuration takes effect only when you enable versioning for the bucket. 
            inventoryConfiguration.setIncludedObjectVersions(InventoryIncludedObjectVersions.Current);

            // Specify whether the inventory is enabled. Valid values: true and false. Set the value to true to enable the inventory. Set the value to false to disable the inventory. 
            inventoryConfiguration.setEnabled(true);

            // Specify the rule used to filter the objects to include in the inventory lists. The following code provides an example on how to filter the objects by prefix. 
            InventoryFilter inventoryFilter = new InventoryFilter().withPrefix("obj-prefix");
            inventoryConfiguration.setInventoryFilter(inventoryFilter);

            // Specify the destination bucket in which you want to store the generated inventory lists. 
            InventoryOSSBucketDestination ossInvDest = new InventoryOSSBucketDestination();
            // Specify the prefix of the path in which you want to store the generated inventory lists. 
            ossInvDest.setPrefix("destination-prefix");
            // Specify the format of the inventory lists. 
            ossInvDest.setFormat(InventoryFormat.CSV);
            // Specify the ID of the account to which the destination bucket belongs. 
            ossInvDest.setAccountId(accountId);
            // Specify the role ARN of the destination bucket. 
            ossInvDest.setRoleArn(roleArn);
            // Specify the name of the destination bucket. 
            ossInvDest.setBucket(destBucketName);

            // The following code provides an example on how to encrypt the inventory lists by using customer master keys (CMKs) hosted in Key Management System (KMS). 
            // InventoryEncryption inventoryEncryption = new InventoryEncryption();
            // InventoryServerSideEncryptionKMS serverSideKmsEncryption = new InventoryServerSideEncryptionKMS().withKeyId("test-kms-id");
            // inventoryEncryption.setServerSideKmsEncryption(serverSideKmsEncryption);
            // ossInvDest.setEncryption(inventoryEncryption);

            // The following code provides an example on how to encrypt the inventory lists on the OSS server. 
            // InventoryEncryption inventoryEncryption = new InventoryEncryption();
            // inventoryEncryption.setServerSideOssEncryption(new InventoryServerSideEncryptionOSS());
            // ossInvDest.setEncryption(inventoryEncryption);

            // Specify the destination for the generated inventory lists. 
            InventoryDestination destination = new InventoryDestination();
            destination.setOssBucketDestination(ossInvDest);
            inventoryConfiguration.setDestination(destination);

            // Configure the inventory for the bucket. 
            ossClient.setBucketInventoryConfiguration(bucketName, inventoryConfiguration);
        } 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.List;

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 inventory name. 
        String inventoryId = "yourInventoryConfigurationId";
        // 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 {
            // Query the configuration of the specified inventory. 
            GetBucketInventoryConfigurationRequest request = new GetBucketInventoryConfigurationRequest(bucketName, inventoryId);
            GetBucketInventoryConfigurationResult getResult = ossClient.getBucketInventoryConfiguration(request);

            // Display the configuration of the inventory. 
            InventoryConfiguration config = getResult.getInventoryConfiguration();
            System.out.println("=====Inventory configuration=====");
            System.out.println("inventoryId:" + config.getInventoryId());
            System.out.println("isenabled:" + config.isEnabled());
            System.out.println("includedVersions:" + config.getIncludedObjectVersions());
            System.out.println("schdule:" + config.getSchedule().getFrequency());
            if (config.getInventoryFilter().getPrefix() != null) {
                System.out.println("filter, prefix:" + config.getInventoryFilter().getPrefix());
            }

            List<String> fields = config.getOptionalFields();
            for (String field : fields) {
                System.out.println("field:" + field);
            }

            System.out.println("===bucket destination config===");
            InventoryOSSBucketDestination destin = config.getDestination().getOssBucketDestination();
            System.out.println("format:" + destin.getFormat());
            System.out.println("bucket:" + destin.getBucket());
            System.out.println("prefix:" + destin.getPrefix());
            System.out.println("accountId:" + destin.getAccountId());
            System.out.println("roleArn:" + destin.getRoleArn());
            if (destin.getEncryption() != null) {
                if (destin.getEncryption().getServerSideKmsEncryption() != null) {
                    System.out.println("server-side kms encryption, key id:" + destin.getEncryption().getServerSideKmsEncryption().getKeyId());
                } else if (destin.getEncryption().getServerSideOssEncryption() != null) {
                    System.out.println("server-side oss encryption.");
                }
            }
        } 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回のリクエストで最大100のインベントリを照会できます。 100を超えるインベントリをクエリするには、複数のリクエストを送信し、各リクエストに対して返されたトークンを次のリクエストのパラメーターとして使用する必要があります。

次のコードは、バケットに設定されたインベントリを一覧表示する方法の例です。

package com.aliyun.oss.demo;

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.List;

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 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 {
            // List the inventories. By default, a maximum of 100 inventories are listed. If more than 100 inventories are configured, the inventories are listed in pages. You can use the continuationToken parameter to list the inventories on the subsequent page. 
            String continuationToken = null;
            while (true) {
                ListBucketInventoryConfigurationsRequest listRequest = new ListBucketInventoryConfigurationsRequest(bucketName, continuationToken);
                ListBucketInventoryConfigurationsResult result = ossClient.listBucketInventoryConfigurations(listRequest);
                System.out.println("=======List bucket inventory configuration=======");
                System.out.println("istruncated:" + result.isTruncated());
                System.out.println("continuationToken:" + result.getContinuationToken());
                System.out.println("nextContinuationToken:" + result.getNextContinuationToken());
                System.out.println("list size :" + result.getInventoryConfigurationList());
                if (result.getInventoryConfigurationList() != null && !result.getInventoryConfigurationList().isEmpty()) {
                    for (InventoryConfiguration config : result.getInventoryConfigurationList()) {
                        System.out.println("===Inventory configuration===");
                        System.out.println("inventoryId:" + config.getInventoryId());
                        System.out.println("isenabled:" + config.isEnabled());
                        System.out.println("includedVersions:" + config.getIncludedObjectVersions());
                        System.out.println("schdule:" + config.getSchedule().getFrequency());
                        if (config.getInventoryFilter().getPrefix() != null) {
                            System.out.println("filter, prefix:" + config.getInventoryFilter().getPrefix());
                        }

                        List<String> fields = config.getOptionalFields();
                        for (String field : fields) {
                            System.out.println("field:" + field);
                        }

                        System.out.println("===bucket destination config===");
                        InventoryOSSBucketDestination destin = config.getDestination().getOssBucketDestination();
                        System.out.println("format:" + destin.getFormat());
                        System.out.println("bucket:" + destin.getBucket());
                        System.out.println("prefix:" + destin.getPrefix());
                        System.out.println("accountId:" + destin.getAccountId());
                        System.out.println("roleArn:" + destin.getRoleArn());
                        if (destin.getEncryption() != null) {
                            if (destin.getEncryption().getServerSideKmsEncryption() != null) {
                                System.out.println("server-side kms encryption key id:" + destin.getEncryption().getServerSideKmsEncryption().getKeyId());
                            } else if (destin.getEncryption().getServerSideOssEncryption() != null) {
                                System.out.println("server-side oss encryption.");
                            }
                        }
                    }

                    if (result.isTruncated()) {
                        continuationToken = result.getNextContinuationToken();
                    } else {
                        break;
                    }
                }
            }
        } 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;

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 name of the inventory that you want to delete. 
        String inventoryId = "yourInventoryConfigurationId";
        // 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 {
            // Delete the inventory. 
            ossClient.deleteBucketInventoryConfiguration(bucketName, inventoryId);
        } 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操作の詳細については、「PutBucketInventory」をご参照ください。

  • バケットに設定されたインベントリを照会するためのAPI操作の詳細については、「GetBucketInventory」をご参照ください。

  • バケットに設定されたインベントリを一覧表示するAPI操作の詳細については、「ListBucketInventory」をご参照ください。

  • バケットに設定されたインベントリを削除するAPI操作の詳細については、「DeleteBucketInventory」をご参照ください。