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
Parameter |
Type |
Mandatory (Yes/No) |
Description |
---|---|---|---|
request |
Yes |
Explanation: Request parameters for obtaining object metadata. For details, see Table 2. |
Parameter |
Type |
Mandatory (Yes/No) |
Description |
---|---|---|---|
bucketName |
String |
Yes |
Explanation: Bucket name. Restrictions:
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 |
No |
Explanation: Storage class of the object. Value range: See Table 3. Default value: None |
|
removeUnset |
boolean |
No |
Explanation: Whether to delete the previously configured metadata if the request is successful. Value range: true: If the API is successfully invoked, the previous metadata will be deleted. Standard metadata is not affected. For user-defined metadata, only the new metadata is retained. false: The previous metadata will not be deleted even if the API is successfully invoked. Standard metadata is not affected. For user-defined metadata, only the new metadata is retained. 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:
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 |
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:
Default value: None |
Constant |
Default Value |
Description |
---|---|---|
STANDARD |
STANDARD |
Standard storage class. |
WARM |
WARM |
Infrequent Access storage class. |
COLD |
COLD |
Archive storage class. |
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
Parameter |
Type |
Mandatory (Yes/No) |
Description |
---|---|---|---|
contentLength |
Long |
No |
Explanation: Object size. Restrictions:
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 |
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:
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(); } } } |
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot