Updated on 2024-06-18 GMT+08:00

Configuring Object Metadata (SDK for Java)

Function

Object metadata is a set of name-value pairs that describe the object and is used for object management.

Currently, only the system-defined metadata is supported.

There are two kinds of metadata: system-controlled metadata and user-controlled metadata. The kind of metadata like Last-Modified is controlled by the system and cannot be modified. However, the kind of metadata configured for objects such as ContentLanguage can be modified by calling APIs.

This API sends a HEAD request to configure the metadata of an object in a specified bucket.

If you have any questions during development, post them on the Issues page of GitHub.

Restrictions

  • To configure object metadata, you must be the bucket owner or have the required permission (obs:object:ModifyObjectMetaData in IAM or ModifyObjectMetaData in a bucket policy). For details, see Introduction to OBS Access Control, IAM Custom Policies, and Configuring an Object Policy.
  • The mapping between OBS regions and endpoints must comply with what is listed in Regions and Endpoints.
  • An object can have multiple pieces of metadata. The size of the metadata cannot exceed 8 KB in total.
  • Currently, metadata names only support ASCII characters. Non-ASCII characters must be Base64-encoded.
  • If versioning is enabled for a bucket, you can set metadata for objects of the latest version, but cannot set metadata for noncurrent objects.
  • You cannot set metadata for Archive objects.
  • If a folder or directory is an actual object in an object bucket, their metadata can be modified. If a directory is a simulated directory, for example, test/ in the test/test1.txt object, the metadata of this simulated directory cannot be modified.

Method

obsClient.setObjectMetadata(SetObjectMetadataRequest request)

Request Parameters

Table 1 List of request parameters

Parameter

Type

Mandatory (Yes/No)

Description

request

SetObjectMetadataRequest

Yes

Explanation:

Request parameters for obtaining object metadata. For details, see Table 2.

Table 2 SetObjectMetadataRequest

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

objectKey

String

Yes

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

No

Explanation:

Object version ID.

Value range:

The value must contain 32 characters.

Default value:

None

storageClass

StorageClassEnum

No

Explanation:

Storage class of the object.

Value range:

See Table 3.

Default value:

None

removeUnset

boolean

No

Explanation:

Whether to delete the previously set metadata.

Value range:

true: If this action is successful, the previously configured metadata (excluding the standard metadata), will be deleted.

false: The previously configured metadata will not be deleted even if this action is successful.

Default value:

false

userMetadata

Map<String, String>

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 and value indicate the name and value of the user-defined metadata respectively. After the metadata is defined, when you later download the object or query its metadata, the user-defined metadata is returned in the response.

Restrictions:

  • The user-defined metadata cannot exceed 8 KB in total. To measure the size, calculate the sum of bytes of all UTF-8 encoded keys and values.
  • The user-defined metadata keys are case insensitive, because OBS converts the uppercase keys to lowercase for storage. However, the metadata values are case sensitive.
  • Both user-defined metadata keys and their values must conform to US-ASCII standards. If non-ASCII or unrecognizable characters are necessary, they must be encoded or decoded in URL or Base64 on the client, because the server side does not perform any decoding.

Default value:

None

userHeaders

HashMap<String, String>

No

Explanation:

User header list. In HashMap, the String key and value indicate the name and value of the user header field respectively. The SDK does not process the userHeaders and instead transparently transmits it to the server for later use.

Default value:

None

encodeHeaders

boolean

No

Explanation:

Whether to enable OBS to automatically encode request headers.

Due to HTTP coding restrictions, only ASCII characters can be sent. If your request headers contain full-width characters, the SDK will URL encode these characters before sending the request. When you use a browser to access the object metadata, the browser automatically decodes the data.

Value range:

true: Encoding with SDK is enabled.

false: Encoding with SDK is disabled.

Default value:

true

replaceMetadata

ObjectRepleaceMetadata

No

Explanation:

It specifies the metadata returned when the object is downloaded. For details, see Table 4.

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.

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/

