Help Center> Object Storage Service> Java> Versioning (SDK for Java)> Listing Object Versions (SDK for Java)
Updated on 2024-05-11 GMT+08:00

Listing Object Versions (SDK for Java)

Function

This API lists some or all of the object versions in a bucket. When listing the object versions, you can specify the criteria such as the prefix, number, and start position. Returned object versions are listed in alphabetical order by object name.

The returned results of ObsClient.listVersions include the object versions and delete markers.

Restrictions

  • To list object versions in a bucket, you must be the bucket owner or have the required permission (obs:bucket:ListBucketVersions in IAM or ListBucketVersions in a bucket policy). For details, see Introduction to OBS Access Control, IAM Custom Policies, and Creating a Custom Bucket Policy.
  • The mapping between OBS regions and endpoints must comply with what is listed in Regions and Endpoints.
  • A maximum of 1,000 object versions can be returned in a single request. If a bucket contains more than 1,000 object versions, you can use pagination to list all versions. If ListVersionsResult.isTruncated is true, only part of object versions are returned. In this case, you can use ListVersionsResult.getNextKeyMarker and ListVersionsResult.getNextVersionIdMarker to obtain the start position for the next listing.

Method

obsClient.listVersions(ListVersionsRequest request)

Request Parameters

Table 1 List of request parameters

Parameter

Type

Mandatory (Yes/No)

Description

request

ListVersionsRequest

Yes

Explanation:

Request parameters for listing object versions in a bucket. For details, see Table 2.

Table 2 ListVersionsRequest parameters

Parameter

Type

Mandatory (Yes/No)

Description

bucketName

String

Yes

Explanation:

Bucket name.

