ContentstackBuilder

View as Markdown

ContentstackBuilder

Contentstack.Builder collects the settings of a Contentstack client and creates the client with build(). Every setter returns the same builder, so you chain the settings in one expression.

Use the builder to set the five kinds of settings below:

  • the host or region, the API version and the network settings, such as the proxy, protocols and connection pool
  • the timeouts and the retry behavior
  • Open Authorization (OAuth) instead of email and password login
  • early access headers and the treatment of null values in request bodies
  • the callback that receives new OAuth tokens
NameTypeDescription
host String

Write, through setHost or setRegion. API host of every request.

port String

Write, through setPort. Stored only. The base URL does not use it.

version String

Write, through setVersion. API version in the base URL.

timeout int

Write, through setTimeout. Connect, read and write timeout.

connectTimeout, readTimeout, writeTimeout Integer

Write, through setConnectTimeout, setReadTimeout, setWriteTimeout. Timeout of one phase.

retry Boolean

Write, through setRetry. HTTP client retry after a connection failure.

retryConfig RetryConfig

Write, through setRetryConfig. SDK retry of failed requests.

proxy Proxy

Write, through setProxy. Proxy for every request.

connectionPool ConnectionPool

Write, through setConnectionPool. Reuse of HTTP connections.

protocols List<Protocol>

Write, through setProtocols. HTTP versions the client may use.

serializeNulls boolean

Write, through setSerializeNulls. Whether request bodies keep null values.

authtoken String

Write, through setAuthtoken. Stored session token.

earlyAccess String[]

Write, through earlyAccess. Early access program values.

OAuth settings OAuthConfig

Write, through setOAuth or setOAuthConfig. App, client and redirect settings.

tokenCallback TokenCallback

Write, through setTokenCallback. Receiver of new OAuth tokens.

build

build checks the builder settings and creates the Contentstack client with its HTTP client.

Returns: Contentstack. A new client.

Validation

  • build checks the host again and throws IllegalArgumentException if it is not a valid host name with an optional port. The check keeps requests on the intended host whichever setter set it.
  • build throws IllegalArgumentException if the Open Authorization (OAuth) settings from setOAuthConfig lack an app ID, client ID or valid redirect URI.
  • build throws IllegalArgumentException if the HTTP client rejects the list from setProtocols.
  • build throws NullPointerException if setRetry received null.
  • build sends no request, so it does not check credentials. A wrong value surfaces when you call execute() on a request.

Behavior

  • build creates the base URL https://<host>/<version>/ and an HTTP client with the timeouts, proxy, connection pool, protocols and retry settings of the builder.
  • build adds one request handler to the HTTP client:
    • Without OAuth, a handler that adds the authtoken from login, the early access header and the SDK retry.
    • With OAuth settings, a handler that adds the OAuth access token, refreshes it when it expires, and applies the SDK retry.
  • Each call returns a new client with its own HTTP client. A setter call after build does not change a client that already exists.

Example

Basic usage: build a client with default settings

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import retrofit2.Response;

import java.io.IOException;

public class BuildDefaultClient {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder().build();
        System.out.println("Base URL: " + client.getBaseUrl());

        Response<ResponseBody> response = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>").find().execute();
        if (!response.isSuccessful()) {
            // The API rejected the request. The body holds error_message, error_code and errors.
            System.out.println("Request failed: " + response.code() + " " + response.errorBody().string());
            return;
        }
        System.out.println(response.body().string());
    }
}

Error handling: catch invalid OAuth settings at build time

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthConfig;

public class CatchBuildError {
    public static void main(String[] args) {
        OAuthConfig config = OAuthConfig.builder()
                .appId("<APP_ID>")
                .clientId("<CLIENT_ID>")
                .build();
        try {
            new Contentstack.Builder().setOAuthConfig(config).build();
        } catch (IllegalArgumentException e) {
            // Thrown because the config has no redirect URI
            System.out.println("Invalid settings: " + e.getMessage());
        }
    }
}

earlyAccess

