Skip to content

About

Java SDK for Featurevisor

Resources

Stars

1 star

Watchers

1 watching

Forks

Latest commit

ย 

History

32 Commits

Folders and files

Repository files navigation

Featurevisor Java SDK

Use the Featurevisor Java SDK to evaluate flags, variations and variables in Java applications.

Table of contents

Installation

Upgrading an existing application? Follow the Java migration guide.

In your Java application, update pom.xml to add the following:

Repository

For finding GitHub Package (public package):

<repositories>
    <repository>
        <id>github</id>
        <name>GitHub Packages</name>
        <url>https://maven.pkg.github.com/featurevisor/featurevisor-java</url>
    </repository>
</repositories>

Dependency

Add the Featurevisor Java SDK as a dependency with your desired version:

<dependencies>
    <dependency>
        <groupId>com.featurevisor</groupId>
        <artifactId>featurevisor-java</artifactId>
        <version>5.0.0</version>
    </dependency>
</dependencies>

Browse Java SDK packages

Authentication

To authenticate with GitHub Packages, in your ~/.m2/settings.xml file, add the following:

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              http://maven.apache.org/xsd/settings-1.0.0.xsd">

  <servers>
    <server>
      <id>github</id>
      <username>YOUR_GITHUB_USERNAME</username>
      <password>YOUR_GITHUB_TOKEN</password>
    </server>
  </servers>

</settings>

Generate a token with read:packages scope in GitHub token settings

Example applications:

Initialization

Read a built datafile from a local file and pass its content to the SDK. Save this Java 11 example as Main.java and place featurevisor-all.json in your working directory:

import com.featurevisor.sdk.Featurevisor;
import com.featurevisor.sdk.DatafileContent;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {
        String json = Files.readString(Path.of("featurevisor-all.json"));
        DatafileContent datafileContent = DatafileContent.fromJson(json);
        Featurevisor f = Featurevisor.createFeaturevisor(
            new Featurevisor.FeaturevisorOptions().datafile(datafileContent)
        );
        try {
            System.out.println(f.isEnabled("checkout", Map.of("userId", "123")));
        } finally {
            f.close();
        }
    }
}

File read and JSON parsing failures propagate to the caller. You can also load the content with Java's HTTP client. Check for a successful HTTP status before passing the response body to the SDK. The following sections cover the available options.

Public API

The main runtime API is Featurevisor.createFeaturevisor():

import com.featurevisor.sdk.FeaturevisorLogLevel;

Featurevisor f = Featurevisor.createFeaturevisor(
    new Featurevisor.FeaturevisorOptions().datafile(datafileContent)
);

Most applications only need Featurevisor.createFeaturevisor, the Featurevisor instance type, and Featurevisor.FeaturevisorOptions. Public extension and observability types include FeaturevisorModule, FeaturevisorDiagnostic, and the datafile model types.

Concurrent evaluations are safe after an instance is configured. Do not call state changing methods such as setDatafile, setContext, setStickyFeatures, setStickyVariables, addModule, removeModule, or close concurrently with evaluations or with each other. Apply those changes from a serialized update path. Module, event, and diagnostic callbacks must synchronize mutable state that they capture.

Evaluation types

Featurevisor evaluates four kinds of values:

  • Flag (boolean): whether the feature is enabled or not
  • Variation (String): the variation of the feature (if any)
  • Feature variable: a configuration value owned by a feature
  • Global variable: a configuration value evaluated independently of a feature

These evaluations are run against the provided context.

Context

Contexts are attribute values you pass to the SDK for evaluating features against.

Conditions compare these attributes using the operators, including empty and notEmpty.

Date comparisons with before and after accept portable timestamp strings, Instant, java.util.Date (including java.sql.Timestamp), OffsetDateTime and ZonedDateTime. Native values are compared by their instant and truncated to milliseconds without rounding. Both the native written year, where present, and the UTC year must be within 1 to 9999. Explicit native offsets must have a magnitude of at most 14 hours, including any seconds. Offsets within that limit retain their full precision. Instant and java.util.Date have only an instant, so no offset check applies. LocalDate and LocalDateTime are not accepted because they do not identify an instant. Invalid values make both operators return false.

They are plain maps:

Map<String, Object> context = new HashMap<>();
context.put("userId", "123");
context.put("country", "nl");
// ...other attributes

Setting initial context

Set context when you create the instance:

