Documentation
NAV Navbar
  • Java SDK
  • Java SDK

    Introduction

    Welcome to the developer documentation for the Kameleoon Java SDK! Our SDK gives you the possibility of running experiments on your back-end Java JEE application server. Integrating our SDK into your web-application is easy, and its footprint (in terms of memory and network usage) is low.

    You can refer to the SDK reference to check out all possible features of the SDK. Also make sure you check out our Getting started tutorial which we have prepared to walk you through the installation and implementation.

    Getting started

    This guide is designed to help you integrate our SDK in a few minutes and start running experiments in your Java applications. This tutorial will explain the setup of a simple A/B test to change the number of recommended products based on different variations.

    Creating an experiment

    First, you must create an experiment in the Kameleoon back-office so that our platform is aware of the new A/B test you're planning to implement on your side. Make sure that server-side type is chosen as shown below:

    Server-side experiment

    Upon successful creation of the experiment, you will need to get its ID to use in the SDK as an argument to the triggerExperiment() method. So the next step is to open the Kameleoon editor and login with your credentials. Click on Open an existing experiment and select the experiment you just created from the list. This will open a pop up with the experiment details as well as its ID.

    Installing the SDK

    <dependency>
      <groupId>com.kameleoon</groupId>
      <artifactId>kameleoon-client-java</artifactId>
      <version>1.0.1</version>
    </dependency>
    
    <?xml version="1.0" encoding="UTF-8"?>
    <settings xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd" xmlns="http://maven.apache.org/SETTINGS/1.1.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <servers>
            <server>
                <username>sdk-puller</username>
                <password>AP48PakWgwqfg3w5VQijE984jkXnrHhp2T2kTJn6ugWY14CeccCaWGCaqkvV</password>
                <id>sdk-central</id>
            </server>
            <server>
                <username>sdk-puller</username>
                <password>AP48PakWgwqfg3w5VQijE984jkXnrHhp2T2kTJn6ugWY14CeccCaWGCaqkvV</password>
                <id>sdk-snapshots</id>
            </server>
        </servers>
        <profiles>
            <profile>
                <repositories>
                    <repository>
                        <snapshots>
                            <enabled>false</enabled>
                        </snapshots>
                        <id>sdk-central</id>
                        <name>sdk-libs-release</name>
                        <url>http://artifacts.kameleoon.net:8081/artifactory/sdk-libs-release</url>
                    </repository>
                    <repository>
                        <snapshots />
                        <id>sdk-snapshots</id>
                        <name>sdk-libs-snapshots</name>
                        <url>http://artifacts.kameleoon.net:8081/artifactory/sdk-libs-snapshot</url>
                    </repository>
                </repositories>
                <id>artifactory</id>
            </profile>
        </profiles>
        <activeProfiles>
            <activeProfile>artifactory</activeProfile>
        </activeProfiles>
    </settings>
    

    If your project uses Apache Maven, 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. It needs a specific repository, so you also need to modify your Maven settings file (~/.m2/settings.xml). An example file is also provided on the right.

    If you are not using Maven, you can install our SDK by downloading it from this link.

    Initializing the Kameleoon client

    import com.kameleoon.ssx.KameleoonClientFactory
    
    String siteCode = "uzguihqmj7";
    
    KameleoonClient kameleoonClient = KameleoonClientFactory.create(siteCode);
    
    // Second version of the kameleoonClient, using a blocking triggerExperiment() method
    KameleoonClient kameleoonClient = KameleoonClientFactory.create(siteCode, true);
    

    After installing the SDK into your application and setting up a server-side experiment on Kameleoon's back-office, the next step is to create the Kameleoon client.

    The code on the right gives a clear example. A Client is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you will need to run an experiment.

    Triggering an experiment

    String userID = UUID.randomUUID().toString();
    int recommendedProductsNumber;
    Cookie[] cookies = request.getCookies();
    boolean foundCookie = false;
    
    for(int i = 0; i < cookies.length; i++) {
        Cookie userCookie = cookies[i];
        if (userCookie.getName().equals("userID")) {
            userID = userCookie.getValue();
            foundCookie = true;
        }
    }
    if (!foundCookie) {
        Cookie userCookie = new Cookie("userID", userID);
        response.addCookies(userCookie);
    }
    try {
        String variationID;
    
        try {
            variationID = kameleoonClient.triggerExperiment(userID, 75253);
        }
        catch (KameleoonException.ExperimentConfigurationNotFound e) {
            // The user will not be counted into the experiment, but should see the reference variation
            variationID = "reference";
        }
    
        if (variationId.equals("reference")) {
            //This is the default / reference number of products to display
            recommendedProductsNumber = 5;
        }
        else if (variationId.equals("148382")) {
            //We are changing number of recommended products for this variation to 10
            recommendedProductsNumber = 10;
        }
        else if (variationId.equals("187791")) {
            //We are changing number of recommended products for this variation to 8
            recommendedProductsNumber = 8;
        }
    
        // Here you should have code to generate the HTML page back to the client, where recommendedProductsNumber will be used
    }
    catch (Exception e) {
        System.out.println("Exception occurred");
    }
    

    Running an A/B experiment on your Java application means bucketing your visitors into several groups (one per variation). The SDK takes care of this bucketing (and the associated reporting) automatically.

    Triggering an experiment by calling the triggerExperiment() method will register a random variation for a given userID. If this userID is already associated with a variation (most likely a returning visitor that has already been exposed to the experiment previously), then it will return the previous variation associated with a given experiment.

    Implementing variation code

    private int recommendedProductsNumber;
    
    if (variationId.equals("reference")) {
        //This is the default / reference number of products to display
        recommendedProductsNumber = 5;
    }
    else if (variationId.equals("148382")) {
        //We are changing number of recommended products for this variation to 10
        recommendedProductsNumber = 10;
    }
    else if (variationId.equals("187791")) {
        //We are changing number of recommended products for this variation to 8
        recommendedProductsNumber = 8;
    }
    

    To execute different code paths depending on the variation assigned to the visitor, you will need the list of all the experiment's variation IDs. You can find these variation IDs by going into the Kameleoon Editor as shown below.

    Once you have the IDs of the different variations, you can implement a different action for each variation, and one of the code paths will be executed, based on the associated variationID for the current visitor. Generally, this can be done using a simple if / else or switch mechanism. In our example, we just change the number of recommended products with two different variations.

    Get variationID

    Tracking conversion

    String userID = UUID.randomUUID().toString();
    int goalID = 83023;
    Cookie[] cookies = request.getCookies();
    
    for(int i = 0; i < cookies.length; i++) {
        Cookie userCookie = cookies[i];
        if (userCookie.getName().equals("userID")) {
            userID = userCookie.getValue();
        }
    }
    
    kameleoonClient.trackConversion(userID, goalID);
    

    After you are done with triggering an experiment, the next step is usually to start tracking conversions. This is done to measure performance characteristics according to the goals that make sense for your business.

    For this purpose, use the trackConversion() method of the SDK as shown in the example. You need to pass the userID and goalID parameters so we can correctly track conversion for this particular visitor.

    Get goalID

    Obtaining results

    Once your implementation is in place on the server side (experiment triggering, variations handling, and conversion tracking), it is time to launch the experiment on the Kameleoon platform. You do this in the same way as for a front-end test. Basic operations such as starting, pausing and stopping the experiment work exactly the same way.

    After the experiment is launched, the first results will be available on our standard results page in the back-office after a duration of 30 minutes. This is because (as is the case with front-end testing) visits are considered over after 30 minutes of inactivity. Inactivity in this context means the absence of calls sent to the Kameleoon back-end servers (such calls are made via triggerExperiment(), trackConversion() or flush() methods).

    Reference

    This is a full reference documentation of the Java SDK.

    If this is your first time working with the Java SDK, we strongly recommend you go over our Getting started tutorial to integrate the SDK and start experimenting in a few minutes.

    Initialization: creating the Kameleoon Client

    import com.kameleoon.ssx.KameleoonClientFactory
    
    KameleoonClient kameleoonClient = KameleoonClientFactory.create("uzguihqmj7");
    

    The starting point for using the SDK is the initialization step. All interaction with the SDK is done through an object called KameleoonClient, therefore you need to create this object.

    Arguments

    NameTypeDescription
    siteCodeStringCode of the website you want to run experiments on. This unique code id can be found in our platform's back-office. This field is mandatory.
    blockingbooleanThis parameter defines if the triggerExperiment() method has a non-blocking or blocking behavior. Value true will set it to be blocking. This field is optional and set to false by default.

    Triggering experiments

    String userID = UUID.randomUUID().toString();
    int experimentID = 75253;
    String variationID;
    
    try {
        variationID = kameleoonClient.triggerExperiment(userID, experimentID);
    }
    catch (KameleoonException.ExperimentConfigurationNotFound e) {
        // The user will not be counted into the experiment, but should see the reference variation
        variationID = "reference";
    }
    catch (Exception e) {
        // This is generic Exception handler which will handle all exceptions.
        System.out.println("Exception occurred");
    }
    

    To trigger an experiment call the triggerExperiment() method of our SDK.

    This method takes userID and experimentId as mandatory arguments to register a variation for a given user.

    If such a user has never been associated with any variation, the SDK returns a randomly selected variation. If a user with a given userId is already registered with a variation, it will detect the previously registered variation and return the variationId.

    You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

    Arguments

    NameTypeDescription
    userIDStringUnique identifier of the user. This field is mandatory.
    experimentIDintID of the experiment you want to expose to a user. This field is mandatory.
    timeoutintTimeout (in milliseconds). This parameter is only used in the blocking version of this method, and specifies the maximum amount of time the method can block to wait for a result. This field is optional, if not provided, it will use the default value of 2000 milliseconds.

    Return value

    NameTypeDescription
    variationIDStringID of the variation that is registered for a given userId.

    Exceptions Thrown

    TypeDescription
    KameleoonException.ExperimentConfigurationNotFoundException indicating that the requested experiment ID has not been found in the internal configuration of the SDK. This is usually normal and means that the experiment has not yet been started on Kameleoon's side (but code triggering / implementing variations is already deployed on the web-application's side).

    Tracking Conversion

    String userID = UUID.randomUUID().toString();
    int goalID = 83023;
    
    kameleoonClient.addData(userID, Data.Browser.CHROME);
    kameleoonClient.addData(
        userID,
        new Data.PageView("http://url.com", "title", 3),
        new Data.Interest(2)
    );
    kameleoonClient.addData(userID, new Data.Conversion(32, 10f, false));
    
    kameleoonClient.trackConversion(userID, goalID);
    

    To track conversion, use the trackConversion() method. This method requires userID and goalID to track conversion on this particular goal. In addition, this method also accepts revenue as a third optional argument to track revenue. The userID usually is 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.

    Arguments

    NameTypeDescription
    userIDStringUnique identifier of the user. This field is mandatory.
    goalIDintID of the goal. This field is mandatory.
    revenuefloatRevenue of the conversion. This field is optional.

    Saving data

    kameleoonClient.addData(userID, Data.Browser.CHROME);
    kameleoonClient.addData(
        userID,
        new Data.PageView("http://url.com", "title", 3),
        new Data.Interest(0, true)
    );
    kameleoonClient.addData(userID, new Data.Conversion(32, 10f, false));
    

    To associate various data with the current user, we can use the addData() method. This method requires the userID as a first parameter, and then accepts several additional parameters. Those additional parameters represent the various Data Types allowed in Kameleoon.

    Note that the addData() method doesn't return any value and doesn't interact with the Kameleoon back-end servers by itself. Instead, the declared data is saved for future sending via the flush() method described in the next paragraph. This reduces the number of server calls made, as data is usually grouped into a single server call triggered by the execution of flush().

    Arguments

    NameTypeDescription
    userIDStringUnique identifier of the user. This field is mandatory.
    dataTypesDataCustom data types which may be passed separated by a comma.

    Data Types

    Browser Data Type

    kameleoonClient.addData(userID, Data.Browser.CHROME);
    
    NameTypeDescription
    browserenumList of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER. This field is mandatory.

    PageView Data Type

    kameleoonClient.addData(
        userID,
        new Data.PageView("http://url.com", "title", 3),
    );
    
    NameTypeDescription
    urlStringURL of the page viewed. This field is mandatory.
    titleStringTitle of the page viewed. This field is mandatory.
    referrerintReferrer of the page viewed. This field is optional.

    Conversion Data Type

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

    Custom Data Type

    kameleoonClient.addData(
        userID,
        new Data.Custom(1, "some custom value")
    );
    
    NameTypeDescription
    indexintIndex of the custom data to be stored. This field is mandatory.
    valueStringValue of the custom data to be stored. This field is mandatory.

    Interest Data Type

    kameleoonClient.addData(
        userID,
        new Data.Interest(0)
    );
    
    NameTypeDescription
    indexintIndex of the interest. This field is mandatory.

    Flushing saved data

    String userID = UUID.randomUUID().toString();
    
    kameleoonClient.addData(userID, Data.Browser.CHROME);
    kameleoonClient.addData(
        userID,
        new Data.PageView("http://url.com", "title", 3),
        new Data.Interest(0)
    );
    kameleoonClient.addData(userID, new Data.Conversion(32, 10f, false));
    
    kameleoonClient.flush(userID);
    

    Data associated with the current user via addData() method is not sent immediately to the server. It is stored and accumulated until it is sent automatically by the triggerExperiment() or trackConversion() methods, or manually by the flush() method. This allows the developer to control exactly when the data is flushed to our servers. For instance, if you call the addData() method a dozen times, it would be a waste of ressources to send data to the server after each addData() invocation. Just call flush() once at the end.

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

    Arguments

    NameTypeDescription
    userIDStringUnique identifier of the user. This field is mandatory.