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.*;
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 full path of the Archive object. Do not include the bucket name in the full path.
String objectName = "exampledir/object";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
try {
ObjectMetadata objectMetadata = ossClient.getObjectMetadata(bucketName, objectName);
// Check whether the object is an Archive object.
StorageClass storageClass = objectMetadata.getObjectStorageClass();
if (storageClass == StorageClass.Archive) {
// Restore the object.
ossClient.restoreObject(bucketName, objectName);
// Specify the time to wait for the object to be restored.
do {
Thread.sleep(1000);
objectMetadata = ossClient.getObjectMetadata(bucketName, objectName);
} while (!objectMetadata.isRestoreCompleted());
}
// Query the restored object.
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
ossObject.getObjectContent().close();
} 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
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
// 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.
$provider = new EnvironmentVariableCredentialsProvider();
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the Archive object. Do not include the bucket name in the full path. Example: srcexampleobject.txt.
$object = "srcexampleobject.txt";
try {
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
);
$ossClient = new OssClient($config);
// Restore the object.
$ossClient->restoreObject($bucket, $object);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
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,
// Specify the name of the bucket. Example: examplebucket.
bucket: 'examplebucket',
});
// Specify the name of the Archive object that you want to restore. Example: exampleobject.txt.
client.restore('exampleobject.txt').then((res) => {
console.log(res);
}).catch(err => {
console.log(err);
})
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import RestoreConfiguration
# 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.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# 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.
# Specify the name of the bucket. Example: examplebucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Specify the full path of the Archive object. Do not include the bucket name in the full path.
objectName = 'yourArchiveObjectName'
# Specify the duration for which the object remains in the restored state. Default value: 1. Unit: day. In this example, the duration is 2 days.
days = 2
restore_config= RestoreConfiguration(days=days)
# Initiate a RestoreObject request.
bucket.restore_object(objectName, input=restore_config)
using Aliyun.OSS;
using Aliyun.OSS.Model;
using Aliyun.OSS.Model;
using System.Net;
using System.Text;
// 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.
var endpoint = "yourEndpoint";
// 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.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket.
var bucketName = "examplebucket";
// Specify the full path of the object. The path cannot contain the bucket name.
var objectName = "yourObjectName";
// Specify the content of the object.
var objectContent = "More than just cloud.";
int maxWaitTimeInSeconds = 600;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
// Create an Archive bucket.
var bucket = client.CreateBucket(bucketName, StorageClass.Archive);
Console.WriteLine("Create Archive bucket succeeded, {0} ", bucket.Name);
}
catch (Exception ex)
{
Console.WriteLine("Create Archive bucket failed, {0}", ex.Message);
}
// Upload the object to the bucket and set the storage class of the object to Archive.
try
{
byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
MemoryStream requestContent = new MemoryStream(binaryData);
client.PutObject(bucketName, objectName, requestContent);
Console.WriteLine("Put object succeeded, {0}", objectName);
}
catch (Exception ex)
{
Console.WriteLine("Put object failed, {0}", ex.Message);
}
var metadata = client.GetObjectMetadata(bucketName, objectName);
string storageClass = metadata.HttpMetadata["x-oss-storage-class"] as string;
if (storageClass != "Archive")
{
Console.WriteLine("StorageClass is {0}", storageClass);
return;
}
// Restore the Archive object.
RestoreObjectResult result = client.RestoreObject(bucketName, objectName);
Console.WriteLine("RestoreObject result HttpStatusCode : {0}", result.HttpStatusCode);
if (result.HttpStatusCode != HttpStatusCode.Accepted)
{
throw new OssException(result.RequestId + ", " + result.HttpStatusCode + " ,");
}
while (maxWaitTimeInSeconds > 0)
{
var meta = client.GetObjectMetadata(bucketName, objectName);
string restoreStatus = meta.HttpMetadata["x-oss-restore"] as string;
if (restoreStatus != null && restoreStatus.StartsWith("ongoing-request=\"false\"", StringComparison.InvariantCultureIgnoreCase))
{
break;
}
Thread.Sleep(1000);
// The maximum wait time decreases by 1 second.
maxWaitTimeInSeconds--;
}
if (maxWaitTimeInSeconds == 0)
{
Console.WriteLine("RestoreObject is timeout. ");
throw new TimeoutException();
}
else
{
Console.WriteLine("RestoreObject is successful. ");
}
// Restore the object.
RestoreObjectRequest restore = new RestoreObjectRequest();
// Specify the name of the bucket. Example: examplebucket.
restore.setBucketName("examplebucket");
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.txt.
restore.setObjectKey("exampleobject.txt");
OSSAsyncTask task = oss.asyncRestoreObject(restore, new OSSCompletedCallback<RestoreObjectRequest,
RestoreObjectResult>() {
@Override
public void onSuccess(RestoreObjectRequest request, RestoreObjectResult result) {
Log.i("info", "code::"+result.getStatusCode());
}
@Override
public void onFailure(RestoreObjectRequest request, ClientException clientException,
ServiceException serviceException) {
Log.e("errorMessage", "error: "+serviceException.getRawMessage());
}
});
task.waitUntilFinished();
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", err)
}
// Create an OSSClient instance.
// 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. Specify your actual endpoint.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the name of the bucket. Example: examplebucket.
bucketName := "examplebucket"
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
objectName := "exampledir/exampleobject.txt"
// Create a bucket.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket '%s': %v", bucketName, err)
}
// Restore the Archive object.
err = bucket.RestoreObject(objectName)
if err != nil {
log.Fatalf("Failed to restore object '%s': %v", objectName, err)
}
log.Println("ArchiveSample completed")
}
OSSRestoreObjectRequest *request = [OSSRestoreObjectRequest new];
// Specify the name of the bucket. Example: examplebucket.
request.bucketName = @"examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.txt.
request.objectKey = @"exampleobject.txt";
OSSTask *restoreObjectTask = [client restoreObject:request];
[restoreObjectTask continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
if (!task.error) {
NSLog(@"restore object success");
} else {
NSLog(@"restore object failed, error: %@", task.error);
}
return nil;
}];
// Implement synchronous blocking to wait for the task to complete.
// [restoreObjectTask waitUntilFinished];
#include <alibabacloud/oss/OssClient.h>
#include <thread>
#include <chrono>
#include <algorithm>
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 name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the Archive object. Do not include the bucket name in the full path. */
std::string ObjectName = "yourObjectName";
/* Initialize resources such as network resources. */
InitializeSdk();
ClientConfiguration conf;
/* 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);
/* Restore the Archive object. */
auto outcome = client.RestoreObject(BucketName, ObjectName);
/* You cannot restore objects of the non-Archive storage class. */
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "RestoreObject fail, code:" << outcome.error().Code() <<
", message:" << outcome.error().Message() <<
", requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
std::string onGoingRestore("ongoing-request=\"false\"");
int maxWaitTimeInSeconds = 600;
while (maxWaitTimeInSeconds > 0)
{
auto meta = client.HeadObject(BucketName, ObjectName);
std::string restoreStatus = meta.result().HttpMetaData()["x-oss-restore"];
std::transform(restoreStatus.begin(), restoreStatus.end(), restoreStatus.begin(), ::tolower);
if (!restoreStatus.empty() &&
restoreStatus.compare(0, onGoingRestore.size(), onGoingRestore)==0) {
std::cout << " success, restore status:" << restoreStatus << std::endl;
/* The Archive object is restored. */
break;
}
std::cout << " info, WaitTime:" << maxWaitTimeInSeconds
<< "; restore status:" << restoreStatus << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(10));
maxWaitTimeInSeconds--;
}
if (maxWaitTimeInSeconds == 0)
{
std::cout << "RestoreObject fail, TimeoutException" << std::endl;
}
/* Release resources such as network resources. */
ShutdownSdk();
return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* 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. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize data of the aos_string_t type. */
aos_str_set(&options->config->endpoint, endpoint);
/* 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. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
/* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Specify network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
aos_pool_t *pool;
/* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate the memory resources in the memory pool to the options. */
oss_client_options = oss_request_options_create(pool);
/* Initialize oss_client_options. */
init_options(oss_client_options);
/* Initialize the parameters. */
aos_string_t bucket;
aos_string_t object;
aos_table_t *headers = NULL;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
aos_str_set(&bucket, bucket_name);
aos_str_set(&object, object_name);
headers = aos_table_make(pool, 0);
/* Restore the object. */
do {
headers = aos_table_make(pool, 0);
resp_status = oss_restore_object(oss_client_options, &bucket, &object, headers, &resp_headers);
printf("restore object resp_status->code: %d \n", resp_status->code);
if (resp_status->code != 409) {
break;
} else {
printf("restore object is already in progress, resp_status->code: %d \n", resp_status->code);
apr_sleep(5000);
}
} while (1);
/* Release the memory pool. This operation releases the memory resources allocated for the request. */
aos_pool_destroy(pool);
/* Release the allocated global resources. */
aos_http_io_deinitialize();
return 0;
}