Map<String, Object> initialContext = new HashMap<>();
initialContext.put("deviceId", "123");
initialContext.put("country", "nl");

Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions()
    .datafile(datafileContent)
    .context(initialContext));

This is useful for values that don't change too frequently and available at the time of application startup.

Setting after initialization

Add context later:

Map<String, Object> additionalContext = new HashMap<>();
additionalContext.put("userId", "123");
additionalContext.put("country", "nl");

f.setContext(additionalContext);

This will merge the new context with the existing one (if already set).

Replacing existing context

Replace the context by passing true as the second argument:

Map<String, Object> newContext = new HashMap<>();
newContext.put("deviceId", "123");
newContext.put("userId", "234");
newContext.put("country", "nl");
newContext.put("browser", "chrome");

f.setContext(newContext, true); // replace existing context

Manually passing context

Pass context to one evaluation without changing the instance context:

Map<String, Object> context = new HashMap<>();
context.put("userId", "123");
context.put("country", "nl");

boolean isEnabled = f.isEnabled("checkout", context);
String variation = f.getVariation("checkout", context);
String variableValue = f.getVariableString("checkout", "bgColor", context);

When manually passing context, it will merge with existing context set to the SDK instance before evaluating the specific value.

Check if enabled

Check whether a feature is enabled:

String featureKey = "checkout";

boolean isEnabled = f.isEnabled(featureKey);

if (isEnabled) {
    // do something
}

Pass additional context to one evaluation:

Map<String, Object> additionalContext = new HashMap<>();
// ...additional context

boolean isEnabled = f.isEnabled(featureKey, additionalContext);

Getting variation

Evaluate a feature's variations:

String featureKey = "checkout";

String variation = f.getVariation(featureKey);

if ("treatment".equals(variation)) {
    // do something for treatment variation
} else {
    // handle default/control variation
}

Pass additional context to one evaluation:

String variation = f.getVariation(featureKey, additionalContext);

Getting variables

Getting feature variables

Evaluate a feature's variables:

String variableKey = "bgColor";

String bgColorValue = f.getVariableString(featureKey, variableKey);

Pass additional context to one evaluation:

String bgColorValue = f.getVariableString(featureKey, variableKey, additionalContext);

Type specific methods

Next to generic getVariable() methods, there are also type specific methods available for convenience:

f.getVariableBoolean(featureKey, variableKey, context);
f.getVariableString(featureKey, variableKey, context);
f.getVariableInteger(featureKey, variableKey, context);
f.getVariableDouble(featureKey, variableKey, context);
f.getVariableArray(featureKey, variableKey, context);

f.<Map<String, Object>>getVariableObject(featureKey, variableKey, context);
f.<MyCustomClass>getVariableObject(featureKey, variableKey, context);

f.<Map<String, Object>>getVariableJSON(featureKey, variableKey, context);
f.<MyCustomClass>getVariableJSON(featureKey, variableKey, context);
f.getVariableJSONNode(featureKey, variableKey, context);

Type specific methods do not coerce values. getVariableInteger() returns null for the string "1", and boolean getters return null for non-boolean values.

For strongly typed decoding, additional overloads are available:

import com.fasterxml.jackson.core.type.TypeReference;

// Array decoding using Class<T>
List<MyItem> items = f.getVariableArray(featureKey, variableKey, context, MyItem.class);

// Array decoding using TypeReference
List<Map<String, Object>> rows = f.getVariableArray(
    featureKey,
    variableKey,
    context,
    new TypeReference<List<Map<String, Object>>>() {}
);

// Object decoding using Class<T>
MyConfig config = f.getVariableObject(featureKey, variableKey, context, MyConfig.class);

// Object decoding using TypeReference
Map<String, List<MyConfig>> nested = f.getVariableObject(
    featureKey,
    variableKey,
    context,
    new TypeReference<Map<String, List<MyConfig>>>() {}
);

If decoding fails for the requested target type, these methods return null.

For dynamic JSON values with unknown shape, use getVariableJSONNode:

import com.fasterxml.jackson.databind.JsonNode;

JsonNode node = f.getVariableJSONNode(featureKey, variableKey, context);

if (node != null && node.isObject()) {
    String nested = node.path("key").path("nested").asText(null);
}

If a variable schema type is json and the resolved value is a malformed stringified JSON, JSON parsing fails safely and these methods return null:

  • getVariable(...)
  • getVariableJSONNode(...)
  • getVariableJSON(...)

Getting global variables

Global variables use the same overloaded methods as variables inside features. A call with one key evaluates a global variable, while a call with a feature key and variable key evaluates a variable owned by that feature:

