Asset

View as Markdown

Asset

An asset is a file, such as an image, video, or PDF, that you upload to a stack. Use this class to

  • fetch one published asset by its UID
  • add dimensions, metadata, branch details, or extra field groups to the response
  • read the file name, URL, size, type, tags, and dates of an asset you already have

The asset method on Stack returns a new Asset and takes one argument:

NameTypeDescription
uidStringUID of the asset to fetch.

Asset objects also arrive filled with data from two other places. The fetchAll method of AssetLibrary passes a List<Asset> to its callback, and the getAsset method of Entry builds an Asset from a file field.

addParam

addParam adds one query parameter by name to the request that fetch sends.

NameTypeDescription
paramKey (required)String

Name of the query parameter.

Default: Not applicable
paramValue (required)String

Value of the query parameter.

Default: Not applicable

Returns: Asset. The same asset, for chaining.

Validation

  • There is no client-side validation. addParam records any key and value as given, including an empty string.
  • An unsupported parameter or value surfaces as an Error in the callback when fetch sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. addParam records the pair and makes no request. fetch sends it to Get a single asset.
  • The SDK writes the value into the URL without URL encoding. Pass values without &, =, or #, because those characters split or end the query string.
  • A second call with the same key replaces the first value. The same key from a dedicated method, such as include_dimension from includeDimension, shares one slot, so the later call wins.
  • fetch sets environment from the stack header before it sends the request, so an environment value from addParam never reaches the API.

Example

Basic usage: add a query parameter by name

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class FetchAssetWithParam {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>").addParam("include_dimension", "true");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                System.out.println(asset.toJSON().toString(2));
            }
        });
    }
}

assetFields

assetFields requests extra field groups for the asset, such as its visual markups.

NameTypeDescription
fields (required)String...

Field groups to add to the response.

Default: Not applicable

Returns: Asset. The same asset, for chaining.

Validation

  • There is no client-side validation of the names. assetFields records any string as given.
  • Calling assetFields with no arguments, or with null, records nothing and returns the asset.
  • An unsupported name surfaces as an Error in the callback when fetch sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. assetFields records the names under asset_fields[] and makes no request. fetch sends one asset_fields[] query parameter per name.
  • The value visual_markups returns the hotspot and bounding-box annotations of the asset under the visual_markups key, as Get a single asset describes. An asset with no markups returns an empty array.
  • A second call replaces the names from the first call. Pass every name in one call.
  • Read the extra groups from toJSON.

Example

Basic usage: fetch an asset with its visual markups

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class FetchAssetMarkups {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>").assetFields("visual_markups");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                System.out.println(asset.toJSON().optJSONArray("visual_markups"));
            }
        });
    }
}

configure

configure fills the asset from an asset JSON object that you already hold, without a request.

NameTypeDescription
jsonObject (required)JSONObject

Asset JSON, such as a file field of an entry.

Default: Not applicable

Returns: Asset. The same asset, holding the JSON values.

Validation

  • There is no client-side validation of the keys. configure accepts an object with any keys, and a missing key leaves its getter returning null.
  • Throws ClassCastException when a key that a getter reads holds a value that is not a string. configure casts uid, content_type, file_size, filename, url, locale, and each item of tags to String.
  • A null argument raises no error. It clears every value the asset held, including its UID.

Behavior

  • Client-side only. configure makes no request.
  • It reads the object as the asset itself, not as a response that wraps it in an asset key. Pass the value of asset when you hold a whole response body.
  • It sets the UID from the uid key, replacing the UID you passed to the asset method of Stack.
  • It fills the values behind getFileName, getUrl, getFileType, getFileSize, getTags, getLocale, and toJSON. The date and user getters read from the same object.
  • The getAsset and getAssets methods of Entry call configure for you on a file field.
  • The JSONObject class comes from the org.json package.

Example

Basic usage: build an asset from stored asset JSON

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Stack;
import org.json.JSONObject;

public class ConfigureAsset {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");

        JSONObject json = new JSONObject();
        json.put("uid", "<ASSET_UID>");
        json.put("filename", "hero-banner.jpg");
        json.put("url", "https://images.contentstack.io/v3/assets/hero-banner.jpg");
        json.put("content_type", "image/jpeg");
        json.put("file_size", "482141");
        json.put("locale", "en-us");

