Config

View as Markdown

Config

The Config class holds the optional settings of a stack. You create a Config, set the values you need, and pass it to stack as the fourth argument.

Use this class to

  • send requests to a region other than North America, or to a custom host
  • read content from a branch of the stack
  • route requests through a proxy or tune the connection pool
  • change or turn off the retry behavior
  • observe each request and response with plugins
  • preview draft content with live preview

Every value has a default, so a Config you create with new Config() and pass unchanged behaves the same as the three-argument stack overload.

NameTypeDescription
releaseId String

Public field, read and write. The release_id value from the last livePreviewQuery call.

previewTimestamp String

Public field, read and write. The preview_timestamp value from the last livePreviewQuery call.

connectionPool

connectionPool replaces the HTTP connection pool, which sets the number of idle connections the stack keeps open for reuse and the time it keeps them.

NameTypeDescription
maxIdleConnections (required)int

Maximum number of idle connections to keep.

Default: Not applicable
keepAliveDuration (required)long

Time an idle connection stays open.

Default: Not applicable
timeUnit (required)TimeUnit

Unit of keepAliveDuration, such as TimeUnit.MINUTES.

Default: Not applicable

Returns: ConnectionPool. The new connection pool.

Validation

  • There is no client-side validation in the SDK. connectionPool passes the three values to the okhttp3.ConnectionPool constructor unchanged, and that constructor decides whether to throw for a value it rejects.
  • timeUnit is a java.util.concurrent.TimeUnit.

Behavior

  • Client-side only. connectionPool creates a pool and makes no request.
  • Without a call to connectionPool, the config uses new okhttp3.ConnectionPool(), which keeps up to 5 idle connections for 5 minutes (OkHttp default, okhttp3 package).
  • connectionPool returns the new okhttp3.ConnectionPool, not the Config, so you cannot chain another Config setter after it.
  • stack passes the pool to the OkHttp client it builds for the stack. It reads the pool once, so a pool you create after that call does not change the existing stack.
  • Each call replaces the previous pool.

Example

Basic usage: keep up to ten idle connections for two minutes

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

import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionPool;

public class TuneConnectionPool {
    public static void main(String[] args) throws IllegalAccessException {
        Config config = new Config();
        ConnectionPool pool = config.connectionPool(10, 2, TimeUnit.MINUTES);

        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
        System.out.println("Idle connections now: " + pool.idleConnectionCount());
    }
}

enableLivePreview

enableLivePreview turns live preview on or off for the stack you create from this config.

NameTypeDescription
enableLivePreview (required)boolean

true turns live preview on.

Default: Not applicable

Returns: Config. The same config, for chaining.

Validation

  • There is no client-side validation. Java typing accepts only true or false.
  • With true, stack throws NullPointerException in the US region when the config has no live preview host. Call setLivePreviewHost before stack.

Behavior

  • Client-side only. enableLivePreview stores the flag and makes no request.
  • Live preview is off by default.
  • Call enableLivePreview(true) before stack. stack builds the preview URL only when the flag is true at that moment. If you turn it on later, the livePreviewQuery method throws NullPointerException.
  • With live preview off, livePreviewQuery throws IllegalStateException, and entry fetches ignore any stored preview entry.
  • See Live preview on the Config class page for the full setup order.
  • Known issue: With live preview on, find throws NullPointerException until livePreviewQuery has run once on the stack. Call livePreviewQuery before any query, or turn live preview on only in the Config of a stack that serves previews.

Example

Basic usage: preview a draft entry

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Entry;
import com.contentstack.sdk.EntryResultCallBack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PreviewDraftEntry {
    public static void main(String[] args) throws IllegalAccessException, IOException {
        Config config = new Config()
                .enableLivePreview(true)
                .setLivePreviewHost("rest-preview.contentstack.com")
                .setPreviewToken("<PREVIEW_TOKEN>");
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);

        // The live_preview hash that the preview frame passes to your page
        String livePreviewHash = System.getenv("LIVE_PREVIEW_HASH");
        Map<String, String> previewQuery = new HashMap<>();
        previewQuery.put("live_preview", livePreviewHash);
        previewQuery.put("content_type_uid", "<CONTENT_TYPE_UID>");
        previewQuery.put("entry_uid", "<ENTRY_UID>");
        stack.livePreviewQuery(previewQuery);

        Entry entry = stack.contentType("<CONTENT_TYPE_UID>").entry("<ENTRY_UID>");
        entry.fetch(new EntryResultCallBack() {
            @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 draft title when the preview request succeeded
                System.out.println(entry.getTitle());
            }
        });
    }
}