Restrictions:

  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain periods (.) and hyphens (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets of the same name in the same region, no error will be reported and the bucket attributes comply with those set in the first creation request.

Default value:

None

prefix

String

No

Explanation:

Prefix that the names of objects to list must contain.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

keyMarker

String

No

Explanation:

Object name to start with when listing object versions in a bucket. All object versions following this parameter are listed in alphabetical order.

Restrictions:

This parameter is only available for listing objects with multiple versions.

Value range:

The value of nextKeyMarker in the response body of the last request.

Default value:

None

maxKeys

int

No

Explanation:

The maximum number of object versions returned in the response in alphabetical order.

Value range:

The value ranges from 1 to 1000. If the specified value is beyond this range, only 1,000 objects are returned.

Default value:

1000

delimiter

String

No

Explanation:

This parameter is used to group object names. If a prefix is specified, objects with the same string from the prefix to the first delimiter are grouped into one CommonPrefixes. If no prefix is specified, objects with the same string from the first character to the first delimiter are grouped into one CommonPrefixes.

Assume that a bucket has objects abcd, abcde, and bbcde in it. If delimiter is set to d and prefix is set to a, objects abcd and abcde are grouped into a commonPrefix with abcd as the prefix. If only delimiter is set to d, objects abcd and abcde are grouped into a commonPrefix with abcd as the prefix, and bbcde is grouped separately into another commonPrefix with bbcd as the prefix.

For a PFS, if this parameter is not specified, all the contents in the current directory are recursively listed by default, and subdirectories are also listed. In big data scenarios, PFSs usually have multiple directory levels and each directory level has a large number of files. In such case, you are advised to configure [delimiter=/] to list the contents in the current directory but exclude the contents in subdirectories, thereby accelerating the listing.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

versionIdMarker

String

No

Explanation:

Version ID you want to start listing from. All object versions following the value specified by this parameter are listed in alphabetical order by object name and version ID. This parameter must be used together with keyMarker. keyMarker specifies the object name, and versionIdMarker specifies the version of the specified object.

Restrictions:

  • This parameter is only available for listing objects with multiple versions.
  • If the object version specified by versionIdMarker and the object name specified by keyMarker do not match, versionIdMarker is invalid.

Value range:

Object version ID, that is, the value of nextVersionIdMarker in the response body of the last request.

Default value:

None

encodingType

String

No

Explanation:

Encoding type for some elements in the response. If delimiter, keyMarker, prefix, nextKeyMarker, and key contain control characters that are not supported by the XML 1.0 standard, you can set encodingType to encode delimiter, keyMarker, prefix (including the prefix in commonPrefixes), nextKeyMarker, and key in the response.

Value range:

url

Default value:

None. If you leave this parameter blank, encoding is not applied.

Responses

Table 3 ListVersionsResult

Parameter

Type

Description

bucketName

String

Explanation:

Bucket name.

Restrictions:

  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain periods (.) and hyphens (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets of the same name in the same region, no error will be reported and the bucket attributes comply with those set in the first creation request.

Default value:

None

prefix

String

Explanation:

Object name prefix.

Assume that you have the following objects: logs/day1, logs/day2, logs/day3, and ExampleObject.jpg. If you specify logs/ as the prefix, logs/day1, logs/day2, and logs/day3 will be returned. If this parameter is null and there are no other filter criteria, all objects in the bucket will be returned.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

versionIdMarker

String

Explanation:

Object version for the object specified by KeyMarker. All object versions following the value specified by this parameter are listed in alphabetical order by object name and version ID. This parameter must be used together with KeyMarker. KeyMarker specifies the object name, and versionIdMarker specifies the version of the specified object.

Restrictions:

  • This parameter is only available for listing objects with multiple versions.
  • If the object version specified by versionIdMarker and the object name specified by keyMarker do not match, versionIdMarker is invalid.

Value range:

The value must contain 32 characters.

Default value:

None

nextVersionIdMarker

String

Explanation:

Version ID to start with in the next request for listing object versions. It must be used together with nextKeyMarker. If only part of the object versions are returned for the current request, this parameter is included in the response for your use in the subsequent request.

Restrictions:

This parameter is only available for listing objects with multiple versions.

Value range:

The value must contain 32 characters.

Default value:

None

objectSummaries

List<ObsObject>

Explanation:

Object information. For details, see Table 4.

commonPrefixes

List<String>

Explanation:

List of object name prefixes grouped according to the delimiter parameter (if specified)

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

truncated

boolean

Explanation:

Whether all objects are returned in the response. A maximum of 1,000 objects can be listed at a time. If the number of objects is greater than 1,000, the objects beyond 1,000 cannot be returned.

Value range:

true: Not all objects are returned.

false: All objects are returned.

Default value:

None

keyMarker

String

Explanation:

Object name to start listing from. All object versions following the value specified by this parameter are listed in alphabetical order by object name.

Restrictions:

This parameter is only available for listing objects with multiple versions.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

maxKeys

int

Explanation:

Maximum number of objects to list. No more than the specified number of objects can be returned in the response in alphabetical order.

Value range:

The value ranges from 1 to 1000. If the specified value is beyond this range, only 1,000 objects are returned.

Default value:

1000

delimiter

String

Explanation:

Object names are grouped by this parameter, which is often used with Prefix. If a prefix is specified, objects with the same string from the prefix to the first delimiter are grouped into one CommonPrefixes. If no prefix is specified, objects with the same string from the first character to the first delimiter are grouped into one CommonPrefixes.

Assume that a bucket has objects abcd, abcde, and bbcde in it. If delimiter is set to d and prefix is set to a, files abcd and abcde are grouped into a CommonPrefixes with abcd as the prefix. If only delimiter is set to d, files abcd and abcde are grouped into a CommonPrefixes with abcd as the prefix, and bbcde is grouped separately into another CommonPrefixes with bbcd as the prefix.

For a PFS, if this parameter is not specified, all the contents in the current directory are recursively listed by default, and subdirectories are also listed. In big data scenarios, PFSs usually have multiple directory levels and each directory level has a large number of files. In such case, you are advised to configure [delimiter=/] to list the contents in the current directory but exclude the contents in subdirectories, thereby accelerating the listing.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

nextKeyMarker

String

Explanation:

Object name to start with for the next request for listing object versions. If only part of the object versions are returned for the current request, this parameter is included in the response for your use in the subsequent request.

Restrictions:

This parameter is only available for listing objects with multiple versions.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

location

String

Explanation:

Region where a bucket is located.

Restrictions:

If the endpoint used is obs.myhuaweicloud.com, this parameter is not required. If any other endpoints are used, this parameter is required.

Value range:

To learn about valid regions and endpoints, see Regions and Endpoints. An endpoint is the request address for calling an API. Endpoints vary depending on services and regions. To obtain the regions and endpoints, contact the enterprise administrator.

Default value:

If obs.myhuaweicloud.com is used as the endpoint and no region is specified, cn-north-1 (the CN North-Beijing1 region) is used by default.

statusCode

int

Explanation:

HTTP status code.

Value range:

A status code is a group of digits that can be 2xx (indicating successes) or 4xx or 5xx (indicating errors). It indicates the status of a response. For more information, see Status Code.

Default value:

None

responseHeaders

Map<String, Object>

Explanation:

Response header list, composed of tuples. In a tuple, the String key indicates the name of the header, and the Object value indicates the value of the header.

Default value:

None

versions

VersionOrDeleteMarker[]

Explanation:

Object version information. For details, see Table 8.

Table 4 ObsObject

Parameter

Type

Description

bucketName

String

Explanation:

Bucket name.

Restrictions:

  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain periods (.) and hyphens (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets of the same name in the same region, no error will be reported and the bucket attributes comply with those set in the first creation request.

Default value:

None

objectKey

String

Explanation:

Object name. An object is uniquely identified by an object name in a bucket. An object name is a complete path that does not contain the bucket name.

For example, if the address for accessing the object is examplebucket.obs.ap-southeast-1.myhuaweicloud.com/folder/test.txt, the object name is folder/test.txt.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

owner

Owner

Explanation:

Owner of the object. For details, see Table 5.

metadata

ObjectMetadata

Explanation:

Object metadata. For details, see Table 6.

objectContent

InputStream

Explanation:

Object data stream.

Default value:

None

Table 5 Owner

Parameter

Type

Mandatory (Yes/No)

Description

id

String

Yes

Explanation:

Account (domain) ID of the bucket owner.

Value range:

To obtain the account ID, see How Do I Get My Account ID and User ID?

Default value:

None

displayName

String

No

Explanation:

Account name of the owner.

Value range:

To obtain the account name, see How Do I Get My Account ID and User ID?

Default value:

None

Table 6 ObjectMetadata

Parameter

Type

Mandatory (Yes/No)

Description

contentLength

Long

No

Explanation:

Object size.

Restrictions:

  • The object size in a single upload ranges from 0 to 5 GB.
  • To upload files larger than 5 GB, multipart uploads should be used.

Default value:

If this parameter is not specified, the SDK automatically calculates the size of the object.

contentType

String

No

Explanation:

MIME type of the object file. MIME type is a standard way of describing a data type and is used by the browser to decide how to display data.

Value range:

See What Is Content-Type (MIME)? (Java SDK)

Default value:

If this parameter is not specified, the SDK determines the file type based on the suffix of the object name and assigns a value to the parameter. For example, if the suffix of the object name is .xml, the object is an application/xml file. If the suffix is .html, the object is a text/html file.

contentEncoding

String

No

Explanation:

Content-Encoding header in the response. It specifies which encoding is applied to the object.

Default value:

None

contentDisposition

String

No

Explanation:

Provides a default file name for the requested object. When the object with the default file name is being downloaded or accessed, the content is displayed as part of a web page in the browser or as an attachment in a download dialog box.

Default value:

None

cacheControl

String

No

Explanation:

Cache-Control header in the response. It specifies the cache behavior of the web page when an object is downloaded.

Default value:

None

contentLanguage

String

No

Explanation:

Language or language combination for visitors to customize and use. For details, see the definition of ContentLanguage in the HTTP protocol.

Default value:

None

expires

String

No

Explanation:

The time a cached web page object expires.

Restrictions:

The time must be in the GMT format.

Default value:

None

contentMd5

String

No

Explanation:

Base64-encoded MD5 value of the file data. It is provided for the OBS server to verify data integrity. The OBS server will compare this MD5 value with the MD5 value calculated based on the file data. If the two values are not the same, HTTP status code 400 is returned.

Restrictions:

  • The MD5 value of the file must be Base64 encoded.
  • If the MD5 value is not specified, the OBS server will not verify the MD5 value of the object.

Value range:

Base64-encoded 128-bit MD5 value of the request body calculated according to RFC 1864.

Example: n58IG6hfM7vqI4K0vnWpog==

Default value:

None

storageClass

StorageClassEnum

No

Explanation:

Storage class of an object that can be specified at object creation. If you do not specify this header, the object inherits the storage class of the bucket.

Value range:

See Table 7.

Default value:

None

webSiteRedirectLocation

String

No

Explanation:

If the bucket is configured with website hosting, the request for obtaining the object can be redirected to another object in the bucket or an external URL. This parameter specifies the address the request for the object is redirected to.

The request is redirected to an object anotherPage.html in the same bucket:

WebsiteRedirectLocation:/anotherPage.html

The request is redirected to an external URL http://www.example.com/:

WebsiteRedirectLocation:http://www.example.com/

Restrictions:

  • The value must start with a slash (/), http://, or https:// and cannot exceed 2 KB.
  • OBS only supports redirection for objects in the root directory of a bucket.

Default value:

None

nextPosition

long

No

Explanation:

Start position for the next append upload.

Value range:

0 to the object length, in bytes.

Default value:

None

appendable

boolean

No

Explanation:

Whether the object is appendable.

Value range:

true: The object is appendable.

false: The object is not appendable.

Default value:

None

userMetadata

Map<String, Object>

No

Explanation:

User-defined metadata of the object. To define it, you can add a header starting with x-obs-meta- in the request. In Map, the String key indicates the name of the user-defined metadata that starts with x-obs-meta-, and the Object value indicates the value of the user-defined metadata. To obtain the user-defined metadata of an object, use ObsClient.getObjectMetadata. For details, see Obtaining Object Metadata (SDK for Java).

Restrictions:

  • An object can have multiple pieces of metadata. The size of the metadata cannot exceed 8 KB in total.
  • When you call ObsClient.getObject to download an object, its user-defined metadata will also be downloaded.

Default value:

None

Table 7 StorageClassEnum

Constant

Default Value

Description

STANDARD

STANDARD

Standard storage class

WARM

WARM

Infrequent Access storage class.

COLD

COLD

Archive storage class.

Table 8 VersionOrDeleteMarker

Parameter

Type

Description

bucketName

String

Explanation:

Bucket name.

Restrictions:

  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain periods (.) and hyphens (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets of the same name in the same region, no error will be reported and the bucket attributes comply with those set in the first creation request.

Default value:

None

key

String

Explanation:

Object name. An object is uniquely identified by an object name in a bucket. An object name is a complete path that does not contain the bucket name.

For example, if the address for accessing the object is examplebucket.obs.ap-southeast-1.myhuaweicloud.com/folder/test.txt, the object name is folder/test.txt.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

versionId

String

Explanation:

Object version ID.

Value range:

The value must contain 32 characters.

Default value:

None

isLatest

boolean

Explanation:

Whether the object is the latest version.

Value range:

  • true: The object is the latest version.
  • false: The object is not the latest version.

Default value:

false

lastModified

Date

Explanation:

Time when the object was last modified.

Value range:

UTC time

Default value:

None

owner

Owner

Explanation:

User information, including the domain ID and name of the object owner. For details, see Table 5.

etag

String

Explanation:

Base64-encoded, 128-bit MD5 value of an object. ETag is the unique identifier of the object contents and is used to determine whether the contents of an object are changed. For example, if the ETag value is A when an object is uploaded and is B when the object is downloaded, this indicates the contents of the object are changed. The ETag reflects changes only to the contents of an object, not its metadata. Objects created by the upload and copy operations have unique ETags after being encrypted using MD5.

Restrictions:

If an object is encrypted using server-side encryption, the ETag is not the MD5 value of the object.

Value range:

The value must contain 32 characters.

Default value:

None

size

long

Explanation:

Object size, in bytes.

Value range:

The value ranges from 0 TB to 48.8 TB, in bytes.

Default value:

None

storageClass

StorageClassEnum

Explanation:

Storage class of an object that can be specified at object creation. If you do not specify this header, the object inherits the storage class of the bucket.

Value range:

See Table 7.

Default value:

None

isDeleteMarker

boolean

Explanation:

Whether the object version is a delete marker.

Value range:

true: The object version is a delete marker.

false: The object version is not a delete marker.

Default value:

None

Code Example: Listing Object Versions in a Bucket

This example lists object versions in bucket examplebucket. A maximum of 1,000 object versions can be returned.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ListVersionsResult;
import com.obs.services.model.VersionOrDeleteMarker;
public class ListVersions001 {
    public static void main(String[] args) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage.
        // Obtain an AK/SK pair and a security token using environment variables or import them in other ways.
        // String securityToken = System.getenv("SECURITY_TOKEN");
        // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Obtain an endpoint using environment variables or import it in other ways.
        //String endPoint = System.getenv("ENDPOINT");
        
        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the client.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);
        // Use the temporary AK/SK pair and security token to initialize the client.
        // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint);

        try {
            // Listing object versions.
            ListVersionsResult result = obsClient.listVersions("examplebucket");
            System.out.println("listVersions successfully");
            for (VersionOrDeleteMarker v : result.getVersions()) {
                System.out.println("Key:" + v.getKey());
                System.out.println("Owner:" + v.getOwner());
                System.out.println("isDeleteMarker:" + v.isDeleteMarker());
            }
        } catch (ObsException e) {
            System.out.println("listVersions failed");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error details.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request ID.
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("listVersions failed");
            // Print other error information.
            e.printStackTrace();
        }
    }
}

Code Example: Specifying the Version Count to List

This example lists a specified number of object versions in bucket examplebucket.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ListVersionsResult;
import com.obs.services.model.VersionOrDeleteMarker;
public class ListVersions002 {
    public static void main(String[] args) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage.
        // Obtain an AK/SK pair and a security token using environment variables or import them in other ways.
        // String securityToken = System.getenv("SECURITY_TOKEN");
        // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Obtain an endpoint using environment variables or import it in other ways.
        //String endPoint = System.getenv("ENDPOINT");
        
        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the client.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);
        // Use the temporary AK/SK pair and security token to initialize the client.
        // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint);

        try {
            // List a specified number of object versions.
            ListVersionsResult result = obsClient.listVersions("examplebucket", 100);
            System.out.println("listVersions successfully");
            for (VersionOrDeleteMarker v : result.getVersions()) {
                System.out.println("Key:" + v.getKey());
                System.out.println("Owner:" + v.getOwner());
                System.out.println("isDeleteMarker:" + v.isDeleteMarker());
            }
        } catch (ObsException e) {
            System.out.println("listVersions failed");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error details.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request ID.
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("listVersions failed");
            // Print other error information.
            e.printStackTrace();
        }
    }
}

Code Example: Specifying the Version Prefix to List

This example specifies a prefix to list object versions in bucket examplebucket. A maximum of 100 object versions will be returned.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ListVersionsRequest;
import com.obs.services.model.ListVersionsResult;
import com.obs.services.model.VersionOrDeleteMarker;
public class ListVersions003 {
    public static void main(String[] args) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage.
        // Obtain an AK/SK pair and a security token using environment variables or import them in other ways.
        // String securityToken = System.getenv("SECURITY_TOKEN");
        // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Obtain an endpoint using environment variables or import it in other ways.
        //String endPoint = System.getenv("ENDPOINT");
        
        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the client.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);
        // Use the temporary AK/SK pair and security token to initialize the client.
        // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint);

        try {
            // List object versions by specifying a prefix.
            // List 100 object versions with the specified prefix.
            ListVersionsRequest request = new ListVersionsRequest("examplebucket", 100);
            request.setPrefix("prefix");
            ListVersionsResult result = obsClient.listVersions(request);
            System.out.println("listVersions successfully");
            for (VersionOrDeleteMarker v : result.getVersions()) {
                System.out.println("Key:" + v.getKey());
                System.out.println("Owner:" + v.getOwner());
                System.out.println("isDeleteMarker:" + v.isDeleteMarker());
            }
        } catch (ObsException e) {
            System.out.println("listVersions failed");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error details.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request ID.
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("listVersions failed");
            // Print other error information.
            e.printStackTrace();
        }
    }
}

