### Build OSS Java SDK V2 from Source Source: https://github.com/aliyun/alibabacloud-oss-java-sdk-v2/blob/main/README-CN.md After downloading the code from GitHub, use this Maven command to build and install the SDK. ```bash mvn clean install -DskipTests ``` -------------------------------- ### List Buckets using OSS Java SDK V2 Source: https://github.com/aliyun/alibabacloud-oss-java-sdk-v2/blob/main/README-CN.md This example demonstrates how to list all buckets in your OSS account using the SDK. Ensure your credentials are set as environment variables. ```java package com.example.oss; import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.OSSClientBuilder; import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider; import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider; import com.aliyun.sdk.service.oss2.models.*; import com.aliyun.sdk.service.oss2.paginator.ListBucketsIterable; public class Example { public static void main(String[] args) { String region = "cn-hangzhou"; CredentialsProvider provider = new EnvironmentVariableCredentialsProvider(); OSSClientBuilder clientBuilder = OSSClient.newBuilder() .credentialsProvider(provider) .region(region); try (OSSClient client = clientBuilder.build()) { ListBucketsIterable paginator = client.listBucketsPaginator( ListBucketsRequest.newBuilder() .build()); for (ListBucketsResult result : paginator) { for (BucketSummary info : result.buckets()) { System.out.printf("bucket: name:%s, region:%s, storageClass:%s\n", info.name(), info.region(), info.storageClass()); } } } catch (Exception e) { //If the exception is caused by ServiceException, detailed information can be obtained in this way. // ServiceException se = ServiceException.asCause(e); // if (se != null) { // System.out.printf("ServiceException: requestId:%s, errorCode:%s\n", se.requestId(), se.errorCode()); //} System.out.printf("error:\n%s", e); } } } ``` -------------------------------- ### listBucketsPaginator - List All Buckets Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt List all buckets in your account with automatic pagination. This is useful for getting an overview of all your storage resources. ```APIDOC ## listBucketsPaginator - List All Buckets ### Description List all buckets in your account with automatic pagination. ### Method GET (implied by paginator usage, actual SDK method may vary) ### Endpoint `/` ### Parameters (No specific parameters mentioned for the request builder in the provided text) ### Request Example ```java ListBucketsIterable paginator = client.listBucketsPaginator( ListBucketsRequest.newBuilder().build()); ``` ### Response #### Success Response (200) - **buckets** (List) - A list of bucket summaries. #### Response Example ```java for (ListBucketsResult result : paginator) { for (BucketSummary info : result.buckets()) { System.out.printf("bucket: name:%s, region:%s, storageClass:%s%n", info.name(), info.region(), info.storageClass()); } } ``` ``` -------------------------------- ### List Objects in a Bucket using OSS Java SDK V2 Source: https://github.com/aliyun/alibabacloud-oss-java-sdk-v2/blob/main/README-CN.md This example shows how to list objects within a specified bucket. Ensure your credentials are set as environment variables and replace 'your bucket name' with your actual bucket name. ```java package com.example.oss; import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.OSSClientBuilder; import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider; import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider; import com.aliyun.sdk.service.oss2.models.*; import com.aliyun.sdk.service.oss2.paginator.ListObjectsV2Iterable; public class Example { public static void main(String[] args) { String region = "cn-hangzhou"; String bucket = "your bucket name"; CredentialsProvider provider = new EnvironmentVariableCredentialsProvider(); OSSClientBuilder clientBuilder = OSSClient.newBuilder() .credentialsProvider(provider) .region(region); try (OSSClient client = clientBuilder.build()) { ListObjectsV2Iterable paginator = client.listObjectsV2Paginator( ListObjectsV2Request.newBuilder() .bucket(bucket) .build()); for (ListObjectsV2Result result : paginator) { for (ObjectSummary info : result.contents()) { System.out.printf("bucket: name:%s, region:%s, storageClass:%s\n", info.key(), info.size(), info.lastModified()); } } } catch (Exception e) { //If the exception is caused by ServiceException, detailed information can be obtained in this way. // ServiceException se = ServiceException.asCause(e); // if (se != null) { // System.out.printf("ServiceException: requestId:%s, errorCode:%s\n", se.requestId(), se.errorCode()); //} System.out.printf("error:\n%s", e); } } } ``` -------------------------------- ### GET Object - Download an Object Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Download an object from an OSS bucket and read its content as bytes or stream. ```APIDOC ## getObject - Download an Object Download an object from OSS bucket and read its content as bytes or stream. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; import com.aliyun.sdk.service.oss2.utils.IOUtils; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { try (GetObjectResult result = client.getObject(GetObjectRequest.newBuilder() .bucket("my-bucket") .key("example/hello.txt") .build())) { // Load all data into memory byte[] data = IOUtils.toByteArray(result.body()); System.out.printf("status code:%d, request id:%s, eTag:%s, content length:%d%n", result.statusCode(), result.requestId(), result.eTag(), result.contentLength()); System.out.println("Content: " + new String(data)); // Output: status code:200, request id:5C3D..., eTag:"5eb63...", content length:11 // Content: hello world } } ``` ``` -------------------------------- ### Configure Bucket Lifecycle Rules with Java Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Set up automatic object expiration and storage class transitions for a bucket. This example configures an expiration rule for objects in 'logs/' after 30 days and transition rules for objects in 'data/' to IA after 30 days and Archive after 90 days. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; import java.util.Arrays; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { // Rule 1: Delete objects in logs/ after 30 days LifecycleRule expirationRule = LifecycleRule.newBuilder() .id("expiration-rule") .status("Enabled") .prefix("logs/") .expiration(LifecycleRuleExpiration.newBuilder().days(30).build()) .build(); // Rule 2: Transition objects in data/ to IA after 30 days, Archive after 90 days LifecycleRule transitionRule = LifecycleRule.newBuilder() .id("transition-rule") .status("Enabled") .prefix("data/") .transitions(Arrays.asList( LifecycleRuleTransition.newBuilder() .days(30) .storageClass("IA") .build(), LifecycleRuleTransition.newBuilder() .days(90) .storageClass("Archive") .build() )) .build(); LifecycleConfiguration config = LifecycleConfiguration.newBuilder() .rules(Arrays.asList(expirationRule, transitionRule)) .build(); PutBucketLifecycleResult result = client.putBucketLifecycle( PutBucketLifecycleRequest.newBuilder() .bucket("my-bucket") .lifecycleConfiguration(config) .build()); System.out.printf("Status code:%d, request id:%s%n", result.statusCode(), result.requestId()); // Output: Status code:200, request id:5C3D5C5E4A5F6D3C... } ``` -------------------------------- ### Generate Presigned URLs with Java Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Generate temporary URLs for object access without exposing credentials. This example shows how to generate a presigned URL with default expiration and with a custom expiration of 1 hour. ```java import com.aliyun.sdk.service.oss2.ClientConfiguration; import com.aliyun.sdk.service.oss2.PresignOptions; import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider; import com.aliyun.sdk.service.oss2.internal.ClientImpl; import com.aliyun.sdk.service.oss2.models.GetObjectRequest; import com.aliyun.sdk.service.oss2.models.PresignResult; import com.aliyun.sdk.service.oss2.operations.Presigner; import java.time.Duration; ClientConfiguration config = ClientConfiguration.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build(); try (ClientImpl client = new ClientImpl(config)) { GetObjectRequest request = GetObjectRequest.newBuilder() .bucket("my-bucket") .key("example/file.txt") .build(); // Generate presigned URL with default expiration PresignResult result = Presigner.getObject(client, request, PresignOptions.defaults()); System.out.println("Presigned URL: " + result.url()); // Generate presigned URL with custom expiration (1 hour) PresignOptions options = PresignOptions.newBuilder() .expiration(Duration.ofHours(1)) .build(); PresignResult customResult = Presigner.getObject(client, request, options); System.out.println("Custom expiration URL: " + customResult.url()); } ``` -------------------------------- ### Get Bucket Information with getBucketInfo Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Retrieve detailed information about a specific bucket, including its creation date, location, and storage class. Requires the bucket name as input. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { GetBucketInfoResult result = client.getBucketInfo(GetBucketInfoRequest.newBuilder() .bucket("my-bucket") .build()); System.out.printf("status code:%d, request id:%s%n", result.statusCode(), result.requestId()); BucketInfo bucketInfo = result.bucketInfo(); System.out.printf("Bucket name: %s%n", bucketInfo.name()); System.out.printf("Creation date: %s%n", bucketInfo.creationDate()); System.out.printf("Location: %s%n", bucketInfo.location()); System.out.printf("Storage class: %s%n", bucketInfo.storageClass()); // Output: // Bucket name: my-bucket // Creation date: 2024-01-10T08:00:00Z // Location: oss-cn-hangzhou // Storage class: Standard } ``` -------------------------------- ### Get Object Metadata with OSS Java SDK Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Retrieve metadata of an object without downloading its content. Ensure the EnvironmentVariableCredentialsProvider is configured. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { HeadObjectResult result = client.headObject(HeadObjectRequest.newBuilder() .bucket("my-bucket") .key("example/hello.txt") .build()); System.out.printf("status code:%d, request id:%s, eTag:%s, last modified:%s, content length:%d%n", result.statusCode(), result.requestId(), result.eTag(), result.lastModified(), result.contentLength()); // Output: status code:200, request id:5C3D..., eTag:"5eb63...", last modified:2024-01-15T10:30:00Z, content length:11 } ``` -------------------------------- ### getBucketInfo - Get Bucket Information Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Retrieve detailed information about a bucket including creation date, location, and storage class. This is useful for auditing and managing bucket configurations. ```APIDOC ## getBucketInfo - Get Bucket Information ### Description Retrieve detailed information about a bucket including creation date, location, and storage class. ### Method GET ### Endpoint `/{bucketName}?bucketInfo` (or similar, specific endpoint not detailed) ### Parameters #### Path Parameters - **bucket** (string) - Required - The name of the bucket to retrieve information for. ### Request Example ```java GetBucketInfoResult result = client.getBucketInfo(GetBucketInfoRequest.newBuilder() .bucket("my-bucket") .build()); ``` ### Response #### Success Response (200) - **statusCode** (integer) - The HTTP status code of the response. - **requestId** (string) - The unique request ID for tracking the operation. - **bucketInfo** (BucketInfo) - An object containing detailed bucket information. - **name** (string) - The name of the bucket. - **creationDate** (string) - The date and time the bucket was created. - **location** (string) - The region where the bucket is located. - **storageClass** (string) - The storage class of the bucket. #### Response Example ```java BucketInfo bucketInfo = result.bucketInfo(); System.out.printf("Bucket name: %s%n", bucketInfo.name()); System.out.printf("Creation date: %s%n", bucketInfo.creationDate()); System.out.printf("Location: %s%n", bucketInfo.location()); System.out.printf("Storage class: %s%n", bucketInfo.storageClass()); ``` ``` -------------------------------- ### Get Object Metadata Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Retrieve metadata of an object without downloading its content. This is useful for checking object properties like size, ETag, and last modified date. ```APIDOC ## GET /objects/{bucket}/{key} ### Description Retrieve metadata of an object without downloading its content. ### Method GET ### Endpoint /objects/{bucket}/{key} ### Parameters #### Path Parameters - **bucket** (string) - Required - The name of the bucket. - **key** (string) - Required - The key of the object. ### Request Example ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { HeadObjectResult result = client.headObject(HeadObjectRequest.newBuilder() .bucket("my-bucket") .key("example/hello.txt") .build()); System.out.printf("status code:%d, request id:%s, eTag:%s, last modified:%s, content length:%d%n", result.statusCode(), result.requestId(), result.eTag(), result.lastModified(), result.contentLength()); } ``` ### Response #### Success Response (200) - **statusCode** (integer) - The HTTP status code of the response. - **requestId** (string) - The unique ID of the request. - **eTag** (string) - The ETag of the object. - **lastModified** (string) - The last modified date of the object. - **contentLength** (integer) - The size of the object in bytes. #### Response Example ```json { "statusCode": 200, "requestId": "5C3D...", "eTag": "5eb63...", "lastModified": "2024-01-15T10:30:00Z", "contentLength": 11 } ``` ``` -------------------------------- ### Initialize OSS Client with Credentials Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Demonstrates how to initialize the OSSClient using different credential providers like environment variables, static credentials, and STS tokens. Ensure the correct region and optional custom endpoint are configured. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.OSSClientBuilder; import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider; import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider; import com.aliyun.sdk.service.oss2.credentials.StaticCredentialsProvider; // Using environment variables (OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, OSS_SESSION_TOKEN) CredentialsProvider provider = new EnvironmentVariableCredentialsProvider(); // Or using static credentials CredentialsProvider staticProvider = new StaticCredentialsProvider( "your-access-key-id", "your-access-key-secret" ); // With security token (STS) CredentialsProvider stsProvider = new StaticCredentialsProvider( "your-access-key-id", "your-access-key-secret", "your-security-token" ); // Build the client try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(provider) .region("cn-hangzhou") .endpoint("https://oss-cn-hangzhou.aliyuncs.com") // optional custom endpoint .build()) { // Use client for operations } ``` -------------------------------- ### Client Initialization Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Initialize the OSS client with credentials and region configuration. The client supports both synchronous (OSSClient) and asynchronous (OSSAsyncClient) operations. ```APIDOC ## Client Initialization Initialize the OSS client with credentials and region configuration. The client supports both synchronous (OSSClient) and asynchronous (OSSAsyncClient) operations. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.OSSClientBuilder; import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider; import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider; import com.aliyun.sdk.service.oss2.credentials.StaticCredentialsProvider; // Using environment variables (OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, OSS_SESSION_TOKEN) CredentialsProvider provider = new EnvironmentVariableCredentialsProvider(); // Or using static credentials CredentialsProvider staticProvider = new StaticCredentialsProvider( "your-access-key-id", "your-access-key-secret" ); // With security token (STS) CredentialsProvider stsProvider = new StaticCredentialsProvider( "your-access-key-id", "your-access-key-secret", "your-security-token" ); // Build the client try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(provider) .region("cn-hangzhou") .endpoint("https://oss-cn-hangzhou.aliyuncs.com") // optional custom endpoint .build()) { // Use client for operations } ``` ``` -------------------------------- ### Create a Bucket with putBucket Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Create a new OSS bucket in the specified region. Ensure the bucket name is globally unique. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { PutBucketResult result = client.putBucket(PutBucketRequest.newBuilder() .bucket("my-new-bucket") .build()); System.out.printf("status code:%d, request id:%s%n", result.statusCode(), result.requestId()); // Output: status code:200, request id:5C3D5C5E4A5F6D3C... } ``` -------------------------------- ### Configure Advanced OSS Client Settings Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Customize OSS client behavior by setting various configuration options such as timeouts, proxy, endpoint, retry attempts, and SSL settings. Use try-with-resources for proper client lifecycle management. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider; import java.time.Duration; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .endpoint("https://oss-cn-hangzhou.aliyuncs.com") .connectTimeout(Duration.ofSeconds(30)) .readWriteTimeout(Duration.ofSeconds(60)) .retryMaxAttempts(3) .useDualStackEndpoint(false) .useInternalEndpoint(false) // Use internal endpoint for ECS .useAccelerateEndpoint(false) // Use transfer acceleration .useCName(false) // Use custom domain .usePathStyle(false) // Use path-style URLs .disableSsl(false) // Disable SSL (not recommended) .insecureSkipVerify(false) // Skip SSL verification (not recommended) .enabledRedirect(true) // Follow HTTP redirects .proxyHost("http://proxy:8080") // Use HTTP proxy .userAgent("MyApp/1.0") // Custom user agent .disableUploadCRC64Check(false) // Disable CRC64 integrity check .build()) { // Use configured client } ``` -------------------------------- ### putBucket - Create a Bucket Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Create a new OSS bucket in the specified region. This operation is essential for setting up storage space before uploading objects. ```APIDOC ## putBucket - Create a Bucket ### Description Create a new OSS bucket in the specified region. ### Method PUT ### Endpoint `/{bucketName}` ### Parameters #### Path Parameters - **bucket** (string) - Required - The name of the bucket to create. #### Request Body (Not explicitly defined in the provided text, typically includes region and storage class) ### Request Example ```java PutBucketResult result = client.putBucket(PutBucketRequest.newBuilder() .bucket("my-new-bucket") .build()); ``` ### Response #### Success Response (200) - **statusCode** (integer) - The HTTP status code of the response. - **requestId** (string) - The unique request ID for tracking the operation. #### Response Example ```java System.out.printf("status code:%d, request id:%s%n", result.statusCode(), result.requestId()); ``` ``` -------------------------------- ### List Objects in Bucket with OSS Java SDK Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt List objects in a bucket with optional prefix filtering. Iterates through the contents to display object details. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { ListObjectsResult result = client.listObjects(ListObjectsRequest.newBuilder() .bucket("my-bucket") .build()); System.out.printf("status code:%d, request id:%s%n", result.statusCode(), result.requestId()); System.out.println("Objects:"); for (ObjectSummary content : result.contents()) { System.out.printf("- %s (size: %d, lastModified: %s)%n", content.key(), content.size(), content.lastModified()); } // Output: // Objects: // - example/file1.txt (size: 1024, lastModified: 2024-01-15T10:30:00Z) // - example/file2.txt (size: 2048, lastModified: 2024-01-15T11:00:00Z) } ``` -------------------------------- ### Download Object using getObject Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Downloads an object from an OSS bucket and reads its content. The content can be loaded into memory as bytes or processed as a stream. Verify the bucket, key, and handle the response body correctly. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; import com.aliyun.sdk.service.oss2.utils.IOUtils; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { try (GetObjectResult result = client.getObject(GetObjectRequest.newBuilder() .bucket("my-bucket") .key("example/hello.txt") .build())) { // Load all data into memory byte[] data = IOUtils.toByteArray(result.body()); System.out.printf("status code:%d, request id:%s, eTag:%s, content length:%d%n", result.statusCode(), result.requestId(), result.eTag(), result.contentLength()); System.out.println("Content: " + new String(data)); // Output: status code:200, request id:5C3D..., eTag:"5eb63...", content length:11 // Content: hello world } } ``` -------------------------------- ### List All Buckets with listBucketsPaginator Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt List all buckets in your account with automatic pagination. This method iterates through all buckets, handling pagination internally. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; import com.aliyun.sdk.service.oss2.paginator.ListBucketsIterable; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { ListBucketsIterable paginator = client.listBucketsPaginator( ListBucketsRequest.newBuilder().build()); for (ListBucketsResult result : paginator) { for (BucketSummary info : result.buckets()) { System.out.printf("bucket: name:%s, region:%s, storageClass:%s%n", info.name(), info.region(), info.storageClass()); } } // Output: // bucket: name:my-bucket-1, region:cn-hangzhou, storageClass:Standard // bucket: name:my-bucket-2, region:cn-shanghai, storageClass:IA } ``` -------------------------------- ### PUT Bucket Lifecycle - Configure Lifecycle Rules Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Configure automatic object expiration and storage class transitions for a bucket. ```APIDOC ## PUT Bucket Lifecycle ### Description Set up automatic object expiration and storage class transitions. ### Method PUT ### Endpoint `/bucket-name?lifecycle` ### Parameters #### Query Parameters - **lifecycle** (string) - Required - Specifies the lifecycle configuration operation. #### Request Body - **lifecycleConfiguration** (LifecycleConfiguration) - Required - The lifecycle configuration object. - **rules** (array of LifecycleRule) - Required - A list of lifecycle rules. - **id** (string) - Required - The ID of the rule. - **status** (string) - Required - The status of the rule ('Enabled' or 'Disabled'). - **prefix** (string) - Optional - Filters objects based on a prefix. - **expiration** (LifecycleRuleExpiration) - Optional - Specifies object expiration. - **days** (integer) - Required - Number of days after creation to expire objects. - **transitions** (array of LifecycleRuleTransition) - Optional - Specifies storage class transitions. - **days** (integer) - Required - Number of days after creation to transition objects. - **storageClass** (string) - Required - The target storage class (e.g., 'IA', 'Archive'). ### Request Example ```json { "lifecycleConfiguration": { "rules": [ { "id": "expiration-rule", "status": "Enabled", "prefix": "logs/", "expiration": { "days": 30 } }, { "id": "transition-rule", "status": "Enabled", "prefix": "data/", "transitions": [ { "days": 30, "storageClass": "IA" }, { "days": 90, "storageClass": "Archive" } ] } ] } } ``` ### Response #### Success Response (200) - **statusCode** (integer) - The HTTP status code of the response. - **requestId** (string) - The unique request ID. #### Response Example ```json { "statusCode": 200, "requestId": "5C3D5C5E4A5F6D3C..." } ``` ``` -------------------------------- ### Upload Object using OSS Java SDK v2 Source: https://github.com/aliyun/alibabacloud-oss-java-sdk-v2/blob/main/README.md Use this snippet to upload an object to an Alibaba Cloud OSS bucket. Ensure you have configured your credentials via environment variables and replaced placeholder values for bucket and key. ```java package com.example.oss; import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.OSSClientBuilder; import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider; import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider; import com.aliyun.sdk.service.oss2.models.*; public class Example { public static void main(String[] args) { String region = "cn-hangzhou"; String bucket = "your bucket name"; String key = "your object name"; CredentialsProvider provider = new EnvironmentVariableCredentialsProvider(); OSSClientBuilder clientBuilder = OSSClient.newBuilder() .credentialsProvider(provider) .region(region); try (OSSClient client = clientBuilder.build()) { String data = "hello world"; PutObjectResult result = client.putObject(PutObjectRequest.newBuilder() .bucket(bucket) .key(key) .body(BinaryData.fromString(data)) .build()); System.out.printf("status code:%d, request id:%s, eTag:%s\n", result.statusCode(), result.requestId(), result.eTag()); } catch (Exception e) { //If the exception is caused by ServiceException, detailed information can be obtained in this way. // ServiceException se = ServiceException.asCause(e); // if (se != null) { // System.out.printf("ServiceException: requestId:%s, errorCode:%s\n", se.requestId(), se.errorCode()); //} System.out.printf("error:\n%s", e); } } } ``` -------------------------------- ### Manage Bucket ACLs with Java Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Use putBucketAcl to set bucket access control lists and getBucketAcl to retrieve them. Supported ACL values are private, public-read, and public-read-write. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { // Set bucket ACL PutBucketAclResult putResult = client.putBucketAcl(PutBucketAclRequest.newBuilder() .bucket("my-bucket") .acl("private") // Options: private, public-read, public-read-write .build()); System.out.printf("Set ACL - status code:%d%n", putResult.statusCode()); // Get bucket ACL GetBucketAclResult getResult = client.getBucketAcl(GetBucketAclRequest.newBuilder() .bucket("my-bucket") .build()); AccessControlPolicy acp = getResult.accessControlPolicy(); if (acp != null && acp.accessControlList() != null) { System.out.printf("Bucket ACL: %s%n", acp.accessControlList().grant()); } // Output: // Set ACL - status code:200 // Bucket ACL: private } ``` -------------------------------- ### Upload Object using putObject Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Uploads data to an OSS bucket using the putObject method. Supports uploading from strings, byte arrays, or input streams via BinaryData. Ensure the bucket, key, and body are correctly specified. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; import com.aliyun.sdk.service.oss2.transport.BinaryData; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { String data = "hello world"; PutObjectResult result = client.putObject(PutObjectRequest.newBuilder() .bucket("my-bucket") .key("example/hello.txt") .body(BinaryData.fromString(data)) .build()); System.out.printf("status code:%d, request id:%s, eTag:%s%n", result.statusCode(), result.requestId(), result.eTag()); // Output: status code:200, request id:5C3D5C5E4A5F6D3C..., eTag:"5eb63bbbe01eeed093..." } ``` -------------------------------- ### PUT Object - Upload an Object Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Upload data to an OSS bucket. Supports uploading from string, byte array, or input stream using BinaryData. ```APIDOC ## putObject - Upload an Object Upload data to OSS bucket. Supports uploading from string, byte array, or input stream using BinaryData. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; import com.aliyun.sdk.service.oss2.transport.BinaryData; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { String data = "hello world"; PutObjectResult result = client.putObject(PutObjectRequest.newBuilder() .bucket("my-bucket") .key("example/hello.txt") .body(BinaryData.fromString(data)) .build()); System.out.printf("status code:%d, request id:%s, eTag:%s%n", result.statusCode(), result.requestId(), result.eTag()); // Output: status code:200, request id:5C3D5C5E4A5F6D3C..., eTag:"5eb63bbbe01eeed093..." } ``` ``` -------------------------------- ### Copy Object with OSS Java SDK Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Copy an object from one location to another within OSS. Requires specifying both source and target bucket and key. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { CopyObjectResult result = client.copyObject(CopyObjectRequest.newBuilder() .sourceBucket("source-bucket") .sourceKey("source/file.txt") .bucket("target-bucket") .key("target/file-copy.txt") .build()); System.out.printf("status code:%d, request id:%s, eTag:%s%n", result.statusCode(), result.requestId(), result.eTag()); // Output: status code:200, request id:5C3D..., eTag:"5eb63..." } ``` -------------------------------- ### List Objects in Bucket Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt List objects in a bucket with optional prefix filtering. This operation returns a list of objects and their metadata. ```APIDOC ## GET /objects/{bucket} ### Description List objects in a bucket with optional prefix filtering. ### Method GET ### Endpoint /objects/{bucket} ### Parameters #### Path Parameters - **bucket** (string) - Required - The name of the bucket. #### Query Parameters - **prefix** (string) - Optional - Filters the results to return only objects that begin with the specified prefix. ### Request Example ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { ListObjectsResult result = client.listObjects(ListObjectsRequest.newBuilder() .bucket("my-bucket") .build()); System.out.printf("status code:%d, request id:%s%n", result.statusCode(), result.requestId()); System.out.println("Objects:"); for (ObjectSummary content : result.contents()) { System.out.printf("- %s (size: %d, lastModified: %s)%n", content.key(), content.size(), content.lastModified()); } } ``` ### Response #### Success Response (200) - **statusCode** (integer) - The HTTP status code of the response. - **requestId** (string) - The unique ID of the request. - **contents** (array) - A list of objects in the bucket. - **key** (string) - The key of the object. - **size** (integer) - The size of the object in bytes. - **lastModified** (string) - The last modified date of the object. #### Response Example ```json { "statusCode": 200, "requestId": "5C3D...", "contents": [ { "key": "example/file1.txt", "size": 1024, "lastModified": "2024-01-15T10:30:00Z" }, { "key": "example/file2.txt", "size": 2048, "lastModified": "2024-01-15T11:00:00Z" } ] } ``` ``` -------------------------------- ### Manage Object Tagging with Java Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Use putObjectTagging to add or update tags on an object and getObjectTagging to retrieve them. Tags are key-value pairs used for categorization. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; import java.util.Arrays; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { // Add tags to object Tag tag1 = Tag.newBuilder().key("environment").value("production").build(); Tag tag2 = Tag.newBuilder().key("team").value("backend").build(); Tagging tagging = Tagging.newBuilder() .tagSet(TagSet.newBuilder() .tags(Arrays.asList(tag1, tag2)) .build()) .build(); PutObjectTaggingResult putResult = client.putObjectTagging( PutObjectTaggingRequest.newBuilder() .bucket("my-bucket") .key("example/file.txt") .tagging(tagging) .build()); System.out.printf("Put tags - status code:%d%n", putResult.statusCode()); // Get object tags GetObjectTaggingResult getResult = client.getObjectTagging( GetObjectTaggingRequest.newBuilder() .bucket("my-bucket") .key("example/file.txt") .build()); System.out.println("Object tags:"); for (Tag tag : getResult.tagging().tagSet().tags()) { System.out.printf(" %s = %s%n", tag.key(), tag.value()); } // Output: // Put tags - status code:200 // Object tags: // environment = production // team = backend } ``` -------------------------------- ### Presigner - Generate Presigned URLs Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Generate temporary URLs for object access without exposing credentials. ```APIDOC ## Presigner - Generate Presigned URLs ### Description Generate temporary URLs for object access without exposing credentials. ### Method GET (for presigned GET URLs) ### Endpoint (Generated URL is a temporary endpoint) ### Parameters #### Path Parameters - **bucket** (string) - Required - The name of the bucket. - **key** (string) - Required - The key of the object. #### Query Parameters (These are part of the generated URL) - **Expires** (string) - Required - The expiration time of the URL. - **Signature** (string) - Required - The signature for authentication. #### Request Body (Not applicable for presigner generation itself, but the object key is required) ### Request Example (SDK method call to generate the URL) ```java // Example for generating a presigned GET URL GetObjectRequest request = GetObjectRequest.newBuilder() .bucket("my-bucket") .key("example/file.txt") .build(); // Generate presigned URL with default expiration PresignResult result = Presigner.getObject(client, request, PresignOptions.defaults()); System.out.println("Presigned URL: " + result.url()); // Generate presigned URL with custom expiration (1 hour) PresignOptions options = PresignOptions.newBuilder() .expiration(Duration.ofHours(1)) .build(); PresignResult customResult = Presigner.getObject(client, request, options); System.out.println("Custom expiration URL: " + customResult.url()); ``` ### Response #### Success Response - **url** (string) - The generated presigned URL. #### Response Example ```json { "url": "https://my-bucket.oss.aliyuncs.com/example/file.txt?Expires=...&Signature=..." } ``` ``` -------------------------------- ### Restore Archived Object with Java Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Restore an archived object to make it accessible for download. A status code of 202 indicates the restore process is in progress and the object will be available shortly. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { RestoreObjectResult result = client.restoreObject(RestoreObjectRequest.newBuilder() .bucket("my-bucket") .key("archived/data.zip") .build()); System.out.printf("status code:%d, request id:%s%n", result.statusCode(), result.requestId()); // Output: status code:202, request id:5C3D5C5E4A5F6D3C... // Note: 202 indicates restore is in progress, object will be available shortly } ``` -------------------------------- ### POST Restore Object - Restore Archived Object Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Restore an archived object to make it accessible for download. ```APIDOC ## POST Restore Object ### Description Restore an archived object to make it accessible for download. ### Method POST ### Endpoint `/bucket-name/object-key?restore` ### Parameters #### Query Parameters - **restore** (string) - Required - Specifies the restore operation. #### Path Parameters - **bucket-name** (string) - Required - The name of the bucket. - **object-key** (string) - Required - The key of the object to restore. ### Request Example (No explicit request body is shown in the example, typically parameters are in the URL or implied by the SDK call) ### Response #### Success Response (202) - **statusCode** (integer) - The HTTP status code of the response. 202 indicates the restore process has started. - **requestId** (string) - The unique request ID. #### Response Example ```json { "statusCode": 202, "requestId": "5C3D5C5E4A5F6D3C..." } ``` ### Notes - A status code of 202 indicates that the restore process is in progress and the object will be available shortly. ``` -------------------------------- ### Maven Dependency for OSS Java SDK V2 Source: https://github.com/aliyun/alibabacloud-oss-java-sdk-v2/blob/main/README-CN.md Add this dependency to your project's pom.xml to include the OSS Java SDK V2. ```xml com.aliyun alibabacloud-oss-v2 latest version ``` -------------------------------- ### Perform Async Operations with OSSAsyncClient Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Use OSSAsyncClient for non-blocking asynchronous operations. The .get() method on the CompletableFuture blocks until the operation is complete. Ensure proper resource management by using try-with-resources. ```java import com.aliyun.sdk.service.oss2.OSSAsyncClient; import com.aliyun.sdk.service.oss2.OSSAsyncClientBuilder; import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider; import com.aliyun.sdk.service.oss2.models.*; import com.aliyun.sdk.service.oss2.transport.BinaryData; import com.aliyun.sdk.service.oss2.utils.IOUtils; try (OSSAsyncClient client = OSSAsyncClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { // Async put object PutObjectResult putResult = client.putObjectAsync(PutObjectRequest.newBuilder() .bucket("my-bucket") .key("async/file.txt") .body(BinaryData.fromString("async content")) .build()).get(); // .get() blocks until complete System.out.printf("Async put - status code:%d, eTag:%s%n", putResult.statusCode(), putResult.eTag()); // Async get object try (GetObjectResult getResult = client.getObjectAsync(GetObjectRequest.newBuilder() .bucket("my-bucket") .key("async/file.txt") .build()).get()) { byte[] data = IOUtils.toByteArray(getResult.body()); System.out.printf("Async get - content length:%d%n", getResult.contentLength()); } // Output: // Async put - status code:200, eTag:"5eb63bbbe01eeed093..." // Async get - content length:13 } ``` -------------------------------- ### Paginate Object Listing with listObjectsV2Paginator Source: https://context7.com/aliyun/alibabacloud-oss-java-sdk-v2/llms.txt Automatically paginate through large object lists using the V2 API. This method handles pagination tokens to iterate through all objects in a bucket. ```java import com.aliyun.sdk.service.oss2.OSSClient; import com.aliyun.sdk.service.oss2.models.*; import com.aliyun.sdk.service.oss2.paginator.ListObjectsV2Iterable; try (OSSClient client = OSSClient.newBuilder() .credentialsProvider(new EnvironmentVariableCredentialsProvider()) .region("cn-hangzhou") .build()) { ListObjectsV2Iterable paginator = client.listObjectsV2Paginator( ListObjectsV2Request.newBuilder() .bucket("my-bucket") .build()); for (ListObjectsV2Result result : paginator) { for (ObjectSummary info : result.contents()) { System.out.printf("key:%s, size:%d, lastModified:%s%n", info.key(), info.size(), info.lastModified()); } } // Automatically handles pagination tokens to iterate through all objects } ```