getBranch

getBranch returns the branch that the config holds.

Returns: String. The branch of the config.

Validation

  • There is no client-side validation. getBranch reads a stored value and cannot fail.

Behavior

  • Client-side only. getBranch makes no request.
  • getBranch returns null until you call setBranch.
  • getBranch returns the value of the config, not the branch header of a stack. A header you change with the setHeader method does not change it.

Example

Basic usage: read the branch

import com.contentstack.sdk.Config;

public class ReadBranch {
    public static void main(String[] args) {
        Config config = new Config();
        System.out.println("Default branch: " + config.getBranch());

        config.setBranch("<BRANCH>");
        System.out.println("Branch: " + config.getBranch());
    }
}

getEarlyAccess

getEarlyAccess returns the early access features that the config holds.

Returns: String[]. The early access features of the config.

Validation

  • There is no client-side validation. getEarlyAccess reads a stored value and cannot fail.

Behavior

  • Client-side only. getEarlyAccess makes no request.
  • getEarlyAccess returns null until you call setEarlyAccess. Check for null before you read the array.
  • getEarlyAccess returns the array you passed to setEarlyAccess, not a copy.

Example

Basic usage: read the early access features

import com.contentstack.sdk.Config;

public class ReadEarlyAccess {
    public static void main(String[] args) {
        Config config = new Config();
        if (config.getEarlyAccess() == null) {
            System.out.println("No early access features set");
        }

        config.setEarlyAccess(new String[] {"taxonomy"});
        for (String feature : config.getEarlyAccess()) {
            System.out.println(feature);
        }
    }
}

getHost

getHost returns the delivery host that the config holds.

Returns: String. The delivery host of the config.

Validation

  • There is no client-side validation. getHost reads a stored value and cannot fail.

Behavior

  • Client-side only. getHost makes no request.
  • getHost returns one of two values, depending on when you call it:
    • Before stack, it returns the host from setHost, or cdn.contentstack.io when you set none. It does not reflect the region yet.
    • After stack, it returns the host the stack sends requests to. Unless you set a host, stack resolves it from the region and writes it into the config.
  • The host has no scheme and no path, for example eu-cdn.contentstack.com.

Example

Basic usage: read the host before and after the stack resolves it

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

public class ReadHost {
    public static void main(String[] args) throws IllegalAccessException {
        Config config = new Config();
        config.setRegion(Config.ContentstackRegion.GCP_NA);
        System.out.println("Before stack: " + config.getHost());

        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
        System.out.println("After stack: " + config.getHost());
    }
}

getProxy

getProxy returns the proxy that the config holds.

Returns: Proxy. The proxy of the config.

Validation

  • There is no client-side validation. getProxy reads a stored value and cannot fail.

Behavior

  • Client-side only. getProxy makes no request.
  • getProxy returns null until you call setProxy. A null proxy means the HTTP client uses the default proxy settings of the JVM.
  • The value is a java.net.Proxy.

Example

Basic usage: read the proxy

import com.contentstack.sdk.Config;

import java.net.InetSocketAddress;
import java.net.Proxy;

public class ReadProxy {
    public static void main(String[] args) {
        Config config = new Config();
        System.out.println("Default proxy: " + config.getProxy());

        config.setProxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("proxy.example.com", 1080)));
        System.out.println("Proxy: " + config.getProxy());
    }
}

getRegion

getRegion returns the Contentstack region that the config holds.

Returns: ContentstackRegion. The region of the config.

Validation

  • There is no client-side validation. getRegion reads a stored value and cannot fail.

Behavior

  • Client-side only. getRegion makes no request.
  • getRegion returns US until you call setRegion, and returns null after setRegion(null).
  • The value is one of the seven Config.ContentstackRegion values: US, EU, AZURE_NA, AZURE_EU, GCP_NA, GCP_EU and AU.
  • getRegion returns the region even when a host from setHost overrides it for the delivery host. Call getHost to read the host the stack uses.