earlyAccess sends the names of the early access programs you joined with every request, so that the API turns on those features for the client.

NameTypeDescription
earlyAccess (required)String[]

Early access program names.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • There is no client-side validation. The SDK sends the names as given.

Behavior

  • Client-side only. Every request from the client carries an x-header-ea header with the names.
  • The SDK joins the names with a comma and a space, for example x-header-ea: name-one, name-two.
  • On a client without Open Authorization (OAuth), a null or empty array sends no header.
  • On an OAuth client, the SDK joins the names with a comma and no space. Without earlyAccess, an OAuth client sends x-header-ea: true.

Example

Basic usage: send early access program names

import com.contentstack.cms.Contentstack;

public class SendEarlyAccessNames {
    public static void main(String[] args) {
        // The early access program names, for example passed on the command line
        String[] programs = args;

        Contentstack client = new Contentstack.Builder()
                .earlyAccess(programs)
                .build();
        System.out.println("Client ready: " + client.getBaseUrl());
    }
}

setAuthtoken

setAuthtoken stores an authtoken on the client that build() creates, as if the client had logged in.

NameTypeDescription
authtoken (required)String

Authtoken of a Contentstack user session.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • There is no client-side validation. setAuthtoken does not check the token with Contentstack, and accepts null, which leaves the client without a token.

Behavior

  • Client-side only. build() copies the token to the client.
  • The token passes the client's login checks. user(), organization(...), stack() and stack(Map) work without a call to login.
  • login on the same client throws IllegalStateException, because the client already holds a token.
  • build() does not give this token to the component that adds the authtoken header to requests. Only login sets that header.

Example

Basic usage: build a client with a stored authtoken

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.user.User;

import java.io.IOException;

public class BuildWithAuthtoken {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder()
                .setAuthtoken("<AUTHTOKEN>")
                .build();

        // The client's login check passes, so user() returns an object
        User user = client.user();
        System.out.println("User object ready: " + user);

        try {
            client.login("<EMAIL>", "<PASSWORD>");
        } catch (IllegalStateException e) {
            // Thrown because the client already holds a token
            System.out.println("Login not allowed: " + e.getMessage());
        }
    }
}

setConnectTimeout

setConnectTimeout sets the time the client waits to open a connection to the API host, in seconds, and leaves the other two timeouts unchanged.

NameTypeDescription
connectTimeoutSeconds (required)int

Connect timeout in seconds.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • setConnectTimeout throws IllegalArgumentException if connectTimeoutSeconds is 0 or less, because a request needs a positive time limit.

Behavior

  • Client-side only. Without setConnectTimeout, the connect timeout is the value of setTimeout, default 30 seconds.
  • setConnectTimeout wins over setTimeout in any call order.
  • Use it for a network with a slow connection set-up.
  • A request that times out throws SocketTimeoutException, an IOException, from execute(), after the SDK retries.

Example

Basic usage: raise the connect timeout only

import com.contentstack.cms.Contentstack;

public class SetConnectTimeout {
    public static void main(String[] args) {
        Contentstack client = new Contentstack.Builder()
                .setTimeout(30)
                .setConnectTimeout(120)
                .build();
        System.out.println("Client ready: " + client.getBaseUrl());
    }
}

setConnectionPool

setConnectionPool sets the maximum number of idle HTTP connections the client keeps open for reuse, and the time each one stays open.

NameTypeDescription
maxIdleConnections (required)int

Maximum idle connections kept open, default 5.

Default: Not applicable
keepAliveDuration (required)int

Time an idle connection stays open, default 5 minutes.

Default: Not applicable
timeUnit (required)TimeUnit

Unit of keepAliveDuration.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • setConnectionPool creates the pool at once. The HTTP client throws IllegalArgumentException if keepAliveDuration is 0 or less.
  • It throws NullPointerException if timeUnit is null.

Behavior

  • Client-side only. setConnectionPool replaces the default pool, which keeps up to 5 idle connections for 5 minutes.
  • Every request from the client uses the pool. A larger pool helps an application that sends many requests in parallel.

Example

Basic usage: keep more idle connections for a shorter time

import com.contentstack.cms.Contentstack;

import java.util.concurrent.TimeUnit;

public class TuneConnectionPool {
    public static void main(String[] args) {
        Contentstack client = new Contentstack.Builder()
                .setConnectionPool(10, 2, TimeUnit.MINUTES)
                .build();
        System.out.println("Client ready: " + client.getBaseUrl());
    }
}

setHost

setHost sets the API host that the client sends every request to, for example the host of your Contentstack region.

NameTypeDescription
hostname (required)String

Host name, with an optional :port.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • setHost throws IllegalArgumentException if hostname is null, empty or only spaces, because the client needs a host to send requests to.
  • It also throws IllegalArgumentException if hostname holds anything other than letters, digits, dots and hyphens, with an optional : and port number at the end. A scheme such as https://, a path, a query string or user credentials fail this check. The check keeps every request on the host you meant.
  • setHost does not check that the host exists. A wrong host surfaces as an IOException from execute().

Behavior

  • Client-side only. setHost stores the host, after it removes leading and trailing spaces.
  • Without setHost or setRegion, the client uses api.contentstack.io, the North America host.
  • setHost and setRegion set the same value. The later call wins.
  • The client sends requests to https://<hostname>/<version>/. The scheme is always https.
  • The three-argument setOAuth overload reads the host when you call it. Call setHost before it.
  • To find the host of a region, call getContentstackEndpoint with omitHttps set to true, or use setRegion.

Example

Basic usage: send requests to the Australia region host

import com.contentstack.cms.Contentstack;
import okhttp3.ResponseBody;
import retrofit2.Response;

import java.io.IOException;

public class UseAustraliaHost {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder()
                .setHost("au-api.contentstack.com")
                .build();

        Response<ResponseBody> response = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>").find().execute();
        if (!response.isSuccessful()) {
            // The API rejected the request. The body holds error_message, error_code and errors.
            System.out.println("Request failed: " + response.code() + " " + response.errorBody().string());
            return;
        }
        System.out.println(response.body().string());
    }
}

Error handling: catch a host that includes a scheme

import com.contentstack.cms.Contentstack;

public class CatchInvalidHost {
    public static void main(String[] args) {
        try {
            new Contentstack.Builder().setHost("https://eu-api.contentstack.com");
        } catch (IllegalArgumentException e) {
            // Thrown because the value includes a scheme. Pass the bare host instead.
            System.out.println("Invalid host: " + e.getMessage());
        }
    }
}

setOAuth

setOAuth turns on Open Authorization (OAuth) for the client with the app ID, client ID and redirect URI of your Contentstack app. Requests then carry an OAuth access token instead of an authtoken.

NameTypeDescription
appId (required)String

UID of the Contentstack app.

Default: Not applicable
clientId (required)String

OAuth client ID of the app.

Default: Not applicable
redirectUri (required)String

Redirect URI registered for the app.

Default: Not applicable
host (required)String

API host that selects the OAuth hosts.

Default: Not applicable
clientSecret (required)String

Client secret. null uses PKCE instead.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Overloads

  • setOAuth(String appId, String clientId, String redirectUri)
  • setOAuth(String appId, String clientId, String redirectUri, String host)
  • setOAuth(String appId, String clientId, String redirectUri, String host, String clientSecret)

Validation

  • setOAuth checks its arguments at once. It throws IllegalArgumentException in the three cases below:
    • appId, clientId or redirectUri is null, empty or only spaces.
    • redirectUri is not a valid URL.
    • host holds anything other than a host name with an optional port, for example a scheme or a path.
  • setOAuth does not check the values with Contentstack. A wrong app ID or client ID surfaces when the code exchange fails.

