# Java v3.0.X

## Introduction

### SDK overview

Welcome to the Flagship Java SDK documentation!

The following article will guide you through the steps to get Flagship up and running on your Java servers or scripts using our client library with preconfigured methods to implement the Decision API.

#### Release notes

[See here](doc:java-sdk)

#### SDK features

That SDK version helps you :

* Set a [visitor ID](https://docs.abtasty.com/server-side/glossary#visitor-id)
* Update [user context](doc:glossary#user-context)
* Assign campaigns via the [Decision API](doc:decision-api#campaigns) or the [Bucketing](doc:bucketing)
* Get flags
* Expose users to campaigns
* Send hits to our [Universal Collect](https://docs.abtasty.com/server-side/concepts/universal-collect-1)

#### Prerequisites

* **Java**: version 1.8 or later
* Your server/device must have access to the internet.

#### Good to know

* Github repository: <https://github.com/flagship-io/flagship-java>
* Weight: 103.0 ko
* Support Java 8
* Open-source app: <https://github.com/flagship-io/flagship-java>

## Getting Started

### Installation

Our SDK is available on Maven Central repository be sur it is present in your dependency manager:

```groovy
repositories {
    mavenCentral()
}
```

Then import the Java SDK using either Maven or Gradle dependency management:

```groovy
implementation 'com.abtasty:flagship-java:3.0.5'
```

```xml
<dependency>
    <groupId>com.abtasty</groupId>
    <artifactId>flagship-java</artifactId>
    <version>2.0.0</version>
</dependency>
```

#### **Manual installation**

For manual installation, jar files are available at :\
\
<https://repo1.maven.org/maven2/com/abtasty/flagship-java/3.0.5/>

Add the needed dependency :

```groovy
implementation 'org.json:json:20201115'
    implementation 'org.xerial:sqlite-jdbc:3.36.0.3'
```

```xml
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20201115</version>
</dependency>
```

### Initialization

To initialize and start the SDK, simply call the `start` function of the `Flagship` class, in the most appropriate location of your application.

```java
Flagship.start("your_env_id", "your_api_key");
```

| Parameter | Type           | Description                                                                                              |
| --------- | -------------- | -------------------------------------------------------------------------------------------------------- |
| envId     | String         | Environment id provided by Flagship                                                                      |
| apiKey    | String         | Api authentication key provided by Flagship                                                              |
| config    | FlagshipConfig | (optional) Custom flagship configuration. It can be DecisionApi (default) or Bucketing see Decision Mode |

#### **Flagship configuration : FlagshipConfig.**

This class aims to help you to configure the SDK via the following two available config implementations: DecisionApi and Bucketing. **See** [**Decision Mode**](#decision-mode) **section**.

```java
Flagship.start("your_env_id", "your_api_key", new FlagshipConfig.DecisionApi() // Will start the SDK with Api mode.
              .withLogManager(new CustomLogManager())
              .withLogLevel(LogManager.Level.ALL)
              .withStatusListener(newStatus -> {
                  if (newStatus == Flagship.Status.READY)
                      System.out.println("SDK is ready to use.");
              })
              .withTimeout(200));
```

```java
// Start SDK in Bucketing mode.
Flagship.start("your_env_id", "your_api_key", new FlagshipConfig.Bucketing() // Will start the SDK with Bucketing mode.
              .withLogManager(new CustomLogManager())
              .withLogLevel(LogManager.Level.ALL)
              .withStatusListener(newStatus -> {
                  if (newStatus == Flagship.Status.READY)
                      System.out.println("SDK is ready to use.");
              })
              .withPollingIntervals(20, TimeUnit.SECONDS)
              .withTimeout(200));
```

#### **`public FlagshipConfig<T> withLogLevel(LogManager.Level level)`**

This method specifies the mode which filters SDK logs.

| Parameter | Type                   | Description                                                                                                                                                                   |
| --------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| level     | LogManager.Level level | <p>The levels in ascending order are :</p><ul><li>NONE(0)</li><li>EXCEPTIONS(1)</li><li>ERROR(2)</li><li>WARNING(3)</li><li>DEBUG(4)</li><li>INFO(5)</li><li>ALL(6)</li></ul> |

#### **`public FlagshipConfig<T> withLogManager(LogManager logManager)`**

Specify a custom implementation of LogManager in order to receive logs from the SDK.

| Parameter  | Type       | Description                          |
| ---------- | ---------- | ------------------------------------ |
| logManager | LogManager | Custom implementation of LogManager. |

#### **`public FlagshipConfig<T> withTimeout(int timeout)`**

Specify timeout for api request.

| Parameter | Type | Description                                                  |
| --------- | ---- | ------------------------------------------------------------ |
| timeout   | int  | Milliseconds for connect and read timeouts. Default is 2000. |

#### **`public FlagshipConfig<T> withStatusListener(Flagship.StatusListener listener)`**

Define a new listener in order to get a callback when the SDK status has changed. **See** [**SDK status**](#sdk-status) **section**.

| Parameter | Type                    | Description                                      |
| --------- | ----------------------- | ------------------------------------------------ |
| listener  | Flagship.StatusListener | Callback to trigger when SDK status has changed. |

#### **`public FlagshipConfig<T> withCacheManager(CacheManager customCacheManager)`**

Provide the desired custom cache implementations.

| Parameter          | Type         | Description                             |
| ------------------ | ------------ | --------------------------------------- |
| customCacheManager | CacheManager | Custom implementation of cache manager. |

***Only available for Bucketing:***

#### **`public FlagshipConfig<T> withPollingIntervals(long time, TimeUnit timeUnit)`**

Define time interval between two bucketing updates. Default is 60 seconds. MICROSECONDS and NANOSECONDS Unit are ignored.

| Parameter | Type     | Description                                         |
| --------- | -------- | --------------------------------------------------- |
| time      | Long     | time value.                                         |
| timeUnit  | TimeUnit | time unit. Must be greater or equal to MILLISECONDS |

### **Decision Mode**

#### **`DecisionApi`Mode**

When the SDK is running in `DecisionApi` mode, the campaign assignments and targeting validation take place server-side. In this mode, each call to the `fetchFlags` method to refresh the flags will create an HTTP request.

#### **`Bucketing`Mode**

When the SDK is running in `Bucketing` mode, the SDK downloads all the campaigns configurations at once in a single bucketing file so that variation assignment can be computed client-side by the SDK. This bucketing file is stored in cache and will only be downloaded again when campaign configurations are modified in the Flagship interface. [**Learn more**](https://docs.abtasty.com/server-side/concepts/bucketing)

### **SDK Status**

List of the possible SDK status :

| Status           | Description                                                                                                                              |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| NOT\_INITIALIZED | Flagship SDK has not been started or initialized successfully.                                                                           |
| STARTING         | Flagship SDK is starting.                                                                                                                |
| POLLING          | Flagship SDK has been started successfully but is still polling campaigns. (Only when Bucketing mode is used)                            |
| PANIC            | Flagship SDK is ready but is running in Panic mode: All visitor's features are disabled except 'fetchFlags' which refreshes this status. |
| READY            | Flagship SDK is ready to use.                                                                                                            |

It is possible to get the current status via the method `getStatus()` from the Flagship class.

#### **`public Status getStatus()`**

Return the current SDK status

```java
Status status = Flagship.getStatus()
```

## Manage visitor

The `visitor` instance is a helper object that lets you manage the context and campaigns for a user identified by a unique ID.

The user context is a property dataset that defines the current user of your app. This dataset is sent and used by the Flagship Decision API as targeting criteria for campaign assignment.

For example, if you want to enable or disable a specific feature based on VIP status, you would pass this attribute as a key-value pair in the user context so that the Decision API can enable or disable the corresponding feature flag for the user.

```java
Visitor visitor = Flagship.newVisitor("visitor_unique_id")
                .context(new HashMap<String, Object>() {{
                    put("age", 32);
                    put("isVip", true);
                }})
                .hasConsented(true)
                .isAuthenticated(true)
                .build();
```

#### **`public static Visitor.Builder newVisitor(String visitorId)`**

Visitor builder class that creates a new visitor.

| Parameter | Type   | Description                |
| --------- | ------ | -------------------------- |
| visitorId | String | Unique visitor identifier. |

### **Visitor Builder**

#### **`public Builder isAuthenticated(boolean isAuthenticated)`**

Specify if the visitor is authenticated or anonymous. Default value is false.

| Parameter       | Type    | Description                                                          |
| --------------- | ------- | -------------------------------------------------------------------- |
| isAuthenticated | Boolean | True for authenticated user, false for anonymous. (false by default) |

#### **`public Builder hasConsented(boolean hasConsented)`**

Specify if the visitor has consented to personal data usage. When false some features will be deactivated, cache will be deactivated and cleared. Default value is True.

| Parameter    | Type    | Description                                                          |
| ------------ | ------- | -------------------------------------------------------------------- |
| hasConsented | Boolean | True when user has given consent, false otherwise. (true by default) |

#### **`public Builder context(HashMap<String, Object> context)`**

Specify visitor initial context key / values used for targeting.\
Context keys must be String, and values types must be one of the following: Number, Boolean, String.

| Parameter | Type                     | Description      |
| --------- | ------------------------ | ---------------- |
| context   | HashMap\<String, Object> | Initial context. |

{% hint style="warning" %}
🚧

* User context keys must have a type of `String`
* User context values must have a type of `String`, `Boolean`, `Number`.
* User context keys & values are **case sensitive**
  {% endhint %}

#### **`public Visitor build()`**

Return the newly created visitor.

### Updating Visitor context

The user context is a property dataset that defines the current user of your app. This dataset is sent and used by the Flagship Decision API as targeting criteria for campaign assignment.

The following method from the `Visitor` instance allows you to set new context values matching the given keys.

```java
Visitor visitor = Flagship.newVisitor("visitor_unique_id")
                .context(new HashMap<String, Object>() {{
                    put("age", 32);
                    put("isVip", true);
                }})
                .build();

visitor.updateContext("lastPurchaseDate", 1615384464);
```

#### **`public <T> void updateContext(String key, T value)`**

Upsert the visitor context values, matching the given keys, used for targeting. Only String, Boolean, Number typed values are accepted.

| Parameter | Type   | Description    |
| --------- | ------ | -------------- |
| key       | String | Context key.   |
| value     | T      | Context value. |

#### **`public void updateContext(HashMap<String, Object> context)`**

Upsert the visitor context values, matching the given keys, used for targeting. Only String, Boolean, Number typed values are accepted.

| Parameter | Type                     | Description              |
| --------- | ------------------------ | ------------------------ |
| context   | HashMap\<String, Object> | HashMap of keys, values. |

{% hint style="warning" %}
🚧

* User context keys must have a type of `String`
* User context values must have a type of `String`, `Boolean`, `Number`.
* User context keys & values are **case sensitive**
  {% endhint %}

#### **`public <T> void updateContext(FlagshipContext<T> flagshipContext, T value)`**

Upsert the visitor context values with Flagship predefined context key. \*\*[See FlagshipContext](#predefined-user-context-keys-flagshipcontext)

| Parameter       | Type            | Description            |
| --------------- | --------------- | ---------------------- |
| flagshipContext | FlagshipContext | Predefined context key |
| value           | T               | value to add.          |

#### **`public <T> void clearContext()`**

Clear all the visitor context values used for targeting.

```java
Visitor visitor = Flagship.newVisitor("visitor_unique_id")
              .context(new HashMap<String, Object>() {{
                  put("age", 32);
                  put("isVip", true);
              }})
              .build();
visitor.clearContext();
```

#### **`public HashMap<String, Object> getContext()`**

Get visitor current context key / values.

```java
Visitor visitor = Flagship.newVisitor("visitor_unique_id")
              .context(new HashMap<String, Object>() {{
                  put("age", 32);
                  put("isVip", true);
              }})
              .build();
HashMap<String, Object visitorContext = visitor.getContext();
```

### Managing visitor consent

The Visitor class provides a method to let you manage visitor consent for data privacy usage. When False, ***campaign activation*** and ***hits*** will be disabled and cache cleared.

#### **`public void setConsent(Boolean hasConsented)`**

| Parameter    | Type    | Description                                                                                                                      |
| ------------ | ------- | -------------------------------------------------------------------------------------------------------------------------------- |
| hasConsented | Boolean | Set visitor consent for private data usage. When false some features will be deactivated, cache will be deactivated and cleared. |

```java
Visitor visitor = Flagship.newVisitor("visitor_unique_id").build();
  visitor.setConsent(false);
```

{% hint style="warning" %}
🚧

When consent is not given: Hits, Activations will be deactivated and all the cached visitor data will be cleared until consent is given again.\
Only consent tracking requests will enabled in order to clear server-side cached data.
{% endhint %}

### Handle Visitor cache

The cache manager helps to cache visitors data, to cache hits not sent due to internet failures or server errors, to cache campaign assignations for offline mode and to prevent reallocation in Bucketing mode. Indeed, as the assignation is made on local device in bucketing mode, changing campaign allocation in the platform without a cache, would make visitors to see different campaigns.

The Flagship Java SDK includes a ready-to-use cache implementation using a local SQLite database. It is recommended to use it on environments that only manage one visitor at a time (client) and therefore it is not implemented by default.

For environments that manage multiple visitors at the same time (server) it is possible to provide a custom cache implementation using the following abstract class and the specific interfaces:

```java
// Use the included ready-to-use local SQlite implemenation. (Client environments only)

Flagship.start("_ENV_ID_", "_API_KEY_", new FlagshipConfig.DecisionApi()
                        .withCacheManager(new SQLiteCacheManager()));

// Use a custom implementation to connect with your own database. (Server environments)
        Flagship.start("_ENV_ID_", "_API_KEY_", new FlagshipConfig.DecisionApi()
                .withCacheManager(new CacheManager.Builder()
                        .withVisitorCacheLookupTimeout(200L)
                        .withHitCacheLookupTimeout(200L)
                        .withVisitorCacheImplementation(new IVisitorCacheImplementation() {
                            @Override
                            public void cacheVisitor(String visitorId, JSONObject data) throws InterruptedException {
                                // Upsert in your database.
                            }

                            @Override
                            public JSONObject lookupVisitor(String visitorId) {
                                // Find in your database.
                                return null;
                            }

                            @Override
                            public void flushVisitor(String visitorId) {
                                // Clear data from your database.
                            }
                        })
                        .withHitCacheImplementation(new IHitCacheImplementation() {
                            @Override
                            public void cacheHit(String visitorId, JSONObject data) {
                                // Insert hit in your database.
                            }

                            @Override
                            public JSONArray lookupHits(String visitorId) {
                                // Find and delete in your database.
                                return null;
                            }

                            @Override
                            public void flushHits(String visitorId) {
                                // Clear data from your database.
                            }
                        })
                        .build()));
```

#### **`interface IVisitorCacheImplementation`**

This interface specifies the methods to implement in order to cache visitors information.

#### **`public void cacheVisitor(String visitorId, JSONObject data)`**

This method is called when the SDK needs to cache visitor information in your database.

| Parameter | Type       | Description                                                  |
| --------- | ---------- | ------------------------------------------------------------ |
| visitorId | String     | Visitor unique identifier from which data need to be cached. |
| data      | JSONObject | data to cache                                                |

#### **`public JSONObject lookupVisitor(String visitorId)`**

This method is called when the SDK needs to get visitor information from your database. This method will block the current thread so it will be called with a configurable timeout. **See** [**Cache format**](#cache-data-format) **section**.

| Parameter | Type   | Description                                                  |
| --------- | ------ | ------------------------------------------------------------ |
| visitorId | String | Visitor unique identifier from which data need to be loaded. |

Return : visitor information json respecting the expected format.

#### **`public void flushVisitor(String visitorId)`**

This method is called when the SDK needs to flush visitor information in your database. For example when the user hasn't given his consent this method will be called.

| Parameter | Type   | Description                                                   |
| --------- | ------ | ------------------------------------------------------------- |
| visitorId | String | Visitor unique identifier from which data need to be cleared. |

#### **`interface IHitCacheImplementation`**

This interface specifies the methods to implement in order to cache visitors hits when they failed to be sent.

#### **`public void cacheHit(String visitorId, JSONObject data)`**

This method is called when the SDK needs to cache visitor hits in your database.

| Parameter | Type       | Description                                                  |
| --------- | ---------- | ------------------------------------------------------------ |
| visitorId | String     | Visitor unique identifier from which hits need to be cached. |
| data      | JSONObject | data to cache                                                |

#### **`public JSONArray lookupHits(String visitorId)`**

This method is called when the SDK needs to get visitor hits from your database in order to send them again. This method will block the current thread so it will be called with a configurable timeout. **See** [**Cache format**](#cache-data-format) **section**.

| Parameter | Type   | Description                                                  |
| --------- | ------ | ------------------------------------------------------------ |
| visitorId | String | Visitor unique identifier from which hits need to be loaded. |

Return : visitor hits json array respecting the expected format.

{% hint style="warning" %}
🚧 Hits must be deleted

Cached hits must be deleted before being returned from `lookupHits` so it prevents hits cache duplication if they failed to be sent again.
{% endhint %}

#### **`public void flushHits(String visitorId)`**

This method is called when the SDK needs to flush visitor hits in your database. For example when the user hasn't given his consent this method will be called.

| Parameter | Type   | Description                                                   |
| --------- | ------ | ------------------------------------------------------------- |
| visitorId | String | Visitor unique identifier from which hits need to be cleared. |

### Experience Continuity

Dealing with anonymous and logged-in users, experience continuity allows you to maintain consistency between sessions and devices.

{% hint style="warning" %}
🚧

Make sure that the experience continuity option is enabled on the flagship platform before using those methods.
{% endhint %}

#### Authenticate

There are 2 ways to authenticate a visitor:

1. Set key isAuthenticated to true when creating a new visitor
2. Use authenticate method of `Visitor` instance

   **`public void authenticate(visitorId: String)`**

| Parameter | Type   | Description                          |
| --------- | ------ | ------------------------------------ |
| visitorId | String | id of the new authenticated visitor. |

{% hint style="warning" %}
🚧

Because we have changed the visitor data, we have to call the **fetchFlags method** after calling this one to update the decision from Flagship. The targeting / Flags could be different for the visitor.
{% endhint %}

#### Unauthenticate

This function change authenticated Visitor to anonymous visitor.

**`public void unauthenticate()`**

{% hint style="warning" %}
🚧

Because we have changed the visitor data, we have to call the **fetchFlags method** after calling this one to update the decision from Flagship.\n\nThe targeting / Flags could be different for the visitor.
{% endhint %}

#### Code example

Let's assume basic scenario to understand how things work:

**1. Your visitor arrives on your app for the first time.**

We need to initialize the visitor but as we don't know anything about this visitor, we'll create a random visitor id or let the SDK do it for us. You can also specify some visitor context if necessary.

```java
Visitor visitor = Flagship.newVisitor("anonymous_001")
                .context(new HashMap<String, Object>() {{
                    put("key", "value");
                }}).build();

visitor.fetchFlags();
```

Here we set an anonymous visitorId property so the SDK or an empty string for auto-generated id for our visitor.

Regardless of how it has been set, the actual visitor id will be what we call the **anonymous id**.

**2. Your visitor is signing in.**

To tell the SDK about this status modification, you'll have to call the authenticate function which takes the required visitor id as argument.

```java
// Once you fetch the visitorId from your DB

visitor.authenticate(visitorId);

// Since your visitor has changed (is now logged-in)
// You have to check if the proper targeting and flags are set

visitor.fetchFlags();
```

The visitor is updated as authenticated, keeping the previous variations from campaigns that are still matched and thus gives you same flags as before being logged in.

{% hint style="info" %}
📘

Keep in mind that if the visitor also has its context changed, you might still have changes on flags as your visitor might target new campaigns.
{% endhint %}

**3. Your visitor decides to sign out.**

If you want to keep the same visitor experience, then you should do:

```java
visitor.unauthenticate();

// Since your visitor has changed (is now logged-out)
// You have to check if the proper targeting and flags are set

visitor.fetchFlags();
```

#### Final implementation example

```java
//The current visitor is anonymous

Visitor visitor = Flagship.newVisitor("anonymous_001")
        .context(new HashMap<String, Object>() {{
            put("key", "value");
        }}).build();

visitor.fetchFlags();


//Once the visitor logs in, and you can get his unique id:

visitor.authenticate(visitorId);
visitor.fetchFlags();

//And When he logs out:

visitor.unauthenticate();
visitor.fetchFlags();
```

## Manage Visitor Flags

### Fetching Flags

The `fetchFlags()` method of the `Visitor` instance automatically updates the campaign assignments according to the current user context and retrieves applicable flags.

These flags are then stored in the SDK and updated asynchronously when `fetchFlags()` is called.

```java
Visitor visitor = Flagship.newVisitor("visitor_unique_id").build();
visitor.updateContext("postcode", "31200");
visitor.fetchFlags().get(); // Synchronous Blocking call
visitor.fetchFlags().whenComplete((instance, error) -> { // Asynchronous non blocking call
    // flag synchronization has been completed.
});
```

#### **`public CompletableFuture<Visitor> fetchFlags()`**

This function will call the decision api and update all the campaigns flags from the server according to the visitor context.

| Return                       | Description                                                               |
| ---------------------------- | ------------------------------------------------------------------------- |
| `CompletableFuture<Visitor>` | Return a CompletableFuture to manage sync/async call to the decision api. |

### Getting flags

Once the campaign has been **assigned** and **fetched**, all the flags are stored in the SDK. You can retrieve these flags using the following functions from the `Visitor` instance:

```java
Visitor visitor = Flagship.newVisitor("visitor_unique_id").build();
visitor.updateContext("isVip", true);
visitor.fetchFlags().whenComplete((instance, error) -> {
    Flag<Boolean> displayVipFeature = visitor.getFlag("displayVipFeature", false);
});
```

#### **`public <T> Flag<T> getFlag(String key, T defaultValue)`**

Retrieve a Flag object by its key. If no flag match the given key an empty flag will be returned. Call exists() to check if the flag has been found.

| Parameter    | Type   | Description                  |
| ------------ | ------ | ---------------------------- |
| key          | String | key associated to the flag.  |
| defaultValue | T      | flag default fallback value. |

{% hint style="warning" %}
🚧

* Default value must be one of the following type : `String`, `Boolean`, `Number`, `JSONArray`, 'JSONObject'.
  {% endhint %}

#### Getting flags current values

To retrieve flag current value, simply call value() method of the Flag object.

```java
Visitor visitor = Flagship.newVisitor("visitor_1");
visitor.updateContext("isVip", true);
visitor.fetchFlags().whenComplete((instance, error) -> {
    Boolean displayVipFeature = visitor.getFlag("displayVipFeature", false).value(false);
    // display or hide the vip feature
});
```

#### **`fun value(userExposed: Boolean = true): T?`**

Returns the value from the assigned campaign variation or the Flag default value if the Flag does not exist, or if types are different.

| Parameter   | Type    | Description                                                                                                                                                                                                                                                                                |
| ----------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| userExposed | Boolean | <p>Tells Flagship the user have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting.<br>If needed it is possible to set this param to false and call <code>userExposed()</code> afterward when the user sees it.</p> |

### Get Flag metadata

You may need to send campaign IDs or variation IDs to a third party for reporting and/or analytics purposes. It is possible to retrieve campaigns metadata for a specific Flag.

```java
val visitor = Flagship.newVisitor("visitor_id").build();
visitor.updateContext("isVip", true);
visitor.fetchFlags().get();
FlagMetadata campaignMetadata = visitor.getFlag("displayVipFeature", false).metadata();
```

#### **`fun metadata() : FlagMetadata`**

Return the flag campaign information metadata or an empty object if the Flag doesn't exist or if the default value type does not correspond to the Flag type in Flagship.

**FlagMetadata**

| Field            | Type    | Description                                     |
| ---------------- | ------- | ----------------------------------------------- |
| campaignId       | String  | Campaign identifier the flag belongs to.        |
| variationGroupId | String  | Variation group identifier the flag belongs to. |
| variationId      | String  | Variation identifier the flag belongs to.       |
| isReference      | Boolean | Is the flag from the original variation.        |
| campaignType     | String  | Type of the flag campaign.                      |
| slug             | String  | Campaign custom id.                             |

### Report a Flag exposition

When the method value() of the Flag instance is called, You have the possibility to tell the SDK that the user have seen the effets of this Flag, unless you pass false to value(). In this case you will have to call userExposed() when necessary.

There are two options for exposing a user to a flag:

1. Pass an `userExposed=true` parameter to the **value()** method.
2. Use the following **userExposed()** method from the Flag instance.

```java
Visitor visitor = Flagship.newVisitor("visitor_1").build();
visitor.updateContext("isVip", true);
visitor.fetchFlags().whenComplete((instance, error) -> {

val displayVipFeature = visitor.getFlag("displayVipFeature", false).value(true);
  
// or
 
val displayVipFeature = visitor.getFlag("displayVipFeature", false).value(false); 
// ...
visitor.userExposed();
	
}
fun userExposed()
```

Tells Flagship the user have been exposed and have seen this flag. This will increment the visits for the current variation on your campaign reporting. No user exposition will be sent if the Flag doesn't exist or if the default value type do not correspond to the Flag type in Flagship.

| Parameter | Type   | Description                           |
| --------- | ------ | ------------------------------------- |
| key       | String | key associated to the Flag to report. |

Check if a Flag exists

#### **`fun exists()`**

This method will return true if a Flag exists in Flagship

```java
Visitor visitor = Flagship.newVisitor("visitor_1").build();
visitor.updateContext("isVip", true);
visitor.fetchFlags().whenComplete((instance, error) -> {

  val isDisplayVipFeatureExists = visitor.getFlag("do_not_exists", false).exists();

}
```

## Hit Tracking

This section helps you track your users in your application and learn how to build hits in order to feed campaign goals. For more information about our measurement protocol, read our [Universal Collect documentation](https://docs.abtasty.com/server-side/concepts/universal-collect-1).

There are four different types of Hits available:

* Page
* Screen
* Transaction
* Item
* Event

**They must all be built and sent with the following function from the`Visitor` instance.**

### **Send Hit**

```java
visitor.sendHit(new Page("https://www.my_domain_com/my_page"))
```

#### **`public void sendHit(Hit hit)`**

Send hits as objectives in your campaign reporting.

| Parameter | Type | Description  |
| --------- | ---- | ------------ |
| hit       | Hit  | Hit to send. |

#### Hit common optional parameters

```java
Screen screen = new Screen("screen location")
                .withResolution(200, 100)
                .withLocale("fr_FR")
                .withIp("127.0.0.1")
                .withSessionNumber(2);
 visitor.sendHit(screen);
```

| Parameter         | Type     | Description                  |
| ----------------- | -------- | ---------------------------- |
| withIp            | String   | Optional. User IP            |
| withResolution    | int, int | Optional. Screen resolution. |
| withLocale        | String   | Optional. User language      |
| withSessionNumber | int      | Optional. Session number     |

### Page

This hit should be sent each time a visitor arrives on a new page on the server side.

```java
Page page = new Page("https://www.my_domain_com/my_page")

visitor.sendHit(page);
```

#### **`public Page(String location)`**

| Builder Parameter | Type   | Description |
| ----------------- | ------ | ----------- |
| location          | String | Valid url.  |

### Screen

This hit should be sent each time a visitor arrives on an interface on the client side.

```java
Screen screen = new Screen("your_screen_name")

visitor.sendHit(screen);
```

#### **`public Screen(String location)`**

| Builder Parameter | Type   | Description     |
| ----------------- | ------ | --------------- |
| location          | String | Interface name. |

### Transaction

This hit should be sent when a user complete a Transaction.

```java
Transaction transaction = new Transaction("#12345", "affiliation")
                .withCouponCode("code")
                .withCurrency("EUR")
                .withItemCount(1)
                .withPaymentMethod("creditcard")
                .withShippingCosts(9.99f)
                .withTaxes(19.99f)
                .withTotalRevenue(199.99f)
                .withShippingMethod("1day");
visitor.sendHit(transaction);
```

#### **`Transaction(String transactionId, String affiliation)`**

| Builder Parameter  | Type   | Description                                                                                                                        |
| ------------------ | ------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| transactionId      | String | Unique identifier for your transaction.                                                                                            |
| affiliation        | String | The name of the KPI that you will have inside your reporting. [**Learn more**](https://docs.abtasty.com/server-side/glossary#kpi)  |
| withTotalRevenue   | float  | (optional) Specifies the total revenue associated with the transaction. This value should include any shipping and/or tax amounts. |
| withShippingCosts  | float  | (optional) The total shipping cost of your transaction.                                                                            |
| withShippingMethod | String | (optional) The shipping method for your transaction.                                                                               |
| withTaxes          | float  | (optional) Specifies the total amount of taxes in your transaction.                                                                |
| withCurrency       | String | (optional) Specifies the currency of your transaction. NOTE: This value should be a valid ISO 4217 currency code.                  |
| withPaymentMethod  | String | (optional) Specifies the payment method used for your transaction.                                                                 |
| withItemCount      | int    | (optional) Specifies the number of items in your transaction.                                                                      |
| withCouponCode     | String | (optional) Specifies the coupon code used by the customer in your transaction.                                                     |

### Item

This hit is used to link an item with a transaction. It must be sent after the corresponding transaction hit.

```java
Item item = new Item("#12345", "product", "sku123")
                .withItemCategory("test")
                .withItemPrice(199.99f)
                .withItemQuantity(1);
visitor.sendHit(item);
```

#### **`Item(String transactionId, String productName, String productSku)`**

| Builder Parameter | Type   | Description                                                 |
| ----------------- | ------ | ----------------------------------------------------------- |
| transactionId     | String | Unique identifier for your transaction.                     |
| productName       | String | Name of your item.                                          |
| productSku        | String | Specifies the SKU or item code.                             |
| withItemCategory  | String | (optional) Specifies the category that the item belongs to. |
| withItemPrice     | float  | (optional) Specifies the price for a single item/unit.      |
| withItemQuantity  | int    | (optional) Specifies the number of items purchased.         |

### Event

This hit can be used for any event (e.g. Add To Cart click, newsletter subscription).

```java
Event event = new Event(Event.EventCategory.USER_ENGAGEMENT, "action")
                .withEventLabel("label")
                .withEventValue(100);
visitor.sendHit(event);
```

#### **`public Event(EventCategory category, String action)`**

| Builder Parameter | Type          | Description                                                                                                                                                                                     |
| ----------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| category          | EventCategory | Specifies the category of your event. NOTE: This value must be either `'ACTION_TRACKING'` or `'USER_ENGAGEMENT'`.                                                                               |
| action            | String        | Event name that will also serve as the KPI that you will have inside your reporting. [**Learn more**](https://docs.abtasty.com/server-side/glossary#kpi)                                        |
| withEventLabel    | String        | (optional) Additional description of your event.                                                                                                                                                |
| withEventValue    | int           | (optional) Specifies the monetary value associated with an event (e.g. you earn 10 to 100 euros depending on the quality of lead generated). NOTE: this value must be non-negative integer > 0. |

## Appendix

### Predefined user context keys : FlagshipContext

The Flagship SDK contains predefined user context keys.

The keys marked as **Yes** in the **Auto-set by SDK** column will be automatically set, while the ones marked as **No** need to be set by the customer.

{% hint style="info" %}
📘

Check the values sent by the SDK by enabling the logs.
{% endhint %}

You can overwrite these keys at any time. The key-value pairs will be sent to the server in the user context and can be edited in the [Persona](https://docs.abtasty.com/server-side/glossary#user-context) section of the Flagship platform.

| SDK Variable Name    | Description                                            | Context variable name   | Type       | Auto-set by SDK | Example       |
| -------------------- | ------------------------------------------------------ | ----------------------- | ---------- | --------------- | ------------- |
| DEVICE\_LOCALE       | Language of the device                                 | sdk\_deviceLanguage     | String     | No              | fra           |
| DEVICE\_TYPE         | Type of the device                                     | sdk\_deviceType         | DeviceType | No              | Mobile        |
| DEVICE\_MODEL        | Model of the device                                    | sdk\_deviceModel        | String     | No              | samsung E1200 |
| LOCATION\_CITY       | City geolocation                                       | sdk\_city               | String     | No              | toulouse      |
| LOCATION\_REGION     | Region geolocation                                     | sdk\_region             | String     | No              | occitanie     |
| LOCATION\_COUNTRY    | Country geolocation                                    | sdk\_country            | String     | No              | France        |
| LOCATION\_LAT        | Current Latitude                                       | sdk\_lat                | Double     | No              | 43.623647     |
| LOCATION\_LONG       | Current Longitude                                      | sdk\_long               | Double     | No              | 1.445397      |
| OS\_NAME             | Name of the OS                                         | sdk\_osName             | String     | No              | android / iOS |
| OS\_VERSION\_NAME    | Version name of the OS                                 | sdk\_osVersionName      | String     | No              | 9.0.0         |
| OS\_VERSION\_CODE    | Version code of the OS                                 | sdk\_osVersionCode      | Number     | No              | 24            |
| CARRIER\_NAME        | Name of the carrier or mobile virtual network operator | sdk\_carrierName        | String     | No              | free          |
| INTERNET\_CONNECTION | What is the internet connection                        | sdk\_internetConnection | String     | No              | 5g            |
| APP\_VERSION\_NAME   | Version name of the app                                | sdk\_versionName        | String     | No              | 1.1.2-beta    |
| APP\_VERSION\_CODE   | Version code of the app                                | sdk\_versionCode        | Number     | No              | 40            |
| INTERFACE\_NAME      | Name of the interface                                  | sdk\_interfaceName      | String     | No              | ProductPage   |
| FLAGSHIP\_CLIENT     | Flagship SDK client (Reserved)                         | fs\_client              | String     | Yes             | Java          |
| FLAGSHIP\_VERSION    | Version of the Flagship SDK (Reserved)                 | fs\_version             | String     | Yes             | 2.0.0         |
| FLAGSHIP\_VISITOR    | Current visitor id (Reserved)                          | fs\_users               | String     | Yes             | 2.0.0         |

{% hint style="info" %}
📘

To overwrite the keys, use the [`updateContext`](#updating-visitor-context) method
{% endhint %}

### Cache data format

#### **IVisitorCacheImplementation lookup format**

```json
{
  "version": 1,
  "data": {
    "visitorId": "visitor_1",
    "consent": true,
    "context": {
      "fs_users": "visitor_1",
      "sdk_osVersionCode": 31,
      "sdk_deviceModel": "Google Pixel 3",
      "fs_client": "android",
      "fs_version": "3.0.0",
      "sdk_carrierName": "Free",
      "sdk_osVersionName": "Android 12 S",
      "sdk_deviceType": "mobile",
      "plan": "enterprise",
      "sdk_deviceLanguage": "fra",
      "sdk_osName": "Android"
    },
    "assignmentsHistory": {
      "xxxxxxxxxxxxxxxxxxxx": "xxxxxxxxxxxxxxxxxxxx",
      "yyyyyyyyyyyyyyyyyyyy": "yyyyyyyyyyyyyyyyyyyy"
    },
    "campaigns": [
      {
        "campaignId": "xxxxxxxxxxxxxxxxxxxx",
        "variationGroupId": "xxxxxxxxxxxxxxxxxxxx",
        "variationId": "xxxxxxxxxxxxxxxxxxxx",
        "isReference": false,
        "type": "",
        "activated": false,
        "flags": {
          "key": "value"
        }
      },
      {
        "campaignId": "xxxxxxxxxxxxxxxxxxxx",
        "variationGroupId": "xxxxxxxxxxxxxxxxxxxx",
        "variationId": "xxxxxxxxxxxxxxxxxxxx",
        "isReference": false,
        "type": "",
        "activated": false,
        "flags": {
          "myAwesomeFeature": 20
        }
      }
    ]
  }
}
```

#### **IHitCacheImplementation lookup format**

```json
[
  {
    "version": 1,
    "data": {
      "time": 1637606817507,
      "visitorId": "visitor_1",
      "anonymousId": "e436e87f-cc61-44d6-ab40-fba15aec0af5",
      "type": "ACTIVATION",
      "content": {
        "cid": "xxxxxxxxxxxxxxxxxxxx",
        "caid": "xxxxxxxxxxxxxxxxxxxx",
        "vaid": "xxxxxxxxxxxxxxxxxxxx",
        "aid": "e436e87f-cc61-44d6-ab40-fba15aec0af5",
        "vid": "visitor_1"
      }
    }
  }
]
```