Example

Basic usage: read the default and the updated region

import com.contentstack.sdk.Config;

public class ReadRegion {
    public static void main(String[] args) {
        Config config = new Config();
        System.out.println("Default region: " + config.getRegion());

        config.setRegion(Config.ContentstackRegion.AZURE_NA);
        System.out.println("Region: " + config.getRegion());
    }
}

getRetryOptions

getRetryOptions returns the retry settings that the config holds.

Returns: RetryOptions. The retry options of the config.

Validation

  • There is no client-side validation. getRetryOptions reads a stored value and cannot fail.

Behavior

  • Client-side only. getRetryOptions makes no request.
  • getRetryOptions returns the default RetryOptions until you call setRetryOptions, and returns null after setRetryOptions(null).
  • getRetryOptions returns the object itself, not a copy. A setter you call on it before stack runs changes the retry behavior of that stack.

Example

Basic usage: read the default retry settings

import com.contentstack.sdk.Config;
import com.contentstack.sdk.RetryOptions;

public class ReadRetryOptions {
    public static void main(String[] args) {
        Config config = new Config();
        RetryOptions retryOptions = config.getRetryOptions();

        System.out.println("Retry on: " + retryOptions.isRetryEnabled());
        System.out.println("Retry limit: " + retryOptions.getRetryLimit());
        System.out.println("Base delay in ms: " + retryOptions.getRetryDelay());
    }
}

getVersion

getVersion returns the Content Delivery API version that the SDK puts in every request path.

Returns: String. The Content Delivery API version.

Validation

  • There is no client-side validation. getVersion reads a stored value and cannot fail.

Behavior

  • Client-side only. getVersion makes no request.
  • getVersion always returns v3. Config has no method that changes the version.
  • The SDK builds each request URL as https://<host>/v3/<path>, for example https://cdn.contentstack.io/v3/content_types.

Example

Basic usage: read the API version

import com.contentstack.sdk.Config;

public class ReadVersion {
    public static void main(String[] args) {
        Config config = new Config();
        System.out.println("API version: " + config.getVersion());
    }
}

setBranch

setBranch sets the branch of the stack that every request reads content from.

NameTypeDescription
branch (required)String

UID of the branch to read from.

Default: Not applicable

Returns: void. This method returns nothing.

Validation

  • There is no client-side validation. setBranch stores any string, including null.
  • stack skips the branch when it is null or empty, so requests read from the main branch.
  • A branch UID that does not exist surfaces as an Error in the callback of the first request.

Behavior

  • Client-side only. setBranch stores the branch and makes no request.
  • stack sends the value in the branch header of every request from that stack. The Content Delivery API reads the branch from this header, as the branch header of Get all entries shows.
  • stack reads the branch once. A branch you set after that call does not change the existing stack. Call the setHeader method with the key branch to change it on an existing stack.
  • setBranch returns void, so call it as a separate statement.

Example

Basic usage: read content from a branch

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Entry;
import com.contentstack.sdk.EntryResultCallBack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class ReadFromBranch {
    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);
        Entry entry = stack.contentType("<CONTENT_TYPE_UID>").entry("<ENTRY_UID>");

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

setEarlyAccess

setEarlyAccess sets the early access features that every request from the stack asks the API for.

NameTypeDescription
earlyAccess (required)String[]

Names of the early access features to request.

Default: Not applicable

Returns: Config. The same config, for chaining.

Validation

  • There is no client-side validation. setEarlyAccess stores the array as given, including null.
  • stack skips the header when the array is null or empty.
  • stack writes a null element as the text null in the header. Pass only non-null names.

Behavior

  • Client-side only. setEarlyAccess stores the array and makes no request.
  • stack joins the names with commas, removes any double quote characters, and sends the result in the x-header-ea header of every request. For example, {"taxonomy", "teams"} becomes x-header-ea: taxonomy,teams.
  • setEarlyAccess keeps a reference to your array, not a copy. A change to the array before stack runs reaches the header.
  • stack reads the value once. A value you set after that call does not change the existing stack.

Example

Basic usage: request two early access features

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