Behavior

  • Client-side only. setOAuth stores the OAuth settings, and build() creates the OAuth handler from them.
  • On a client with OAuth, every request carries an Authorization: Bearer header with the access token. Until exchangeOAuthCode stores tokens, every request throws IOException.
  • The three-argument overload uses the host of the builder at the time of the call: the host from an earlier setHost or setRegion call, or api.contentstack.io.
  • The host argument selects the OAuth hosts. It does not change the API host of the client:
    • api.contentstack.io gives the authorization page on app.contentstack.com and the token endpoint on developerhub-api.contentstack.com.
    • eu-api.contentstack.com gives eu-app.contentstack.com and eu-developerhub-api.contentstack.com.
    • null, or a host outside contentstack.com and contentstack.io, gives the North America hosts.
  • Without a client secret (the first two overloads, or a null or blank clientSecret), the client uses Proof Key for Code Exchange (PKCE). With one, it sends the secret in token requests. Keep a client secret on a server, never in an app that users install.
  • setOAuth reads the callback from setTokenCallback at the time of the call. Call setTokenCallback first.
  • setOAuth and setOAuthConfig set the same OAuth settings. The later call wins.

Example

Basic usage: OAuth with PKCE

import com.contentstack.cms.Contentstack;

public class BuildOAuthClient {
    public static void main(String[] args) {
        try {
            Contentstack client = new Contentstack.Builder()
                    .setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
                    .build();
            System.out.println("Open this URL to authorize the app: " + client.getOAuthAuthorizationUrl());
        } catch (IllegalArgumentException e) {
            // Thrown for an empty app ID, client ID or redirect URI, or a redirect URI that is not a URL
            System.out.println("Invalid OAuth settings: " + e.getMessage());
        }
    }
}

All parameters: OAuth in the Europe region with a client secret

import com.contentstack.cms.Contentstack;

public class BuildOAuthClientWithSecret {
    public static void main(String[] args) {
        // Four arguments: the host selects the Europe OAuth hosts, and the flow uses PKCE
        Contentstack pkceClient = new Contentstack.Builder()
                .setRegion("eu")
                .setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>", "eu-api.contentstack.com")
                .build();
        System.out.println(pkceClient.getOAuthAuthorizationUrl());

        // Five arguments: a client secret replaces PKCE
        Contentstack secretClient = new Contentstack.Builder()
                .setRegion("eu")
                .setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>", "eu-api.contentstack.com",
                        System.getenv("CONTENTSTACK_CLIENT_SECRET"))
                .build();
        System.out.println(secretClient.getOAuthAuthorizationUrl());
    }
}

setOAuthConfig

setOAuthConfig turns on Open Authorization (OAuth) for the client with a complete OAuthConfig, for settings that setOAuth does not take, such as scopes or custom endpoints.

NameTypeDescription
config (required)OAuthConfig

OAuth settings from OAuthConfig.builder().

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • setOAuthConfig does not check the settings when you call it.
  • build() throws IllegalArgumentException if the config has no app ID, client ID or redirect URI, or the redirect URI is not a valid URL. The OAuth flow needs all three.
  • Passing null removes OAuth settings from an earlier setOAuth or setOAuthConfig call. The client then uses no OAuth.

Behavior

  • Client-side only. build() creates the OAuth handler from the config.
  • setOAuthConfig does not apply the callback from setTokenCallback. Set the callback on the config with OAuthConfig.builder().tokenCallback(...) instead.
  • setOAuthConfig does not run the host check of setHost on the config's host. A host outside contentstack.com and contentstack.io makes the OAuth flow use the North America hosts.
  • setOAuthConfig and setOAuth set the same OAuth settings. The later call wins.

Example

Basic usage: OAuth in the Europe region with a token callback

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthConfig;
import com.contentstack.cms.models.OAuthTokens;
import com.contentstack.cms.oauth.TokenCallback;