String message = f.getVariableString("welcomeMessage", context, null);
Object value = f.getVariable("checkoutSettings", context);
Evaluation evaluation = f.evaluateVariable("checkoutSettings", context);

The type specific methods are getVariableBoolean, getVariableString, getVariableInteger, getVariableDouble, getVariableArray, getVariableObject, and getVariableJSON.

Root conditions and overrides are applied for you. See Variables and Conditions for authoring.

Conditions and composed variables

Conditions combine attribute comparisons, literal segment keys, feature getters and variable comparisons. Arrays imply AND. Logical groups use and, or and not, with NOT negating the AND of its children. Empty expressions are false. Variable paths in generated datafiles are compiled arrays, not authored dotted paths.

Feature evaluation checks sticky values, force rules, root conditions and traffic rules in that order. Global variables check sticky values and root conditions before sources and overrides. An unmet root returns conditions_unmet and exposes Evaluation.getConditions(). Disabled variations and feature variables retain their existing disabled reasons.

Composed global variables use the ordinary getters:

Object screen = f.getVariable("checkoutScreen", context);
Object policy = f.getVariable("policyAlias", context);
Evaluation evaluation = f.evaluateVariable("checkoutScreen", context);

A map composition assembles a fresh outer object with literal properties from feature flags, variations, feature variables and global variables. A string composition aliases one literal global variable key and returns its value directly. Sources use effective context, child sticky state and modules. False, zero, empty strings, arrays and explicit null remain values. JSON sources decode exactly once, even through alias chains. An outer caller default is never forwarded to sources.

Compositions have no defaultValue or useDefaultWhenDisabled. Root conditions can return disabledValue or null without reading sources or overrides. Whole variable sticky state bypasses composition. Sources are read before runtime overrides, whose mutation operations copy changed paths without modifying sources, siblings or sticky values. Successful composition reports variable_composed, or variable_override_rule when an override matches.

Treat supplied datafiles and returned objects as read only. Copy values before changing them. Composed members and string aliases retain ordinary getter ownership. Only the map's outer object is freshly assembled.

Conditions, segments and composition share cycle detection and a combined dependency depth bound of 256. A cycle or exhausted depth fails the complete evaluation through its ordinary error result. A thread stack too small for the chain fails the same way, and getters never throw StackOverflowError. A subsequent public call starts a fresh session.

To see which overrides changed a value, read variableOverridePaths from evaluateVariable. The singular override fields describe the final match.

Getting evaluations

Evaluate all features available in the instance:

import com.featurevisor.sdk.EvaluatedFeatures;
import com.featurevisor.sdk.EvaluatedFeature;

EvaluatedFeatures allEvaluations = f.getFeatureEvaluations(context);

// Access the evaluations map
Map<String, EvaluatedFeature> evaluations = allEvaluations.getValue();

System.out.println(evaluations);
// {
//   "checkout": {
//     "enabled": true,
//     "variation": "control",
//     "variables": {
//       "myVariableKey": "myVariableValue"
//     }
//   },
//
//   "anotherFeature": {
//     "enabled": true,
//     "variation": "treatment"
//   }
// }

This is handy especially when you want to pass all evaluations from a backend application to the frontend.

Global variables can be evaluated together as well:

Map<String, Object> variables = f.getVariableEvaluations(context, null, null);

Sticky

Set sticky values to take precedence over feature evaluation against the datafile:

Sticky values belong to an SDK or child instance. Feature sticky values and global variable sticky values are independent.

Map<String, Object> stickyFeatures = new HashMap<>();

Map<String, Object> checkoutSticky = new HashMap<>();
checkoutSticky.put("enabled", true);
checkoutSticky.put("variation", "treatment");

Map<String, Object> checkoutVariables = new HashMap<>();
checkoutVariables.put("myVariableKey", "myVariableValue");
checkoutSticky.put("variables", checkoutVariables);

stickyFeatures.put("checkout", checkoutSticky);

Map<String, Object> anotherFeatureSticky = new HashMap<>();
anotherFeatureSticky.put("enabled", false);
stickyFeatures.put("anotherFeatureKey", anotherFeatureSticky);

Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions()
    .datafile(datafile)
    .stickyFeatures(stickyFeatures)
    .stickyVariables(Map.of("welcomeMessage", "Hello")));

Once initialized with sticky features, the SDK will look for values there first before evaluating the targeting conditions and going through the bucketing process.