public class SetEarlyAccess {
    public static void main(String[] args) throws IllegalAccessException {
        Config config = new Config().setEarlyAccess(new String[] {"taxonomy", "teams"});

        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
        System.out.println("Early access: " + String.join(",", config.getEarlyAccess()));
    }
}

setHost

setHost sets a custom delivery host that the stack sends every content request to, in place of the region's host.

NameTypeDescription
hostName (required)String

Host name without a scheme, such as eu-cdn.contentstack.com.

Default: Not applicable

Returns: void. This method returns nothing.

Validation

  • setHost ignores null and an empty string. The config keeps its previous host, and the region still decides the delivery host.
  • There is no other client-side validation. setHost does not check the format of the host name.
  • An unreachable or wrong host surfaces as an Error in the callback of the first request. Its message starts with IO error occurred: when no server answers.

Behavior

  • Client-side only. setHost stores the host and makes no request.
  • stack adds https:// in front of the host and /v3/ after it to build the base URL of every request. Pass the host only:
    • "eu-cdn.contentstack.com" gives https://eu-cdn.contentstack.com/v3/.
    • "https://eu-cdn.contentstack.com" gives https://https://eu-cdn.contentstack.com/v3/, which no request can reach.
  • A host you set takes precedence over the region from setRegion, whatever order you call the two methods in.
  • stack reads the host once. A host you set after that call does not change the existing stack.
  • To get the host of a Contentstack service in a region, call the getContentstackEndpoint method with omitHttps set to true.

Example

Basic usage: send requests to a custom host

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Entry;
import com.contentstack.sdk.EntryResultCallBack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

public class SetCustomHost {
    public static void main(String[] args) throws IllegalAccessException {
        Config config = new Config();
        // Host only, without https://
        config.setHost("eu-cdn.contentstack.com");

        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
        Entry entry = stack.contentType("<CONTENT_TYPE_UID>").entry("<ENTRY_UID>");

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

Edge case: an empty host keeps the region host

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

public class EmptyHostIgnored {
    public static void main(String[] args) throws IllegalAccessException {
        Config config = new Config();
        config.setRegion(Config.ContentstackRegion.AU);
        // setHost ignores an empty string, so the AU region decides the host
        config.setHost("");

        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
        System.out.println("Delivery host: " + config.getHost());
    }
}

setLivePreviewHost

setLivePreviewHost sets the host of the preview service that the livePreviewQuery method fetches draft entries from.

NameTypeDescription
livePreviewHost (required)String

Preview host without a scheme, such as rest-preview.contentstack.com.

Default: Not applicable

Returns: Config. The same config, for chaining.

Validation

  • There is no client-side validation. setLivePreviewHost stores any string, including null.
  • With live preview on and the region US, a null host makes stack throw NullPointerException.
  • An empty host makes livePreviewQuery throw IllegalStateException.

Behavior

  • Client-side only. setLivePreviewHost stores the host and makes no request.
  • Pass the host only. stack builds the preview URL as https://<host>/v3/content_types/, and livePreviewQuery adds the content type and entry UIDs to it.
  • For every region except US, stack adds the region name in lowercase and a hyphen in front of the host. Pass the host without a region prefix, as the two cases below show:
    • With EU, rest-preview.contentstack.com becomes eu-rest-preview.contentstack.com.
    • With EU, eu-rest-preview.contentstack.com becomes eu-eu-rest-preview.contentstack.com, which no request can reach.
  • stack reads the host once, and only when live preview is on at that moment.
  • The host decides which token livePreviewQuery sends. With the host rest-preview.contentstack.com, it sends the preview token from setPreviewToken. With any other host, it sends the management token from setManagementToken.
  • Known issue: For AZURE_NA, AZURE_EU, GCP_NA and GCP_EU, stack keeps the underscore of the region name in the prefix, for example azure_na-rest-preview.contentstack.com. Workaround: keep the region US, pass the full regional hosts to setHost and setLivePreviewHost, and use a management token. The livePreviewQuery method page describes the same issue.

Example

Basic usage: set the preview host for the Europe region

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

public class SetPreviewHostEurope {
    public static void main(String[] args) throws IllegalAccessException {
        Config config = new Config()
                .enableLivePreview(true)
                // Host without the region prefix, because stack adds eu-
                .setLivePreviewHost("rest-preview.contentstack.com")
                .setManagementToken("<MANAGEMENT_TOKEN>");
        config.setRegion(Config.ContentstackRegion.EU);

        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
        System.out.println("Delivery host: " + config.getHost());
    }
}

setManagementToken

setManagementToken sets the management token that the livePreviewQuery method sends to a preview host other than rest-preview.contentstack.com.

NameTypeDescription
managementToken (required)String

Management token of the stack.

Default: Not applicable

Returns: Config. The same config, for chaining.

Validation

  • There is no client-side validation. setManagementToken stores any string, including null.
  • A wrong token surfaces only in the preview response, which livePreviewQuery does not report. Later fetches then return published content.

Behavior

  • Client-side only. setManagementToken stores the token and makes no request.
  • livePreviewQuery sends the token in the authorization header whenever the live preview host is not exactly rest-preview.contentstack.com. That covers every region except US, because stack adds a region prefix to the host there.
  • The SDK sends the management token only on livePreviewQuery. Content requests use the delivery token.
  • The SDK reads the token at each livePreviewQuery call, so a token you set after stack applies to the next call.

Note A management token can grant write access to the stack. Keep it in server-side code and out of anything that reaches a browser or a mobile app.

Example

Basic usage: preview in the Europe region with a management token

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

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PreviewWithManagementToken {
    public static void main(String[] args) throws IllegalAccessException, IOException {
        Config config = new Config()
                .enableLivePreview(true)
                .setLivePreviewHost("rest-preview.contentstack.com")
                .setManagementToken("<MANAGEMENT_TOKEN>");
        config.setRegion(Config.ContentstackRegion.EU);
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);

        // The live_preview hash that the preview frame passes to your page
        String livePreviewHash = System.getenv("LIVE_PREVIEW_HASH");
        Map<String, String> previewQuery = new HashMap<>();
        previewQuery.put("live_preview", livePreviewHash);
        previewQuery.put("content_type_uid", "<CONTENT_TYPE_UID>");
        previewQuery.put("entry_uid", "<ENTRY_UID>");
        stack.livePreviewQuery(previewQuery);
        System.out.println("Preview request sent");
    }
}

setPlugins

setPlugins sets the plugins that the SDK calls before it sends each request and after each successful response.

NameTypeDescription
plugins (required)List<ContentstackPlugin>

Plugins to call on each request, in list order.

Default: Not applicable

Returns: void. This method returns nothing.

Validation