OBS obtains the specified value from the header and stores it in the object metadata WebsiteRedirectLocation.

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

Table 3 StorageClassEnum

Constant

Default Value

Description

STANDARD

STANDARD

Standard storage class.

WARM

WARM

Infrequent Access storage class.

COLD

COLD

Archive storage class.

Table 4 ObjectRepleaceMetadata

Parameter

Type

Mandatory (Yes/No)

Description

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:

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:

Expires header in the response. It specifies the cache expiration time of the web page when the object is downloaded.

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

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

contentEncoding

String

No

Explanation:

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

Default value:

None

Responses

Table 5 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:

None

contentEncoding

String

No

Explanation:

It specifies the content encoding format when an object is downloaded.

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:

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 object data. It is provided for the OBS server to verify data integrity.

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:

Object storage class. If you do not specify this header, the object inherits the storage class of the bucket.

Value range:

See Table 3.

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.

Default value:

None

statusCode

int

This parameter is automatically set in the response.

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>

This parameter is automatically set in the response.

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

Code Example: Configuring Metadata for the Object

This example configures metadata for object objectname by specifying the user-defined metadata and using userHeaders that are transparently transmitted.

 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
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.ObjectMetadata;
import com.obs.services.model.SetObjectMetadataRequest;
import java.util.HashMap;
public class SetObjectMetadata001 {
    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 {
            // Configure metadata for the object.
            SetObjectMetadataRequest request = new SetObjectMetadataRequest("examplebucket", "objectname");
            // Standard HTTP headers of an object
            request.setContentType("ContentType");
            request.setExpires("Expires");
            // During the user-defined metadata setting, the SDK automatically adds x-obs-meta-.
            request.addUserMetadata("property1", "property-value1");
            HashMap<String, String> userHeaders = new HashMap<>();
            // userHeaders set by the SDK are transparently transmitted. They are not processed so they can be used more flexibly later. If a userHeader needs to be displayed as user-defined metadata on the server, add x-obs-meta- before the userHeader for the server to identify.
            userHeaders.put("property2", "property-value2");
            userHeaders.put("x-obs-meta-property3", "property-value3");
            request.setUserHeaders(userHeaders);
            ObjectMetadata metadata = obsClient.setObjectMetadata(request);
            System.out.println("setObjectMetadata successfully");
            System.out.println("UserMetadata:" + metadata.getUserMetadata("property1"));
        } catch (ObsException e) {
            System.out.println("setObjectMetadata 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("setObjectMetadata failed");
            // Print other error information.
            e.printStackTrace();
        }
    }
}

After you run the sample code above and configure the user-defined metadata property1 and user headers property2 and x-obs-meta-property3, the HTTP header in the packet capture is as follows:

Code Example: Deleting Metadata for the Object

If you want to delete some metadata by calling the API for setting object metadata, configure the metadata to be retained and set SetObjectMetadataRequest.setRemoveUnset to true. Then, once the API is called, the data whose metadata is not configured will be deleted. Therefore, exercise caution when using SetObjectMetadataRequest.setRemoveUnset(true).

This example deletes the user-defined metadata of object objectname 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
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.SetObjectMetadataRequest;
import java.util.HashMap;
public class SetObjectMetadata002 {
    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 {
            SetObjectMetadataRequest request = new SetObjectMetadataRequest();
            request.setBucketName("examplebucket");
            request.setObjectKey("objectname");
            request.setRemoveUnset(true);
            HashMap<String, String> userHeaders = new HashMap<>();
            // After request.setRemoveUnset is set to true, the server saves metadata property1 and deletes the user-defined metadata saved before.
            userHeaders.put("x-obs-meta-property1", "property-value1");
            request.setUserHeaders(userHeaders);
            obsClient.setObjectMetadata(request);
            System.out.println("setObjectMetadata successfully");
        } catch (ObsException e) {
            System.out.println("setObjectMetadata 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("setObjectMetadata failed");
            // Print other error information.
            e.printStackTrace();
        }
    }
}