All Products
Search
Document Center

Object Storage Service:Java-based lifecycle rules

Last Updated:Nov 06, 2024

Not all data that is uploaded to Object Storage Service (OSS) buckets is frequently accessed. Rarely accessed data is stored in cold storage for compliance and archiving purposes. If you want to delete data stored in multiple OSS buckets at the same time, you can configure lifecycle rules based on the last modified time of the data. To reduce storage costs, we recommend that you store cold data and hot data separately. To achieve separate storage of hot data and cold data, you can configure OSS to automatically monitor data access modes, identify cold data, and then change the storage class of the cold data. In this scenario, you can also configure lifecycle rules based on the last access time of the data.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions, endpoints and open ports.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Create an OSSClient instance.

  • To configure lifecycle rules, you must have the oss:PutBucketLifecycle permission. To query lifecycle rules, you must have the oss:GetBucketLifecycle permission. To clear lifecycle rules, you must have the oss:DeleteBucketLifecycle permission. For more information, see Attach a custom policy to a RAM user.

Configure lifecycle rules

The following code provides examples of two lifecycle rules. One lifecycle rule is configured based on the last modified time of data. The other lifecycle rule is configured based on the last access time of data. After you configure lifecycle rules, you can modify the lifecycle rules based on your business requirements. For information about how to modify existing lifecycle rules, see How do I modify a configuration item in one or more lifecycle rules for a bucket?.

Configure a lifecycle rule based on the last modified time that matches objects with the specific tag and name prefix