public class BuildClientFromOAuthConfig {
    public static void main(String[] args) {
        TokenCallback callback = new TokenCallback() {
            @Override
            public void onTokensUpdated(OAuthTokens tokens) {
                System.out.println("New tokens, expiring at " + tokens.getExpiresAt());
            }

            @Override
            public void onTokensCleared() {
                System.out.println("Tokens cleared");
            }
        };

        OAuthConfig config = OAuthConfig.builder()
                .appId("<APP_ID>")
                .clientId("<CLIENT_ID>")
                .redirectUri("<REDIRECT_URI>")
                .host("eu-api.contentstack.com")
                .tokenCallback(callback)
                .build();

        try {
            Contentstack client = new Contentstack.Builder()
                    .setRegion("eu")
                    .setOAuthConfig(config)
                    .build();
            System.out.println(client.getOAuthAuthorizationUrl());
        } catch (IllegalArgumentException e) {
            // Thrown by build() when the config lacks an app ID, client ID or valid redirect URI
            System.out.println("Invalid OAuth settings: " + e.getMessage());
        }
    }
}

setPort

setPort stores a port number on the builder. The client does not use the stored value.

NameTypeDescription
port (required)String

Port number, default "443".

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • There is no client-side validation. setPort accepts any value, including null.

Behavior

  • setPort has no effect on requests. build() creates the base URL from https://, the host and the API version only, so the stored port never reaches a request.
  • To send requests to another port, put the port in the host: setHost("<host>:<port>"). See the setHost method.

Example

Basic usage: set a port through the host

import com.contentstack.cms.Contentstack;

public class UsePortInHost {
    public static void main(String[] args) {
        // setPort("8443") would not change the base URL. Put the port in the host instead.
        Contentstack client = new Contentstack.Builder()
                .setHost("api.contentstack.io:8443")
                .build();
        System.out.println(client.getBaseUrl());
    }
}

setProtocols

setProtocols limits the HTTP versions the client may use, for example to force HTTP/1.1 when a proxy or gateway mishandles HTTP/2.

NameTypeDescription
protocols (required)List<Protocol>

okhttp3.Protocol values the client may use.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • setProtocols does not check the list.
  • build() passes the list to the HTTP client, which throws IllegalArgumentException when the list breaks its rules. For example, the list must contain Protocol.HTTP_1_1, unless it holds only Protocol.H2_PRIOR_KNOWLEDGE.

Behavior

  • Client-side only. Without setProtocols, the HTTP client uses HTTP/2 when the server supports it, and HTTP/1.1 otherwise.
  • build() ignores a null or empty list and keeps the default.
  • The setting applies to every request from the client.

Example

Basic usage: force HTTP/1.1

import com.contentstack.cms.Contentstack;
import okhttp3.Protocol;

import java.util.Collections;

public class ForceHttp11 {
    public static void main(String[] args) {
        Contentstack client = new Contentstack.Builder()
                .setProtocols(Collections.singletonList(Protocol.HTTP_1_1))
                .build();
        System.out.println("Client ready: " + client.getBaseUrl());
    }
}

setProxy

setProxy sends every request of the client through a proxy server, for networks that allow outbound traffic only through one.

NameTypeDescription
proxy (required)Proxy

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

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • There is no client-side validation. A proxy that the client cannot reach surfaces as an IOException from execute().
  • Passing null restores the default, which uses the system proxy settings.

Behavior

  • Client-side only. build() gives the proxy to the HTTP client, so every request from the client uses it, including Open Authorization (OAuth) token requests.
  • Without setProxy, the HTTP client uses the default proxy selector of the Java Virtual Machine (JVM), which reads system properties such as https.proxyHost.
  • setProxy does not set proxy credentials.
  • refreshRegions does not use this proxy.

Example

Basic usage: send requests through an HTTP proxy

import com.contentstack.cms.Contentstack;

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

public class UseHttpProxy {
    public static void main(String[] args) {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080));

        Contentstack client = new Contentstack.Builder()
                .setProxy(proxy)
                .build();
        System.out.println("Client ready: " + client.getBaseUrl());
    }
}

setReadTimeout

setReadTimeout sets the time the client waits for data from the API after it sends a request, in seconds, and leaves the other two timeouts unchanged.

NameTypeDescription
readTimeoutSeconds (required)int

