The Featurevisor Java SDK evaluates flags, variations and variables in Java and Kotlin applications, from a datafile it holds in memory.
- Install
- Create an instance
- Context
- Check a flag
- Get a variation
- Get a variable
- Default values
- Evaluate everything at once
- Sticky values
- Update the datafile
- Child instances
- Events
- Diagnostics
- Evaluation details
- Modules
- Schemas
- Close
- OpenFeature
- CLI usage
- GitHub repositories
- Development of this package
- License
The SDK is published to GitHub Packages. Add the repository and the dependency to your pom.xml:
<repositories>
<repository>
<id>github</id>
<name>GitHub Packages</name>
<url>https://maven.pkg.github.com/featurevisor/featurevisor-java</url>
</repository>
</repositories><dependencies>
<dependency>
<groupId>com.featurevisor</groupId>
<artifactId>featurevisor-java</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>Browse the Java SDK packages for every version. The SDK supports Java 11 and later. Upgrading an existing application? Follow the Java migration guide.
GitHub Packages needs a token, even for public packages. Generate one with the read:packages scope in your GitHub token settings, and add it to ~/.m2/settings.xml:
<?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>See the Java application and the Kotlin Android application for complete examples.
Read a datafile and create an instance with it. Save this example as Main.java, with 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", "user-4")));
} finally {
f.close();
}
}
}This example closes the instance at once. In a long running application, keep it for every evaluation and close it at shutdown. To fetch a datafile over HTTP instead, check for a successful status before passing the body to DatafileContent.fromJson. Every option is optional, so an instance can start without a datafile and receive one later:
| Option | Sets |
|---|---|
datafile, datafileString |
The datafile to evaluate |
context |
The instance context |
stickyFeatures, stickyVariables |
Sticky values |
logLevel, onDiagnostic |
Diagnostics |
modules |
Modules |
Create one instance and reuse it. On a server that handles many users, give each request a child instance.
Evaluations are safe from many threads once an instance is set up. Apply changes, such as setDatafile, setContext, setStickyFeatures, setStickyVariables, addModule, removeModule and close, from one thread at a time, never during evaluations. Module, event and diagnostic callbacks synchronize any state of their own.
Context is a plain map of attribute values. The instance keeps a context of its own, and each evaluation can add to it.
Set it when creating the instance:
Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions()
.datafile(datafileContent)
.context(Map.of("country", "nl")));Add to it later with setContext, or replace it by passing true as the second argument:
f.setContext(Map.of("userId", "user-4"));
f.setContext(Map.of(
"userId", "user-2",
"country", "nl"
), true);Context passed to an evaluation is merged over the instance context for that call only:
Map<String, Object> context = Map.of(
"userId", "user-4",
"country", "nl"
);
f.isEnabled("checkout", context);getContext() returns the instance context, and getContext(Map.of("country", "de")) shows it merged with extra values without storing them.
Dates compare as portable timestamp strings, Instant, java.util.Date, OffsetDateTime or ZonedDateTime, by their instant, truncated to milliseconds. Offsets stay within 14 hours and years within 1 and 9999. LocalDate and LocalDateTime name no instant, so they are not accepted.
isEnabled reads a flag. Dutch users have the new checkout:
Map<String, Object> context = Map.of(
"userId", "user-4",
"country", "nl"
);
if (f.isEnabled("checkout", context)) {
// show the new checkout
}getVariation returns the variation of a feature, or null if the feature is disabled or has none:
String variation = f.getVariation("pricing", context);
if ("treatment".equals(variation)) {
// show the new pricing
}For user-4 it returns "control", and for user-2 it returns "treatment".
getVariable reads a feature variable with a feature key and a variable key. For user-4, the netherlands rule sets the buy button's label to "Nu kopen":
Object label = f.getVariable("buyButton", "label", context);With a context as its second argument, it reads a global variable instead. supportEmail returns "support-nl@example.com" for user-4:
Object email = f.getVariable("supportEmail", context);Two keys mean a feature variable, and one key a global variable. The typed methods below follow the same rule.
Treat returned maps and lists as read only. The SDK can share them with its datafile rather than copy them on every evaluation, so copy a value before changing it, and never change a datafile after passing it to the instance.
Each typed method returns null when the value has a different type, and never converts it. getVariableInteger returns null for the string "1", and getVariableBoolean returns null for "true".
| Method | Returns |
|---|---|
getVariableBoolean |
Boolean |
getVariableString |
String |
getVariableInteger |
Integer |
getVariableDouble |
Double, whole or fractional |
getVariableArray |
List |
getVariableObject<T> |
T, or Map<String, Object> |
getVariableJSON<T> |
T, decoded JSON |
getVariableJSONNode |
A Jackson JsonNode |
Map<String, Object> settings = f.getVariableObject("checkoutSettings", context, null);
// {currency=EUR, paymentMethods=[card]}For a feature variable, pass a Class or a Jackson TypeReference to decode it into your own type, and get null when it does not decode:
ButtonStyle style = f.getVariableObject(
"buyButton",
"style",
context,
ButtonStyle.class
);
List<PaymentMethod> methods = f.getVariableArray(
"checkout",
"paymentMethods",
context,
new TypeReference<List<PaymentMethod>>() {}
);getVariableJSONNode suits a value of unknown shape. A json variable whose text does not parse returns null from getVariable, getVariableJSON and getVariableJSONNode.
Read a composed global variable like any other global variable. For a string compose alias, choose the getter for the source's type, such as getVariableString for an alias of supportEmail. It returns what the source's own getter returns, including decoded JSON and null, with no wrapper or copy.
A composition is evaluated in this order:
- A sticky value for the whole variable, which skips everything after it.
- Root
conditions. When they miss, no source is read and no override runs. The result isdisabledValuewhen supplied, otherwisenull, with reasonconditions_unmet. - The sources, with their own sticky values, the context and modules taking part as usual.
- The overrides, which run as they do for any global variable.
Compositions have no defaultValue or useDefaultWhenDisabled. With no override match, the reason is variable_composed, and a match reports variable_override_rule, with getVariableOverridePaths() listing every override that changed the value. Only the outer map of a composition is fresh, so treat what it holds as read only.
Cycles, and chains of more than 256 dependencies, fail the whole evaluation. A thread stack too small for a chain fails it the same way, so getters never throw StackOverflowError.
Pass defaultVariationValue or defaultVariableValue in OverrideOptions for when an evaluation produces no value, such as a feature missing from the datafile:
Object label = f.getVariable(
"buyButton",
"label",
context,
new Featurevisor.OverrideOptions().defaultVariableValue("Buy")
);A default counts as given whenever it is set, so "", 0, false and null are all valid defaults.
getFeatureEvaluations evaluates every loaded feature, or only the keys you pass:
EvaluatedFeatures evaluations = f.getFeatureEvaluations(
context,
List.of("checkout", "pricing", "buyButton"),
null
);
// checkout: enabled
// pricing: enabled, variation control
// buyButton: enabled, variation treatment, variables {label: Nu kopen}getVariableEvaluations does the same for global variables:
Map<String, Object> variables = f.getVariableEvaluations(
context,
List.of("supportEmail", "checkoutSettings"),
null
);Pass null as the keys to evaluate them all. To see what is loaded without evaluating anything:
getFeatureKeys()lists every feature in the datafile, enabled or not.getVariableKeys()lists global variables, andgetVariableKeys("buyButton")lists that feature's variables.hasVariations("pricing")istruewhen a feature has variations, andfalsefor an unknown feature.
Both results have the shape sticky values take. A server can evaluate once per request and pass the results to its client, so the first render matches what the server saw. The JavaScript SDK's sticky values read them in a browser.
Sticky values take precedence over the datafile. Use them to keep a user's result fixed, to answer before a datafile has loaded, or in unit tests:
Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions()
.stickyFeatures(Map.of(
"checkout", Map.of("enabled", true),
"pricing", Map.of("enabled", true, "variation", "treatment")
))
.stickyVariables(Map.of(
"supportEmail", "support@example.com"
)));A sticky feature can also set variables. Change sticky values later with setStickyFeatures and setStickyVariables. Both merge by default, and replace the whole map when the second argument is true:
f.setStickyFeatures(Map.of(
"checkout", Map.of("enabled", false)
), true);Treat sticky maps as read only once given to an instance, and change them only through these methods.
setDatafile gives the instance a newer datafile, parsed or as a JSON string:
boolean accepted = f.setDatafile(datafileContent);It returns true when the datafile is accepted, even if nothing changed, and false when it is rejected or the instance is closed. A rejected datafile leaves the previous one in place and is reported through diagnostics.
By default, the new datafile is merged into the current one:
- Its features, segments and global variables replace those with the same keys.
- Definitions it does not contain are kept.
- Its
revisionandschemaVersionare taken.
Pass true to replace the current datafile entirely. Do this when refreshing a complete datafile, so definitions removed from it do not linger:
f.setDatafile(datafileContent, true);Merging is what lets one instance hold datafiles for several targets, loaded as each part of the application needs them. See Loading datafiles on demand.
Fetch the datafile again every few minutes:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create(datafileUrl))
.timeout(Duration.ofSeconds(30))
.build();
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(() -> {
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
f.setDatafile(response.body(), true);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
System.err.println("Could not refresh datafile: " + e.getMessage());
}
}, 5, 5, TimeUnit.MINUTES);A failed fetch keeps the previous datafile. setDatafile does not throw for an invalid datafile, it reports it through diagnostics. Call scheduler.shutdownNow() when you stop, since close() does not stop your scheduler. Each accepted update emits datafile_set.
A server handles many users at once, so give each request a child with its own context:
ChildInstance child = f.spawn(Map.of(
"userId", "user-4",
"country", "nl"
));
child.isEnabled("checkout");- The child copies the parent's context keys when it is spawned, and its own values win. Keys the parent adds later still reach it.
- Sticky values are not inherited. Pass
Featurevisor.SpawnOptionsas the second argument when the child needs some. - A child has the parent's evaluation methods, plus
getContext,setContext,setStickyFeatures,setStickyVariables,onandclose. close()removes the child's listeners, including the ones it registered on its parent.
on subscribes to an event and returns a FeaturevisorUnsubscribe, whose unsubscribe() stops it.
Emitted for every accepted datafile:
FeaturevisorUnsubscribe subscription = f.on(FeaturevisorEventName.DATAFILE_SET, event -> {
String revision = (String) event.get("revision");
String previousRevision = (String) event.get("previousRevision");
Boolean revisionChanged = (Boolean) event.get("revisionChanged");
Boolean replaced = (Boolean) event.get("replaced");
List<?> features = (List<?>) event.get("features");
List<?> variables = (List<?>) event.get("variables");
List<?> segments = (List<?>) event.get("segments");
// evaluate the listed features and variables again
});
subscription.unsubscribe();replaced says whether the datafile replaced the previous one or merged into it. features and variables list the keys whose results may have changed: those added, updated or removed, and those that depend on them through conditions, segments and composition sources, however indirectly. Evaluate those again and you have everything that changed.
segments lists the segments whose definitions were added, changed or, on a replace, removed. If a new datafile has the netherlands segment take Belgium too, segments is ["netherlands"], and features and variables include checkout and supportEmail, whose conditions read it. The first datafile lists every feature, global variable and segment. sections lists the changed entries of each datafile section, such as schemas.
Emitted by setContext:
f.on(FeaturevisorEventName.CONTEXT_SET, event -> {
Map<?, ?> context = (Map<?, ?>) event.get("context"); // the new instance context
List<?> keys = (List<?>) event.get("keys"); // the top level keys whose values changed
});keys compares values, so a key set again to the value it already holds is not listed. Starting from the instance context {"userId": "user-4", "country": "nl"}:
f.setContext(Map.of(
"country", "de"
));
// keys: ["country"]
f.setContext(Map.of(
"country", "de",
"plan", "paid"
));
// keys: ["plan"]
f.setContext(Map.of(
"userId", "user-4",
"country", "de"
), true);
// keys: ["plan"]A replace also lists the keys it removed, as plan above. Maps and lists compare item by item, and numbers by value, so 30 and 30.0 are the same, but a map or list given again as the same object counts as changed, since it may have been changed in place.
Emitted by setStickyFeatures, with features, every feature that had a sticky value before the call or has one after it, and replaced:
f.on(FeaturevisorEventName.STICKY_FEATURES_SET, event -> {
List<?> features = (List<?>) event.get("features");
});Emitted by setStickyVariables, with variables and replaced:
f.on(FeaturevisorEventName.STICKY_VARIABLES_SET, event -> {
List<?> variables = (List<?>) event.get("variables");
});Emitted for every diagnostic at ERROR:
f.on(FeaturevisorEventName.ERROR, event -> {
FeaturevisorDiagnostic diagnostic = (FeaturevisorDiagnostic) event.get("diagnostic");
});The SDK reports what happens during evaluation as diagnostics, at one of five levels: FATAL, ERROR, WARN, INFO and DEBUG. By default, those at INFO and above go to the console with a [Featurevisor] prefix.
DEBUG shows how each value was evaluated, which helps when a result surprises you. Set the level when creating the instance, or later:
Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions()
.logLevel(FeaturevisorLogLevel.DEBUG));
f.setLogLevel(FeaturevisorLogLevel.WARN);To send diagnostics somewhere other than the console, pass a handler:
Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions()
.onDiagnostic(diagnostic -> {
// send diagnostic.getLevel(), getCode(), getMessage() and getDetails() to your observability system
}));Every diagnostic has a level, a code, a message and a details map. Values about an evaluation, such as featureKey, variableKey, reason and evaluation, are in the details. The module, module name and original error say where an error came from, when known. A handler that throws stops neither other handlers nor evaluations.
conditions_parse_error is an ERROR diagnostic for malformed stringified conditions. It fires once per selector per datafile load, on first read for v4 datafiles and during setDatafile for v3 datafiles. Its details contain conditions with the raw string, entityType and entityKey.
The whole malformed selector evaluates to false, even under not, while other entities keep working and setDatafile returns true for an otherwise valid datafile. A malformed root gate is unmet and reports conditions_unmet.
Dependency cycles fail the whole evaluation with reason error. SDK evaluation errors return the ordinary false or null result, and other entities keep working.
The evaluate methods return how a value was reached, not only the value:
f.evaluateFlag("checkout", context);
f.evaluateVariation("pricing", context);
f.evaluateVariable("buyButton", "label", context);
f.evaluateVariable("supportEmail", context);For user-4, evaluateFlag returns an Evaluation with these getters answering:
| Getter | Value |
|---|---|
getType() |
"flag" |
getFeatureKey() |
"checkout" |
getReason() |
"rule" |
getBucketKey() |
"user-4.checkout" |
getBucketValue() |
89312 |
getRuleKey() |
"netherlands" |
getEnabled() |
true |
Every evaluation has a type and a reason. The others are null unless they apply:
getFeatureKey(),nullfor global variablesgetBucketKey()andgetBucketValue(), from 0 to 100,000, and thegetRuleKey()that matchedgetEnabled(),getVariation()andgetVariationValue()getVariableKey(),getVariableValue(),getVariableSchema()andgetVariable(), the global variable's definitiongetVariableOverrideKey()andgetVariableOverrideIndex()when a keyed override matched, andgetVariableOverridePath()for a nested onegetVariableOverridePaths(), every override path matched in order, for accumulating overrides. The singular getters describe the last matchgetConditions()when a root gate stopped the evaluationgetError()when evaluation failed
Test specs can assert them.
| Reason | Meaning |
|---|---|
feature_not_found |
The feature is not in the datafile |
disabled |
The feature is disabled |
no_variations |
A variation was requested from a feature without variations |
variation_disabled |
A disabled feature returned its disabledVariationValue |
variable_not_found |
The feature variable or global variable is not in the datafile |
variable_default |
The variable returned its default value |
variable_composed |
A global variable read its composition sources with no override match |
variable_disabled |
A disabled feature returned the variable's disabled value |
variable_override_variation |
A feature variable override matched inside a variation |
variable_override_rule |
A feature variable override or global variable override matched |
conditions_unmet |
Root conditions did not match. See getConditions() |
no_match |
No rule, allocation or variation matched, or the bucket fell outside the rollout |
forced |
A force entry supplied the result |
sticky |
A sticky value supplied the result |
rule |
A matching rule supplied the result |
allocated |
Bucketing allocated the result |
error |
Evaluation failed. See getError() |
A module hooks into evaluation. It can change the context before an evaluation, change the result after it, or decide how users are bucketed. Every part is optional:
FeaturevisorModule auditModule = new FeaturevisorModule("audit")
.setup(api -> {
api.onDiagnostic(diagnostic -> {
// diagnostics at this module's own level
});
api.reportDiagnostic(new FeaturevisorDiagnostic()
.level(FeaturevisorLogLevel.INFO)
.code("module_ready")
.message("Ready for revision " + api.getRevision()));
})
.beforeEvaluation(options -> {
// type, feature key, variable key and context
Map<String, Object> context = new HashMap<>(options.getContext());
context.put("plan", "paid");
return options.copy().context(context);
})
.afterEvaluation((evaluation, options) -> {
// log evaluation.getError() when the reason is error
return evaluation;
})
.bucketKey(options -> options.getBucketKey())
// between 0 and 100,000
.bucketValue(options -> options.getBucketValue())
.close(() -> {
// clean up when the instance closes
});beforeEvaluation and afterEvaluation run for flags, variations and both kinds of variable, every module in registration order, and must return the options and the evaluation, changed or not. A variable evaluation without a feature key is a global one.
beforeEvaluation also runs when a schema validates, with getType() schema and the schema's key in getKey() instead of a feature key, so context it adds reaches the schema's conditions too. afterEvaluation does not run then, since a validation's result is not an evaluation. Check the type before reading the keys.
The before evaluation and after evaluation phases each use the module membership at the start of that phase, and the bucket key and bucket value phases each use their own. Adding or removing a module during a phase does not change the iteration already in progress.
If setup throws, the module is not registered. The SDK removes the diagnostic subscriptions it made, reports module_setup_error, and calls its close if it has one.
Conditions and composition members are evaluated through modules too. Their options answer getDependencyOf(), naming the requesting evaluation by type, feature key and variable key. getDependencyPurpose() is condition for an eligibility check and composition for a consumed member value. Direct calls have neither.
When tracking consumed evaluations, skip eligibility checks, not every read with a requester, since a variation read through a composition can be an experiment exposure. Within one call, repeated reads with the same inputs and purpose are memoized, so callbacks can run fewer times than there are reads. Return the same result for the same input during one evaluation, and pass values that change through the context.
Pass modules when creating the instance, or add them later:
Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions()
.modules(List.of(auditModule)));
Runnable remove = f.addModule(trackingModule);
// later
remove.run();
f.removeModule("audit");A package, such as schemas, reads the datafile through the API setup receives:
getEntry(section, key)returns an entry of a section, a top level key besides Featurevisor's own whose value is an object, such asschemas. Treat it as read only.getEntryKeys(section)lists a section's keys.matchConditions(conditions, context, options)answers the package's own conditions with the instance's engine, segments and feature leaves included.MatchConditionsOptionsreaders answer leaves only the package knows, such asinput.evaluate(new PackageEvaluationRequest(type, key).context(context), scope -> ...)evaluates the package's own entry as a getter evaluates a flag. Every module'sbeforeEvaluationruns first, withgetType()andgetKey()naming the entry, and the conditions the callback answers withscope.matchConditions(conditions, readers)read the context the modules leave, in one dependency session.
Feature and variable leaves reach modules as dependencies, naming the package's entry as their requester. A module with no evaluation callbacks, such as a package's, costs evaluations nothing.
Schemas validate data against the schemas your datafiles deliver, with the instance you already have, and the same rules, messages and conditions as @featurevisor/schemas in JavaScript.
Schemas are experimental, so their API may change in a minor release, as in JavaScript.
They are a separate artifact, released with the same version as the SDK:
<dependency>
<groupId>com.featurevisor</groupId>
<artifactId>featurevisor-schemas</artifactId>
<version>5.1.0</version>
</dependency>Create it from the SDK instance. Call it s, as the SDK instance is f:
import com.featurevisor.schemas.Schemas;
Schemas s = Schemas.create(f);It holds no copy of the schemas. Every call reads the datafile f has now, so a new datafile applies at the next validation. Compiled schemas are kept until a datafile changes them, and handles are safe to share between threads.
Map<String, Object> value = Map.of(
"email", "user-1@example.com",
"displayName", "A",
"country", "nl"
);
ValidationResult result = s.validate("signUp", value);
if (!result.isValid()) {
// show result.getIssues() beside the form's fields
}s.validate(key, value)returns aValidationResultwith the value itself and its issues. It never coerces, fills defaults or strips keys.s.isValid(key, value)returns a boolean.s.parse(key, value)returns the value, or throws aSchemaValidationException, for a server or a script that wants a value or a stop.- All three take a context as a third argument, merged over the instance's, for the conditions a schema's rules read.
- A validation runs as the schema's own evaluation, so a module's
beforeEvaluationsees it, with typeschemaand the schema's key, and context the module adds reaches every condition, as it does for flags. s.getKeys()lists the schemas the datafile has, ands.has(key)says whether it has one.
A value can be maps, lists, strings, numbers, booleans and null, a Jackson JsonNode, or any object Jackson can convert, such as a request class with getters.
A key the datafile does not have fails closed, with one schemaNotFound issue, and a schema_not_found diagnostic at WARN, once per key.
Every issue has a message, a path of object keys and list indices, the code of the rule that failed, its params, and the schema validated. issue.getField() gives its path as a form names a field, such as items.0.name.
Validation reports every issue it finds, so a form can mark every field at once. An issue about a field with a title carries it in its title param, and one whose rule a mutation set names it in getMutation().
| Code | Raised when |
|---|---|
type |
The value has another type |
const, enum |
The value is not one allowed |
minimum, maximum |
A number is out of range |
minLength, maxLength |
A string is too short or too long |
pattern, format |
A string has the wrong shape |
minItems, maxItems |
A list has too few or too many items |
uniqueItems |
A list repeats an item |
required, additionalProperties |
A key is missing, or there is one it does not allow |
oneOf |
No branch matches, or more than one does |
refine |
An issues entry matches, or a check in code fails |
refineError |
A check in code throws, or the schema itself cannot be applied |
schemaNotFound |
The datafile has no such schema or field |
result.flatten() groups the messages by field, in the shape of Zod's flattenError, and so does flatten() on a SchemaValidationException, for an error response.
A handle is one schema as an object your code holds: it validates, and describes the schema's fields, constraints, choices and annotations for a form. s.get(key) gives one:
SchemaHandle signUp = s.get("signUp");A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application. s.get(key, options) gives the same handle for the same HandleOptions object, so build the options once. A key the datafile lacks keeps no handle.
| Member | What it is |
|---|---|
validate, isValid, parse |
As on s, without the key |
validateAsync |
Validation as a CompletableFuture, for checks in code |
field(path) |
The handle of one field, such as field("displayName") |
getFields() |
An object's fields' handles, in order, each with its getName() |
getConstraints(), getFieldConstraints() |
HTML validation attributes, by field path on an object, below |
getOptions(), getFieldOptions(), option(value) |
Its choices, by field path on an object, and one choice by value |
getRenderAs() |
What its rules say the field renders as, such as RenderAs.SELECT |
getAnnotations() |
Its annotations |
withInput(input) |
The same handle with an input |
getReads() |
The fields its rules' conditions read |
subscribe(listener) |
A call when a new datafile changes the schema |
getKey(), getPath(), getName() |
The schema's key, and the field's path and own name |
field takes a field name as form libraries write it: address.city, items.0.name or items[0].name, and items[].name for every item alike. It follows references and stops at oneOf. A path the schema lacks fails closed with schemaNotFound.
getConstraints() are named after HTML attributes:
FieldConstraints constraints = signUp.field("displayName").getConstraints();
constraints.isRequired(); // true
constraints.getMinLength(); // 2
constraints.getMaxLength(); // 40
constraints.toAttributes();
// {required=true, minlength=2, maxlength=40}, for a templateisRequired(), when the key is required, so an input left empty failsgetMinLength()andgetMaxLength(), from the same rules on a stringgetMin()andgetMax(), fromminimumandmaximumon a numbergetStep()of 1, for anintegerisMultiple(), for a list, such as a multiple select
getOptions() lists a field's choices in the order of its rules, each with what its annotations say, and option(value) finds one, for showing a value saved earlier:
SchemaHandle country = signUp.field("country");
country.getOptions(); // nl, de and be, each a SchemaOption
country.option("nl").getTitle(); // "Netherlands"
country.option("fr"); // nullA schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. getRenderAs() answers the switch every generic form writes, from the field's rules alone: TEXT, DATE_TIME, VERSION, NUMBER, BOOLEAN, SELECT, MULTISELECT, OBJECT or LIST. Your own annotation, such as input: select, still wins over it.
A handle's getAnnotations() are its node's own, and getFields() gives an object's fields in its order:
signUp.getAnnotations().get("title"); // "Create your account"
signUp.getFields().stream().map(SchemaHandle::getPath).collect(Collectors.toList());
// [displayName, email, country]default is the value a form starts a field with, and a handle from withInput has the one a mutation sets. Fields an order annotation leaves out come after it, in name order by Unicode code point, as in every SDK. A field or schema the datafile lacks has no annotations. Annotations on Schemas writes them.
A handle's constraints and choices describe the schema's own rules, which no condition changes. withInput(input) gives the same handle with an input, such as a form's values, with the mutations that match it applied, so a tax ID shows as required once a business account is chosen:
Map<String, Object> values = Map.of(
"accountType", "business",
"country", "nl"
);
signUp.field("taxId").getConstraints().isRequired(); // false
signUp.withInput(values).field("taxId").getConstraints().isRequired(); // trueEvery member follows the input, at every depth. getReads() lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes.
SchemasOptions words every schema's issues, per code, as a template or a SchemaMessage:
Schemas s = Schemas.create(f, new SchemasOptions()
.message("required", "This field is required"));HandleOptions.message(field, code, template) on s.get words one form. For each issue, the first of these that words it wins:
- A check in code's own message, then the form's.
- The schema's own, and then the
messageof its issues entry. - The application's, from
SchemasOptions. - The default, in English.
A translator on SchemasOptions gets each issue, with the message chosen, and returns what the issue says, or null to keep it. With translations, messages hold keys, such as errors.required, and the translator turns each into text.
Some checks need your application, such as whether a display name is taken. Give them to a handle with HandleOptions.refine, each a Refinement with a key and a check, and the path it checks, a message and reads as it needs them:
SchemaHandle signUp = s.get("signUp", new HandleOptions()
.refine(Refinement.of("nameAvailable", "displayName",
(displayName, info) -> names.isAvailable((String) displayName))
.message("That display name is taken")));
ValidationResult result = signUp.validate(value);- A check gets the value at its path, and a
CheckInfowith the context and the input, whereinfo.read("country")reads another field. The input is the whole value, except in a field's handle outside a view taken at the schema's root, where it is the field's value. It returnstruewhen the value passes. - It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database.
- Without a path, the check gets the whole value, and runs only when the value has no issue at all.
readsnames other fields whose issues hold it back too, such asitemsfor a check of an order's total. - Its issue has code
refineand therefineparam"nameAvailable", with the field's title. A check that throws givesrefineError, and validation fails closed. Refinement.asynctakes a check returning aCompletionStage.validatewaits for it, andvalidateAsyncreturns aCompletableFutureinstead. Cancelling that future stops waiting for the checks. It does not reach the work your application started.- A check that throws, or completes exceptionally, also reports one
schema_check_errordiagnostic.
Some lists only your application can answer for, such as cities for a city field. Give a handle an OptionSource with HandleOptions.optionSource, with a key, a path, and a search, a lookup or both:
SchemaHandle signUp = s.get("signUp", new HandleOptions()
.optionSource(OptionSource.of("cities", "city")
.reads("country")
.search((query, info) -> cities.search((String) info.read("country"), query))
.lookup((city, info) -> cities.find((String) info.read("country"), (String) city))
.message("Choose a city from the list")));
SchemaHandle city = signUp.withInput(Map.of("country", "nl")).field("city");
List<SchemaOption> suggestions = city.search("am").join();
// Amsterdam and Amersfoortsearchreturns choices shaped likegetOptions(), or values alone. A handle'ssearchpasses it the values given towithInput, so the cities follow the country.canSearch()says whether a field has one.lookupreturns the choice for a value,truewhen it carries nothing more, ornullwhen there is none. A handle'slookup(value)returns the schema's own choice first, then the source's.- Validation runs
lookupas a check in code, after the schema's rules, only for a value that is there, and not while a fieldreadsnames has an issue. A value it cannot find has codeenum, worded by its message.searchAsyncandlookupAsynctake sources that answer later.
parse answers a request with a value or a SchemaValidationException, whose flatten() gives the issues by field:
@PostMapping("/sign-up")
public ResponseEntity<?> signUp(@RequestBody Map<String, Object> body) {
try {
Object value = s.parse("signUp", body);
return ResponseEntity.ok(accounts.create(value));
} catch (SchemaValidationException error) {
return ResponseEntity.badRequest().body(error.flatten());
}
}A rule changed in your project reaches the browser and the server at their next datafile, so the two never disagree.
subscribe calls back when a new datafile changes the schema, through a schema it references too, and returns a FeaturevisorUnsubscribe that stops it:
FeaturevisorUnsubscribe stop = s.get("signUp").field("country")
.subscribe(() -> renderChoices());A datafile whose schema is unchanged calls nothing. s.close() stops every listener the instance started and removes its module from the Featurevisor instance.
Schema patterns are JavaScript regular expressions with the u flag, and they mean the same here: $ is the end of the value, \s is JavaScript's whitespace, and . reads an emoji as one character, as lengths do. A pattern that does not compile with u, such as [a-z\_], fails every value.
A schema that cannot answer fails the value closed and says why with an ERROR diagnostic, once per schema and datafile revision:
schema_pattern_unsupported: a pattern does not compile.schema_mutation_error: a mutation's operations cannot be applied. The value fails withrefineError.schema_reference_depth: the value is nested more than 128 references deep, which is how deep a tree of nodes that each reference the tree's schema can go. The 129th fails withrefineError.schema_check_error: a check in code or an option source's lookup threw, or completed exceptionally. The value fails withrefineError.detailsholdsschemaKey,checkandpath, andoriginalErrorthe exception. A check that fails because the validation was cancelled reports nothing.
A type the package does not know fails every value with a type issue. required lists keys that must be there whatever properties holds, so an object with additionalProperties only, or no properties at all, still reports each missing key.
A field handle for a field the schema lacks reports its schemaNotFound issue, with field, and no schema_not_found diagnostic, which is for a schema the datafile lacks. Java has no "no value" for a field handle to validate, since null is a value, so a field validated alone is never read as absent. Validate the whole value to have required reported.
close() removes event listeners and closes modules, on the instance and on a child:
f.close();The OpenFeature provider is published as a separate artifact. Applications that use only com.featurevisor:featurevisor-java receive no provider classes or OpenFeature dependency.
Add the provider with the same version as the Featurevisor Java SDK:
<dependency>
<groupId>com.featurevisor</groupId>
<artifactId>featurevisor-openfeature</artifactId>
<version>5.1.0</version>
</dependency>The provider artifact depends on the matching Featurevisor Java SDK and the official OpenFeature Java SDK 1.23.0, so no additional dependency is required. Both retain Java 11 as the minimum runtime.
import com.featurevisor.openfeature.FeaturevisorOpenFeatureProvider;
import com.featurevisor.sdk.Featurevisor;
import dev.openfeature.sdk.ImmutableContext;
import dev.openfeature.sdk.OpenFeatureAPI;
var provider = new FeaturevisorOpenFeatureProvider(
new Featurevisor.FeaturevisorOptions().datafile(datafileContent)
);
var api = OpenFeatureAPI.getInstance();
api.setProviderAndWait(provider);
var client = api.getClient();
boolean enabled = client.getBooleanValue("checkout", false, new ImmutableContext("user-4"));Use checkout for a flag, checkout:variation for its variation, buyButton:label for a feature variable, and variable:supportEmail for a global variable. Boolean variables use the boolean resolver. Lists, structures, and JSON variables use the object resolver.
OpenFeature's targeting key maps to userId by default. targetingKeyField, keySeparator, variationKey, and globalVariablePrefix on FeaturevisorOpenFeatureProvider.Options can customize the mapping. The global variable prefix defaults to variable and cannot contain the configured separator.
Reuse an existing Featurevisor instance:
Featurevisor featurevisor = Featurevisor.createFeaturevisor(featurevisorOptions);
var provider = new FeaturevisorOpenFeatureProvider(featurevisor);The caller owns an instance passed this way. Provider shutdown does not close it. Call featurevisor.close() when every consumer is finished with it. When the provider creates the instance from options, the provider owns and closes it. If both are configured, the existing instance takes precedence.
An invalid initial datafile in an owned instance fails setProviderAndWait with a parse error, independently of the diagnostic log level. Valid updates clear the error and emit readiness. Supplied diagnostic callbacks and module setup remain unchanged, and shutdown closes only an owned instance.
Composed values map to TARGETING_MATCH without additional JSON decoding. Unmet root conditions map to DISABLED. Ordinary null values retain the provider default policy.
See the OpenFeature provider guide for resolution reasons, errors, metadata, tracking, lifecycle, and providers for other languages.
Compile the CLI module from this SDK repository:
mvn -pl featurevisor-sdk compileThe native test runner requires Node.js 24 or later. Install the Node.js CLI in your Featurevisor project:
npm install --save-dev @featurevisor/cli@^4.0.0Project parsing and datafile generation use npx featurevisor. Evaluations run through this Java SDK. The SDK runtime has no Node.js dependency. All three commands accept repeated --target=<target> options.
Use the Node.js CLI directly for authoring commands such as init, lint, build and list. Native commands delegate project parsing, test expansion and datafile generation to Node.js, then evaluate the results with this SDK.
Options use kebab case, such as --project-directory-path. The camelCase forms from earlier releases still work, and --root-directory-path is an alias for --project-directory-path. Pass values as --name=value or --name value. Repeat --target to select several targets in order. Run <command> --help to list every option.
--n and -n accept both value forms. Repeat --populate-uuid for multiple context attributes. Quote JSON and paths containing spaces.
mvn -q install -DskipTests
mvn -q -pl featurevisor-schemas exec:java -Dexec.mainClass=com.featurevisor.cli.CLI \
-Dexec.args="test --project-directory-path=/path/to/featurevisor-project --only-failures"Running from featurevisor-schemas puts the schemas artifact beside the SDK, so schema specs validate their values as the JavaScript CLI does. From featurevisor-sdk alone the other specs run as before, and each schema spec case fails asking for featurevisor-schemas.
See Testing for authoring specs and Checks for check syntax and operators.
Segment specs and checks evaluate ordinary SDK gates with the selected datafile, context, fixed bucket and isolated sticky state. Compiled execution definitions restore missing segments. Existing Target segment specializations remain authoritative. Attribute only segment chains can omit the environment, while segments depending on features or variables require the selected datafile. All transitive root and child check references are preflighted before getters. Synthetic segment gates do not count towards coverage.
Useful test options:
--key-pattern=<pattern>and--assertion-pattern=<pattern>filter tests.--entity-type=scenarioselects scenarios, and--entity-type=schemaschema specs.--set=<set>selects one project set. Omitting--setruns all sets.--case=<id>reruns one expanded case. Copy the opaque ID or rerun command from a failure report.--json --prettyproduces an indented JSON report.--coveragereports observed rule and override selections.--uncoveredlists features and global variables without associated specs.--only-failures,--quiet,--verboseand--show-datafilecontrol diagnostic output.
JSON rerun arguments use argumentEncoding: maven-exec. Pass the shell quoted native argument list as one -Dexec.args value, or copy the printed rerun command.
The examples below use a project without environments. Add --environment=<name> if your project configures environments. In a sets project, omit --set to run every set or pass --set=<name>. Repeat --target=<key> to evaluate specific target datafiles. The Node.js CLI validates these options and builds the datafiles. Java evaluates them. Replace checkout with a feature defined in your project.
mvn -q -pl featurevisor-sdk exec:java -Dexec.mainClass=com.featurevisor.cli.CLI \
-Dexec.args="benchmark --project-directory-path=/path/to/featurevisor-project --feature=checkout --context='{\"country\":\"nl\"}' --n=1000"Use --variation for a variation or --variable=<key> for a feature variable. Omit --feature to benchmark a global variable. Do not combine --variation with --variable. See Benchmarking.
mvn -q -pl featurevisor-sdk exec:java -Dexec.mainClass=com.featurevisor.cli.CLI \
-Dexec.args="assess-distribution --project-directory-path=/path/to/featurevisor-project --feature=checkout --populate-uuid=userId --n=1000"The Java CLI also accepts --variation or --variable=<key> to assess a variation or feature variable instead of the enabled state. These selectors are specific to this runner and are not supported by the Node.js assess-distribution command. Repeat --populate-uuid=<key> to generate UUID values for multiple context attributes. See Assess distribution.
- SDK: featurevisor/featurevisor-java
- Example application: featurevisor/featurevisor-example-java
- Kotlin Android example application: featurevisor/featurevisor-example-android
The aggregate evaluation reference has moved to Evaluate everything at once.
The sticky state reference has moved to Sticky values.
Clone the repository, and install the dependencies using Maven:
$ mvn install$ mvn testCompile the actual initialization snippet for Java 11 and execute it with an isolated local datafile:
mvn -Dmaven.test.skip=true package
bash scripts/test-readme-initialization.shThe README check also covers missing files and invalid JSON. CI runs it on both configured JDKs. Pass --offline to reuse cached Maven dependencies locally.
To check runtime command selection against an already built Node.js monorepo:
mvn -pl featurevisor-sdk test-compile dependency:build-classpath -Dmdep.outputFile=target/runtime-classpath.txt
node scripts/test-runtime-commands.mjs ../featurevisor java \
-cp "featurevisor-sdk/target/classes:$(cat featurevisor-sdk/target/runtime-classpath.txt)" \
com.featurevisor.cli.CLI
bash scripts/test-release.sh 5.1.0These checks create temporary flat, environment and sets projects without changing the monorepo or downloading packages. The classpath command above uses the POSIX : separator.
The repository is a Maven reactor with three published libraries:
com.featurevisor:featurevisor-javacom.featurevisor:featurevisor-schemascom.featurevisor:featurevisor-openfeature
Every installation example in this README must match the release version, whichever artifact it installs.
To verify their published JAR and POM boundaries locally:
$ make verify-artifactsThe SDK, schemas, provider and parent POM share version 5.1.0. Before tagging, run bash scripts/verify-release.sh v5.1.0 to check the Maven revision, CLI and every README installation example.
- Merge the release changes into
main. - Tag the release with a
vprefix, such asvX.Y.Z, and push the tag. - GitHub Actions verifies and publishes the parent POM, Java SDK, schemas and OpenFeature provider to GitHub Packages.
- Create the corresponding GitHub release.
MIT © Fahad Heylaal