The following code provides an example on how to configure a lifecycle rule based on the last modified time for a bucket named examplebucket. The lifecycle rule matches objects by prefix and tag. The storage classes of the matched objects are changed, or the matched objects are deleted based on the lifecycle rule.

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.common.utils.DateUtil;
import com.aliyun.oss.model.LifecycleRule;
import com.aliyun.oss.model.SetBucketLifecycleRequest;
import com.aliyun.oss.model.StorageClass;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Create a request by using SetBucketLifecycleRequest. 
            SetBucketLifecycleRequest request = new SetBucketLifecycleRequest(bucketName);

            // Specify the ID of the lifecycle rule. 
            String ruleId0 = "rule0";
            // Specify the prefix that you want the lifecycle rule to match. 
            String matchPrefix0 = "A0/";
            // Specify the tag that you want the lifecycle rule to match. 
            Map<String, String> matchTags0 = new HashMap<String, String>();
            // Specify the key and value of the tag. In the example, the key is set to owner and the value is set to John. 
            matchTags0.put("owner", "John");


            String ruleId1 = "rule1";
            String matchPrefix1 = "A1/";
            Map<String, String> matchTags1 = new HashMap<String, String>();
            matchTags1.put("type", "document");

            String ruleId2 = "rule2";
            String matchPrefix2 = "A2/";

            String ruleId3 = "rule3";
            String matchPrefix3 = "A3/";

            String ruleId4 = "rule4";
            String matchPrefix4 = "A4/";

            String ruleId5 = "rule5";
            String matchPrefix5 = "A5/";

            String ruleId6 = "rule6";
            String matchPrefix6 = "A6/";

            // Set the expiration time to three days after the last modified time. 
            LifecycleRule rule = new LifecycleRule(ruleId0, matchPrefix0, LifecycleRule.RuleStatus.Enabled, 3);
            rule.setTags(matchTags0);
            request.AddLifecycleRule(rule);

            // Specify that objects that are created before the specified date expire. 
            rule = new LifecycleRule(ruleId1, matchPrefix1, LifecycleRule.RuleStatus.Enabled);
            rule.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
            rule.setTags(matchTags1);
            request.AddLifecycleRule(rule);

            // Specify that parts expire three days after they are last modified. 
            rule = new LifecycleRule(ruleId2, matchPrefix2, LifecycleRule.RuleStatus.Enabled);
            LifecycleRule.AbortMultipartUpload abortMultipartUpload = new LifecycleRule.AbortMultipartUpload();
            abortMultipartUpload.setExpirationDays(3);
            rule.setAbortMultipartUpload(abortMultipartUpload);
            request.AddLifecycleRule(rule);

            // Specify that parts that are created before the specific date expire. 
            rule = new LifecycleRule(ruleId3, matchPrefix3, LifecycleRule.RuleStatus.Enabled);
            abortMultipartUpload = new LifecycleRule.AbortMultipartUpload();
            abortMultipartUpload.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
            rule.setAbortMultipartUpload(abortMultipartUpload);
            request.AddLifecycleRule(rule);

            // Specify that the storage classes of objects are changed to IA 10 days after they are last modified, and to Archive 30 days after they are last modified. 
            rule = new LifecycleRule(ruleId4, matchPrefix4, LifecycleRule.RuleStatus.Enabled);
            List<LifecycleRule.StorageTransition> storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
            LifecycleRule.StorageTransition storageTransition = new LifecycleRule.StorageTransition();
            storageTransition.setStorageClass(StorageClass.IA);
            storageTransition.setExpirationDays(10);
            storageTransitions.add(storageTransition);
            storageTransition = new LifecycleRule.StorageTransition();
            storageTransition.setStorageClass(StorageClass.Archive);
            storageTransition.setExpirationDays(30);
            storageTransitions.add(storageTransition);
            rule.setStorageTransition(storageTransitions);
            request.AddLifecycleRule(rule);

            // Specify that the storage classes of objects that are last modified before October 12, 2022 are changed to Archive. 
            rule = new LifecycleRule(ruleId5, matchPrefix5, LifecycleRule.RuleStatus.Enabled);
            storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
            storageTransition = new LifecycleRule.StorageTransition();

            storageTransition.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));

            storageTransition.setStorageClass(StorageClass.Archive);
            storageTransitions.add(storageTransition);
            rule.setStorageTransition(storageTransitions);
            request.AddLifecycleRule(rule);

            // Specify that rule6 is configured for versioning-enabled buckets. 
            rule = new LifecycleRule(ruleId6, matchPrefix6, LifecycleRule.RuleStatus.Enabled);
            // Specify that the storage classes of objects are changed to Archive 365 days after the objects are last modified. 
            storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
            storageTransition = new LifecycleRule.StorageTransition();
            storageTransition.setStorageClass(StorageClass.Archive);
            storageTransition.setExpirationDays(365);
            storageTransitions.add(storageTransition);
            rule.setStorageTransition(storageTransitions);
            // Configure the lifecycle rule to automatically delete expired delete markers. 
            rule.setExpiredDeleteMarker(true);
            // Specify that the storage classes of the previous versions of objects are changed to IA 10 days after the objects are last modified. 
            LifecycleRule.NoncurrentVersionStorageTransition noncurrentVersionStorageTransition =
                    new LifecycleRule.NoncurrentVersionStorageTransition().withNoncurrentDays(10).withStrorageClass(StorageClass.IA);
            // Specify that the storage classes of the previous versions of objects are changed to Archive 20 days after the objects are last modified. 
            LifecycleRule.NoncurrentVersionStorageTransition noncurrentVersionStorageTransition2 =
                    new LifecycleRule.NoncurrentVersionStorageTransition().withNoncurrentDays(20).withStrorageClass(StorageClass.Archive);
            // Specify that the previous versions of objects are deleted 30 days after the objects are last modified. 
            LifecycleRule.NoncurrentVersionExpiration noncurrentVersionExpiration = new LifecycleRule.NoncurrentVersionExpiration().withNoncurrentDays(30);
            List<LifecycleRule.NoncurrentVersionStorageTransition> noncurrentVersionStorageTransitions = new ArrayList<LifecycleRule.NoncurrentVersionStorageTransition>();
            noncurrentVersionStorageTransitions.add(noncurrentVersionStorageTransition2);
            rule.setStorageTransition(storageTransitions);
            rule.setNoncurrentVersionExpiration(noncurrentVersionExpiration);
            rule.setNoncurrentVersionStorageTransitions(noncurrentVersionStorageTransitions);
            request.AddLifecycleRule(rule);

            // Initiate a request to configure lifecycle rules. 
            ossClient.setBucketLifecycle(request);

            // Query the lifecycle rules that are configured for the bucket. 
            List<LifecycleRule> listRules = ossClient.getBucketLifecycle(bucketName);
            for(LifecycleRule rules : listRules){
                System.out.println("ruleId="+rules.getId()+", matchPrefix="+rules.getPrefix());
            }
        } 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();
            }
        }
    }
}

Configure a lifecycle rule based on the last modified time that matches objects without the specific tag or name prefix

The following code provides an example on how to configure a lifecycle rule based on the last modified time. The lifecycle rule changes the storage classes of objects that meet the following conditions in the examplebucket bucket to IA 30 days after the objects are last modified: The names of the objects do not contain the log prefix and the objects do not have the tag whose key is tag1 and whose value is value1. The conditions are specified in the Not element of the filter node.

Note

