全部產品
Search
文件中心

Object Storage Service:Java儲存空間清單

更新時間:Oct 25, 2024

本文介紹如何添加、查看、批量列舉和刪除儲存空間(Bucket)的清單(Inventory)配置。

注意事項

  • 本文以華東1(杭州)外網Endpoint為例。如果您希望通過與OSS同地區的其他阿里雲產品訪問OSS,請使用內網Endpoint。關於OSS支援的Region與Endpoint的對應關係,請參見OSS訪問網域名稱、資料中心、開放連接埠

  • 本文以從環境變數讀取存取憑證為例。如何配置訪問憑證,請參見Java配置訪問憑證

  • 本文以OSS網域名稱建立OSSClient為例。如果您希望通過自訂網域名、STS等方式建立OSSClient,請參見建立OSSClient

  • 請確保您擁有調用添加、查看、列舉和刪除儲存空間清單配置的許可權。Bucket所有者預設擁有此類許可權,如果您無此類許可權,請先向Bucket所有者申請對應操作的許可權。

  • 單個Bucket最多隻能有1000條清單配置。

  • 配置清單的源Bucket與存放匯出的資訊清單檔所在的目標Bucket必須位於同一個Region。

添加清單配置

以下代碼用於為某個Bucket添加清單配置:

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 {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 填寫存放清單結果的Bucket名稱。
        String destBucketName ="yourDestinationBucketName";
        // 填寫Bucket所有者授予的賬戶ID。
        String accountId ="yourDestinationBucketAccountId";
        // 填寫具有讀取源Bucket所有檔案和向目標Bucket寫入檔案許可權的角色名稱。
        String roleArn ="yourDestinationBucketRoleArn";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 建立清單配置。
            InventoryConfiguration inventoryConfiguration = new InventoryConfiguration();

            // 設定清單規則名稱。
            String inventoryId = "testid";
            inventoryConfiguration.setInventoryId(inventoryId);

            // 設定清單中包含的Object屬性。
            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);

            // 設定清單的產生計劃,以下樣本為每周一次。其中,Weekly表示每周一次,Daily表示每天一次。
            inventoryConfiguration.setSchedule(new InventorySchedule().withFrequency(InventoryFrequency.Weekly));

            // 設定清單中包含的Object的版本為目前的版本。如果設定為InventoryIncludedObjectVersions.All則表示Object的所有版本在版本控制狀態下生效。
            inventoryConfiguration.setIncludedObjectVersions(InventoryIncludedObjectVersions.Current);

            // 清單配置是否啟用的標識,取值為true或者false,設定為true表示啟用清單配置,設定為false表示關閉清單配置。
            inventoryConfiguration.setEnabled(true);

            // 設定清單篩選規則,指定篩選Object的首碼。
            InventoryFilter inventoryFilter = new InventoryFilter().withPrefix("obj-prefix");
            inventoryConfiguration.setInventoryFilter(inventoryFilter);

            // 建立存放清單結果的目標Bucket配置。
            InventoryOSSBucketDestination ossInvDest = new InventoryOSSBucketDestination();
            // 設定存放清單結果的儲存路徑首碼。
            ossInvDest.setPrefix("destination-prefix");
            // 設定清單格式。
            ossInvDest.setFormat(InventoryFormat.CSV);
            // 設定目標Bucket的使用者accountId。
            ossInvDest.setAccountId(accountId);
            // 設定目標Bucket的roleArn。
            ossInvDest.setRoleArn(roleArn);
            // 設定目標Bucket的名稱。
            ossInvDest.setBucket(destBucketName);

            // 如果需要使用KMS加密清單,請參考如下設定。
            // InventoryEncryption inventoryEncryption = new InventoryEncryption();
            // InventoryServerSideEncryptionKMS serverSideKmsEncryption = new InventoryServerSideEncryptionKMS().withKeyId("test-kms-id");
            // inventoryEncryption.setServerSideKmsEncryption(serverSideKmsEncryption);
            // ossInvDest.setEncryption(inventoryEncryption);

            // 如果需要使用OSS服務端加密清單,請參考如下設定。
            // InventoryEncryption inventoryEncryption = new InventoryEncryption();
            // inventoryEncryption.setServerSideOssEncryption(new InventoryServerSideEncryptionOSS());
            // ossInvDest.setEncryption(inventoryEncryption);

            // 設定清單的目的地。
            InventoryDestination destination = new InventoryDestination();
            destination.setOssBucketDestination(ossInvDest);
            inventoryConfiguration.setDestination(destination);

            // 上傳清單配置。
            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();
            }
        }
    }
}

查看清單配置

以下代碼用於查看某個Bucket的清單配置:

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 {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 指定清單規則名稱。
        String inventoryId = "yourInventoryConfigurationId";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 查看指定清單規則的配置資訊。
            GetBucketInventoryConfigurationRequest request = new GetBucketInventoryConfigurationRequest(bucketName, inventoryId);
            GetBucketInventoryConfigurationResult getResult = ossClient.getBucketInventoryConfiguration(request);

            // 列印清單配置資訊。
            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();
            }
        }
    }
}

批量列舉清單配置

說明

單次請求最多可擷取100條清單配置項內容。若需擷取超過100條清單配置項,則需發送多次請求,並保留相應的Token,作為下一次請求的參數。

以下代碼用於批量列舉某個Bucket的清單配置:

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 {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 列舉清單配置項。預設每次最多列舉100條結果,如果配置超過100條,結果將會分頁返回,通過傳入Token方式列舉下一頁。
            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();
            }
        }
    }
}

刪除清單配置

以下代碼用於刪除某個Bucket的清單配置:

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 {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 指定待刪除的清單規則名稱。
        String inventoryId = "yourInventoryConfigurationId";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 刪除清單配置。
            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();
            }
        }
    }
}

相關文檔