Java SDK reference
This documentation applies to the v8.x version of the ConfigCat Java SDK. For the documentation of the latest release, please refer to this page.
Getting Started
1. Add the ConfigCat SDK to your project
- Gradle
- Maven
dependencies {
implementation 'com.configcat:configcat-java-client:8.+'
}
<dependency>
<groupId>com.configcat</groupId>
<artifactId>configcat-java-client</artifactId>
<version>[8.0.0,)</version>
</dependency>
2. Import the ConfigCat SDK
import com.configcat.*;
3. Create and get the ConfigCat client for your SDK Key
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#");
4. Get your setting value
boolean isMyAwesomeFeatureEnabled = client.getValue(Boolean.class, "isMyAwesomeFeatureEnabled", false);
if (isMyAwesomeFeatureEnabled) {
doTheNewThing();
} else {
doTheOldThing();
}
5. Stop ConfigCat client
You can safely shut down the client instance and release all associated resources on application exit.
client.close();
You can close all singleton client instances and release all associated resources on application exit.
ConfigCatClient.closeAll();
Java compatibility
The ConfigCat Java SDK is compatible with Java 8 and higher.
Creating the ConfigCat Client
ConfigCat Client is responsible for:
- managing the communication between your application and ConfigCat servers.
- caching your setting values and feature flags.
- serving values quickly in a failsafe way.
ConfigCatClient.get(<sdkKey>)
returns a client with default options.
Customizing the ConfigCat Client
To customize the SDK's behavior, you can pass an additional Consumer<Options>
parameter to the get()
static
factory method where the Options
class is used to set up the ConfigCat Client.
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#", options -> {
options.pollingMode(PollingModes.autoPoll());
options.logLevel(LogLevel.INFO);
});
These are the available options on the Options
class:
Option | Description |
---|---|
dataGovernance(DataGovernance) | Optional, defaults to Global . Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. More about Data Governance. Available options: Global , EuOnly . |
baseUrl(string) | Optional, sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the configurations. |
httpClient(OkHttpClient) | Optional, sets the underlying OkHttpClient used to download the feature flags and settings over HTTP. More about the HTTP Client. |
cache(ConfigCache) | Optional, sets a custom cache implementation for the client. More about cache. |
pollingMode(PollingMode) | Optional, sets the polling mode for the client. More about polling modes. |
logLevel(LogLevel) | Optional, defaults to WARNING . Sets the internal log level. More about logging. |
flagOverrides(OverrideDataSourceBuilder, OverrideBehaviour) | Optional, sets the local feature flag & setting overrides. More about feature flag overrides. |
defaultUser(User) | Optional, sets default user. More about default user. |
offline(boolean) | Optional, defaults to false . Indicates whether the SDK should be initialized in offline mode. More about offline mode. |
hooks() | Optional, used to subscribe events that the SDK sends in specific scenarios. More about hooks. |
We strongly recommend you to use the ConfigCatClient
as a Singleton object in your application.
The ConfigCatClient.get("#YOUR-SDK-KEY#")
static factory method constructs singleton client instances for your SDK keys.
These clients can be closed all at once with the ConfigCatClient.closeAll()
method or individually with client.close()
.
Anatomy of getValue()
Parameters | Description |
---|---|
classOfT | REQUIRED. The type of the setting. |
key | REQUIRED. Setting-specific key. Set on ConfigCat Dashboard for each setting. |
user | Optional, User Object. Essential when using Targeting. Read more about Targeting. |
defaultValue | REQUIRED. This value will be returned in case of an error. |
boolean value = client.getValue(
Boolean.class, // Setting type
"keyOfMySetting", // Setting Key
User.newBuilder().build("#UNIQUE-USER-IDENTIFIER#"), // Optional User Object
false // Default value
);
It is important to provide an argument for the classOfT
parameter, specifically for the T
generic type parameter,
that matches the type of the feature flag or setting you are evaluating. Please refer to the following table for the corresponding types.
Setting type mapping
Setting Kind | Type parameter T |
---|---|
On/Off Toggle | boolean / Boolean |
Text | String |
Whole Number | int / Integer |
Decimal Number | double / Double |
It's important to note that providing any other type for the type parameter will result in an IllegalArgumentException
.
If you specify an allowed type but it mismatches the setting kind, an error message will be logged and defaultValue
will be returned.
Anatomy of getValueAsync()
Parameters | Description |
---|---|
classOfT | REQUIRED. The type of the setting. |
key | REQUIRED. Setting-specific key. Set on ConfigCat Dashboard for each setting. |
user | Optional, User Object. Essential when using Targeting. Read more about Targeting. |
defaultValue | REQUIRED. This value will be returned in case of an error. |
client.getValueAsync(
Boolean.class, // Setting type
"keyOfMySetting", // Setting Key
User.newBuilder().build("#UNIQUE-USER-IDENTIFIER#"), // Optional User Object
false // Default value
).thenAccept(isMyAwesomeFeatureEnabled -> {
if (isMyAwesomeFeatureEnabled) {
doTheNewThing();
} else {
doTheOldThing();
}
});
It is important to provide an argument for the classOfT
parameter, specifically for the T
generic type parameter,
that matches the type of the feature flag or setting you are evaluating. Please refer to this table for the corresponding types.
Anatomy of getValueDetails()
getValueDetails()
is similar to getValue()
but instead of returning the evaluated value only, it gives more detailed information about the evaluation result.
Parameters | Description |
---|---|
classOfT | REQUIRED. The type of the setting. |
key | REQUIRED. Setting-specific key. Set on ConfigCat Dashboard for each setting. |
user | Optional, User Object. Essential when using Targeting. Read more about Targeting. |
defaultValue | REQUIRED. This value will be returned in case of an error. |
EvaluationDetails<Boolean> details = client.getValueDetails(
Boolean.class, // Setting type
"keyOfMySetting", // Setting Key
User.newBuilder().build("#UNIQUE-USER-IDENTIFIER#"), // Optional User Object
false // Default value
);
// Or asynchronously
client.getValueDetailsAsync(
Boolean.class, // Setting type
"keyOfMySetting", // Setting Key
User.newBuilder().build("#UNIQUE-USER-IDENTIFIER#"), // Optional User Object
false // Default value
).thenAccept(details -> {
// Use the details result
});
It is important to provide an argument for the classOfT
parameter, specifically for the T
generic type parameter,
that matches the type of the feature flag or setting you are evaluating. Please refer to this table for the corresponding types.
The details result contains the following information:
Property | Type | Description |
---|---|---|
getValue() | boolean / String / int / double | The evaluated value of the feature flag or setting. |
getKey() | String | The key of the evaluated feature flag or setting. |
isDefaultValue() | boolean | True when the default value passed to getValueDetails() is returned due to an error. |
getError() | String | In case of an error, this field contains the error message. |
getUser() | User | The User Object that was used for evaluation. |
getMatchedEvaluationPercentageRule() | PercentageRule | If the evaluation was based on a Percentage Rule, this field contains that specific rule. |
getMatchedEvaluationRule() | RolloutRule | If the evaluation was based on a Targeting Rule, this field contains that specific rule. |
getFetchTimeUnixMilliseconds() | long | The last download time of the current config in unix milliseconds format. |
User Object
The User Object is essential if you'd like to use ConfigCat's Targeting feature.
User user = User.newBuilder().build("#UNIQUE-USER-IDENTIFIER#");
User user = User.newBuilder().build("[email protected]");
Builder options | Description |
---|---|
identifier() | REQUIRED. Unique identifier of a user in your application. Can be any value, even an email address. |
email() | Optional parameter for easier Targeting Rule definitions. |
country() | Optional parameter for easier Targeting Rule definitions. |
custom() | Optional dictionary for custom attributes of a user for advanced Targeting Rule definitions. e.g. User role, Subscription type. |
java.util.Map<String,String> customAttributes = new java.util.HashMap<String,String>();
customAttributes.put("SubscriptionType", "Pro");
customAttributes.put("UserRole", "Admin");
User user = User.newBuilder()
.email("[email protected]")
.country("United Kingdom")
.custom(customAttributes)
.build("#UNIQUE-USER-IDENTIFIER#");
Default User
There's an option to set a default User Object that will be used at feature flag and setting evaluation. It can be useful when your application has a single user only, or rarely switches users.
You can set the default User Object either with the ConfigCatClient builder:
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#", options -> {
options.mode(PollingModes.manualPoll());
options.baseUrl(server.url("/").toString());
options.defaultUser(User.newBuilder().build("[email protected]"));
});
or with the setDefaultUser()
method of the ConfigCat client.
client.setDefaultUser(User.newBuilder().build("[email protected]"));
Whenever the getValue()
, getValueDetails()
, getAllValues()
, or getAllValueDetails()
methods are called without an explicit user
parameter, the SDK will automatically use the default user as a User Object.
client.setDefaultUser(User.newBuilder().build("[email protected]"));
// The default user will be used at the evaluation process.
boolean value = client.getValue(Boolean.class, "keyOfMySetting", false);
When the user
parameter is specified on the requesting method, it takes precedence over the default user.
client.setDefaultUser(User.newBuilder().build("[email protected]"));
User otherUser = User.newBuilder().build("user");
// otherUser will be used at the evaluation process.
boolean value = client.getValue(Boolean.class, "keyOfMySetting", false, otherUser);
For deleting the default user, you can do the following:
client.clearDefaultUser();
Polling Modes
The ConfigCat SDK supports 3 different polling mechanisms to acquire the setting values from ConfigCat. After latest setting values are downloaded, they are stored in the internal cache, then all getValue()
calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle.
More about polling modes.
Auto polling (default)
The ConfigCat SDK downloads the latest values and stores them automatically every 60 seconds.
Use the the autoPollIntervalInSeconds
option parameter of the PollingModes.autoPoll()
to change the polling interval.
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#", options -> {
options.pollingMode(PollingModes.autoPoll(60 /* polling interval in seconds */));
});
Available options:
Option Parameter | Description | Default |
---|---|---|
autoPollIntervalInSeconds | Polling interval. | 60 |
maxInitWaitTimeSeconds | Maximum waiting time between the client initialization and the first config acquisition in seconds. | 5 |
Lazy Loading
When calling getValue()
, the ConfigCat SDK downloads the latest setting values if they are not present or expired in the cache. In this case getValue()
will return the setting value after the cache is updated.
Use the cacheRefreshIntervalInSeconds
option parameter of the PollingModes.lazyLoad()
to set cache lifetime.
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#", options -> {
options.pollingMode(PollingModes.lazyLoad(60 /* the cache will expire in 120 seconds */));
});
If you set the asyncRefresh
to false
, the refresh operation will be awaited until the downloading of the new configuration is completed.
Available options:
Option Parameter | Description | Default |
---|---|---|
cacheRefreshIntervalInSeconds | Cache TTL. | 60 |
Manual Polling
Manual polling gives you full control over when the config JSON
(with the setting values) is downloaded. ConfigCat SDK will not update them automatically. Calling forceRefresh()
is your application's responsibility.
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#", options ->{
options.pollingMode(PollingModes.manualPoll());
});
client.forceRefresh();
getValue()
returnsdefaultValue
if the cache is empty. CallforceRefresh()
to update the cache.
Hooks
With the following hooks you can subscribe to particular events fired by the SDK:
-
onClientReady()
: This event is sent when the SDK reaches the ready state. If the SDK is configured with lazy load or manual polling it's considered ready right after instantiation. If it's using auto polling, the ready state is reached when the SDK has a valid config JSON loaded into memory either from cache or from HTTP. If the config couldn't be loaded neither from cache nor from HTTP theonClientReady
event fires when the auto polling'smaxInitWaitTimeSeconds
is reached. -
onConfigChanged(Map<String, Setting>)
: This event is sent when the SDK loads a valid config JSON into memory from cache, and each subsequent time when the loaded config JSON changes via HTTP. -
onFlagEvaluated(EvaluationDetails)
: This event is sent each time when the SDK evaluates a feature flag or setting. The event sends the same evaluation details that you would get fromgetValueDetails()
. -
onError(String)
: This event is sent when an error occurs within the ConfigCat SDK.
You can subscribe to these events either on SDK initialization:
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#", options -> {
options.hooks().addOnFlagEvaluated(details -> {
/* handle the event */
});
});
or with the getHooks()
property of the ConfigCat client:
client.getHooks().addOnFlagEvaluated(details -> {
/* handle the event */
});
Online / Offline mode
In cases when you'd want to prevent the SDK from making HTTP calls, you can put it in offline mode:
client.setOffline();
In offline mode, the SDK won't initiate HTTP requests and will work only from its cache.
To put the SDK back in online mode, you can do the following:
client.setOnline();
With
client.isOffline()
you can check whether the SDK is in offline mode.
Flag Overrides
With flag overrides you can overwrite the feature flags & settings downloaded from the ConfigCat CDN with local values. Moreover, you can specify how the overrides should apply over the downloaded values. The following 3 behaviours are supported:
-
Local only (
OverrideBehaviour.LOCAL_ONLY
): When evaluating values, the SDK will not use feature flags & settings from the ConfigCat CDN, but it will use all feature flags & settings that are loaded from local-override sources. -
Local over remote (
OverrideBehaviour.LOCAL_OVER_REMOTE
): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the local-override version will take precedence. -
Remote over local (
OverrideBehaviour.REMOTE_OVER_LOCAL
): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the downloaded version will take precedence.
You can load your feature flag & setting overrides from a file or from a simple Map<String, Object>
structure.
JSON File
The SDK can load your feature flag & setting overrides from a file or classpath resource. You can also specify whether the file should be reloaded when it gets modified.
File
ConfigCatClient client = ConfigCatClient.get("localhost", options -> {
options.flagOverrides(OverrideDataSourceBuilder.localFile(
"path/to/the/local_flags.json", // path to the file
true // reload the file when it gets modified
),
OverrideBehaviour.LOCAL_ONLY
);
});
Classpath Resource
ConfigCatClient client = ConfigCatClient.get("localhost", options -> {
options.flagOverrides(OverrideDataSourceBuilder.classPathResource(
"local_flags.json", // name of the resource
true // reload the resource when it gets modified
),
OverrideBehaviour.LOCAL_ONLY
);
});
JSON File Structure
The SDK supports 2 types of JSON structures to describe feature flags & settings.
1. Simple (key-value) structure
{
"flags": {
"enabledFeature": true,
"disabledFeature": false,
"intSetting": 5,
"doubleSetting": 3.14,
"stringSetting": "test"
}
}
2. Complex (full-featured) structure
This is the same format that the SDK downloads from the ConfigCat CDN. It allows the usage of all features that are available on the ConfigCat Dashboard.
You can download your current config JSON from ConfigCat's CDN and use it as a baseline.
The URL to your current config JSON is based on your Data Governance settings:
- GLOBAL:
https://cdn-global.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v5.json
- EU:
https://cdn-eu.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v5.json
{
"f": {
// list of feature flags & settings
"isFeatureEnabled": {
// key of a particular flag
"v": false, // default value, served when no rules are defined
"i": "430bded3", // variation id (for analytical purposes)
"t": 0, // feature flag's type, possible values:
// 0 -> BOOLEAN
// 1 -> STRING
// 2 -> INT
// 3 -> DOUBLE
"p": [
// list of Percentage Rules
{
"o": 0, // rule's order
"v": true, // value served when the rule is selected during evaluation
"p": 10, // % value
"i": "bcfb84a7" // variation id (for analytical purposes)
},
{
"o": 1, // rule's order
"v": false, // value served when the rule is selected during evaluation
"p": 90, // % value
"i": "bddac6ae" // variation id (for analytical purposes)
}
],
"r": [
// list of Targeting Rules
{
"o": 0, // rule's order
"a": "Identifier", // comparison attribute
"t": 2, // comparator, possible values:
// 0 -> 'IS ONE OF',
// 1 -> 'IS NOT ONE OF',
// 2 -> 'CONTAINS',
// 3 -> 'DOES NOT CONTAIN',
// 4 -> 'IS ONE OF (SemVer)',
// 5 -> 'IS NOT ONE OF (SemVer)',
// 6 -> '< (SemVer)',
// 7 -> '<= (SemVer)',
// 8 -> '> (SemVer)',
// 9 -> '>= (SemVer)',
// 10 -> '= (Number)',
// 11 -> '<> (Number)',
// 12 -> '< (Number)',
// 13 -> '<= (Number)',
// 14 -> '> (Number)',
// 15 -> '>= (Number)',
// 16 -> 'IS ONE OF (Hashed)',
// 17 -> 'IS NOT ONE OF (Hashed)'
"c": "@example.com", // comparison value
"v": true, // value served when the rule is selected during evaluation
"i": "bcfb84a7" // variation id (for analytical purposes)
}
]
}
}
}
Map
You can set up the SDK to load your feature flag & setting overrides from a Map<String, Object>
.
Map<String, Object> map = new HashMap<>();
map.put("enabledFeature", true);
map.put("disabledFeature", false);
map.put("intSetting", 5);
map.put("doubleSetting", 3.14);
map.put("stringSetting", "test");
ConfigCatClient client = ConfigCatClient.get("localhost", options -> {
options.flagOverrides(OverrideDataSourceBuilder.map(map), OverrideBehaviour.LOCAL_ONLY)
});
getAllKeys()
, getAllKeysAsync()
You can query the keys of each feature flag and setting with the getAllKeys()
or getAllKeysAsync()
method.
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#");
java.util.Collection<String> keys = client.getAllKeys();
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#");
client.getAllKeysAsync().thenAccept(keys -> {
});
getAllValues()
, getAllValuesAsync()
Evaluates and returns the values of all feature flags and settings. Passing a User Object is optional.
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#");
Map<String, Object> settingValues = client.getAllValues();
// invoke with User Object
User user = User.newBuilder().build("#UNIQUE-USER-IDENTIFIER#")
Map<String, Object> settingValuesTargeting = client.getAllValues(user);
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#");
client.getAllValuesAsync().thenAccept(settingValues -> { });
// invoke with User Object
User user = User.newBuilder().build("#UNIQUE-USER-IDENTIFIER#")
client.getAllValuesAsync(user).thenAccept(settingValuesTargeting -> { });
getAllValueDetails()
, getAllValueDetailsAsync()
Evaluates and returns the detailed values of all feature flags and settings. Passing a User Object is optional.
User user = User.newBuilder().build("#UNIQUE-USER-IDENTIFIER#");
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#");
List<EvaluationDetails<Object>> allValueDetails = client.getAllValueDetails(user);
User user = User.newBuilder().build("#UNIQUE-USER-IDENTIFIER#");
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#");
client.getAllValueDetailsAsync(user).thenAccept(allValueDetails -> { });
Custom Cache
The ConfigCat SDK stores the downloaded config data in a local cache to minimize network traffic and enhance client performance.
If you prefer to use your own cache solution, such as an external or distributed cache in your system,
you can subclass the ConfigCache
abstract class
and call the cache
method with your implementation in the setup callback of ConfigCatClient.get
.
This allows you to seamlessly integrate ConfigCat with your existing caching infrastructure.
public class MyCustomCache extends ConfigCache {
@Override
public String read(String key) {
// here you have to return with the cached value
}
@Override
public void write(String key, String value) {
// here you have to store the new value in the cache
}
}
Then use your custom cache implementation:
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#", options -> {
options.cache(new MyCustomCache()) // inject your custom cache
});
The Java SDK supports shared caching. You can read more about this feature and the required minimum SDK versions here.
HttpClient
The ConfigCat SDK internally uses an OkHttpClient instance to download the latest configuration over HTTP. You have the option to override the internal Http client with your customized one.
HTTP Proxy
If your application runs behind a proxy you can do the following:
import java.net.InetSocketAddress;
import java.net.Proxy;
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyHost", proxyPort));
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#", options -> {
options.httpClient(new OkHttpClient.Builder()
.proxy(proxy)
.build())
});
HTTP Timeout
You can set the maximum wait time for a ConfigCat HTTP response by using OkHttpClient's timeouts.
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#", options -> {
options.httpClient(new OkHttpClient.Builder()
.readTimeout(2, TimeUnit.SECONDS) // set the read timeout to 2 seconds
.build())
});
OkHttpClient's default timeout is 10 seconds.
As the ConfigCatClient SDK maintains the whole lifetime of the internal http client, it's being closed simultaneously with the ConfigCatClient, refrain from closing the http client manually.
Force refresh
Call the forceRefresh()
method on the client to download the latest config JSON and update the cache.
Logging
As the SDK uses the facade of slf4j for logging, so you can use any of the slf4j implementation packages.
You can change the verbosity of the logs by passing a LogLevel
parameter to the ConfigCatClientBuilder's logLevel
function.
ConfigCatClient client = ConfigCatClient.get("#YOUR-SDK-KEY#", options -> {
options.logLevel(LogLevel.INFO);
});
Available log levels:
Level | Description |
---|---|
NO_LOG | Turn the logging off. |
ERROR | Only error level events are logged. |
WARNING | Default. Errors and Warnings are logged. |
INFO | Errors, Warnings and feature flag evaluation is logged. |
DEBUG | All of the above plus debug info is logged. Debug logs can be different for other SDKs. |
Info level logging helps to inspect how a feature flag was evaluated:
INFO com.configcat.ConfigCatClient - [5000] Evaluating getValue(isPOCFeatureEnabled).
User object: User{Identifier=435170f4-8a8b-4b67-a723-505ac7cdea92, Email=[email protected]}
Evaluating rule: [Email:[email protected]] [CONTAINS] [@something.com] => no match
Evaluating rule: [Email:[email protected]] [CONTAINS] [@example.com] => match, returning "true"
Logging Implementation
You have the flexibility to use any slf4j implementation for logging with ConfigCat. However, some logger implementations may not display debug level messages by default. In these cases, you simply need to adjust the logger configuration to receive all log messages from the ConfigCat SDK.
Examples fo slf4j-simple and logback are available under the Sample Apps section.
Sample Apps
Check out our Sample Applications how they use the ConfigCat SDK
Guides
See this guide on how to use ConfigCat's Java SDK.