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;
}