AssetLibrary

View as Markdown

AssetLibrary

AssetLibrary lists the published assets of a stack. Use this class to

  • list the assets published to an environment, one page at a time
  • filter the list by a field value and sort it by a field
  • count the matching assets
  • add fallback-locale details, metadata, or extra field groups to each asset

The assetLibrary method on Stack returns a new AssetLibrary and takes no arguments. Chain the filter and option methods on it, then call fetchAll. The callback receives a List<Asset>, and each Asset in it arrives with its values filled in.

addParam

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

NameTypeDescription
paramKey (required)String

Name of the query parameter.

Default: Not applicable
paramValue (required)Object

Value, such as a String, number, boolean, or JSONObject.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • addParam checks the key and a string value against the sets on the AssetLibrary class page. When either fails, it logs a warning through java.util.logging, records nothing, and returns the library. It does not throw.
  • Throws NullPointerException when paramKey is null.
  • A null paramValue removes the key, because the org.json JSONObject.put method removes a key whose value is null.
  • Errors from the request surface as an Error in the callback when fetchAll sends it.

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. fetchAll sends it to Get all assets.
  • Use it for parameters that have no dedicated method, such as include_dimension and include_branch.
  • A JSONObject value under the key query replaces any where condition. fetchAll sends it as URL-encoded JSON, which lets you combine conditions and use operators.
  • A second call with the same key replaces the first value.
  • fetchAll 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 image dimensions and branch details

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class ListAssetsWithParams {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary()
                .addParam("include_dimension", true)
                .addParam("include_branch", true);

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName());
                }
            }
        });
    }
}

assetFields

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

NameTypeDescription
fields (required)String...

Field groups to add to each asset.

Default: Not applicable

Returns: AssetLibrary. The same asset library, 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 library.
  • An unsupported name surfaces as an Error in the callback when fetchAll 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. fetchAll sends one asset_fields[] query parameter per name.
  • The value visual_markups returns the hotspot and bounding-box annotations of each asset under the visual_markups key, as Get all assets 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 on each asset.

Example

Basic usage: list assets with their visual markups

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class ListAssetMarkups {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary().assetFields("visual_markups");

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName() + " " + asset.toJSON().optJSONArray("visual_markups"));
                }
            }
        });
    }
}

fetchAll

fetchAll retrieves the published assets that match the recorded filters and passes them to the callback as a list.

NameTypeDescription
callback (required)FetchAssetsCallback

Receives the assets or an Error. See Callbacks.

Default: Not applicable

Returns: void. The result arrives in the callback.

Validation

  • There is no client-side validation. fetchAll sends whatever the option methods recorded.
  • fetchAll does not throw on an API rejection or a network failure. It calls onCompletion with an Error and a null list, and error is null on success. See the Error class.
  • A null callback makes fetchAll 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 all assets request (GET /assets). It carries the stack's environment as a query parameter, plus every recorded parameter. The key and value check on the AssetLibrary class page decides which recorded parameters go out.
  • Each Asset in the list holds its UID, file name, URL, content type, file size, tags, and full JSON, so its getters work without a fetch.
  • The assets in the list do not hold a locale, so getLocale returns null on each of them. Read asset.toJSON().optString("locale") instead. See the Known issue on that method page.
  • When the response carries a count key, fetchAll stores it for getCount.
  • The recorded parameters stay on the library, so a second fetchAll sends them again.
  • Known issue: In 2.8.3, when no asset matches, fetchAll returns without calling the callback. The callback runs before fetchAll returns, so set a flag inside it and check the flag after the call, as the second example below shows.

Example

Basic usage: list the published assets

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

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

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName());
                }
            }
        });
    }
}

Edge case: detect a result with no assets

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class DetectEmptyResult {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        final boolean[] answered = {false};
        AssetLibrary library = stack.assetLibrary().where("filename", "hero-banner.jpg");

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, Error error) {
                // The callback ran, so the request returned assets or an error
                answered[0] = true;
                if (error != null) { System.out.println(error.getErrorMessage()); return; }
                System.out.println(assets.size() + " assets matched");
            }
        });
        // fetchAll skips the callback when no asset matches
        if (!answered[0]) {
            System.out.println("No assets matched");
        }
    }
}

getCount