Read timeout in seconds.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • setReadTimeout throws IllegalArgumentException if readTimeoutSeconds is 0 or less, because a request needs a positive time limit.

Behavior

  • Client-side only. Without setReadTimeout, the read timeout is the value of setTimeout, default 30 seconds.
  • setReadTimeout wins over setTimeout in any call order.
  • Use it for requests whose response takes long, such as a large export.
  • A request that times out throws SocketTimeoutException, an IOException, from execute(), after the SDK retries.

Example

Basic usage: raise the read timeout only

import com.contentstack.cms.Contentstack;

public class SetReadTimeout {
    public static void main(String[] args) {
        Contentstack client = new Contentstack.Builder()
                .setTimeout(30)
                .setReadTimeout(120)
                .build();
        System.out.println("Client ready: " + client.getBaseUrl());
    }
}

setRegion

setRegion sets the API host from a Contentstack region ID, so the client sends requests to the Content Management API host of that region.

NameTypeDescription
region (required)String

Region ID or alias, such as "eu".

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • setRegion throws IllegalArgumentException if region is null, empty or only spaces, or matches no region ID or alias, because it cannot pick a host.
  • It throws RuntimeException only when the SDK jar has no bundled region registry and the download fails.

Behavior

  • setRegion looks up the contentManagement endpoint of the region in the region registry and stores its host. It is the same lookup as getContentstackEndpoint with omitHttps set to true.
  • The region IDs are na (aliases us and aws-na), eu (aws-eu), au (aws-au), azure-na, azure-eu, gcp-na and gcp-eu. Matching ignores case and treats _ and - as the same character.
  • For example, setRegion("eu") sets the host eu-api.contentstack.com.
  • setRegion and setHost set the same value. The later call wins.
  • The three-argument setOAuth overload reads the host when you call it. Call setRegion before it.

Example

Basic usage: build a client for the Azure North America region

import com.contentstack.cms.Contentstack;

public class UseAzureRegion {
    public static void main(String[] args) {
        try {
            Contentstack client = new Contentstack.Builder()
                    .setRegion("azure-na")
                    .build();
            System.out.println("Host: " + client.getHost());
        } catch (IllegalArgumentException e) {
            // Thrown for an empty or unknown region
            System.out.println("Unknown region: " + e.getMessage());
        }
    }
}

setRetry

setRetry turns the HTTP client's own retry after a connection failure on or off. It does not change the SDK retry of failed requests.

NameTypeDescription
retry (required)Boolean

true retries after a connection failure, default true.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • setRetry accepts null, but build() then throws NullPointerException, because the HTTP client needs a true or false value.

Behavior

  • Client-side only. setRetry sets the retryOnConnectionFailure option of the OkHttp client, default true.
  • With true, the HTTP client tries again when a connection fails, for example after it reuses a pooled connection that the server already closed. It also tries another IP address of the host when one is available.
  • setRetry does not turn the SDK retry on or off. The SDK still retries status 408, 429, 500, 502, 503 and 504, and timeouts. To change that, use the setRetryConfig method.

Example

Basic usage: turn off the connection retry

import com.contentstack.cms.Contentstack;

public class TurnConnectionRetryOff {
    public static void main(String[] args) {
        Contentstack client = new Contentstack.Builder()
                .setRetry(false)
                .build();
        System.out.println("Client ready: " + client.getBaseUrl());
    }
}

setRetryConfig

setRetryConfig sets the SDK retry behavior for a failed request: the number of retries, the wait between attempts, and the failures to retry.

NameTypeDescription
retryConfig (required)RetryConfig

Retry limit, delay and condition for every request.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • There is no client-side validation in setRetryConfig. RetryConfig.Builder checks its own values. See the RetryConfig class.
  • Passing null makes the client retry with the default settings. getRetryConfig then returns null.

Behavior

  • Client-side only. Without setRetryConfig, the client uses RetryConfig.defaultConfig(): up to 3 retries, 300 milliseconds apart.
  • By default, the SDK retries a request that fails with status 408, 429, 500, 502, 503 or 504, or that times out.
  • A retry limit of 0 turns the SDK retry off.
  • The SDK waits between attempts on the thread that called execute(), so a retried request blocks that thread for the whole delay.
  • The setting applies to clients with and without Open Authorization (OAuth).
  • setRetryConfig is separate from setRetry, which controls a lower-level retry of the HTTP client after a connection failure.

Example

Basic usage: retry up to 5 times, 1 second apart

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.core.RetryConfig;

public class RetryFiveTimes {
    public static void main(String[] args) {
        RetryConfig retryConfig = RetryConfig.builder()
                .retryLimit(5)
                .retryDelay(1000)
                .build();

        Contentstack client = new Contentstack.Builder()
                .setRetryConfig(retryConfig)
                .build();
        System.out.println("Retry limit: " + client.getRetryConfig().getRetryLimit());
    }
}

Turn the SDK retry off

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.core.RetryConfig;

public class TurnRetryOff {
    public static void main(String[] args) {
        Contentstack client = new Contentstack.Builder()
                .setRetryConfig(RetryConfig.builder().retryLimit(0).build())
                .build();
        System.out.println("Retry limit: " + client.getRetryConfig().getRetryLimit());
    }
}

setSerializeNulls

setSerializeNulls controls whether request bodies keep keys whose value is null. Turn it on to send a null field value to the API, for example to clear a field when you update or localize an entry.

NameTypeDescription
serializeNulls (required)boolean

true keeps null values in request bodies, default false.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • There is no client-side validation.

Behavior

  • Client-side only. build() configures the JSON converter of the client with this setting.
  • With the default false, the SDK drops every key whose value is null from a request body. The API never sees the key.
  • With true, the SDK sends such a key as "key": null.
  • The setting applies to every request body of the client, in every class. The SDK added it in version 1.15.0.

Note With setSerializeNulls(true), every key that your code sets to null reaches the API, in every request, including updates. To leave a field unchanged, leave its key out of the body instead of setting it to null.

Example

Basic usage: send a null field value in an entry update

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.stack.Entry;
import okhttp3.ResponseBody;
import org.json.simple.JSONObject;
import retrofit2.Response;

import java.io.IOException;

public class SendNullFieldValue {
    public static void main(String[] args) throws IOException {
        Contentstack client = new Contentstack.Builder()
                .setSerializeNulls(true)
                .build();
        Entry entry = client.stack("<API_KEY>", "<MANAGEMENT_TOKEN>")
                .contentType("<CONTENT_TYPE_UID>")
                .entry("<ENTRY_UID>");

        JSONObject fields = new JSONObject();
        fields.put("title", "Spring sale");
        fields.put("price", null); // sent as "price": null
        JSONObject body = new JSONObject();
        body.put("entry", fields);

        Response<ResponseBody> response = entry.update(body).execute();
        if (!response.isSuccessful()) {
            // The API rejected the request. The body holds error_message, error_code and errors.
            System.out.println("Request failed: " + response.code() + " " + response.errorBody().string());
            return;
        }
        System.out.println(response.body().string());
    }
}

setTimeout

setTimeout sets the connect, read and write timeouts of every request, in seconds.

NameTypeDescription
timeout (required)int

Timeout in seconds, default 30.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • setTimeout throws IllegalArgumentException if timeout is 0 or less, because a request needs a positive time limit.

Behavior

  • Client-side only. setTimeout replaces the default of 30 seconds for three phases of a request: connecting, reading the response, and writing the request body.
  • setConnectTimeout, setReadTimeout and setWriteTimeout override one phase each. They win over setTimeout in any call order.
  • A request that times out throws SocketTimeoutException, an IOException, from execute(). The SDK retries a timed-out request first. See the setRetryConfig method.

Example

Basic usage: allow 60 seconds for slow requests

import com.contentstack.cms.Contentstack;

public class SetLongerTimeout {
    public static void main(String[] args) {
        Contentstack client = new Contentstack.Builder()
                .setTimeout(60)
                .build();
        System.out.println("Client ready: " + client.getBaseUrl());
    }
}

Error handling: catch a timeout of zero

import com.contentstack.cms.Contentstack;

public class CatchZeroTimeout {
    public static void main(String[] args) {
        try {
            new Contentstack.Builder().setTimeout(0);
        } catch (IllegalArgumentException e) {
            // Thrown because the timeout must be positive
            System.out.println("Invalid timeout: " + e.getMessage());
        }
    }
}

setTokenCallback

setTokenCallback sets the object that receives new Open Authorization (OAuth) tokens, so that your application can save them, for example to a database.

NameTypeDescription
callback (required)TokenCallback

Receiver of OAuth token updates.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • There is no client-side validation. Passing null removes a callback for a later setOAuth call.

Behavior

  • Client-side only. setTokenCallback stores the callback on the builder.
  • Only a later setOAuth call reads it. Call setTokenCallback before setOAuth. setOAuthConfig ignores it, so set the callback on the OAuthConfig instead.
  • The SDK calls onTokensUpdated after each successful code exchange and token refresh. No code path in 1.16.0 calls onTokensCleared. See TokenCallback on the Contentstack.Builder class page.

Example

Basic usage: save new tokens

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.models.OAuthTokens;
import com.contentstack.cms.oauth.TokenCallback;

public class SaveTokensOnUpdate {
    public static void main(String[] args) {
        TokenCallback callback = new TokenCallback() {
            @Override
            public void onTokensUpdated(OAuthTokens tokens) {
                // Runs on the thread of the token request. Save the tokens here.
                System.out.println("Save tokens for user " + tokens.getUserUid());
            }

            @Override
            public void onTokensCleared() {
                System.out.println("Delete the saved tokens");
            }
        };

        Contentstack client = new Contentstack.Builder()
                .setTokenCallback(callback)
                .setOAuth("<APP_ID>", "<CLIENT_ID>", "<REDIRECT_URI>")
                .build();
        System.out.println(client.getOAuthAuthorizationUrl());
    }
}

setVersion

setVersion sets the API version segment of the base URL that the client puts in front of every request path.

NameTypeDescription
version (required)String

API version path segment, default v3.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • There is no client-side validation. setVersion accepts any value. A null value puts the text null in the base URL.
  • A version that the API does not serve surfaces as an API error when you call execute() on a request.

Behavior

  • Client-side only. setVersion replaces the default v3.
  • The client builds the base URL https://<host>/<version>/. getBaseUrl returns it.
  • Every request path in the SDK targets the version 3 API. Keep the default unless you route requests through a proxy that expects another path.

Example

Basic usage: set the version explicitly

import com.contentstack.cms.Contentstack;

public class SetApiVersion {
    public static void main(String[] args) {
        Contentstack client = new Contentstack.Builder()
                .setVersion("v3")
                .build();
        System.out.println(client.getBaseUrl());
    }
}

setWriteTimeout

setWriteTimeout sets the time the client waits while it sends the request body, in seconds, and leaves the other two timeouts unchanged.

NameTypeDescription
writeTimeoutSeconds (required)int

Write timeout in seconds.

Default: Not applicable

Returns: Contentstack.Builder. The same builder, for chaining.

Validation

  • setWriteTimeout throws IllegalArgumentException if writeTimeoutSeconds is 0 or less, because a request needs a positive time limit.

Behavior

  • Client-side only. Without setWriteTimeout, the write timeout is the value of setTimeout, default 30 seconds.
  • setWriteTimeout wins over setTimeout in any call order.
  • Use it for large uploads, such as assets.
  • A request that times out throws SocketTimeoutException, an IOException, from execute(), after the SDK retries.

Example

Basic usage: raise the write timeout only

import com.contentstack.cms.Contentstack;

public class SetWriteTimeout {
    public static void main(String[] args) {
        Contentstack client = new Contentstack.Builder()
                .setTimeout(30)
                .setWriteTimeout(120)
                .build();
        System.out.println("Client ready: " + client.getBaseUrl());
    }
}