        Asset asset = stack.asset("<ASSET_UID>").configure(json);
        System.out.println(asset.getFileName() + " " + asset.getFileType() + " " + asset.getLocale());
    }
}

fetch

fetch retrieves one published asset by its UID and fills the asset object with the response.

NameTypeDescription
callback (required)FetchResultCallback

Receives the outcome. See Callbacks.

Default: Not applicable

Returns: void. The result arrives in the callback.

Validation

  • There is no client-side validation. fetch does not check the asset UID, so an empty or wrong UID reaches the callback as an Error.
  • fetch does not throw on an API rejection or a network failure. It calls onCompletion with an Error, and error is null on success. See the Error class.
  • A null callback makes fetch return without sending a request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • One call sends one Get a single asset request (GET /assets/{asset_uid}). It carries the stack's environment as a query parameter, plus every parameter that the request methods on this asset recorded.
  • On success, fetch copies the UID, file name, URL, content type, file size, tags, and the full asset object into the asset you called it on. The callback receives no asset argument, so read the values from that object.
  • fetch does not copy the locale key, so getLocale returns null after a fetch. Read toJSON().optString("locale") instead, as the Known issue on that method describes.
  • On failure, the asset keeps the values it held before the call.
  • The recorded parameters stay on the asset, so a second fetch sends them again.

Example

Basic usage: fetch one asset and read its file name and URL

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class FetchAsset {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                System.out.println(asset.getFileName() + " " + asset.getUrl());
            }
        });
    }
}

All request options: fetch a localized asset with dimensions, metadata, and branch details

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class FetchAssetWithOptions {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>")
                .setLocale("<LOCALE>")
                .includeFallback()
                .includeDimension()
                .includeMetadata()
                .includeBranch()
                .assetFields("visual_markups");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) { System.out.println(error.getErrorMessage()); return; }
                System.out.println(asset.toJSON().toString(2));
            }
        });
    }
}

Error handling: report an unknown asset UID

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class FetchMissingAsset {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // getErrorCode is the API's error_code, not the HTTP status
                    System.out.println(error.getErrorCode() + ": " + error.getErrorMessage());
                    System.out.println(error.getErrorDetail());
                    return;
                }
                System.out.println(asset.getAssetUid());
            }
        });
    }
}

getAssetUid

getAssetUid returns the UID of the asset.

Returns: String. The asset's UID.

Validation

  • There is no client-side validation. getAssetUid reads a stored value and makes no request.

Behavior

  • Before fetch, getAssetUid returns the UID you passed to the asset method of Stack.
  • After a successful fetch, it returns the uid key of the response.
  • On an asset from configure, it returns the uid key of the JSON object, or null when that object has none.

Example

Basic usage: read the UID of a fetched asset

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class ReadAssetUid {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                System.out.println(asset.getAssetUid());
            }
        });
    }
}

getCreateAt

getCreateAt returns the created_at value of the asset as a Calendar.

Returns: Calendar. The asset's creation date.

Validation

  • There is no client-side validation. getCreateAt makes no request.
  • Throws NullPointerException when the asset holds no JSON, because getCreateAt reads created_at from it. That is the case before a successful fetch and after a failed one.

Behavior

  • getCreateAt parses the created_at key of the asset JSON into a java.util.Calendar.
  • It returns null when the asset JSON has no created_at key.
  • Known issue: In 2.8.3, getCreateAt returns a date one month later than created_at, with the UTC time read in the default time zone of the JVM. Parse toJSON().optString("created_at") with Instant.parse instead, as the second example below shows.

Example

Basic usage: read the created_at value of a fetched asset

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.Calendar;

public class ReadCreatedAtCalendar {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                Calendar value = asset.getCreateAt();
                // See the Known issue above before you rely on this value
                System.out.println(value == null ? "no created_at" : value.getTime().toString());
            }
        });
    }
}

Workaround: read created_at as an exact UTC instant

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.time.Instant;

public class ReadCreatedAtInstant {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) { System.out.println(error.getErrorMessage()); return; }
                String raw = asset.toJSON().optString("created_at");
                if (!raw.isEmpty()) {
                    Instant value = Instant.parse(raw);
                    System.out.println(value);
                }
            }
        });
    }
}

