Skip to main content

Java SDK

With the Kameleoon Java SDK, you can run experiments and activate feature flags on your Java EE / Jakarta EE application server.

Getting started: For help getting started, see the developer guide

Changelog: Latest version of the Java SDK: 4.7.2 Changelog.

SDK methods: For the full reference documentation of the Java SDK, see the reference section.

Developer guide

This guide is designed to help you integrate our SDK in a few minutes and start running experiments in your Java applications.

Getting started

Starter kit

If you're just getting started with Kameleoon, we provide a starter kit and demo application to test the SDK and learn how it works. The starter kit includes a fully configured app with examples demonstrating how you might use the SDK methods in your app. You can find the starter kit, the demo application and detailed instructions on how to use it at Starter kit for Java

Install the Java client

The package is available from the Maven Central repository. You can install the Java SDK by adding a dependency into your project's pom.xml file, as shown in the example to the right. If you're using another project management system, see the integrations page for additional examples.

pom.xml
<dependency>
<groupId>com.kameleoon</groupId>
<artifactId>kameleoon-client-java</artifactId>
<version>4.7.1</version>
</dependency>

Additional configuration

Create a .properties configuration file to provide credentials and customize the SDK behavior. You can also download our sample configuration file.

We recommend saving this file to the default path of /etc/kameleoon/client-java.conf, but you can save it anywhere in the classpath as kameleoon-client-java.properties.

The following table shows the available properties that you can set:

KeyDescription
client_idRequired for authentication to the Kameleoon service. To find your client_id, see the API credentials documentation.
client_secretRequired for authentication to the Kameleoon service. To find your client_secret, see the API credentials documentation.
session_duration_minuteDesignates the predefined time interval that Kameleoon stores the visitor and their associated data in memory (RAM). Note that increasing the session duration increases the amount of RAM that needs to be allocated to store visitor data. The default session duration is 30 minutes.
refresh_interval_minuteSpecifies the refresh interval, in minutes, that the SDK fetches the configuration for the active experiments and feature flags. The value determines the maximum time it takes to propagate changes, such as activating or deactivating feature flags or launching experiments, to your production servers. If left unspecified, the default interval is set to 60 minutes. Additionally, we offer a streaming mode that uses server-sent events (SSE) to push new configurations to the SDK automatically and apply new configurations in real-time, without any delays.
default_timeout_millisecondSpecifies the timeout, in milliseconds, for network requests from the SDK. Set the value to 30 seconds or more if you do not have a stable connection. The default value is 10000 ms. Some methods have an additional parameter that you can use to override the default timeout for that particular method. If you do not specify the timeout for a method explicitly, the SDK uses this default value.
tracking_interval_millisecondSpecifies the interval for tracking requests, in milliseconds. All visitors who were evaluated for any feature flag or had data flushed will be included in this tracking request, which is performed once per interval. The minimum value is 100 ms and the maximum value is 1000 ms, which is also the default value.
environmentEnvironment from which a feature flag’s configuration is to be used. The value can be production, staging, development. The default environment value is production. See the managing environments article for details.
top_level_domainThe current top-level domain for your website . Use the format: example.com. Don't include https://, www, or other subdomains. Kameleoon uses this information to set the corresponding cookie on the top-level domain. This field is mandatory.
proxy_hostSets the proxy host for all outgoing server calls made by the SDK.

Initialize the Kameleoon client

After you've installed the SDK into your application and configured your credentials and SDK behavior (in /etc/kameleoon/client-java.conf), the next step is to create the Kameleoon client in your application code. For example:

import com.kameleoon.KameleoonClientFactory;

String siteCode = "a8st4f59bj";

try {
KameleoonClient kameleoonClient = KameleoonClientFactory.create(siteCode, "custom/file/path/client-java.properties");
} catch (KameleoonException.SiteCodeIsEmpty e) {
// indicates that provided site code is empty
} catch (KameleoonException.ConfigCredentialsInvalid exception) {
// indicates that provided clientId / clientSecret are not valid
}

try {
KameleoonClientConfig config = new KameleoonClientConfig.Builder()
.clientId("<clientId>") // mandatory
.clientSecret("<clientSecret>") // mandatory
.configurationRefreshInterval(60) // in minutes, optional (60 minutes by default)
.sessionDuration(30) // in minutes, optional (30 minutes by default)
.defaultTimeout(10_000) // in milliseconds, optional (10000 ms by default)
.trackingInterval(1000) // in milliseconds, optional (1000 ms by default)
.topLevelDomain("example.com") // mandatory if you use hybrid mode (engine or web experiments)
.environment("development") // optional
.proxyHost(new HttpHost("192.168.0.25", 8080, "http")) // optional
.build();
KameleoonClientFactory.create(siteCode, config);
} catch (KameleoonException.SiteCodeIsEmpty e) {
// indicates that provided site code is empty
} catch (KameleoonException.ConfigCredentialsInvalid exception) {
// indicates that provided clientId / clientSecret are not valid
}

A KameleoonClient is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you need to run an experiment. Note that we also support the use of an HTTP proxy in the Java SDK (see the create() method reference for details).

note

It's your responsibility as the app developer to ensure the proper logic of your application code within the context of A/B testing via Kameleoon. A good practice is to always assume that you can exclude the current visitor from the experiment if the experiment has not yet been launched. This is actually easy to do, because this corresponds to the implementation of the default and reference variation logic.

You're now ready to begin creating and implementing experiments and feature flagging.

Activating a feature flag

Assigning a unique ID to a user

To assign a unique ID to a user, you can use the getVisitorCode() method. If a visitor code doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a defaultVisitorCode that you would have generated. The ID is then set in a response headers cookie.

If you are using Kameleoon in Hybrid mode, calling the getVisitorCode() method ensures that the unique ID (visitor code) is shared between the application file (kameleoon.js) and the SDK.

Retrieving a flag configuration

To implement a feature flag in your code, you must first create the feature flag in your Kameleoon account.

To determine the status or variation of a feature flag for a specific user, you should use the getVariation() or isFeatureActive() method to retrieve the configuration based on the featureKey.

The getVariation() method handles both simple feature flags with ON/OFF states and more complex flags with multiple variations. The method retrieves the appropriate variation for the user by checking the feature rules, assigning the variation, and returning it based on the featureKey and visitorCode.

The isFeatureActive() method can be used if you want to retrieve the configuration of a simple feature flag that has only an ON or OFF state, as opposed to more complex feature flags with multiple variations or targeting options.

If your feature flag has associated variables (such as specific behaviors tied to each variation) getVariation() also enables you to access the Variation object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When track=true, the SDK will send the exposure event to the specified experiment on the next tracking request, which is automatically triggered based on the SDK’s tracking_interval_millisecond. By default, this interval is set to 1000 milliseconds (1 second).

The getVariation() method allows you to control whether tracking is done. If track=false, no exposure events will be sent by the SDK. This is useful if you prefer not to track data through the SDK and instead rely on client-side tracking managed by the Kameleoon engine, for example. Additionally, setting track=false is helpful when using the getVariations() method, where you might only need the variations for all flags without triggering any tracking events. If you want to know more about how tracking works, view this article

Adding data points to target a user or filter / breakdown visits in reports

To target a user, ensure you've added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use the addData() method to add these data points to the user's profile.

To retrieve data points that have been collected on other devices or to access past data points about a user (which would have been collected client-side if you are using Kameleoon in Hybrid mode), use the getRemoteVisitorData() method. This method asynchronously fetches data from our servers. However, it is important you call getRemoteVisitorData() before retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation of a feature flag.

To learn more about available targeting conditions, read our detailed article on the subject.

Additionally, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device and browser. Kameleoon Hybrid mode automatically collects a variety of data points on the client-side, making it easy to break down your results based on these pre-collected data points. See the complete list here.

If you need to track additional data points beyond what's automatically collected, you can use Kameleoon's Custom Data feature. Custom Data allows you to capture and analyze specific information relevant to your experiments. Don't forget to call the flush() method to send the collected data to Kameleoon servers for analysis.

note

To ensure your results are accurate, it's recommended to filter out bots by using the UserAgent data type.

Tracking goal conversions

When a user completes a desired action (such as making a purchase), it is recorded as a conversion. To track conversions, use the trackConversion() method and provide the required visitorCode and goalId parameters.

The conversion tracking request will be sent along with the next scheduled tracking request, which the SDK sends at regular intervals (defined by tracking_interval_millisecond). If you prefer to send the request immediately, use the flush() method with the parameter instant=true.

Sending events to analytics solutions

To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in Hybrid mode. Then, use the getEngineTrackingCode() method.

The getEngineTrackingCode() method retrieves the unique tracking code required to send exposure events to your analytics solution. Using this method allows you to record events and send them to your desired analytics platform.

Targeting conditions

The Kameleoon SDKs support a variety of predefined targeting conditions that you can use to target users in your campaigns. For the list of conditions this SDK supports, see use visit history to target users.

You can also use your own external data to target users.

Cross-device experimentation

To support visitors who access your app from multiple devices, Kameleoon allows you to synchronize previously collected visitor data across each of the visitor's devices and reconcile their visit history across devices through cross-device experimentation.

Synchronizing custom data across devices

If you want to synchronize your Custom Data across multiple devices, Kameleoon provides a custom data synchronization mechanism.

To synchronize visitor data across multiple devices, Kameleoon provides a native synchronization mechanism. To use this feature, you need to create a Kameleoon custom data and set as a value the visitor identifier that uniquely identifies this user across multiple devices (internal user ID). The custom data should be configured as follows:

  • Scope: Visitor
  • Option "Use this custom data as a unique identifier for cross-device matching" turned ON.

After the custom data is set up, calling getRemoteVisitorData() makes the latest data accessible on any device.

See the following example of data synchronization between two devices:

Device A
// In this example Custom data with index `90` was set to "Visitor" scope on Kameleoon Platform.
final int VISITOR_SCOPE_CUSTOM_DATA_INDEX = 90;

kameleoonClient.addData(visitorCode, new CustomData(VISITOR_SCOPE_CUSTOM_DATA_INDEX, "your data"));
kameleoonClient.flush(visitorCode);
Device B
// Before working with the data, call the `getRemoteVisitorData` method.
kameleoonClient.getRemoteVisitorData(visitorCode).get();

// After that the SDK on Device B will have an access to CustomData of Visitor scope defined on Device A.
// So "your data" will be available for targeting and tracking for the visitor.

Using custom data for session merging

Cross-device experimentation allows you to combine a visitor's history across each of their devices (history reconciliation). One of the powerful features that history reconciliation provides is the ability to merge different visitors sessions into one. To reconcile visit history, you can use CustomData to provide a unique identifier for the visitor.

Follow the activating cross-device history reconciliation guide to set up your custom data on the Kameleoon platform

When your custom data is set up, you can use it in your code to merge a visitor's sessions.

Sessions with the same identifier will always see the same experiment variation and will be displayed as a single visitor in the Visitor view of your experiment's result pages.

The SDK configuration ensures that associated sessions always see the same variation of the experiment.

Afterwards, you can use the SDK normally. The following methods that may be helpful in the context of session merging:

tip

As the custom data you use as the identifier must be set to Visitor scope, you need to use cross-device custom data synchronization to retrieve the identifier with the getRemoteVisitorData() method on each device.

Here's an example of how to use custom data for session merging.

// In this example, 91 represents the index of the Custom Data configured as a unique identifier on the Kameleoon Platform.
final int MAPPING_INDEX = 91;
final String FEATURE_KEY = "ff123";

// 1. Before the visitor is authenticated

// Retrieve the variation for an unauthenticated visitor.
// Assume anonymousVisitorCode is the randomly generated ID for that visitor.
Variation anonymousVariation = kameleoonClient.getVariation(anonymousVisitorCode, FEATURE_KEY);

// 2. After the visitor is authenticated

// Assume `userId` is the visitor code of the authenticated visitor.
kameleoonClient.addData(anonymousVisitorCode, new CustomData(MAPPING_INDEX, userId));
kameleoonClient.flush(true, anonymousVisitorCode);

// Indicate that `userId` is a unique identifier.
kameleoonClient.addData(userId, new UniqueIdentifier(true));

// 3. After the visitor was authorized

// Retrieve the variation for the `userId`, which will match the anonymous visitor code's variation.
Variation userVariation = kameleoonClient.getVariation(userId, FEATURE_KEY);
boolean isSameVariation = userVariation.getKey().equals(anonymousVariation.getKey()); // true

// `userId` and `anonymousVisitorCode` are now linked and can be tracked as a single visitor.
kameleoonClient.trackConversion(userId, 123, 10.0);

// Also the linked visitors share all fetched previously tracked remote data.
kameleoonClient.getRemoteVisitorData(userId).get();

In this example, we have an application with a login page. Since we don't know the user ID at the moment of login, we use an anonymous visitor identifier generated by the getVisitorCode() method. After the user logs in, we can associate the anonymous visitor with the user ID and use it as a unique identifier for the visitor.

Logging

The SDK generates logs to reflect various internal processes and issues.

Log levels

The SDK supports configuring limiting logging by a log level.

// The `NONE` log level allows no logging.
com.kameleoon.logging.KameleoonLogger.setLogLevel(com.kameleoon.logging.LogLevel.NONE);

// The `ERROR` log level allows to log only issues that may affect the SDK's main behaviour.
com.kameleoon.logging.KameleoonLogger.setLogLevel(com.kameleoon.logging.LogLevel.ERROR);

// The `WARNING` log level allows to log issues which may require an attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is a default log level.
com.kameleoon.logging.KameleoonLogger.setLogLevel(com.kameleoon.logging.LogLevel.WARNING);

// The `INFO` log level allows to log general information on the SDK's internal processes.
// It extends the `WARNING` log level.
com.kameleoon.logging.KameleoonLogger.setLogLevel(com.kameleoon.logging.LogLevel.INFO);

// The `DEBUG` log level allows to log extra information on the SDK's internal processes.
// It extends the `INFO` log level.
com.kameleoon.logging.KameleoonLogger.setLogLevel(com.kameleoon.logging.LogLevel.DEBUG);

Custom handling of logs

The SDK writes its logs to the console output by default. This behaviour can be overridden.

note

Logging limiting by a log level is performed apart from the log handling logic.

public class CustomLogger implements com.kameleoon.logging.Logger {
private final java.util.logging.Logger inner;

public CustomLogger(java.util.logging.Logger inner) {
this.inner = inner;
}

// `log` method accepts logs from the SDK
@Override
public void log(com.kameleoon.logging.LogLevel level, String message) {
// Custom log handling logic here. For example:
switch (level) {
case ERROR:
inner.log(java.util.logging.Level.SEVERE, message);
break;
case WARNING:
inner.log(java.util.logging.Level.WARNING, message);
break;
case INFO:
inner.log(java.util.logging.Level.INFO, message);
break;
case DEBUG:
inner.log(java.util.logging.Level.FINE, message);
break;
}
}
}

// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
com.kameleoon.logging.KameleoonLogger.setLogLevel(com.kameleoon.logging.LogLevel.DEBUG); // Optional, defaults to `LogLevel.WARNING`.
com.kameleoon.logging.KameleoonLogger.setLogger(new CustomLogger());

Reference

This is the full reference documentation for the Java SDK.

Initialization

create()

The starting point for using the SDK is the initialization step. Your app conducts all interactions with the SDK through an object of the KameleoonClient class. Create this object using the static method create() in KameleoonClientFactory.

Arguments
NameTypeDescription
siteCodeStringThis is a unique key of the Kameleoon project you are using with the SDK. This field is mandatory.
configurationPathStringPath to the SDK configuration file. This field is optional and set to /etc/kameleoon/client-java.conf by default.
kameleoonConfigKameleoonClientConfigConfiguration SDK object that you can pass instead of using a configuration file. This field is optional.
proxyHostHttpHostAllows your app to set an HTTP proxy for all the network calls made by the SDK. This field is optional. This field is optional. If not specified, the SDK uses a proxy specified in the configuration file. If the configuration file doesn't contain a proxy, no proxy will be used.
Return value
TypeDescription
KameleoonClientAn instance of the KameleoonClient class that your app can then use to manage your experiments and feature flags.
Exceptions thrown
TypeDescription
KameleoonException.ConfigCredentialsInvalidException indicating that the requested credentials were not provided (either in the configuration file or as arguments to the method).
KameleoonException.SiteCodeIsEmptyException indicating that the specified site code is empty string which is invalid value.
Example code
import com.kameleoon.KameleoonClientFactory;

String siteCode = "a8st4f59bj";

try {
KameleoonClient kameleoonClient = KameleoonClientFactory.create(siteCode, "custom/file/path/client-java.properties");
} catch (KameleoonException.SiteCodeIsEmpty e) {
// indicates that provided site code is empty
} catch (KameleoonException.ConfigCredentialsInvalid exception) {
// indicates that provided clientId / clientSecret are not valid
}

try {
KameleoonClientConfig config = new KameleoonClientConfig.Builder()
.clientId("<clientId>") // mandatory
.clientSecret("<clientSecret>") // mandatory
.configurationRefreshInterval(60) // in minutes, optional (60 minutes by default)
.sessionDuration(30) // in minutes, optional (30 minutes by default)
.defaultTimeout(10_000) // in milliseconds, optional (10000 ms by default)
.trackingInterval(1000) // in milliseconds, optional (1000 ms by default)
.topLevelDomain("example.com") // mandatory if you use hybrid mode (engine or web experiments)
.environment("development") // optional
.proxyHost(new HttpHost("192.168.0.25", 8080, "http")) // optional
.build();
KameleoonClientFactory.create(siteCode, config);
} catch (KameleoonException.SiteCodeIsEmpty e) {
// indicates that provided site code is empty
} catch (KameleoonException.ConfigCredentialsInvalid exception) {
// indicates that provided clientId / clientSecret are not valid
}

waitInit()

waitInit() awaits the initialization of the KameleoonClient. This method allows you to check if the client has been successfully initialized before proceeding with other operations.

note

If the waitInit() method fails, the initialization process will continue without interruption. Subsequent calls to the waitInit() method will return results that reflect the current state of the KameleoonClient. Thus, you can invoke the waitInit() method multiple times to check the status of the SDK.

Return value
TypeDescription
CompletableFuture<Void>The task will complete when the client has been successfully initialized.
Exceptions thrown
TypeDescription
SDKNotReadyException indicating that client is not initialized properly and cannot be used yet.
Example code
// Synchronized approach
try {
kameleoonClient.waitInit().get();
} catch (InterruptedException | ExecutionException exception) {
// Indicates that the client could not be initialized due to the thrown exception.
}

// Asynchronous approach
kameleeoonClient.waitInit().handle((res, ex) -> {
if (ex != null) {
// indicates that client could not be initialized due to the thrown exception.
}
return res;
});

Feature flags and variations

isFeatureActive()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)
note

This method was previously named activeFeature, which was removed in SDK version 4.0.0.

Call this method to check whether a feature flag should be active for a specified user. This method takes a visitorCode and a featureKey as mandatory arguments to check if the feature is active for the specified user.

If the user has never been associated with this feature flag, the SDK returns a random boolean value (either true to add the user to this feature or false to exclude them from the feature). If a user with the specified visitorCode is already registered with this feature flag, the SDK detects the previous featureFlagvalue.

Make sure you catch and handle potential exceptions.

If you specify a visitorCode, the isFeatureActive() method uses it as the unique visitor identifier, which is useful for Cross-device experimentation. When you specify a visitorCode and set the isUniqueIdentifier parameter to true, the SDK links the flushed data with the visitor associated with the specified identifier.

note

The parameter isUniqueIdentifier is deprecated. Please use UniqueIdentifier instead.

The isUniqueIdentifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Arguments
NameTypeDescription
trackbooleanAn optional parameter to enable or disable tracking of the feature evaluation (true by default).
visitorCodeStringUnique identifier of the user. This field is required.
featureKeyStringKey of the feature that you want to check the status of for the user. This field is required.
isUniqueIdentifier (Deprecated)booleanAn optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false. The field is optional.
Return value
TypeDescription
booleanValue of the feature that is registered for the specified `visitorCode.
Exceptions thrown
TypeDescription
KameleoonException.FeatureNotFoundException indicating that the requested feature ID wasn't found in the internal configuration of the SDK. This usually means that the feature flag has not yet been activated on Kameleoon's side (but code that implements the feature is already deployed in the application).
KameleoonException.VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.
Example code
String visitorCode = kameleoonClient.getVisitorCode(httpServletRequest, httpServletResponse);
String featureKey = "new_checkout";
Boolean hasNewCheckout = false;

try {
hasNewCheckout = kameleoonClient.isFeatureActive(visitorCode, featureKey);
// disabling tracking
hasNewCheckout = kameleoonClient.isFeatureActive(false, visitorCode, featureKey);
}
catch (KameleoonException.FeatureNotFound e) {
// Feature toggle not yet activated on Kameleoon's side - we consider the feature inactive
hasNewCheckout = false;
}
catch (Exception e) {
// This is a generic exception handler that handles all exceptions.
System.out.println("Exception occurred");
}
if (hasNewCheckout)
{
// Implement new checkout code here
}

getVariation()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)

Retrieves the Variation assigned to a given visitor for a specific feature flag.

This method takes a visitorCode and featureKey as mandatory arguments. The track argument is optional and defaults to true.

It returns the assigned Variation for the visitor. If the visitor is not associated with any feature flag rules, the method returns the default Variation for the given feature flag.

Ensure that proper error handling is implemented in your code to manage potential exceptions.

note

The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.

String visitorCode = kameleoonClient.getVisitorCode(httpServletRequest, httpServletResponse);
String featureKey = "new_checkout";
Variation variation;

try {
variation = kameleoonClient.getVariation(visitorCode, featureKey);
// disabling tracking
variation = kameleoonClient.getVariation(visitorCode, featureKey, false);
} catch (KameleoonException.FeatureNotFound e) {
// The error has happened, the feature flag isn't found in current configuration
} catch (KameleoonException.FeatureEnvironmentDisabled e) {
// The feature flag is disabled for the environment
} catch (KameleoonException.VisitoCodeInvalid e) {
// The visitor code you passed to the method is invalid and can't be accepted by SDK
}

// Fetch a variable value for the assigned variation
String title = (String) variation.getVariables().get("title").getValue();

switch (variation.getKey()) {
case 'on':
// Main variation key is selected for visitorCode
break;
case 'alternative_variation':
// Alternative variation key
break;
default:
// Default variation key
break;
}
Arguments
NameTypeDescriptionDefault
visitorCode (required)StringUnique identifier of the user.
featureKey (required)StringKey of the feature you want to expose to a user.
track (optional)booleanAn optional parameter to enable or disable tracking of the feature evaluation.true
Return value
TypeDescription
VariationAn assigned variation to a given visitor for a specific feature flag.
Exceptions thrown
TypeDescription
VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.
FeatureNotFoundException indicating that the requested feature key wasn't found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is already deployed on your application).
FeatureEnvironmentDisabledException indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).

getVariations()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)

Retrieves a map of Variation objects assigned to a given visitor across all feature flags.

This method iterates over all available feature flags and returns the assigned Variation for each flag associated with the specified visitor. It takes visitorCode as a mandatory argument, while onlyActive and track are optional.

  • If onlyActive is set to true, the method getVariations() will return feature flags variations provided the user is not bucketed with the off variation.
  • The track parameter controls whether or not the method will track the variation assignments. By default, it is set to true. If set to false, the tracking will be disabled.

The returned map consists of feature flag keys as keys and their corresponding Variation as values. If no variation is assigned for a feature flag, the method returns the default Variation for that flag.

Proper error handling should be implemented to manage potential exceptions.

note

The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.

try {
Map<String, Variation> variations = kameleoonClient.getVariations(visitorCode);
// only active variations
Map<String, Variation> variations = kameleoonClient.getVariations(visitorCode, true);
// disable tracking
Map<String, Variation> variations = kameleoonClient.getVariations(visitorCode, true, false);
}
catch (VisitorCodeInvalid e) {
// Handle exception
}
Arguments
NameTypeDescriptionDefault
visitorCode (required)StringUnique identifier of the user.
onlyActive (optional)booleanAn optional parameter indicating whether to return variations for active (true) or all (false) feature flags.false
track (optional)booleanAn optional parameter to enable or disable tracking of the feature evaluation.true
Return value
TypeDescription
Map<String, Variation>Map that contains the assigned Variation objects of the feature flags using the keys of the corresponding features.
Exceptions thrown
TypeDescription
VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.

getFeatureVariationKey()

  • 📨 Sends Tracking Data to Kameleoon
note

This method is deprecated and will be removed in SDK version 5.0.0. Use getVariation() instead.

Call this method to get the feature variation key for a specified user and feature. This method takes a visitorCode and featureKey as mandatory arguments to get the variation key for the specified user.

If the user has never been associated with this feature flag, the SDK returns a randomly-assigned variation key (according to the feature flag rules). If a user with the specified visitorCode is already registered with this feature flag, the SDK detects the previous variation key value. If the user doesn't match any of the rules, the default value is returned, which you can customize in the Kameleoon app.

Make sure you catch and handle potential exceptions.

If you specify a visitorCode, the flush() method uses it as the unique visitor identifier, which is useful for Cross-device experimentation. When you specify a visitorCode and set the isUniqueIdentifier parameter to true, the SDK links the flushed data with the visitor associated with the specified identifier.

note

The parameter isUniqueIdentifier is deprecated. Please use UniqueIdentifier instead.

The isUniqueIdentifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Arguments
NameTypeDescription
visitorCodeStringUnique identifier of the user. This field is required.
featureKeyStringKey of the feature you want to expose to a user. This field is required.
isUniqueIdentifier (Deprecated)booleanAn optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false. The field is optional.
Return value
TypeDescription
StringVariation key of the feature flag that is registered for the specified visitorCode.
Exceptions thrown
TypeDescription
KameleoonException.FeatureNotFoundException indicating that the requested feature key wasn't found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is already deployed on your application).
KameleoonException.FeatureEnvironmentDisabledException indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).
KameleoonException.VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is empty or longer than 255 characters.
Example code
String visitorCode = kameleoonClient.getVisitorCode(httpServletRequest, httpServletResponse);
String featureKey = "new_checkout";
String variationKey = ""

try {
variationKey = kameleoonClient.GetFeatureVariationKey(visitorCode, featureKey);
} catch (KameleoonException.FeatureNotFound e) {
// The error has happened, the feature flag isn't found in current configuration
} catch (KameleoonException.FeatureEnvironmentDisabled e) {
// The feature flag is disabled for the environment
} catch (KameleoonException.VisitoCodeInvalid e) {
// The visitor code you passed to the method is invalid and can't be accepted by SDK
}

switch (variationKey) {
case 'on':
// Main variation key is selected for visitorCode
break;
case 'alternative_variation':
// Alternative variation key
break;
default:
// Default variation key
break;
}

getFeatureList()

note

This method was previously named obtainFeatureList, which was removed in SDK version 4.0.0.

Returns a list of feature flag keys currently available for the SDK.

Return value
TypeDescription
List<String>List of feature flag keys
Example code
List<String> allFeatureFlagKey = kameleoonClient.getFeatureList();

getActiveFeatures()

note

This method is deprecated and will be removed in SDK version 5.0.0. Use getVariations() instead.

try {
Map<String, Variation> activeFeatures = kameleoonClient.getActiveFeatures(visitorCode);
}
catch (VisitorCodeInvalid e) {
// Handle exception
}

This method takes only input parameters: visitorCode. Result contains only active features for a given visitor.

Arguments
NameTypeDescription
visitorCodeStringUnique identifier of the user. This field is required.
Return value
TypeDescription
Map<String, Variation>Map that contains the assigned variations of the active features using the keys of the corresponding active features.
Exceptions thrown
TypeDescription
VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.

getActiveFeatureListForVisitorCode()

note
  • This method is deprecated and will be removed in SDK version 5.0.0. Use getVariations() instead.
  • This method was previously named obtainFeatureListForVisitorCode, which was removed in SDK version 4.0.0.

This method takes a single visitorCode parameter. Return only the active feature flags for the specified visitor.

Arguments
NameTypeDescription
visitorCodeStringUnique identifier of the user. This field is required.
Return value
TypeDescription
List<String>List of active feature flag keys available for specific visitorCode
Example code
List<String> listActiveFeatureFlags = kameleoonClient.getActiveFeatureListForVisitorCode(visitorCode);

Variables

getFeatureVariable()

  • 📨 Sends Tracking Data to Kameleoon
note

This method is deprecated and will be removed in SDK version 5.0.0. Use getVariation() instead.

Call this method to get the feature variation value associated with a user. This method takes a visitorCode, featureKey and variableKey as required arguments to get the variable of the variation key for the specified user.

If a user has never been associated with this feature flag, the SDK returns a randomly assigned variable value of the variation key, in accordance with the feature flag rules. If a user with the specified visitorCode is already registered with this feature flag, the SDK returns the variable value for previously associated variation. If the user does not match any of the rules, the default variable is returned.

Make sure you catch and handle potential exceptions.

If you specify a visitorCode, the getFeatureVariable() method uses it as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitorCode and set the isUniqueIdentifier parameter to true, the SDK links the flushed data with the visitor associated with the specified identifier.

note

The parameter isUniqueIdentifier is deprecated. Please use UniqueIdentifier instead.

The isUniqueIdentifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Arguments
NameTypeDescription
visitorCodeStringUnique identifier of the user. This field is required.
featureKeyStringKey of the feature you want to expose to a user. This field is required.
variableKeyStringName of the variable you want to get a value for. This field is required.
isUniqueIdentifier (Deprecated)booleanAn optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false. The field is optional.
Return value
TypeDescription
objectValue of variable of variation that is registered for the specified visitorCode for this feature flag. Possible types: bool, int, double, string, JObject, JArray
Exceptions thrown
TypeDescription
KameleoonException.FeatureNotFoundException indicating that the requested feature key wasn't found in the internal SDK configuration. This usually means that the feature flag has not yet been activated in the Kameleoon app (but code implementing the feature is already deployed in your application).
KameleoonException.FeatureEnvironmentDisabledException indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).
KameleoonException.FeatureVariableNotFoundException indicating that the requested variable wasn't found. Check that the variable's key in the Kameleoon app matches the one in your code.
KameleoonException.VisitorCodeInvalidException indicating that the specified visitor code is not valid. (It is either empty or longer than 255 characters).
Example code
String visitorCode = kameleoonClient.getVisitorCode(httpServletRequest, httpServletResponse);
String featureKey = "feature_key";
String variableKey = "var"

try {
var variableValue = kameleoonClient.getFeatureVariable(visitorCode, featureKey, variableKey);
// Your custom code depending on variableValue
} catch (KameleoonException.FeatureNotFound e) {
// The error has occurred, the feature flag isn't found in current configuration
} catch (KameleoonException.FeatureEnvironmentDisabled e) {
// The feature flag is disabled for the environment
} catch (KameleoonException.FeatureVariableNotFound e) {
// Requested variable not defined on Kameleoon's side
} catch (KameleoonException.VisitoCodeInvalid e) {
// The visitor code passed to the method is invalid and can't be accepted by SDK
}

getFeatureVariables()

  • 📨 Sends Tracking Data to Kameleoon
note

This method is deprecated and will be removed in SDK version 5.0.0. Use getVariation() instead.

Retrieves a map containing variable keys and their values assigned according the variation that the visitor is assigned to in the specified feature flag. Feature variables can be easily modified through the Kameleoon app.

If a user has never been associated with this feature flag, the SDK returns a randomly assigned set of variable values in the variation, in accordance with the feature flag rules. If a user with the specified visitorCode is already registered with this feature flag, the SDK returns the variable values for the variation used previously. If the user does not match any of the rules, the default variables are returned.

Make sure you catch and handle potential exceptions.

Arguments
NameTypeDescription
featureKeyStringKey of the feature you want to obtain. This field is required.
variationKeyStringKey of the variation you want to obtain. This field is required.
Return value
TypeDescription
Map<String,Object>Data associated with this feature flag. The values can be Boolean, Integer, Double, String, JsonObject, or JsonArray (the type is defined in the Kameleoon app).
Exceptions thrown
TypeDescription
KameleoonException.FeatureNotFoundException indicating that the requested feature key wasn't found in the internal SDK configuration. This usually means that the feature flag has not yet been activated in the Kameleoon app (but code implementing the feature is already deployed in your application).
KameleoonException.FeatureEnvironmentDisabledException indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).
KameleoonException.FeatureVariationNotFoundException indicating that the requested variation key wasn't found in the internal configuration of the SDK. This usually means that the variation's corresponding experiment is not activated in the Kameleoon app.
KameleoonException.VisitorCodeInvalidException indicating that the specified visitor code is not valid. (It is either empty or longer than 255 characters).
Example code
String visitorCode = kameleoonClient.getVisitorCode(httpServletRequest, httpServletResponse);
String featureKey = "feature_key";
String variableKey = "var"

try {
var variableValue = kameleoonClient.getFeatureVariables(visitorCode, featureKey);
// Your custom code depending on variable values
} catch (KameleoonException.FeatureNotFound e) {
// The error has occurred, the feature flag isn't found in current configuration
} catch (KameleoonException.FeatureEnvironmentDisabled e) {
// The feature flag is disabled for the environment
} catch (KameleoonException.FeatureVariableNotFound e) {
// Requested variable not defined on Kameleoon's side
} catch (KameleoonException.VisitoCodeInvalid e) {
// The visitor code passed to the method is invalid and can't be accepted by SDK
}

getFeatureVariationVariables()

note
  • This method is deprecated and will be removed in SDK version 5.0.0. Use getVariation() instead.
  • This method was previously named: getFeatureAllVariables, which was removed in SDK version 4.0.0.

Call this method to retrieve all feature variables for a feature. You can modify feature variables in the Kameleoon app.

This method takes two input parameters: featureKey and variationKey. It returns the data with the Map<String, Object> type, as defined in the Kameleoon app. It throws an exception (KameleoonException.FeatureNotFound) if the requested feature isn't found in the internal configuration of the SDK.

Arguments
NameTypeDescription
featureKeyStringKey of the feature you want to obtain. This field is required.
variationKeyStringKey of the variation you want to obtain. This field is required.
Return value
TypeDescription
Map<String,Object>Data associated with this feature flag. The values can be Boolean, Integer, Double, String, JsonObject, JsonArray (depending on the type defined in the Kameleoon app).
Exceptions thrown
TypeDescription
KameleoonException.FeatureNotFoundException indicating that the requested feature wasn't found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app.
KameleoonException.FeatureEnvironmentDisabledException indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).
KameleoonException.FeatureVariationNotFoundException indicating that the requested variation key wasn't found in the internal configuration of the SDK. This usually means that the variation's corresponding experiment is not activated in the Kameleoon app.
Example code
String featureKey = "featureKey";
String variationKey = "variationKey";

try {
Map<String, Object> allVariables = kameleoonClient.getFeatureVariationVariables(featureKey, variationKey);
}
catch (KameleoonException.FeatureNotFound e) {
// The feature is not yet activated in the Kameleoon app
} catch (KameleoonException.FeatureEnvironmentDisabled e) {
// The feature flag is disabled for the environment
} catch (KameleoonException.FeatureVariationNotFound e) {
// The variation is not yet activated in the Kameleoon app (most likely, the associated experiment is not active)
} catch (Exception e) {
// This is a generic Exception handler which will handle all exceptions.
System.out.println("Exception occurred");
}

Visitor data

getVisitorCode()

note

This method was previously named obtainVisitorCode, which was removed in SDK version 4.0.0.

The getVisitorCode() helper method should be called to obtain the Kameleoon visitorCode for the current visitor. This is especially important when using Kameleoon in a mixed front-end and back-end environment, where user identification consistency must be guaranteed. The implementation logic is described here:

  1. First we check if a kameleoonVisitorCode cookie or query parameter associated with the current HTTP request can be found. If so, we will use this as the visitor identifier.

  2. If no cookie / parameter is found in the current request, we either randomly generate a new identifier, or use the defaultVisitorCode argument as identifier if it is passed. This allows our customers to use their own identifiers as visitor codes, should they wish to. This can have the added benefit of matching Kameleoon visitors with their own users without any additional look-ups in a matching table.

  3. In any case, the server-side (via HTTP header) kameleoonVisitorCode cookie is set with the value. Then this identifier value is finally returned by the method.

For more information, refer to this article.

note

If you provide your own visitorCode, its uniqueness must be guaranteed on your end - the SDK cannot check it. Also note that the length of visitorCode is limited to 255 characters. Any excess characters will throw an exception.

Arguments
NameTypeDescription
httpServletRequestHttpServletRequestThe current HttpServletRequest object should be passed as the first parameter. This field is mandatory.
httpServletResponseHttpServletResponseThe current HttpServletResponse object should be passed as the second parameter. This field is mandatory.
defaultVisitorCodeStringThis parameter will be used as the visitorCode when an existing kameleoonVisitorCode cookie is not found on the request. This field is optional. If not specified, the SDK generates a random visitorCode when no existing kameleoonVisitorCode cookie.
Return value
TypeDescription
StringA visitorCode that will be associated with this particular user and should be used with most of the methods of the SDK.
Example code
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

String visitorCode = kameleoonClient.getVisitorCode(httpServletRequest, httpServletResponse);

String visitorCode = kameleoonClient.getVisitorCode(httpServletRequest, httpServletResponse, userID);

String visitorCode = kameleoonClient.getVisitorCode(httpServletRequest, httpServletResponse, UUID.randomUUID().toString());

addData()

The addData() method adds targeting data to storage so other methods can use the data to decide whether or not to target the current visitor.

The addData() method does not return any value and does not interact with Kameleoon back-end servers on its own. Instead, all the declared data is saved for future transmission using the flush() method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered the flush().

The trackConversion() method also sends out any previously associated data, just like the flush(). The same holds true for getVariation() and getVariations() methods if an experimentation rule is triggered.

tip

Each visitor can only have one instance of associated data for most data types. However, CustomData is an exception. Visitors can have one instance of associated CustomData per index.

kameleoonClient.addData(visitorCode, Browser.CHROME);
kameleoonClient.addData(visitorCode, new PageView("https://url.com", "title", Array.asList(3)));
kameleoonClient.addData(visitorCode, new Conversion(32, 10f, false));
Arguments
NameTypeDescription
visitorCode (required)StringUnique identifier of the user.
data (required)Data...Collection of Kameleoon data types.
Exceptions
TypeDescription
VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.

flush()

  • 📨 Sends Tracking Data to Kameleoon

flush() takes the Kameleoon data associated with the visitor, then sends a tracking request along with all of the data that were added previously using the addData method, that has not yet been sent when calling one of these methods. flush() is non-blocking as the server call is made asynchronously.

flush allows you to control when the data associated with a given visitorCode is sent to our servers. For instance, if you call addData() a dozen times, it would be inefficient to send data to the server after each time addData() is invoked, so all you have to do is call flush() once at the end.

If you specify a visitorCode, the flush() method uses it as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitorCode and set the isUniqueIdentifier parameter to true, the SDK links the flushed data with the visitor associated with the specified identifier.

note

The parameter isUniqueIdentifier is deprecated. Please use UniqueIdentifier instead.

The isUniqueIdentifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Arguments
NameTypeDescription
instantbooleanBoolean flag indicating whether the data should be sent instantly (true) or according to the default tracking interval (false) set with the SDK parameter tracking_interval_millisecond. This field is optional.
visitorCodeStringUnique identifier of the user. This field is required.
isUniqueIdentifier (Deprecated)booleanAn optional parameter for specifying if the visitorCode is a unique identifier. The visitorCode should be provided and not null to apply isUniqueIdentifier for a visitor, otherwise it will be ignored. If not provided, the default value is false. The field is optional.
Example code

try {
kameleoonClient.flush(visitorCode); // Interval tracking (most performant way for tracking)
kameleoonClient.flush(true, visitorCode); // Instant tracking
} catch (VisitorCodeInvalid e) {
// Catch exception
}

getRemoteData()

note

This method was previously named retrieveDataFromRemoteSource, which was removed in SDK version 4.0.0.

The getRemoteData() method allows you to retrieve data (according to a key passed as argument) for the specified siteCode stored on a remote Kameleoon server. Your site code was specified in KameleoonClientFactory.create(). Usually data is stored on our remote servers using our Data API. This method, along with the availability of our highly scalable servers, provides a convenient way to quickly store additional data that you can later retrieve for your app.

Arguments
NameTypeDescription
keyStringThe key that is associated with the data you want to get. This field is mandatory.
Return value
TypeDescription
CompletableFuture<JsonObject>Future JsonObject associated with retrieving data for specific key.
Example code
CompletableFuture<JsonObject> data = kameleoonClient.getRemoteData("key");

try {
JsonObject test = kameleoonClient.getRemoteData("key").get(5_000, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
// Catch exception
}

getRemoteVisitorData()

getRemoteVisitorData() is an asynchronous method for retrieving Kameleoon Visits Data for the visitorCode from the Kameleoon Data API. The method adds the data to storage for other methods to use when making targeting decisions.

Data obtained using this method plays an important role when you want to:

  • use data collected from other devices.
  • access a user's history, such as previously visited pages during past visits.
  • use data that is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.

Read this article for a better understanding of possible use cases.

caution

By default, getRemoteVisitorData() automatically retrieves the latest stored custom data with scope=Visitor and attaches them to the visitor without the need to call the method addData(). It is particularly useful for synchronizing custom data between multiple devices.

note

The parameter isUniqueIdentifier is deprecated. Please use UniqueIdentifier instead.

The isUniqueIdentifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Using parameters in getRemoteVisitorData()

The getRemoteVisitorData() method offers flexibility by allowing you to define various parameters when retrieving data on visitors. Whether you're targeting based on goals, experiments, or variations, the same approach applies across all data types.

For example, let's say you want to retrieve data on visitors who completed a goal "Order transaction". You can specify parameters within the getRemoteVisitorData() method to refine your targeting. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the previousVisitAmount parameter to 5 and conversions to true.

The flexibility shown in this example is not limited to goal data. You can use parameters within the getRemoteVisitorData() method to retrieve data on a variety of visitor behaviors.

Arguments
NameTypeDescription
visitorCodestringThe visitor code for which you want to retrieve the assigned data. This field is mandatory.
filterkameleoon.types.RemoteVisitorDataFilterFilter for specifying what data should be retrieved from visits, by default only CustomData is retrieved from the current and latest previous visit (RemoteVisitorDataFilter.builder().build() or new RemoteVisitorDataFilter()). Other filters parameters are set to false. This filed is optional.
addDatabooleanA boolean indicating whether the method should automatically add retrieved data for a visitor. This field is optional.
isUniqueIdentifier (Deprecated)booleanAn optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false. The field is optional.
note

Here is the list of available kameleoon.types.RemoteVisitorDataFilter options:

NameTypeDescriptionDefault
previousVisitAmount (optional)intNumber of previous visits to retrieve data from. Number between 1 and 251
currentVisit (optional)booleanIf true, current visit data will be retrievedtrue
customData (optional)booleanIf true, custom data will be retrieved.true
pageViews (optional)booleanIf true, page data will be retrieved.false
geolocation (optional)booleanIf true, geolocation data will be retrieved.false
device (optional)booleanIf true, device data will be retrieved.false
browser (optional)booleanIf true, browser data will be retrieved.false
operatingSystem (optional)booleanIf true, operating system data will be retrieved.false
conversions (optional)booleanIf true, conversion data will be retrieved.false
experiments (optional)booleanIf true, experiment data will be retrieved.false
kcs (optional)booleanIf true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-onfalse
visitorCode (optional)booleanIf true, Kameleoon will retrieve the visitorCode from the most recent visit and use it for the current visit. This is necessary if you want to ensure that the visitor, identified by their visitorCode, always receives the same variant across visits for Cross-device experimentation.true
Return value
TypeDescription
CompletableFuture<List<Data>>Future List<Data> associated with a given visitor.
Example code
String visitorCode = "visitorCode";
// Visitor data will be fetched and automatically added for `visitorCode`
CompletableFuture<List<Data>> visitorData = kameleoonClient.getRemoteVisitorData(visitorCode);

// If you only want to fetch data and add it yourself manually, set addData == `false`
CompletableFuture<List<Data>> visitorData = kameleoonClient.getRemoteVisitorData(visitorCode, false);

// If you want to fetch custom list of data types
RemoteVisitorDataFilter filter = RemoteVisitorDataFilter.builder()
.previousVisitAmount(25)
.customData(false)
.conversions(true)
.build();
CompletableFuture<List<Data>> visitorData = kameleoonClient.getRemoteVisitorData(visitorCode, filter, true, false);

try {
List<Data> visitorData = kameleoonClient.getRemoteVisitorData(visitorCode).get(5_000, TimeUnit.MILLISECONDS);
// Your custom code
} catch (CancellationException | InterruptedException | ExecutionException | TimeoutException e) {
// Catch exception
}

getVisitorWarehouseAudience()

Retrieves all audience data associated with the visitor in your data warehouse using the specified visitorCode and warehouseKey. The warehouseKey is typically your internal user ID. The customDataIndex parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details. The method passes the result to the returned future as a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.

Arguments
NameTypeDescription
visitorCodeStringThe unique identifier of the visitor for whom you want to retrieve and add the data.
warehouseKeyStringThe unique key to identify the warehouse data (usually, your internal user ID). This field is optional.
customDataIndexintAn integer representing the index of the custom data you want to use to target your BigQuery Audiences.
Return value
TypeDescription
CompletableFuture<CustomData>Future CustomData instance confirming that the data has been added to the visitor.
Exceptions thrown
TypeDescription
VisitorCodeInvalidException indicating that the provided visitor code is not valid (it is either empty or longer than 255 characters).
Example code
CompletableFuture<CustomData> warehouseAudienceDataCF =
kameleoonClient.getVisitorWarehouseAudience(visitorCode, warehouseKeyValue, customDataIndex);

// If you need to specify warehouse key
CompletableFuture<CustomData> warehouseAudienceDataCF =
kameleoonClient.getVisitorWarehouseAudience(visitorCode, customDataIndex);

try {
CustomData warehouseAudienceData = warehouseAudienceDataCF.get(5_000, TimeUnit.MILLISECONDS);
// Your custom code
} catch (CancellationException | InterruptedException | ExecutionException | TimeoutException e) {
// Catch exception
}

setLegalConsent()

You must use this method to specify whether the visitor has given legal consent to use personal data. Setting the legalConsent parameter to false limits the types of data that you can include in tracking requests. This helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the consent management policy.

Arguments
NameTypeDescription
visitorCodeStringThe user's unique identifier. This field is required.
legalConsentbooleanA boolean value representing the legal consent status. true indicates the visitor has given legal consent, false indicates the visitor has never provided, or has withdrawn, legal consent. This field is required.
responseHttpServletResponseThe HTTP servlet response where values in the cookies will be adjusted based on the legal consent status. The field is optional.
Exceptions thrown
TypeDescription
KameleoonException.VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.
Example code
// if you do not need to set the visitor code in a cookie to respond
kameleoonClient.setLegalConsent(visitorCode, true);

String visitorCode = kameleoonClient.getVisitorCode(httpServletRequest, httpServletResponse);
kameleoonClient.setLegalConsent(visitorCode, true, httpServletResponse);

Goals and third-party analytics

trackConversion()

  • 📨 Sends Tracking Data to Kameleoon

Use this method to track a conversion for a specific goal and user. This method requires visitorCode and goalID. In addition, this method also accepts an optional revenue argument to track revenue generated by the conversion. The visitorCode is usually identical to the one that was used when triggering the experiment.

The trackConversion() method doesn't return any value. This method is non-blocking as the server call is made asynchronously.

If you specify a visitorCode, the trackConversion() method uses it as the unique visitor identifier, which is useful for Cross-device experimentation. When you specify a visitorCode and set the isUniqueIdentifier parameter to true, the SDK links the flushed data with the visitor associated with the specified identifier.

note

The parameter isUniqueIdentifier is deprecated. Please use UniqueIdentifier instead.

The isUniqueIdentifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Arguments
NameTypeDescription
visitorCodeStringUnique identifier of the user. This field is required.
goalIDintID of the goal. This field is required.
revenuefloatRevenue of the conversion. This field is optional.
isUniqueIdentifier (Deprecated)booleanAn optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is false. The field is optional.
Example code
String visitorCode = kameleoonClient.getVisitorCode(httpServletRequest, httpServletResponse);
int goalID = 83023;

kameleoonClient.trackConversion(visitorCode, goalID);

getEngineTrackingCode()

Kameleoon offers built-in integrations with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To ensure that you can track and analyze your server-side experiments, Kameleoon provides the method getEngineTrackingCode() to automatically send exposure events to the analytics solution you are using. The SDK builds a tracking code for your active analytics solution based on the experiments the visitor has triggered in the last 5 seconds. Please refer to our hybrid experimentation for more information on implementing this method.

note

You must implement both the Java SDK and our Kameleoon JavaScript tag to benefit from this feature. We recommend you implement the Kameleoon asynchronous tag, which you can install before your closing <body> tag in your HTML page, as it will be only used for tracking purposes.

info

The following string will be returned:

window.kameleoonQueue = window.kameleoonQueue || [];
window.kameleoonQueue.push(['Experiments.assignVariation', experiment1ID, variation1ID]);
window.kameleoonQueue.push(['Experiments.trigger', experiment1ID, true]);
window.kameleoonQueue.push(['Experiments.assignVariation', experiment2ID, variation2ID]);
window.kameleoonQueue.push(['Experiments.trigger', experiment2ID, true]);

Here, experiment1ID, experiment2ID and variation1ID, variation2ID represent the specific experiments and variations that users have been assigned to.

String engineTrackingCode = kameleoonClient.getEngineTrackingCode(visitorCode);
Arguments
NameTypeDescription
visitorCode (required)StringUnique identifier of the user.
Return value
TypeDesription
StringJavaScript code to be inserted in your page

Events

updateConfigurationHandler()

The updateConfigurationHandler() method allows you to handle the event when configuration has updated data. It takes one input parameter, handler. The handler that will be called when the configuration is updated using a real-time configuration event.

Arguments
NameTypeDescription
handlerKameleoonUpdateConfigurationHandlerThe handler that will be called when the configuration is updated using a real-time configuration event.
Example code
kameleoonClient.updateConfigurationHandler(() -> {
// Configuration was updated
});

Data types

This section lists the data types supported by Kameleoon in com.kameleoon.Data. We provide several standard data types as well as the CustomData type that allows you to define custom data types.

Browser

The Browser data set stored here can be used to filter experiment and personalization reports by any value associated with it.

kameleoonClient.addData(visitorCode, Browser.chrome());
kameleoonClient.addData(visitorCode, Browser.safari());

kameleoonClient.addData(visitorCode, new Browser(Browser.Type.CHROME, 10.0));
NameTypeDescription
type (required)Browser.TypeList of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER.
version (optional)FloatVersion of the browser, floating point number represents major and minor version of the browser

Conversion

Store conversion data.

NameTypeDescription
goalIDintID of the goal. This field is required.
revenuefloatConversion revenue. This field is optional.
negativebooleanDefines if the revenue is positive or negative. This field is optional.
kameleoonClient.addData(visitorCode, new Conversion(32, 10f, false));

Cookie contains information about the cookie stored on the visitor's device.

note

Each visitor can only have one Cookie. Adding second Cookie overwrites the first one.

NameTypeDescription
cookiesMap<String, String>A string object map consisting of cookie keys and values. This field is required.
Cookie cookie = new Cookie (new HashMap<String, String>() {{
put("my_key1", "my_value1");
put("my_key2", "my_value1");
}});
kameleoonClient.addData(visitorCode, cookie);

Geolocation

Geolocation contains the visitor's geolocation details.

tip
  • Each visitor can have only one Geolocation. Adding a second Geolocation overwrites the first one.
kameleoonClient.addData(visitorCode, new Geolocation("France", "Île-de-France", "Paris"));
NameTypeDescription
country (required)StringThe country of the visitor.
region (optional)StringThe region of the visitor.
city (optional)StringThe city of the visitor.
postalCode (optional)StringThe postal code of the visitor.
latitude (optional)floatThe latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees.
longitude (optional)floatThe longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees.

CustomData

Define your own custom data types in the Kameleoon app or the Data API and use them from the SDK.

NameTypeDescription
indexintIndex / ID of the custom data to be stored. This field is required.
valueString... or List<String>Value of the custom data to be stored. This field is required.
note

The index (ID) of the custom data is available in the Kameleoon app, in the Custom data configuration page. Be careful, this index starts at 0 so the first custom data you create for the specified site would have the ID 0, not 1.

kameleoonClient.addData(visitorCode, new CustomData(1, "some custom value"));

kameleoonClient.addData(visitorCode, new CustomData(1, "first value", "second value"));

Device

NameTypeDescription
deviceDeviceList of devices: PHONE, TABLET, DESKTOP. This field is required.
kameleoonClient.addData(visitorCode, Device.desktop());

PageView

Store page view events.

NameTypeDescription
urlStringURL of the page viewed. This field is required.
titleStringTitle of the page viewed. This field is required.
referrersList<Integer>Referrers of viewed pages. This field is optional.
note

The index (ID) of the referrer is available in the Kameleoon app, in the acquisition channel configuration page. Be careful: this index starts at 0, so the first acquisition channel you create for the specified site would have the ID 0, not 1.

kameleoonClient.addData(
visitorCode,
new PageView("https://url.com", "title", Array.asList(3))
);

UserAgent

Store information on the user-agent of the visitor. Server-side experiments are more vulnerable to bot traffic than client-side experiments. To address this, Kameleoon uses the IAB/ABC International Spiders and Bots List to identify known bots and spiders. Kameleoon also uses the UserAgent field to filter out bots and other unwanted traffic that could otherwise skew your conversion metrics. For more details, see the help article on bot filtering.

If you use internal bots, we suggest that you pass the value curl/8.0 of the userAgent to exclude them from our analytics.

NameTypeDescription
valueStringThe User-Agent value that will be sent with tracking requests. This field is required.
kameleoonClient.addData(visitorCode, new UserAgent("Your User Agent"));

UniqueIdentifier

If you don't add UniqueIdentifier for a visitor, visitorCode is used as the unique visitor identifier, which is useful for Cross-device experimentation. When you add UniqueIdentifier for a visitor, the SDK links the flushed data with the visitor associated with the specified identifier.

The UniqueIdentifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitorCode that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

NameTypeDescription
valuebooleanParameter for specifying if the visitorCode is a unique identifier. This field is required.
kameleoonClient.addData(visitorCode, new UniqueIdentifier(true));

OperatingSystem

OperatingSystem contains information about the operating system on the visitor's device.

note

Each visitor can only have one OperatingSystem. Adding a second OperatingSystem overwrites the first one.

NameTypeDescription
typeOperatingSystem.TypeList of operating systems: WINDOWS_PHONE, WINDOWS, ANDROID, LINUX, MAC, and IOS. This field is required.
kameleoonClient.addData(visitorCode, new OperatingSystem(OperatingSystem.Type.WINDOWS));

kameleoonClient.addData(visitorCode, OperatingSystem.mac());

Returned Types

Variation

Variation contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).

NameTypeDescription
keyStringThe unique key identifying the variation.
idIntegerThe ID of the assigned variation (or null if it's the default variation).
experimentIdIntegerThe ID of the experiment associated with the variation (or null if default).
variablesMap<String, Variable>A map containing the variables of the assigned variation, keyed by variable names. This could be an empty collection if no variables are associated.
note
  • The Variation object provides details about the assigned variation and its associated experiment, while the Variable object contains specific details about each variable within a variation.
  • Ensure that your code handles the case where id or experimentId may be null, indicating a default variation.
  • The variables map might be empty if no variables are associated with the variation.
Example code
// Retrieving the variation key
String variationKey = variation.getKey();

// Retrieving the variation id
Integer variationId = variation.getId();

// Retrieving the experiment id
Integer experimentId = variation.getExperimentId();

// Retrieving the variables map
Map<String, Variable> variables = variation.getVariables();

Variable

Variable contains information about a variable associated with the assigned variation.

NameTypeDescription
keyStringThe unique key identifying the variable.
typeStringThe type of the variable. Possible values: BOOLEAN, NUMBER, STRING, JSON, JS, CSS.
valueObjectThe value of the variable, which can be of the following types: Boolean, Integer, Long, Double, String, JsonObject, JsonArray.
Example code
// Retrieving the variables map
Map<String, Variable> variables = variation.getVariables();

// Variable type can be retrieved for further processing
String type = variables.get("isDiscount").getType();

// Retrieving the variable value by key
Boolean isDiscount = (Boolean) variables.get("isDiscount").getValue();

// Variable value can be of different types
String title = (String) variables.get("title").getValue();