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 {
// 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实例。
// 当OSSClient实例不再使用时,调用shutdown方法以释放资源。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 创建InitiateBucketWormRequest对象。
InitiateBucketWormRequest initiateBucketWormRequest = new InitiateBucketWormRequest(bucketName);
// 指定Object保护天数为1天。
initiateBucketWormRequest.setRetentionPeriodInDays(1);
// 创建合规保留策略。
InitiateBucketWormResult initiateBucketWormResult = ossClient.initiateBucketWorm(initiateBucketWormRequest);
// 查看合规保留策略ID。
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
// 引入自动加载文件 加载依赖库
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// 定义命令行参数描述
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // 区域是必填项 存储空间所在的区域
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // 终端节点是可选项 其他服务可以用来访问OSS的域名
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // 存储空间名称是必填项
];
// 生成长选项列表 用于解析命令行参数
$longopts = \array_map(function ($key) {
return "$key:"; // 每个参数后面加冒号 表示需要值
}, array_keys($optsdesc));
// 解析命令行参数
$options = getopt("", $longopts);
// 检查必填参数是否缺失
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // 提示用户缺少必填参数
exit(1);
}
}
// 获取命令行参数值
$region = $options["region"]; // 存储空间所在区域
$bucket = $options["bucket"]; // 存储空间名称
// 使用环境变量加载凭证信息 AccessKeyId 和 AccessKeySecret
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// 使用SDK的默认配置
$cfg = Oss\Config::loadDefault();
// 设置凭证提供者
$cfg->setCredentialsProvider($credentialsProvider);
// 设置区域
$cfg->setRegion($region);
// 如果提供了终端节点 则设置终端节点
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// 创建OSS客户端实例
$client = new Oss\Client($cfg);
// 创建初始化存储空间合规保留策略的请求对象 设置保留天数为3天
$request = new Oss\Models\InitiateBucketWormRequest(
bucket: $bucket,
initiateWormConfiguration: new Oss\Models\InitiateWormConfiguration(
retentionPeriodInDays: 3 // 保留天数
));
// 调用initiateBucketWorm方法初始化存储空间的合规保留策略
$result = $client->initiateBucketWorm($request);
// 打印返回结果
printf(
'status code:' . $result->statusCode . PHP_EOL . // HTTP响应状态码
'request id:' . $result->requestId . PHP_EOL . // 请求的唯一标识
'worm id:' . $result->wormId // 合规保留策略的ID
);
Node.js
const OSS = require('ali-oss');
const client = new OSS({
// yourregion填写Bucket所在地域。以华东1(杭州)为例,Region填写为oss-cn-hangzhou。
region: 'yourregion',
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// yourBucketName填写Bucket名称。
bucket: 'yourBucketName',
});
// 创建保留策略。
async function initiateBucketWorm() {
// yourbucketname填写存储空间名称。
const bucket = 'yourbucketname'
// 指定Object保护天数。
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
# 创建命令行参数解析器,并描述脚本用途:示例展示如何初始化OSS存储空间的WORM配置
parser = argparse.ArgumentParser(description="initiate bucket worm sample")
# 添加命令行参数 --region,表示存储空间所在的区域,必需参数
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# 添加命令行参数 --bucket,表示要操作的存储空间名称,必需参数
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# 添加命令行参数 --endpoint,表示其他服务可用来访问OSS的域名,非必需参数
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# 添加命令行参数 --retention_period_in_days,表示对象保留天数,必需参数
parser.add_argument('--retention_period_in_days', help='The number of days for which objects can be retained.', required=True)
def main():
# 解析命令行提供的参数,获取用户输入的值
args = parser.parse_args()
# 从环境变量中加载访问OSS所需的认证信息,用于身份验证
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# 使用SDK的默认配置创建配置对象,并设置认证提供者
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
# 如果提供了自定义endpoint,则更新配置对象中的endpoint属性
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# 使用上述配置初始化OSS客户端,准备与OSS交互
client = oss.Client(cfg)
# 发送请求以初始化指定存储空间的WORM配置
result = client.initiate_bucket_worm(oss.InitiateBucketWormRequest(
bucket=args.bucket, # 存储空间名
initiate_worm_configuration=oss.InitiateWormConfiguration(
retention_period_in_days=int(args.retention_period_in_days), # 对象保留天数,转换为整数
),
))
# 打印操作结果的状态码、请求ID和WORM ID,以便确认请求状态
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' worm id: {result.worm_id}'
)
# 当此脚本被直接执行时,调用main函数开始处理逻辑
if __name__ == "__main__":
main() # 脚本入口点,控制程序流程从这里开始
Go
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Error creating credentials provider: %v", err)
}
// 创建OSSClient实例。
// yourEndpoint填写Bucket对应的Endpoint,以华东1(杭州)为例,填写为https://oss-cn-hangzhou.aliyuncs.com。其它Region请按实际情况填写。
// yourRegion填写Bucket所在地域,以华东1(杭州)为例,填写为cn-hangzhou。其它Region请按实际情况填写。
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// 设置签名版本
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Error creating OSS client: %v", err)
}
// 填写待配置合规保留策略的Bucket名称。
bucketName := "<yourBucketName>"
// 指定Object保护天数为60天。
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)
{
/* 初始化OSS账号信息。*/
/* yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。*/
std::string Endpoint = "yourEndpoint";
/* yourRegion填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。*/
std::string Region = "yourRegion";
/* 填写Bucket名称,例如examplebucket。*/
std::string BucketName = "examplebucket";
/* 初始化网络等资源。*/
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。*/
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* 创建保留策略,指定Object保护天数为1天。*/
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 {
/* 异常处理。*/
std::cout << "InitiateBucketWorm fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* 释放网络等资源。*/
ShutdownSdk();
return 0;
}