getCreatedBy

getCreatedBy returns the UID of the user in the created_by key of the asset.

Returns: String. The UID of the user who created the asset.

Validation

  • There is no client-side validation. getCreatedBy makes no request.
  • Throws NullPointerException when the asset holds no JSON, because getCreatedBy reads created_by from it. That is the case before a successful fetch and after a failed one.

Behavior

  • getCreatedBy returns the created_by key of the asset JSON, which holds a user UID.
  • It returns an empty string, not null, when the asset JSON has no created_by key.

Example

Basic usage: read the created_by value of a fetched asset

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class ReadCreatedBy {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                String user = asset.getCreatedBy();
                System.out.println(user.isEmpty() ? "no created_by" : user);
            }
        });
    }
}

getDeleteAt

getDeleteAt returns the deleted_at value of the asset as a Calendar.

Returns: Calendar. The asset's deletion date.

Validation

  • There is no client-side validation. getDeleteAt makes no request.
  • Throws NullPointerException when the asset holds no JSON, because getDeleteAt reads deleted_at from it. That is the case before a successful fetch and after a failed one.

Behavior

  • getDeleteAt parses the deleted_at key of the asset JSON into a java.util.Calendar.
  • It returns null when the asset JSON has no deleted_at key.
  • Known issue: In 2.8.3, getDeleteAt returns a date one month later than deleted_at, with the UTC time read in the default time zone of the JVM. Parse toJSON().optString("deleted_at") with Instant.parse instead, as the second example below shows.

Example

Basic usage: read the deleted_at value of a fetched asset

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.Calendar;

public class ReadDeletedAtCalendar {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                Calendar value = asset.getDeleteAt();
                // See the Known issue above before you rely on this value
                System.out.println(value == null ? "no deleted_at" : value.getTime().toString());
            }
        });
    }
}

Workaround: read deleted_at as an exact UTC instant

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.time.Instant;

public class ReadDeletedAtInstant {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) { System.out.println(error.getErrorMessage()); return; }
                String raw = asset.toJSON().optString("deleted_at");
                if (!raw.isEmpty()) {
                    Instant value = Instant.parse(raw);
                    System.out.println(value);
                }
            }
        });
    }
}

getDeletedBy

getDeletedBy returns the UID of the user in the deleted_by key of the asset.

Returns: String. The UID of the user who deleted the asset.

Validation

  • There is no client-side validation. getDeletedBy makes no request.
  • Throws NullPointerException when the asset holds no JSON, because getDeletedBy reads deleted_by from it. That is the case before a successful fetch and after a failed one.

Behavior

  • getDeletedBy returns the deleted_by key of the asset JSON, which holds a user UID.
  • It returns an empty string, not null, when the asset JSON has no deleted_by key.

Example

Basic usage: read the deleted_by value of a fetched asset

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class ReadDeletedBy {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                String user = asset.getDeletedBy();
                System.out.println(user.isEmpty() ? "no deleted_by" : user);
            }
        });
    }
}

getFileName

getFileName returns the file name of the asset.

Returns: String. The asset's file name.

Validation

  • There is no client-side validation. getFileName reads a stored value and makes no request.
  • getFileName returns null until a successful fetch or a call to configure fills the asset.

Behavior

  • getFileName returns the filename key of the asset JSON, for example hero-banner.jpg.
  • The value is the stored file name, not the asset title. Read title from toJSON for the title.

Example

Basic usage: read the file name of a fetched asset

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class ReadFileName {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                System.out.println(asset.getFileName());
            }
        });
    }
}

getFileSize

getFileSize returns the file size of the asset as a string.

Returns: String. The asset's file size.

Validation

  • There is no client-side validation. getFileSize reads a stored value and makes no request.
  • getFileSize returns null until a successful fetch or a call to configure fills the asset.

Behavior

  • getFileSize returns the file_size key of the asset JSON as a String, for example "482141".
  • Convert it with Long.parseLong before you compare or add sizes.

Example

Basic usage: read the file size of a fetched asset as a number

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class ReadFileSize {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                String size = asset.getFileSize();
                if (size != null) {
                    long sizeValue = Long.parseLong(size);
                    System.out.println("file size: " + sizeValue);
                }
            }
        });
    }
}

getFileType