Code Example: Specifying the Start Position to List

This example lists 100 object versions whose names follow test in lexicographical order in bucket examplebucket.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ListVersionsRequest;
import com.obs.services.model.ListVersionsResult;
import com.obs.services.model.VersionOrDeleteMarker;
public class ListVersions004 {
    public static void main(String[] args) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage.
        // Obtain an AK/SK pair and a security token using environment variables or import them in other ways.
        // String securityToken = System.getenv("SECURITY_TOKEN");
        // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Obtain an endpoint using environment variables or import it in other ways.
        //String endPoint = System.getenv("ENDPOINT");
        
        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the client.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);
        // Use the temporary AK/SK pair and security token to initialize the client.
        // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint);

        try {
            // List objects from a specified start position.
            // List 100 object versions whose names following test in lexicographic order.
            ListVersionsRequest request = new ListVersionsRequest("examplebucket", 100);
            request.setKeyMarker("test");
            ListVersionsResult result = obsClient.listVersions(request);
            System.out.println("listVersions successfully");
            for (VersionOrDeleteMarker v : result.getVersions()) {
                System.out.println("Key:" + v.getKey());
                System.out.println("Owner:" + v.getOwner());
                System.out.println("isDeleteMarker:" + v.isDeleteMarker());
            }
        } catch (ObsException e) {
            System.out.println("listVersions failed");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error details.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request ID.
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("listVersions failed");
            // Print other error information.
            e.printStackTrace();
        }
    }
}