getCount returns the total number of matching assets from the last response that carried a count.

Returns: int. The total asset count from the last response.

Validation

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

Behavior

  • getCount returns the count key of the last fetchAll response that had one. Call includeCount before fetchAll to make the API send it.
  • It returns 0 until a response carries a count key.
  • A later response without a count key, such as one from a fetchAll after removeParam dropped include_count, leaves the earlier value in place.
  • fetchAll stores the count even when no asset matches and it skips the callback, so getCount after the call returns 0 in that case.

Example

Basic usage: read the total count after a page of results

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class ReadAssetCount {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary().limit(5).includeCount();

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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("showing " + assets.size() + " of " + library.getCount());
            }
        });
    }
}

includeCount

includeCount adds the total number of matching assets to the response.

Returns: AssetLibrary. The same asset library, for chaining.

Validation

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

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

Behavior

  • Client-side only. includeCount records include_count=true and makes no request. fetchAll sends it.
  • The API adds a count key with the total number of matching assets, as Count describes. The count covers every match, not only the current page.
  • Read the total with getCount inside the callback.
  • A second call changes nothing. Remove the flag with removeParam.

Example

Basic usage: list ten assets and read the total count

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class ListAssetsWithCount {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary().limit(10).includeCount();

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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(assets.size() + " of " + library.getCount() + " assets");
            }
        });
    }
}

includeFallback

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

Returns: AssetLibrary. The same asset library, for chaining.

Validation

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

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. fetchAll sends it.
  • The API returns the published details from the fallback locale when the requested locale holds no published version, as Get all assets describes.
  • Pair it with setLocale to name the requested locale.
  • A second call changes nothing. Remove the flag with removeParam.

Example

Basic usage: list localized assets with fallback

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class ListLocalizedAssets {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary().setLocale("<LOCALE>").includeFallback();

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    // The locale key shows which locale the API returned
                    System.out.println(asset.getFileName() + " " + asset.toJSON().optString("locale"));
                }
            }
        });
    }
}

includeMetadata

includeMetadata adds the metadata of each asset to the response.

Returns: AssetLibrary. The same asset library, for chaining.

Validation

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

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. fetchAll sends it.
  • The API returns the metadata of each asset under its _metadata key, with one entry per extension UID, as Get all assets describes.
  • Asset has no metadata getter. Read _metadata from toJSON.
  • A second call changes nothing. Remove the flag with removeParam.

Example

Basic usage: list assets with their metadata

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

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

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName() + " " + asset.toJSON().optJSONObject("_metadata"));
                }
            }
        });
    }
}

includeRelativeUrl

includeRelativeUrl sends the relative_urls flag with the asset list request.

Returns: AssetLibrary. The same asset library, for chaining.

Validation

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

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

Behavior

  • Client-side only. includeRelativeUrl records relative_urls=true and makes no request. fetchAll sends it.
  • The Get all assets reference does not list relative_urls. Compare getUrl on the returned assets with and without the flag before you depend on the format.
  • A second call changes nothing. Remove the flag with removeParam.

Example

Basic usage: list assets with the relative URL flag

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

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

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    System.out.println(asset.getUrl());
                }
            }
        });
    }
}

limit

limit caps the number of assets that one fetchAll call returns.

NameTypeDescription
number (required)int

Maximum number of assets to return.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation. limit records zero or a negative number as given.
  • The API accepts positive integers only. A limit of 0 returns the default number of assets, not every asset, as Limit describes.
  • Errors from the request surface as an Error in the callback when fetchAll sends it.

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

Behavior

  • Client-side only. limit records the limit query parameter and makes no request. fetchAll sends it.
  • Omitting limit does not return every asset. The SDK sets no default, so the API returns its first 100 assets. See Pagination on the AssetLibrary class page.
  • A second call replaces the first value.
  • Combine it with skip to read the list one page at a time.

Example

Basic usage: return at most five assets

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class ListFiveAssets {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary().limit(5);

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName());
                }
            }
        });
    }
}

removeHeader

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

NameTypeDescription
headerKey (required)String

Name of the header to remove.

Default: Not applicable

Returns: void. This method returns nothing.

Validation

  • An empty string, or a key that is not in the map, changes nothing and raises no error.
  • Throws NullPointerException when headerKey is null, because removeHeader checks the key for emptiness first.