Only OSS SDK for Java 3.16.0 and later support the NOT element.

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.*;
import java.util.ArrayList;
import java.util.List;

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. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            String ruleId = "mtime transition1";
            String matchPrefix = "logs";

            SetBucketLifecycleRequest request = new SetBucketLifecycleRequest(bucketName);

            LifecycleFilter filter = new LifecycleFilter();
            LifecycleNot not = new LifecycleNot();
            Tag tag = new Tag("key1","value1");
            not.setPrefix("logs/not-prefix");
            not.setTag(tag);
            List<LifecycleNot> notList = new ArrayList<LifecycleNot>();
            notList.add(not);
            filter.setNotList(notList);

            List<LifecycleRule.StorageTransition> storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
            LifecycleRule.StorageTransition storageTransition = new LifecycleRule.StorageTransition();
            storageTransition.setStorageClass(StorageClass.IA);
            storageTransition.setExpirationDays(30);
            storageTransitions.add(storageTransition);

            LifecycleRule rule = new LifecycleRule(ruleId, matchPrefix, LifecycleRule.RuleStatus.Enabled);
            rule.setFilter(filter);
            rule.setStorageTransition(storageTransitions);
            request.AddLifecycleRule(rule);

            VoidResult result = ossClient.setBucketLifecycle(request);

            System.out.println("Returned status code:"+result.getResponse().getStatusCode()+" set lifecycle succeed");
        } 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();
            }
        }
    }
}

Configure a lifecycle rule based on the last access time to change the storage classes of objects

The following code provides an example on how to configure a lifecycle rule based on the last access time to change the storage classes of objects in the examplebucket bucket:

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.*;
import java.util.ArrayList;
import java.util.List;

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. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            ossClient.putBucketAccessMonitor(bucketName, AccessMonitor.AccessMonitorStatus.Enabled.toString());
            // Create a lifecycle rule and set the ID to rule1. Specify that the storage classes of objects whose names contain the logs prefix and whose size is less than or equal to 64 KB are changed to IA 30 days after the objects are last accessed. In addition, specify that the objects whose name contain the logs prefix are still stored as IA objects when the objects are accessed again. 
            LifecycleRule lifecycleRule = new LifecycleRule("rule1", "logs", LifecycleRule.RuleStatus.Enabled);
            List<LifecycleRule> lifecycleRuleList = new ArrayList<LifecycleRule>();
            SetBucketLifecycleRequest setBucketLifecycleRequest = new SetBucketLifecycleRequest(bucketName);

            LifecycleRule.StorageTransition storageTransition = new LifecycleRule.StorageTransition();
            storageTransition.setStorageClass(StorageClass.IA);
            storageTransition.setExpirationDays(30);
            storageTransition.setIsAccessTime(true);
            storageTransition.setReturnToStdWhenVisit(false);
            storageTransition.setAllowSmallFile(true);
            List<LifecycleRule.StorageTransition> storageTransitionList = new ArrayList<LifecycleRule.StorageTransition>();
            storageTransitionList.add(storageTransition);
            lifecycleRule.setStorageTransition(storageTransitionList);
            lifecycleRuleList.add(lifecycleRule);
            
            // Create a lifecycle rule and set the ID to rule2. Specify that the previous versions of the objects whose names contain the dir prefix and whose size is greater than 64 KB are changed to IA 10 days after the objects are last accessed. In addition, specify that the storage classes of the objects whose names contain the dir prefix are changed to Standard when the objects are accessed again. 
            LifecycleRule lifecycleRule2 = new LifecycleRule("rule2", "dir", LifecycleRule.RuleStatus.Enabled);
            LifecycleRule.NoncurrentVersionStorageTransition noncurrentVersionStorageTransition = new LifecycleRule.NoncurrentVersionStorageTransition();
            noncurrentVersionStorageTransition.setStorageClass(StorageClass.IA);
            noncurrentVersionStorageTransition.setNoncurrentDays(10);
            noncurrentVersionStorageTransition.setIsAccessTime(true);
            noncurrentVersionStorageTransition.setReturnToStdWhenVisit(true);
            noncurrentVersionStorageTransition.setAllowSmallFile(false);

            List<LifecycleRule.NoncurrentVersionStorageTransition> noncurrentVersionStorageTransitionList = new ArrayList<LifecycleRule.NoncurrentVersionStorageTransition>();
            noncurrentVersionStorageTransitionList.add(noncurrentVersionStorageTransition);
            lifecycleRule2.setNoncurrentVersionStorageTransitions(noncurrentVersionStorageTransitionList);
            lifecycleRuleList.add(lifecycleRule2);

            setBucketLifecycleRequest.setLifecycleRules(lifecycleRuleList);

            // Configure the lifecycle rules. 
            ossClient.setBucketLifecycle(setBucketLifecycleRequest);
        } 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();
            }
        }
    }
}

Query lifecycle rules