  • There is no client-side validation. setPlugins stores the list as given.
  • setPlugins(null) turns plugins off.
  • An exception that a plugin throws stops the request and reaches your code from the request method, not as an Error in the callback.

Behavior

  • Client-side only. setPlugins stores the list and makes no request.
  • ContentstackPlugin is an interface with two default methods. onRequest(Stack stack, Request request) receives each request before the SDK sends it. onResponse(Stack stack, Request request, Response<ResponseBody> response) receives each successful response. Override the one you need. The Callbacks class page covers both, with an example.
  • The SDK reads the list on every request, so a list you set after stack applies to the next request.
  • For each request, the SDK calls onRequest on every plugin in list order, then sends the request. After a successful response, it calls onResponse on every plugin. It does not call onResponse when the API returns an error status.
  • When the config holds plugins, the SDK replaces the header map of the stack with the headers of the request it built. The headers it sends stay the same.
  • Known issue: The SDK ignores the Request that onRequest returns and the Response that onResponse returns, so a plugin can read a request but cannot change it. Add a header with the setHeader method instead.

Example

Basic usage: log the URL of each request

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.ContentstackPlugin;
import com.contentstack.sdk.Entry;
import com.contentstack.sdk.EntryResultCallBack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class LogRequests {
    public static void main(String[] args) throws IllegalAccessException {
        ContentstackPlugin logger = new ContentstackPlugin() {
            @Override
            public Request onRequest(Stack stack, Request request) {
                System.out.println("Sending " + request.url());
                return request;
            }

            @Override
            public Response<ResponseBody> onResponse(Stack stack, Request request, Response<ResponseBody> response) {
                System.out.println("Received " + response.code() + " for " + request.url());
                return response;
            }
        };

        List<ContentstackPlugin> plugins = new ArrayList<>();
        plugins.add(logger);

        Config config = new Config();
        config.setPlugins(plugins);

        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
        Entry entry = stack.contentType("<CONTENT_TYPE_UID>").entry("<ENTRY_UID>");

        entry.fetch(new EntryResultCallBack() {
            @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(entry.getTitle());
            }
        });
    }
}