getFileType returns the content type of the asset file, such as image/jpeg.

Returns: String. The asset's content type.

Validation

  • There is no client-side validation. getFileType reads a stored value and makes no request.
  • getFileType returns null until a successful fetch or a call to configure fills the asset.

Behavior

  • getFileType returns the content_type key of the asset JSON, which holds a MIME type such as image/png or application/pdf.

Example

Basic usage: check whether a fetched asset is an image

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class CheckFileType {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                String type = asset.getFileType();
                System.out.println(type != null && type.startsWith("image/") ? "image" : "other file");
            }
        });
    }
}

getLocale

getLocale returns the locale of the asset data.

Returns: String. The asset's locale.

Validation

  • There is no client-side validation. getLocale reads a stored value and makes no request.

Behavior

  • getLocale returns the locale key that configure read from an asset JSON object, such as the one the getAsset method of Entry passes to it. It returns null when that object has no locale key.
  • It does not return the value you passed to setLocale. setLocale records a query parameter only.
  • Known issue: In 2.8.3, getLocale returns null after fetch and on every asset from the fetchAll method of AssetLibrary, even when the response carries a locale key. Read asset.toJSON().optString("locale") instead, as the example below shows.

Example

Basic usage: read the locale of a fetched asset

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class ReadAssetLocale {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                // getLocale returns null after fetch, so read the key from the JSON
                String locale = asset.toJSON().optString("locale");
                System.out.println(locale.isEmpty() ? "no locale key" : locale);
                System.out.println(asset.getLocale());
            }
        });
    }
}

getTags

getTags returns the tags on the asset.

Returns: String[]. The asset's tags.

Validation

  • There is no client-side validation. getTags reads a stored value and makes no request.
  • getTags returns null until a successful fetch or a call to configure fills the asset.

Behavior

  • getTags returns the tags array of the asset JSON as a String[].
  • An asset with no tags, or with an empty tags array, returns null, not an empty array. Check for null before you loop.

Example

Basic usage: print every tag on a fetched asset

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class ReadAssetTags {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                String[] tags = asset.getTags();
                if (tags == null) {
                    System.out.println("no tags");
                    return;
                }
                for (String tag : tags) {
                    System.out.println(tag);
                }
            }
        });
    }
}

getUpdateAt

getUpdateAt returns the updated_at value of the asset as a Calendar.

Returns: Calendar. The asset's last update date.

Validation

  • There is no client-side validation. getUpdateAt makes no request.
  • Throws NullPointerException when the asset holds no JSON, because getUpdateAt reads updated_at from it. That is the case before a successful fetch and after a failed one.

Behavior

  • getUpdateAt parses the updated_at key of the asset JSON into a java.util.Calendar.
  • It returns null when the asset JSON has no updated_at key.
  • Known issue: In 2.8.3, getUpdateAt returns a date one month later than updated_at, with the UTC time read in the default time zone of the JVM. Parse toJSON().optString("updated_at") with Instant.parse instead, as the second example below shows.

Example

Basic usage: read the updated_at value of a fetched asset

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.Calendar;

public class ReadUpdatedAtCalendar {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                Calendar value = asset.getUpdateAt();
                // See the Known issue above before you rely on this value
                System.out.println(value == null ? "no updated_at" : value.getTime().toString());
            }
        });
    }
}

Workaround: read updated_at as an exact UTC instant

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.time.Instant;

public class ReadUpdatedAtInstant {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) { System.out.println(error.getErrorMessage()); return; }
                String raw = asset.toJSON().optString("updated_at");
                if (!raw.isEmpty()) {
                    Instant value = Instant.parse(raw);
                    System.out.println(value);
                }
            }
        });
    }
}

getUpdatedBy

getUpdatedBy returns the UID of the user in the updated_by key of the asset.

Returns: String. The UID of the user who last updated the asset.

Validation

  • There is no client-side validation. getUpdatedBy makes no request.
  • Throws NullPointerException when the asset holds no JSON, because getUpdatedBy reads updated_by from it. That is the case before a successful fetch and after a failed one.

Behavior

  • getUpdatedBy returns the updated_by key of the asset JSON, which holds a user UID.
  • It returns an empty string, not null, when the asset JSON has no updated_by key.

Example

Basic usage: read the updated_by value of a fetched asset

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class ReadUpdatedBy {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                String user = asset.getUpdatedBy();
                System.out.println(user.isEmpty() ? "no updated_by" : user);
            }
        });
    }
}

getUrl

getUrl returns the address of the asset file.

Returns: String. The asset's URL.

Validation

  • There is no client-side validation. getUrl reads a stored value and makes no request.
  • getUrl returns null until a successful fetch or a call to configure fills the asset.

Behavior

  • getUrl returns the url key of the asset JSON.
  • Pass the value to the imageTransform method of Stack to add image transformation parameters.

Example

Basic usage: read the URL of a fetched asset

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class ReadAssetUrl {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                System.out.println(asset.getUrl());
            }
        });
    }
}

includeBranch

includeBranch asks the API to add the _branch key, which names the branch the asset belongs to.

Returns: Asset. The same asset, for chaining.

Validation

  • There is no client-side validation. includeBranch takes no input and cannot fail.
  • Errors surface as an Error in the callback when fetch sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. includeBranch records include_branch=true and makes no request. fetch sends it.
  • Get a single asset describes _branch as a top-level key of the response. fetch keeps only the asset object of the response, so toJSON holds _branch only when the API places it inside that object.
  • The branch the API reads from comes from the branch header. Call setBranch on the Config you pass to Contentstack.stack to send it.
  • A second call changes nothing, and no method removes the flag.

Example

Basic usage: fetch an asset from a branch with branch details

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class FetchAssetBranch {
    public static void main(String[] args) throws IllegalAccessException {
        Config config = new Config();
        config.setBranch("<BRANCH>");
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
        Asset asset = stack.asset("<ASSET_UID>").includeBranch();

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                // Prints null when the API places _branch outside the asset object
                System.out.println(asset.toJSON().opt("_branch"));
            }
        });
    }
}

includeDimension

includeDimension adds the height and width of an image asset to the response.

Returns: Asset. The same asset, for chaining.

Validation

  • There is no client-side validation. includeDimension takes no input and cannot fail.
  • Errors surface as an Error in the callback when fetch sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. includeDimension records include_dimension=true and makes no request. fetch sends it.
  • The API adds the dimensions for JPG, GIF, PNG, WebP, BMP, TIFF, SVG, and PSD images, as Get a single asset describes.
  • Asset has no dimension getter. Read the values from toJSON.
  • A second call changes nothing, and no method removes the flag.

Example

Basic usage: fetch an image with its dimensions

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class FetchImageDimensions {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>").includeDimension();

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                // The asset JSON now carries the image height and width
                System.out.println(asset.toJSON().toString(2));
            }
        });
    }
}

includeFallback

includeFallback returns the asset from the fallback locale when it has no published version in the requested locale.

Returns: Asset. The same asset, for chaining.

Validation

  • There is no client-side validation. includeFallback takes no input and cannot fail.
  • Errors surface as an Error in the callback when fetch sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. includeFallback records include_fallback=true and makes no request. fetch sends it.
  • The API returns the published details from the fallback locale when the requested locale holds no published version, as Get a single asset describes.
  • Pair it with setLocale to name the requested locale.
  • A second call changes nothing, and no method removes the flag.

Example

Basic usage: fetch a localized asset, or its fallback version

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class FetchAssetWithFallback {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>").setLocale("<LOCALE>").includeFallback();

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                // The locale key shows which locale the API returned
                System.out.println(asset.getFileName() + " " + asset.toJSON().optString("locale"));
            }
        });
    }
}

includeMetadata

includeMetadata adds the metadata of the asset to the response.

Returns: Asset. The same asset, for chaining.

Validation

  • There is no client-side validation. includeMetadata takes no input and cannot fail.
  • Errors surface as an Error in the callback when fetch sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. includeMetadata records include_metadata=true and makes no request. fetch sends it.
  • The API returns the metadata under the _metadata key, with one entry per extension UID, as Get a single asset describes.
  • Asset has no metadata getter. Read _metadata from toJSON.
  • A second call changes nothing, and no method removes the flag.

Example

Basic usage: fetch an asset with its metadata

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class FetchAssetMetadata {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>").includeMetadata();

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                System.out.println(asset.toJSON().optJSONObject("_metadata"));
            }
        });
    }
}