The following code provides an example on how to query the lifecycle rules configured for the bucket named examplebucket:

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.LifecycleRule;
import java.util.List;

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. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Query the lifecycle rules of the bucket. 
            List<LifecycleRule> rules = ossClient.getBucketLifecycle(bucketName);

            // Query the lifecycle rules that are configured for the bucket. 
            for (LifecycleRule r : rules) {
                System.out.println("================");

                // View the rule ID. 
                System.out.println("rule id: " + r.getId());

                // View the status of the rule. 
                System.out.println("rule status: " + r.getStatus());

                // View the prefix configured in the lifecycle rule. 
                System.out.println("rule prefix: " + r.getPrefix());

                // View the tag configured in the lifecycle rule. 
                if (r.hasTags()) {
                    System.out.println("rule tagging: "+ r.getTags().toString());
                }

                // View the validity period configured in the lifecycle rule. 
                if (r.hasExpirationDays()) {
                    System.out.println("rule expiration days: " + r.getExpirationDays());
                }

                // View the expiration date configured in the lifecycle rule. 
                if (r.hasCreatedBeforeDate()) {
                    System.out.println("rule expiration create before days: " + r.getCreatedBeforeDate());
                }

                // View the rule for expired parts. 
                if(r.hasAbortMultipartUpload()) {
                    if(r.getAbortMultipartUpload().hasExpirationDays()) {
                        System.out.println("rule abort uppart days: " + r.getAbortMultipartUpload().getExpirationDays());
                    }

                    if (r.getAbortMultipartUpload().hasCreatedBeforeDate()) {
                        System.out.println("rule abort uppart create before date: " + r.getAbortMultipartUpload().getCreatedBeforeDate());
                    }
                }

                // View the rule of storage class change. 
                if (r.getStorageTransition().size() > 0) {
                    for (LifecycleRule.StorageTransition transition : r.getStorageTransition()) {
                        if (transition.hasExpirationDays()) {
                            System.out.println("rule storage trans days: " + transition.getExpirationDays() +
                                    " trans storage class: " + transition.getStorageClass());
                        }

                        if (transition.hasCreatedBeforeDate()) {
                            System.out.println("rule storage trans before create date: " + transition.getCreatedBeforeDate());
                        }
                        // Check whether lifecycle rules are configured based on the last access time. This configuration applies only to OSS SDK for Java 3.16.0 and later. 
                        System.out.println("StorageTransition IsAccessTime: "+transition.getIsAccessTime());
                        // View the lifecycle rule to check whether the storage class of the object is changed to Standard when the object is accessed again after the storage class of the object is changed to IA. This configuration applies only to OSS SDK for Java 3.16.0 and later. 
                        System.out.println("StorageTransition ReturnToStdWhenVisit: "+transition.getReturnToStdWhenVisit());
                    }
                }

                // View the lifecycle rule to check whether expired delete markers are automatically deleted. 
                if (r.hasExpiredDeleteMarker()) {
                    System.out.println("rule expired delete marker: " + r.getExpiredDeleteMarker());
                }

                // View the configurations used to change the storage classes of previous versions of the objects. 
                if (r.hasNoncurrentVersionStorageTransitions()) {
                    for (LifecycleRule.NoncurrentVersionStorageTransition transition : r.getNoncurrentVersionStorageTransitions()) {
                        System.out.println("rule noncurrent versions trans days:" + transition.getNoncurrentDays() +
                                " trans storage class: " + transition.getStorageClass());
                        // View the access time of objects.  This configuration applies only to OSS SDK for Java 3.16.0 and later. 
                        System.out.println("NoncurrentVersionStorageTransition IsAccessTime: "+transition.getIsAccessTime());
                        // View the ReturnToStdWhenVisit.  This configuration applies only to OSS SDK for Java 3.16.0 and later. 
                        System.out.println("NoncurrentVersionStorageTransition ReturnToStdWhenVisit: "+transition.getReturnToStdWhenVisit());
                    }
                }

                // View the expiration rule for previous versions of objects. 
                if (r.hasNoncurrentVersionExpiration()) {
                    System.out.println("rule noncurrent versions expiration days:" + r.getNoncurrentVersionExpiration().getNoncurrentDays());
                }
            }
        } 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();
            }
        }
    }
}

Clear lifecycle rules

The following code provides an example on how to clear lifecycle rules in a bucket named examplebucket. If you want to delete one or more lifecycle rules, refer to How do I delete one or more lifecycle rules that are configured for a bucket?.

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;

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. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            ossClient.deleteBucketLifecycle(bucketName);
        } 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();
            }
        }
    }
}

References

  • For the complete sample code for lifecycle rules, visit GitHub.

  • For more information about the API operation that you can call to configure a lifecycle rule, see PutBucketLifecycle.

  • For more information about the API operation that you can call to query lifecycle rules, see GetBucketLifecycle.

  • For more information about the API operation that you can call to delete lifecycle rules, see DeleteBucketLifecycle.