Behavior

  • Client-side only. removeHeader makes no request.
  • The library shares the header map of its Stack, so the header disappears from every later request from that stack.
  • IMPORTANT: Without api_key, access_token, or environment, later requests from the stack lack a header that the Get all assets reference lists as required. Without the environment header, fetchAll 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.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

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

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName());
                }
            }
        });
    }
}

removeParam

removeParam removes one recorded query parameter by name.

NameTypeDescription
paramKey (required)String

Name of the query parameter to remove.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • removeParam checks the key against the set on the AssetLibrary class page. When it fails, removeParam logs a warning through java.util.logging, removes nothing, and returns the library.
  • A key that the library does not hold changes nothing and raises no error.
  • Throws NullPointerException when paramKey is null.
  • Errors from the request surface as an Error in the callback when fetchAll sends it.

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

Behavior

  • Client-side only. removeParam makes no request.
  • It removes any recorded key, including keys that dedicated methods wrote, such as include_count from includeCount, asc or desc from sort, and query from where.
  • fetchAll writes environment again on every call, so removing it has no effect.

Example

Basic usage: drop the count from a reused library

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class RemoveCountParam {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary().limit(10).includeCount().removeParam("include_count");

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName());
                }
            }
        });
    }
}

setHeader

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

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 key and value check on the AssetLibrary class page covers query parameters only, not headers.

Behavior

  • Client-side only. setHeader makes no request. fetchAll sends the header.
  • The library shares the header map of its Stack. The header therefore travels with every later request from that stack, including entry, query, and single asset requests.
  • 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 the asset list request

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

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

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName());
                }
            }
        });
    }
}

setLocale

setLocale sets the locale of the assets that fetchAll lists.

NameTypeDescription
locale (required)String

Locale code to list, such as fr-fr.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation at the setLocale call.
  • A locale code with characters outside the set on the AssetLibrary class page, or an empty string, never reaches the API. fetchAll leaves it out without a warning. Standard codes such as en-us pass.
  • Errors from the request surface as an Error in the callback when fetchAll sends it.

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. fetchAll sends it to Get all assets.
  • 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 fallback-locale versions of assets with no published version in this locale.

Example

Basic usage: list the French versions of the assets

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class ListFrenchAssets {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary().setLocale("fr-fr");

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName());
                }
            }
        });
    }
}

skip

skip sets the number of matching assets that the API skips before the list starts.

NameTypeDescription
number (required)int

Number of assets to skip.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation. skip records zero or a negative number as given.
  • Errors from the request surface as an Error in the callback when fetchAll sends it.

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

Behavior

  • Client-side only. skip records the skip query parameter and makes no request. fetchAll sends it, as Skip describes for entries and assets.
  • A second call replaces the first value. Reuse one library and call skip again to read the next page.
  • A skip value at or past the total number of matching assets returns no assets, and in 2.8.3 fetchAll then returns without calling the callback. See the Known issue on that method page.
  • See Pagination on the AssetLibrary class page.

Example

Basic usage: read the third page of ten assets

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class ReadThirdPage {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary().skip(20).limit(10);

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName());
                }
            }
        });
    }
}

Pagination: read every asset, one hundred at a time

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class ReadAllAssets {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary();
        final int pageSize = 100;
        final int[] received = {0};
        int skip = 0;

        do {
            // Reset first: fetchAll skips the callback when a page is empty
            received[0] = 0;
            library.skip(skip).limit(pageSize).fetchAll(new FetchAssetsCallback() {
                @Override
                public void onCompletion(ResponseType responseType, List<Asset> assets, Error error) {
                    if (error != null) { System.out.println(error.getErrorMessage()); return; }
                    received[0] = assets.size();
                    for (Asset asset : assets) {
                        System.out.println(asset.getFileName());
                    }
                }
            });
            skip += pageSize;
        } while (received[0] == pageSize);
    }
}

sort

sort orders the asset list by the value of one field.

NameTypeDescription
keyOrderBy (required)String

UID of the field to sort by, such as created_at.

Default: Not applicable
orderby (required)AssetLibrary.ORDERBY