Set sticky features after initialization:

Map<String, Object> stickyFeatures = new HashMap<>();
// ... build sticky features map

f.setStickyFeatures(stickyFeatures, true); // replace existing sticky features
f.setStickyVariables(Map.of("welcomeMessage", "Welcome back"), true); // replace

Setting datafile

You may also initialize the SDK without passing datafile, and set it later on:

f.setDatafile(datafileContent);

setDatafile accepts either a parsed DatafileContent or a raw JSON string. All overloads return true when the datafile is accepted, including unchanged content, and false when the input is rejected or the instance is closed. Rejected input leaves the last accepted datafile in place and reports the existing diagnostic and error event, without a datafile_set event. Calls after closing do nothing. Accepted calls still emit datafile_set, even when nothing changed. The return value reports acceptance, not whether any features changed.

boolean accepted = f.setDatafile(datafileContent);

Merging by default

By default, setDatafile(datafile) merges the incoming datafile with the SDK's stored datafile. Incoming top level metadata is used, and incoming segments, features, and global variables override existing entities with the same keys.

Call setDatafile with different datafiles to merge their features, segments, and global variables. Use this to load datafiles on demand.

Replacing

To replace the stored datafile entirely, pass true:

f.setDatafile(datafileContent, true); // replace

Loading datafiles on demand

Merge datafiles for different targets into the same instance. Here, the two datafile values have already been loaded and validated by your application from the same published release:

f.setDatafile(productsDatafile);
f.setDatafile(checkoutDatafile);

Use immutable release URLs, check HTTP responses and keep shared dependencies consistent. See Loading datafiles on demand for the complete loading and refresh flow.

Updating datafile

Each accepted datafile update emits a datafile_set event. Subscribe to react to updates.

The triggers for setting the datafile again can be:

  • periodic updates based on an interval (like every 5 minutes), or
  • reacting to:
    • a specific event in your application (like a user action), or
    • an event served via websocket or server-sent events (SSE)

Interval-based update

Replace the complete datafile on each refresh so definitions removed upstream are removed from the SDK too. Use merging only when loading partial datafiles intentionally.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.featurevisor.sdk.DatafileContent;

// f is the existing Featurevisor instance
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create(datafileUrl))
    .timeout(Duration.ofSeconds(30))
    .build();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() -> {
    try {
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() == 200) {
            DatafileContent newDatafile = DatafileContent.fromJson(response.body());
            f.setDatafile(newDatafile, true); // replace
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } catch (Exception e) {
        System.err.println("Failed to update datafile: " + e.getMessage());
    }
}, 0, 5, TimeUnit.MINUTES);

Call scheduler.shutdownNow() when your application shuts down.

Diagnostics

By default, Featurevisor reports diagnostics to the console for info level and above with a [Featurevisor] prefix.

Levels

Available diagnostic levels are FATAL, ERROR, WARN, INFO, and DEBUG.

Set the level during initialization or update it afterwards:

Featurevisor f = Featurevisor.createFeaturevisor(
    new Featurevisor.FeaturevisorOptions().logLevel(FeaturevisorLogLevel.DEBUG)
);

f.setLogLevel(FeaturevisorLogLevel.INFO);

Handler

Use onDiagnostic to send structured diagnostics to your observability system:

Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions()
    .logLevel(FeaturevisorLogLevel.INFO)
    .onDiagnostic(diagnostic -> {
        System.out.println(diagnostic.getLevel() + ": " + diagnostic.getCode());
    }));

Generated datafiles use schemaVersion "4". Schema "2" selectors normalize eagerly when accepted, while schema "4" entities normalize on first read. Partial updates invalidate only incoming entities. Replacement clears all entity caches. Legacy compatibility conversion does not change caller objects or the informational version metadata.

Malformed stringified conditions fail only their complete selector, including through NOT or segment aliases, without rejecting the datafile. conditions_parse_error is reported at error level once per selector per incoming entity load. Its details are exactly conditions, entityType and entityKey. Eager diagnostics run after storage, and lazy diagnostics run after caching, so callbacks may safely reenter getters.

Every diagnostic has level, code, message, and an object shaped details map. Optional module, moduleName, and originalError fields describe provenance. Evaluation metadata belongs in details.

Diagnostic handlers are isolated from SDK behaviour. An exception in a handler does not stop other handlers or evaluations.

Events

Subscribe to SDK events to respond to context, sticky state and datafile changes.

Subscribe to instance lifecycle events: