Cette rubrique explique comment créer un inventaire pour un compartiment, ainsi que comment consulter, répertorier et supprimer les inventaires configurés pour un compartiment.
Notes d'utilisation
Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez un point de terminaison interne. Pour plus de détails sur les régions et les points de terminaison pris en charge, consultez Régions et points de terminaison.
Les informations d'identification d'accès sont obtenues à partir des variables d'environnement. Pour plus d'informations, consultez Configurer les informations d'identification d'accès.
Cette rubrique illustre la création d'une instance OSSClient avec un point de terminaison OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification avec des informations d'identification du Security Token Service (STS), consultez Configuration du client.
Assurez-vous de disposer des autorisations nécessaires pour créer, consulter, répertorier et supprimer les inventaires d'un compartiment. Par défaut, le propriétaire du compartiment dispose des autorisations pour effectuer ces opérations. Si vous ne possédez pas ces autorisations, demandez au propriétaire du compartiment de vous les accorder.
Vous pouvez configurer jusqu'à 1 000 inventaires pour un compartiment.
Le compartiment source pour lequel vous souhaitez configurer un inventaire doit se trouver dans la même région que le compartiment de destination où la liste d'inventaire est stockée.
Créer un inventaire pour un compartiment
L'exemple de code suivant montre comment créer un inventaire pour un compartiment :
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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 OSS Client instance.
// Call the shutdown method to release associated resources when the OSS Client is no longer in use.
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();
}
}
}
}
Consulter un inventaire configuré pour un compartiment
L'exemple de code suivant montre comment consulter un inventaire configuré pour un compartiment :
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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 OSS Client instance.
// Call the shutdown method to release associated resources when the OSS Client is no longer in use.
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();
}
}
}
}
Répertorier les inventaires configurés pour un compartiment
Vous pouvez consulter jusqu'à 100 inventaires en une seule requête. Pour consulter plus de 100 inventaires, envoyez plusieurs requêtes et utilisez le jeton renvoyé pour chaque requête comme paramètre de la suivante.
L'exemple de code suivant montre comment répertorier les inventaires configurés pour un compartiment :
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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 OSS Client instance.
// Call the shutdown method to release associated resources when the OSS Client is no longer in use.
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();
}
}
}
}
Supprimer un inventaire configuré pour un compartiment
L'exemple de code suivant montre comment supprimer un inventaire configuré pour un compartiment :
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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 OSS Client instance.
// Call the shutdown method to release associated resources when the OSS Client is no longer in use.
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();
}
}
}
}
Références
Pour plus d'informations sur l'exemple de code complet relatif aux inventaires de compartiment, visitez GitHub.
Pour plus d'informations sur l'opération API permettant de créer un inventaire pour un compartiment, consultez PutBucketInventory.
Pour plus d'informations sur l'opération API permettant de consulter un inventaire configuré pour un compartiment, consultez GetBucketInventory.
Pour plus d'informations sur l'opération API permettant de répertorier les inventaires configurés pour un compartiment, consultez ListBucketInventory.
Pour plus d'informations sur l'opération API permettant de supprimer les inventaires configurés pour un compartiment, consultez DeleteBucketInventory.