Sort direction, ASCENDING or DESCENDING.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • There is no client-side validation at the sort call.
  • A null orderby sorts in descending order, because sort treats every value other than ASCENDING as descending.
  • A keyOrderBy value with characters outside the set on the AssetLibrary class page never reaches the API. fetchAll leaves it out without a warning.
  • Errors from the request surface as an Error in the callback when fetchAll sends it.

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

Behavior

  • Client-side only. sort records asc=<keyOrderBy> for ASCENDING and desc=<keyOrderBy> otherwise, and makes no request. fetchAll sends it.
  • The API sorts entries and assets alike, as Order by asc and Order by desc describe.
  • The two directions use two different keys. A second call in the same direction replaces the field.
  • A call in the other direction adds a second key, and the request then carries both asc and desc.
  • To change direction on the same library, remove the old key with removeParam first, as the second example below shows.
  • The AssetLibrary class page describes the ORDERBY enum.

Example

Basic usage: list assets from oldest to newest

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class SortAssetsAscending {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary().sort("created_at", AssetLibrary.ORDERBY.ASCENDING);

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName());
                }
            }
        });
    }
}

Edge case: switch the sort direction on the same library

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class SwitchSortDirection {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary().sort("created_at", AssetLibrary.ORDERBY.ASCENDING);

        // Without removeParam, the request would carry both asc and desc
        library.removeParam("asc").sort("created_at", AssetLibrary.ORDERBY.DESCENDING);

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, Error error) {
                if (error != null) { System.out.println(error.getErrorMessage()); return; }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName());
                }
            }
        });
    }
}

where

where matches the assets whose field equals the given value.

NameTypeDescription
key (required)String

UID of the asset field to match, such as filename.

Default: Not applicable
value (required)String

Value the field must equal.

Default: Not applicable

Returns: AssetLibrary. The same asset library, for chaining.

Validation

  • Throws IllegalArgumentException at the where call when key or value holds a character outside the sets on the AssetLibrary class page. The SDK checks both before it writes them into the URL. For example, where("content_type", "image/png") throws, because / is not in the value set.
  • Throws NullPointerException when key is null.
  • The compiler does not require a try block, because IllegalArgumentException is a RuntimeException. Catch it when the value comes from user input.
  • Errors from the request surface as an Error in the callback when fetchAll sends it.

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

Behavior

  • Client-side only. where records query={"<key>":"<value>"} and makes no request. fetchAll sends the query as URL-encoded JSON to Get all assets.
  • The match is exact, as the Equals Operator reference describes for entries and assets.
  • Each call replaces the whole query, so only the last where condition reaches the API.

Limitations

  • Does not combine conditions. Build the query as a JSONObject with an AND Operator and pass it to the addParam method under the key query, as the last example below shows.
  • Does not accept values with characters such as /, :, or @. The addParam route above covers those values too, because the SDK checks only string values, not the strings inside a JSONObject.

Example

Basic usage: find an asset by file name

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;

public class FindAssetByFileName {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary().where("filename", "hero-banner.jpg");

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, 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;
                }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName());
                }
            }
        });
    }
}

Error handling: catch a value that where rejects

import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Stack;

public class RejectedWhereValue {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        AssetLibrary library = stack.assetLibrary();
        try {
            library.where("content_type", "image/png");
        } catch (IllegalArgumentException invalid) {
            // Fires before any request: "/" is outside the accepted value characters
            System.out.println("where rejected the value: " + invalid.getMessage());
        }
    }
}

Workaround: match two fields with a query object

import com.contentstack.sdk.Asset;
import com.contentstack.sdk.AssetLibrary;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.FetchAssetsCallback;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;

public class FindPngBanner {
    public static void main(String[] args) throws IllegalAccessException {
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>");
        JSONArray conditions = new JSONArray();
        conditions.put(new JSONObject().put("content_type", "image/png"));
        conditions.put(new JSONObject().put("title", "Hero banner"));
        JSONObject query = new JSONObject().put("$and", conditions);
        AssetLibrary library = stack.assetLibrary().addParam("query", query);

        library.fetchAll(new FetchAssetsCallback() {
            @Override
            public void onCompletion(ResponseType responseType, List<Asset> assets, Error error) {
                if (error != null) { System.out.println(error.getErrorMessage()); return; }
                for (Asset asset : assets) {
                    System.out.println(asset.getFileName());
                }
            }
        });
    }
}