Skip to content

ThomasKrieger/java-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Repository files navigation

OpenFeature Logo

OpenFeature Java SDK

SpecificationRelease
JavadocMaven CentralCodecovCII Best Practices

OpenFeature is an open specification that provides a vendor-agnostic, community-driven API for feature flagging that works with your favorite feature flag management tool.

🚀 Quick start

Requirements

  • Java 11+ (compiler target is 11)

Note that this library is intended to be used in server-side contexts and has not been evaluated for use on mobile devices.

Install

Maven

<dependency> <groupId>dev.openfeature</groupId> <artifactId>sdk</artifactId> <version>1.18.1</version> </dependency>

If you would like snapshot builds, this is the relevant repository information:

<repositories> <repository> <snapshots> <enabled>true</enabled> </snapshots> <id>sonatype</id> <name>Sonatype Repository</name> <url>https://s01.oss.sonatype.org/content/repositories/snapshots/</url> </repository> </repositories>

Gradle

dependencies{implementation 'dev.openfeature:sdk:1.18.1' }

Usage

publicvoidexample(){// flags defined in memoryMap<String, Flag<?>> myFlags = newHashMap<>(); myFlags.put("v2_enabled", Flag.builder() .variant("on", true) .variant("off", false) .defaultVariant("on") .build()); // configure a providerOpenFeatureAPIapi = OpenFeatureAPI.getInstance(); try{api.setProviderAndWait(newInMemoryProvider(myFlags))} catch (Exceptione){// handle initialization failuree.printStackTrace()} // create a clientClientclient = api.getClient(); // get a bool flag valuebooleanflagValue = client.getBooleanValue("v2_enabled", false)}

API Reference

See here for the Javadocs.

🌟 Features

StatusFeaturesDescription
ProvidersIntegrate with a commercial, open source, or in-house feature management tool.
TargetingContextually-aware flag evaluation using evaluation context.
HooksAdd functionality to various stages of the flag evaluation life-cycle.
TrackingAssociate user actions with feature flag evaluations.
LoggingIntegrate with popular logging packages.
DomainsLogically bind clients with providers.
EventingReact to state changes in the provider or flag management system.
ShutdownGracefully clean up a provider during application shutdown.
Transaction Context PropagationSet a specific evaluation context for a transaction (e.g. an HTTP request or a thread).
ExtendingExtend OpenFeature with custom providers and hooks.

Implemented: ✅ | In-progress: ⚠️ | Not implemented yet: ❌

Providers

Providers are an abstraction between a flag management system and the OpenFeature SDK. Look here for a complete list of available providers. If the provider you're looking for hasn't been created yet, see the develop a provider section to learn how to build it yourself.

Once you've added a provider as a dependency, it can be registered with OpenFeature like this:

Synchronous

To register a provider in a blocking manner to ensure it is ready before further actions are taken, you can use the setProviderAndWait method as shown below:

OpenFeatureAPIapi = OpenFeatureAPI.getInstance(); try{api.setProviderAndWait(newMyProvider())} catch (Exceptione){// handle initialization failuree.printStackTrace()}

Asynchronous

To register a provider in a non-blocking manner, you can use the setProvider method as shown below:

OpenFeatureAPI.getInstance().setProvider(newMyProvider());

In some situations, it may be beneficial to register multiple providers in the same application. This is possible using domains, which is covered in more detail below.

Targeting

Sometimes, the value of a flag must consider some dynamic criteria about the application or user, such as the user's location, IP, email address, or the server's location. In OpenFeature, we refer to this as targeting. If the flag management system you're using supports targeting, you can provide the input data using the evaluation context.

// set a value to the global contextOpenFeatureAPIapi = OpenFeatureAPI.getInstance(); Map<String, Value> apiAttrs = newHashMap<>(); apiAttrs.put("region", newValue(System.getEnv("us-east-1"))); EvaluationContextapiCtx = newImmutableContext(apiAttrs); api.setEvaluationContext(apiCtx); // set a value to the client contextMap<String, Value> clientAttrs = newHashMap<>(); clientAttrs.put("region", newValue(System.getEnv("us-east-1"))); EvaluationContextclientCtx = newImmutableContext(clientAttrs); Clientclient = api.getInstance().getClient(); client.setEvaluationContext(clientCtx); // set a value to the invocation contextMap<String, Value> requestAttrs = newHashMap<>(); requestAttrs.put("email", newValue(session.getAttribute("email"))); requestAttrs.put("product", newValue("productId")); StringtargetingKey = session.getId(); EvaluationContextreqCtx = newImmutableContext(targetingKey, requestAttrs); booleanflagValue = client.getBooleanValue("some-flag", false, reqCtx);

Hooks

Hooks allow for custom logic to be added at well-defined points of the flag evaluation life-cycle Look here for a complete list of available hooks. If the hook you're looking for hasn't been created yet, see the develop a hook section to learn how to build it yourself.

Once you've added a hook as a dependency, it can be registered at the global, client, or flag invocation level.

// add a hook globally, to run on all evaluationsOpenFeatureAPIapi = OpenFeatureAPI.getInstance(); api.addHooks(newExampleHook()); // add a hook on this client, to run on all evaluations made by this clientClientclient = api.getClient(); client.addHooks(newExampleHook()); // add a hook for this evaluation onlyBooleanretval = client.getBooleanValue(flagKey, false, null, FlagEvaluationOptions.builder().hook(newExampleHook()).build());

Tracking

The tracking API allows you to use OpenFeature abstractions to associate user actions with feature flag evaluations. This is essential for robust experimentation powered by feature flags. Note that, unlike methods that handle feature flag evaluations, calling track(...) may throw an IllegalArgumentException if an empty string is passed as the trackingEventName.

OpenFeatureAPIapi = OpenFeatureAPI.getInstance(); api.getClient().track("visited-promo-page", newMutableTrackingEventDetails(99.77).add("currency", "USD"));

Logging

The Java SDK uses SLF4J. See the SLF4J manual for complete documentation. Note that in accordance with the OpenFeature specification, the SDK doesn't generally log messages during flag evaluation.

Logging Hook

The Java SDK includes a LoggingHook, which logs detailed information at key points during flag evaluation, using SLF4J's structured logging API. This hook can be particularly helpful for troubleshooting and debugging; simply attach it at the global, client or invocation level and ensure your log level is set to "debug".

See hooks for more information on configuring hooks.

Domains

Clients can be assigned to a domain. A domain is a logical identifier which can be used to associate clients with a particular provider. If a domain has no associated provider, the global provider is used.

FeatureProviderscopedProvider = newMyProvider(); // registering the default providerOpenFeatureAPI.getInstance().setProvider(LocalProvider()); // registering a provider to a domainOpenFeatureAPI.getInstance().setProvider("my-domain", newCachedProvider()); // A client bound to the default providerClientclientDefault = OpenFeatureAPI.getInstance().getClient(); // A client bound to the CachedProvider providerClientdomainScopedClient = OpenFeatureAPI.getInstance().getClient("my-domain");

Providers for domains can be set in a blocking or non-blocking way. For more details, please refer to the providers section.

Eventing

Events allow you to react to state changes in the provider or underlying flag management system, such as flag definition changes, provider readiness, or error conditions. Initialization events (PROVIDER_READY on success, PROVIDER_ERROR on failure) are dispatched for every provider. Some providers support additional events, such as PROVIDER_CONFIGURATION_CHANGED.

Please refer to the documentation of the provider you're using to see what events are supported.

// add an event handler to a clientClientclient = OpenFeatureAPI.getInstance().getClient(); client.onProviderConfigurationChanged((EventDetailseventDetails) ->{// do something when the provider's flag settings change }); // add an event handler to the global APIOpenFeatureAPI.getInstance().onProviderStale((EventDetailseventDetails) ->{// do something when the provider's cache goes stale });

Shutdown

The OpenFeature API provides a close function to perform a cleanup of all registered providers. This should only be called when your application is in the process of shutting down.

// shut down all providersOpenFeatureAPI.getInstance().shutdown();

Transaction Context Propagation

Transaction context is a container for transaction-specific evaluation context (e.g. user id, user agent, IP). Transaction context can be set where specific data is available (e.g. an auth service or request handler) and by using the transaction context propagator it will automatically be applied to all flag evaluations within a transaction (e.g. a request or thread). By default, the NoOpTransactionContextPropagator is used, which doesn't store anything. To register a ThreadLocal context propagator, you can use the setTransactionContextPropagator method as shown below.

// registering the ThreadLocalTransactionContextPropagatorOpenFeatureAPI.getInstance().setTransactionContextPropagator(newThreadLocalTransactionContextPropagator());

Once you've registered a transaction context propagator, you can propagate the data into request-scoped transaction context.

// adding userId to transaction contextOpenFeatureAPIapi = OpenFeatureAPI.getInstance(); Map<String, Value> transactionAttrs = newHashMap<>(); transactionAttrs.put("userId", newValue("userId")); EvaluationContexttransactionCtx = newImmutableContext(transactionAttrs); api.setTransactionContext(transactionCtx);

Additionally, you can develop a custom transaction context propagator by implementing the TransactionContextPropagator interface and registering it as shown above.

Extending

Develop a provider

To develop a provider, you need to create a new project and include the OpenFeature SDK as a dependency. This can be a new repository or included in the existing contrib repository available under the OpenFeature organization. You’ll then need to write the provider by implementing the FeatureProvider interface exported by the OpenFeature SDK.

publicclassMyProviderimplementsFeatureProvider{@OverridepublicMetadatagetMetadata(){return () -> "My Provider"} @Overridepublicvoidinitialize(EvaluationContextevaluationContext) throwsException{// start up your provider } @Overridepublicvoidshutdown(){// shut down your provider } @OverridepublicProviderEvaluation<Boolean> getBooleanEvaluation(Stringkey, BooleandefaultValue, EvaluationContextctx){// resolve a boolean flag value } @OverridepublicProviderEvaluation<String> getStringEvaluation(Stringkey, StringdefaultValue, EvaluationContextctx){// resolve a string flag value } @OverridepublicProviderEvaluation<Integer> getIntegerEvaluation(Stringkey, IntegerdefaultValue, EvaluationContextctx){// resolve an int flag value } @OverridepublicProviderEvaluation<Double> getDoubleEvaluation(Stringkey, DoubledefaultValue, EvaluationContextctx){// resolve a double flag value } @OverridepublicProviderEvaluation<Value> getObjectEvaluation(Stringkey, ValuedefaultValue, EvaluationContextctx){// resolve an object flag value } }

If you'd like your provider to support firing events, such as events for when flags are changed in the flag management system, extend EventProvider.

classMyEventProviderextendsEventProvider{@OverridepublicMetadatagetMetadata(){return () -> "My Event Provider"} @Overridepublicvoidinitialize(EvaluationContextevaluationContext) throwsException{// emit events when flags are changed in a hypothetical REST APIthis.restApiClient.onFlagsChanged(() ->{ProviderEventDetailsdetails = ProviderEventDetails.builder().message("flags changed in API!").build(); this.emitProviderConfigurationChanged(details)})} @Overridepublicvoidshutdown(){// shut down your provider } // remaining provider methods... }

Providers no longer need to manage their own state, this is done by the SDK itself. If desired, the state of a provider can be queried through the client that uses the provider.

OpenFeatureAPI.getInstance().getClient().getProviderState();

Built a new provider? Let us know so we can add it to the docs!

Develop a hook

To develop a hook, you need to create a new project and include the OpenFeature SDK as a dependency. This can be a new repository or included in the existing contrib repository available under the OpenFeature organization. Implement your own hook by conforming to the Hook interface.

classMyHookimplementsHook{@OverridepublicOptionalbefore(HookContextctx, Maphints){// code that runs before the flag evaluation } @Overridepublicvoidafter(HookContextctx, FlagEvaluationDetailsdetails, Maphints){// code that runs after the flag evaluation succeeds } @Overridepublicvoiderror(HookContextctx, Exceptionerror, Maphints){// code that runs when there's an error during a flag evaluation } @OverridepublicvoidfinallyAfter(HookContextctx, FlagEvaluationDetailsdetails, Maphints){// code that runs regardless of success or error } };

Built a new hook? Let us know so we can add it to the docs!

⭐️ Support the project

🤝 Contributing

Interested in contributing? Great, we'd love your help! To get started, take a look at the CONTRIBUTING guide.

Thanks to everyone who has already contributed

Pictures of the folks who have contributed to the project

Made with contrib.rocks.

About

Java implementation of the OpenFeature SDK

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Java100.0%