setPreviewToken

setPreviewToken sets the preview token that the livePreviewQuery method sends to the preview service.

NameTypeDescription
previewToken (required)String

Preview token of the delivery token you use.

Default: Not applicable

Returns: Config. The same config, for chaining.

Validation

  • There is no client-side validation. setPreviewToken stores any string, including null.
  • When the live preview host is rest-preview.contentstack.com and the token is null, livePreviewQuery throws IllegalAccessError. IllegalAccessError is a java.lang.Error, not an Exception, so catch (Exception e) does not catch it. Set the token before you call livePreviewQuery.
  • A wrong token surfaces only in the preview response, which livePreviewQuery does not report. Later fetches then return published content.

Behavior

  • Client-side only. setPreviewToken stores the token and makes no request.
  • livePreviewQuery sends the token in the preview_token header only when the live preview host is exactly rest-preview.contentstack.com. For any other host, it sends the management token from setManagementToken instead.
  • The SDK reads the token at each livePreviewQuery call, so a token you set after stack applies to the next call.
  • Known issue: Outside the US region, livePreviewQuery sends the management token instead of the preview token, because stack adds a region prefix to the preview host. Use setManagementToken in other regions.

Example

Basic usage: preview with a preview token

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

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PreviewWithPreviewToken {
    public static void main(String[] args) throws IllegalAccessException, IOException {
        Config config = new Config()
                .enableLivePreview(true)
                .setLivePreviewHost("rest-preview.contentstack.com")
                .setPreviewToken("<PREVIEW_TOKEN>");
        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);

        // The live_preview hash that the preview frame passes to your page
        String livePreviewHash = System.getenv("LIVE_PREVIEW_HASH");
        Map<String, String> previewQuery = new HashMap<>();
        previewQuery.put("live_preview", livePreviewHash);
        previewQuery.put("content_type_uid", "<CONTENT_TYPE_UID>");
        previewQuery.put("entry_uid", "<ENTRY_UID>");
        try {
            stack.livePreviewQuery(previewQuery);
        } catch (IllegalStateException e) {
            // Thrown when live preview is off, the host is empty, the query lacks content_type_uid,
            // or the preview request does not complete
            System.out.println("Preview not ready: " + e.getMessage());
        }
    }
}

setProxy

setProxy routes every request from the stack through a proxy server.

NameTypeDescription
proxy (required)Proxy

java.net.Proxy with the proxy type and address.

Default: Not applicable

Returns: void. This method returns nothing.

Validation

  • There is no client-side validation. setProxy stores any java.net.Proxy, including null.
  • With null, the HTTP client uses the default proxy settings of the JVM.
  • A proxy that does not answer surfaces as an Error in the callback of the first request. Its message starts with IO error occurred:.

Behavior

  • Client-side only. setProxy stores the proxy and makes no request.
  • stack passes the proxy to the OkHttp client it builds for the stack. Every request from that stack, including retries, goes through it.
  • stack reads the proxy once. A proxy you set after that call does not change the existing stack.
  • setProxy returns void, so call it as a separate statement.

Example

Basic usage: send requests through an HTTP proxy

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Entry;
import com.contentstack.sdk.EntryResultCallBack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.Stack;

import java.net.InetSocketAddress;
import java.net.Proxy;

public class UseProxy {
    public static void main(String[] args) throws IllegalAccessException {
        Config config = new Config();
        config.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080)));

        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
        Entry entry = stack.contentType("<CONTENT_TYPE_UID>").entry("<ENTRY_UID>");

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

setRegion

setRegion sets the Contentstack region whose delivery host the stack sends requests to.

NameTypeDescription
region (required)Config.ContentstackRegion

Region of your stack, such as EU.

Default: Not applicable

Returns: ContentstackRegion. The region you set.

