The following sample code provides examples of how to configure retention policies using SDKs for common programming languages. For more information about sample code for other programming languages, see Overview.
Java
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.InitiateBucketWormRequest;
import com.aliyun.oss.model.InitiateBucketWormResult;
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.
// Call the shutdown method to release resources when the OSSClient 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 InitiateBucketWormRequest object.
InitiateBucketWormRequest initiateBucketWormRequest = new InitiateBucketWormRequest(bucketName);
// Set the retention period to 1 day.
initiateBucketWormRequest.setRetentionPeriodInDays(1);
// Create a retention policy.
InitiateBucketWormResult initiateBucketWormResult = ossClient.initiateBucketWorm(initiateBucketWormRequest);
// Display the ID of the retention policy.
String wormId = initiateBucketWormResult.getWormId();
System.out.println(wormId);
} 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();
}
}
}
}
PHP
<?php
// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify descriptions for command line parameters.
$optsdesc = [
"region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
"bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Specify that the required parameters are not configured.
exit(1);
}
}
// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Use environment variables to load the AccessKey ID and AccessKey secret.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// Specify the endpoint if an endpoint is provided.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create an InitiateBucketWormRequest object to create a retention policy for the bucket and set the retention period of the retention policy to three days.
$request = new Oss\Models\InitiateBucketWormRequest(
bucket: $bucket,
initiateWormConfiguration: new Oss\Models\InitiateWormConfiguration(
retentionPeriodInDays: 3 // Set the retention period to three days.
));
// Use the initiateBucketWorm method to create a retention policy for the bucket.
$result = $client->initiateBucketWorm($request);
// Display the returned result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
'request id:' . $result->requestId . PHP_EOL . // The request ID of the request, which is the unique identifier of the request.
'worm id:' . $result->wormId // The ID of the retention policy.
);
Node.js
const OSS = require('ali-oss');
const client = new OSS({
// 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 oss-cn-hangzhou.
region: 'yourregion',
// 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.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of your bucket.
bucket: 'yourBucketName',
});
// Create a retention policy.
async function initiateBucketWorm() {
// Specify the name of the bucket.
const bucket = 'yourbucketname'
// Specify the retention period of the retention policy.
const days = '<Retention Days>'
const res = await client.initiateBucketWorm(bucket, days)
console.log(res.wormId)
}
initiateBucketWorm()
Python
import argparse
import alibabacloud_oss_v2 as oss
# Create a command line parameter parser and describe the purpose of the script. The example describes how to use the Write Once Read Many (WORM) feature to create a retention policy for a bucket.
parser = argparse.ArgumentParser(description="initiate bucket worm sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint of the region in which the bucket is located. This command line parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --retention_period_in_days parameter, which specifies the number of days for which objects can be retained. This command line parameter is required.
parser.add_argument('--retention_period_in_days', help='The number of days for which objects can be retained.', required=True)
def main():
# Parse the command line parameters to obtain the values specified by the user.
args = parser.parse_args()
# Load the authentication information required to access OSS from the environment variables.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configurations of the SDK to create a configuration object and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
# If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
client = oss.Client(cfg)
# Send a request to create a retention policy for the bucket.
result = client.initiate_bucket_worm(oss.InitiateBucketWormRequest(
bucket=args.bucket, # The name of the bucket.
initiate_worm_configuration=oss.InitiateWormConfiguration(
retention_period_in_days=int(args.retention_period_in_days), # The number of days for which objects can be retained. Set the value to an integer.
),
))
# Display the HTTP status code of the operation, request ID, and retention policy ID to check the request status.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' worm id: {result.worm_id}'
)
# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
main() # Specify the entry points in the functions of the script. The control program flow starts here.
Go
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Error creating credentials provider: %v", err)
}
// Create an OSSClient instance.
// Set yourEndpoint to the endpoint of the bucket. For example, for China (Hangzhou), set it to https://oss-cn-hangzhou.aliyuncs.com. For other regions, specify the actual endpoint.
// Set yourRegion to the region where the bucket is located. For example, for China (Hangzhou), set it to cn-hangzhou. For other regions, specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Error creating OSS client: %v", err)
}
// Specify the name of the bucket for which you want to configure a retention policy.
bucketName := "<yourBucketName>"
// Set the object retention period to 60 days.
result, err := client.InitiateBucketWorm(bucketName, 60)
if err != nil {
log.Fatalf("Error initiating bucket WORM: %v", err)
}
log.Println("WORM policy initiated successfully:", result)
}
C++
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* 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. */
std::string Region = "yourRegion";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 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. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Create a retention policy and set the retention period to 1 day. */
auto outcome = client.InitiateBucketWorm(InitiateBucketWormRequest(BucketName, 1));
if (outcome.isSuccess()) {
std::cout << " InitiateBucketWorm success " << std::endl;
std::cout << "WormId:" << outcome.result().WormId() << std::endl;
}
else {
/* Handle exceptions. */
std::cout << "InitiateBucketWorm fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}