removeHeader

removeHeader removes a request header from the header map of the stack that created this asset.

NameTypeDescription
headerKey (required)String

Name of the header to remove.

Default: Not applicable

Returns: void. This method returns nothing.

Validation

  • There is no client-side validation. A key that is not in the map, an empty string, or null changes nothing and raises no error.

Behavior

  • Client-side only. removeHeader makes no request.
  • The asset shares the header map of its Stack, so the header disappears from every later request from that stack, not only from this asset.
  • IMPORTANT: If you remove api_key, access_token, or environment, every later request from the stack lacks a required value. The Get a single asset reference lists all three as required. Without the environment header, fetch also sends no environment query parameter. Do not remove these three headers.

Example

Basic usage: stop sending a custom header

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class FetchAssetWithoutHeader {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");
        asset.setHeader("x-request-source", "catalog-sync");
        // Removes the header from the stack, so no later request sends it
        asset.removeHeader("x-request-source");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                System.out.println(asset.getFileName());
            }
        });
    }
}

setHeader

setHeader adds a request header to the header map of the stack that created this asset.

NameTypeDescription
headerKey (required)String

Name of the header.

Default: Not applicable
headerValue (required)String

Value of the header.

Default: Not applicable

Returns: void. This method returns nothing.

Validation

  • There is no client-side validation. setHeader stores an empty or null key or value as given. The setHeader method of Stack, by contrast, ignores an empty key or value.

Behavior

  • Client-side only. setHeader makes no request. fetch sends the header.
  • The asset shares the header map of its Stack. The header therefore travels with every later request from that stack, including entry, query, and asset list requests, not only with this asset.
  • A second call with the same key replaces the first value.
  • Remove the header again with removeHeader.

Example

Basic usage: send a custom header with an asset request

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class FetchAssetWithHeader {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");
        // The header applies to every later request from this stack
        asset.setHeader("x-request-source", "catalog-sync");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                System.out.println(asset.getFileName());
            }
        });
    }
}

setLocale

setLocale sets the locale of the asset version that fetch requests.

NameTypeDescription
locale (required)String

Locale code to fetch, such as fr-fr.

Default: Not applicable

Returns: Asset. The same asset, for chaining.

Validation

  • There is no client-side validation. setLocale records any string as given.
  • An unknown locale code surfaces as an Error in the callback when fetch sends the request.

Additional Resource Refer to Content Delivery API Errors for the full error code list.

Behavior

  • Client-side only. setLocale records the locale query parameter and makes no request. fetch sends it to Get a single asset.
  • Without setLocale, the SDK sends no locale, and the API applies its own default.
  • A second call replaces the first value. Passing null removes the recorded value, because the org.json JSONObject.put method removes a key whose value is null.
  • Pair it with includeFallback to get the fallback-locale version when the asset has no published version in this locale.
  • setLocale does not change what getLocale returns. getLocale reads a value from the asset data, not from this parameter.

Example

Basic usage: fetch the French version of an asset

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class FetchFrenchAsset {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>").setLocale("fr-fr");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                System.out.println(asset.getFileName() + " " + asset.getUrl());
            }
        });
    }
}

toJSON

toJSON returns every key the API returned for the asset as a JSONObject.

Returns: JSONObject. The asset's full JSON.

Validation

  • There is no client-side validation. toJSON reads a stored value and makes no request.
  • toJSON returns null until a successful fetch or a call to configure fills the asset.

Behavior

  • After fetch, toJSON returns the asset object of the response, not the whole response body.
  • Use it for keys that have no getter, such as title, _version, publish_details, the dimensions from includeDimension, and _metadata from includeMetadata.
  • The JSONObject class comes from the org.json package. Nested objects arrive as JSONObject and arrays as JSONArray.
  • toJSON returns the object the asset holds, not a copy, and the date and user getters read from it.

Example

Basic usage: read keys that have no getter

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchResultCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import org.json.JSONObject;

public class ReadAssetJson {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        Asset asset = stack.asset("<ASSET_UID>");

        asset.fetch(new FetchResultCallback() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or it did not complete
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                JSONObject json = asset.toJSON();
                System.out.println(json.optString("title"));
                System.out.println(json.optInt("_version"));
            }
        });
    }
}