Code Example: Using Pagination to List All Versions

This example lists 100 object versions whose names follow test in lexicographical order in bucket examplebucket.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ListVersionsRequest;
import com.obs.services.model.ListVersionsResult;
import com.obs.services.model.VersionOrDeleteMarker;
public class ListVersions005 {
    public static void main(String[] args) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage.
        // Obtain an AK/SK pair and a security token using environment variables or import them in other ways.
        // String securityToken = System.getenv("SECURITY_TOKEN");
        // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Obtain an endpoint using environment variables or import it in other ways.
        //String endPoint = System.getenv("ENDPOINT");
        
        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the client.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);
        // Use the temporary AK/SK pair and security token to initialize the client.
        // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint);

        try {
            // List all object versions using pagination.
            ListVersionsResult result;
            ListVersionsRequest request = new ListVersionsRequest("examplebucket", 100);
            do {
                result = obsClient.listVersions(request);
                System.out.println("listVersions successfully");
                for (VersionOrDeleteMarker v : result.getVersions()) {
                    System.out.println("Key:" + v.getKey());
                    System.out.println("Owner:" + v.getOwner());
                    System.out.println("isDeleteMarker:" + v.isDeleteMarker());
                }
                request.setKeyMarker(result.getNextKeyMarker());
                request.setVersionIdMarker(result.getNextVersionIdMarker());
            } while (result.isTruncated());
        } catch (ObsException e) {
            System.out.println("listVersions failed");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error details.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request ID.
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("listVersions failed");
            // Print other error information.
            e.printStackTrace();
        }
    }
}

Code Example: Listing All Object Versions in a Folder

There is no concept of folders in OBS. All elements stored in OBS buckets are objects. Folders are actually objects whose sizes are 0 and whose names end with a slash (/). You can set a folder name as a prefix to list objects in this folder. This example lists all object versions in a folder.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ListVersionsRequest;
import com.obs.services.model.ListVersionsResult;
import com.obs.services.model.VersionOrDeleteMarker;
public class ListVersions006 {
    public static void main(String[] args) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage.
        // Obtain an AK/SK pair and a security token using environment variables or import them in other ways.
        // String securityToken = System.getenv("SECURITY_TOKEN");
        // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Obtain an endpoint using environment variables or import it in other ways.
        //String endPoint = System.getenv("ENDPOINT");
        
        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the client.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);
        // Use the temporary AK/SK pair and security token to initialize the client.
        // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint);

        try {
            //List all object versions in a folder.
            ListVersionsResult result;
            ListVersionsRequest request = new ListVersionsRequest("examplebucket", 100);
            // Set folder name dir/ as the prefix.
            request.setPrefix("dir/");
            do {
                result = obsClient.listVersions(request);
                System.out.println("listVersions successfully");
                for (VersionOrDeleteMarker v : result.getVersions()) {
                    System.out.println("Key:" + v.getKey());
                    System.out.println("Owner:" + v.getOwner());
                    System.out.println("isDeleteMarker:" + v.isDeleteMarker());
                }
                request.setKeyMarker(result.getNextKeyMarker());
                request.setVersionIdMarker(result.getNextVersionIdMarker());
            } while (result.isTruncated());
        } catch (ObsException e) {
            System.out.println("listVersions failed");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error details.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request ID.
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("listVersions failed");
            // Print other error information.
            e.printStackTrace();
        }
    }
}

Code Example: Listing All Object Versions in a Bucket by Folder Name

This example lists all object versions in bucket examplebucket.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ListVersionsRequest;
import com.obs.services.model.ListVersionsResult;
import com.obs.services.model.VersionOrDeleteMarker;
public class ListVersions007 {
    public static void main(String[] args) {
        // Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
        // Obtain an AK/SK pair on the management console.
        String ak = System.getenv("ACCESS_KEY_ID");
        String sk = System.getenv("SECRET_ACCESS_KEY_ID");
        // (Optional) If you are using a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage.
        // Obtain an AK/SK pair and a security token using environment variables or import them in other ways.
        // String securityToken = System.getenv("SECURITY_TOKEN");
        // Enter the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
        String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
        // Obtain an endpoint using environment variables or import it in other ways.
        //String endPoint = System.getenv("ENDPOINT");
        
        // Create an ObsClient instance.
        // Use the permanent AK/SK pair to initialize the client.
        ObsClient obsClient = new ObsClient(ak, sk,endPoint);
        // Use the temporary AK/SK pair and security token to initialize the client.
        // ObsClient obsClient = new ObsClient(ak, sk, securityToken, endPoint);

        try {
            // List all object versions in the root directory.
            ListVersionsRequest request = new ListVersionsRequest("examplebucket", 1000);
            request.setDelimiter("/");
            ListVersionsResult result = obsClient.listVersions(request);
            System.out.println("listVersions successfully");
            System.out.println("Objects in the root directory:");
            for (VersionOrDeleteMarker v : result.getVersions()) {
                System.out.println("Key:" + v.getKey());
                System.out.println("Owner:" + v.getOwner());
                System.out.println("isDeleteMarker:" + v.isDeleteMarker());
            }
            listVersionsByPrefix(obsClient, result);
        } catch (ObsException e) {
            System.out.println("listVersions failed");
            // Request failed. Print the HTTP status code.
            System.out.println("HTTP Code:" + e.getResponseCode());
            // Request failed. Print the server-side error code.
            System.out.println("Error Code:" + e.getErrorCode());
            // Request failed. Print the error details.
            System.out.println("Error Message:" + e.getErrorMessage());
            // Request failed. Print the request ID.
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("listVersions failed");
            // Print other error information.
            e.printStackTrace();
        }
    }

Code Example: Recursively Listing Object Versions in a Sub-folder

This example recursively lists object versions in a sub-folder.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    // Recursively list object versions in a sub-folder.
    static void listVersionsByPrefix(ObsClient obsClient, ListVersionsResult result) throws ObsException {
        for (String prefix : result.getCommonPrefixes()) {
            System.out.println("Objects in folder [" + prefix + "]:");
            ListVersionsRequest request = new ListVersionsRequest("examplebucket", 1000);
            request.setDelimiter("/");
            request.setPrefix(prefix);
            result = obsClient.listVersions(request);
            for (VersionOrDeleteMarker v : result.getVersions()) {
                System.out.println("Key:" + v.getKey());
                System.out.println("Owner:" + v.getOwner());
                System.out.println("isDeleteMarker:" + v.isDeleteMarker());
            }
            listVersionsByPrefix(obsClient, result);
        }
    }
}
  • The code examples above do not involve scenarios where there are more than 1,000 object versions in a folder.
  • Since all folder names end with a slash (/) and the objects and sub-folders to list are under the folder, delimiter is always a slash (/).
  • In the returned result of each recursion, ListVersionsResult.getVersions includes the object versions under the folder, and ListVersionsResult.getCommonPrefixes includes the sub-folders under the folder.