Validation

  • There is no client-side validation. Java typing accepts only a Config.ContentstackRegion value or null.
  • setRegion accepts null. stack then throws NullPointerException when it looks up the delivery host, unless you also set a host with setHost.

Behavior

  • Client-side only. setRegion stores the region and makes no request.
  • setRegion returns the region you pass, not the Config, so you cannot chain another Config setter after it.
  • The default region is US. Config.ContentstackRegion has seven values: US, EU, AZURE_NA, AZURE_EU, GCP_NA, GCP_EU and AU. See Regions on the Config class page for the delivery host of each one.
  • stack reads the region once and looks up its delivery host. A region you set after that call does not change the existing stack.
  • A host from setHost takes precedence over the region for the delivery host, whatever order you call the two methods in.
  • With live preview on, stack also adds the region name as a prefix to the live preview host for every region except US. See setLivePreviewHost.

Example

Basic usage: send requests to the Europe region

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

public class SetEuropeRegion {
    public static void main(String[] args) throws IllegalAccessException {
        Config config = new Config();
        Config.ContentstackRegion region = config.setRegion(Config.ContentstackRegion.EU);
        System.out.println("Region: " + region);

        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
        // stack resolved the Europe delivery host and wrote it into the config
        System.out.println("Delivery host: " + config.getHost());
    }
}

setRetryOptions

setRetryOptions replaces the retry settings that decide which failed requests the stack resends, and the number and timing of the retries.

NameTypeDescription
retryOptions (required)RetryOptions

Retry limit, delay, backoff strategy and retried statuses.

Default: Not applicable

Returns: Config. The same config, for chaining.

Validation

  • There is no client-side validation in setRetryOptions. The RetryOptions setters check their own values when you call them.
  • setRetryOptions accepts null. stack then adds no retry step, so the stack sends each request once.

Behavior

  • Client-side only. setRetryOptions stores the object and makes no request.
  • Without a call to setRetryOptions, the config holds new RetryOptions(). Retry is on. The SDK retries 408, 429, 502, 503 and 504 responses and network failures. It sends the initial request plus up to three retries. See the RetryOptions class page for the full defaults.
  • stack adds the retry step to the HTTP client only when the options are not null and retry is on. It reads the options once, so a value you set after that call does not change the existing stack.
  • The retry wait runs on the calling thread, so a request method returns later when it retries.

Example

Basic usage: retry twice with a fixed two-second delay

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.Entry;
import com.contentstack.sdk.EntryResultCallBack;
import com.contentstack.sdk.Error;
import com.contentstack.sdk.ResponseType;
import com.contentstack.sdk.RetryOptions;
import com.contentstack.sdk.Stack;

public class CustomRetry {
    public static void main(String[] args) throws IllegalAccessException {
        RetryOptions retryOptions = new RetryOptions()
                .setRetryLimit(2)
                .setRetryDelay(2000)
                .setBackoffStrategy(RetryOptions.BackoffStrategy.FIXED);
        Config config = new Config().setRetryOptions(retryOptions);

        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
        Entry entry = stack.contentType("<CONTENT_TYPE_UID>").entry("<ENTRY_UID>");

        entry.fetch(new EntryResultCallBack() {
            @Override
            public void onCompletion(ResponseType responseType, Error error) {
                if (error != null) {
                    // The API rejected the request, or every retry failed
                    System.out.println("Request failed: " + error.getErrorCode() + " " + error.getErrorMessage());
                    return;
                }
                System.out.println(entry.getTitle());
            }
        });
    }
}

Edge case: turn retry off

import com.contentstack.sdk.Config;
import com.contentstack.sdk.Contentstack;
import com.contentstack.sdk.RetryOptions;
import com.contentstack.sdk.Stack;

public class DisableRetry {
    public static void main(String[] args) throws IllegalAccessException {
        // setRetryEnabled(false) and setRetryOptions(null) both make the stack send each request once
        Config config = new Config().setRetryOptions(new RetryOptions().setRetryEnabled(false));

        Stack stack = Contentstack.stack("<API_KEY>", "<DELIVERY_TOKEN>", "<ENVIRONMENT>", config);
        System.out.println("Retry on: " + config.getRetryOptions().isRetryEnabled());
    }
}