Giter Club home page Giter Club logo

java-sdk's Introduction

OpenFeature Logo

OpenFeature Java SDK

Specification Release
Javadoc Maven Central Codecov CII 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 8+ (compiler target is 1.8)

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

Install

Maven

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

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

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

Gradle

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

Usage

public void example(){

    // flags defined in memory
    Map<String, Flag<?>> myFlags = new HashMap<>();
    myFlags.put("v2_enabled", Flag.builder()
        .variant("on", true)
        .variant("off", false)
        .defaultVariant("on")
        .build());

    // configure a provider
    OpenFeatureAPI api = OpenFeatureAPI.getInstance();
    api.setProviderAndWait(new InMemoryProvider(myFlags));

    // create a client
    Client client = api.getClient();

    // get a bool flag value
    boolean flagValue = client.getBooleanValue("v2_enabled", false);
}

API Reference

See here for the Javadocs.

๐ŸŒŸ Features

Status Features Description
โœ… Providers Integrate with a commercial, open source, or in-house feature management tool.
โœ… Targeting Contextually-aware flag evaluation using evaluation context.
โœ… Hooks Add functionality to various stages of the flag evaluation life-cycle.
โœ… Logging Integrate with popular logging packages.
โœ… Named clients Utilize multiple providers in a single application.
โœ… Eventing React to state changes in the provider or flag management system.
โœ… Shutdown Gracefully clean up a provider during application shutdown.
โœ… Extending Extend 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:

    OpenFeatureAPI api = OpenFeatureAPI.getInstance();
    api.setProviderAndWait(new MyProvider());

Asynchronous

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

    OpenFeatureAPI.getInstance().setProvider(new MyProvider());

In some situations, it may be beneficial to register multiple providers in the same application. This is possible using named clients, which is covered in more details 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 context
OpenFeatureAPI api = OpenFeatureAPI.getInstance();
Map<String, Value> apiAttrs = new HashMap<>();
apiAttrs.put("region", new Value(System.getEnv("us-east-1")));
EvaluationContext apiCtx = new ImmutableContext(apiAttrs);
api.setEvaluationContext(apiCtx);

// set a value to the client context
Map<String, Value> clientAttrs = new HashMap<>();
clientAttrs.put("region", new Value(System.getEnv("us-east-1")));
EvaluationContext clientCtx = new ImmutableContext(clientAttrs);
Client client = api.getInstance().getClient();
client.setEvaluationContext(clientCtx);

// set a value to the invocation context
Map<String, Value> requestAttrs = new HashMap<>();
requestAttrs.put("email", new Value(session.getAttribute("email")));
requestAttrs.put("product", new Value("productId"));
String targetingKey = session.getId();
EvaluationContext reqCtx = new ImmutableContext(targetingKey, requestAttrs);

boolean flagValue = 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 evaluations
  OpenFeatureAPI api = OpenFeatureAPI.getInstance();
  api.addHooks(new ExampleHook());
  
  // add a hook on this client, to run on all evaluations made by this client
  Client client = api.getClient();        
  client.addHooks(new ExampleHook());
  
  // add a hook for this evaluation only
  Boolean retval = client.getBooleanValue(flagKey, false, null,
          FlagEvaluationOptions.builder().hook(new ExampleHook()).build());

Logging

The Java SDK uses SLF4J. See the SLF4J manual for complete documentation.

Named clients

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

FeatureProvider scopedProvider = new MyProvider();

// registering the default provider
OpenFeatureAPI.getInstance().setProvider(LocalProvider());
// registering a named provider
OpenFeatureAPI.getInstance().setProvider("clientForCache", new CachedProvider());

// a client backed by default provider
Client clientDefault = OpenFeatureAPI.getInstance().getClient();
// a client backed by CachedProvider
Client clientNamed = OpenFeatureAPI.getInstance().getClient("clientForCache");

Named providers 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 client
Client client = OpenFeatureAPI.getInstance().getClient();
client.onProviderConfigurationChanged((EventDetails eventDetails) -> {
    // do something when the provider's flag settings change
});

// add an event handler to the global API
OpenFeatureAPI.getInstance().onProviderStale((EventDetails eventDetails) -> {
    // 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 providers
OpenFeatureAPI.getInstance().shutdown();

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.

public class MyProvider implements FeatureProvider {
    @Override
    public Metadata getMetadata() {
        return () -> "My Provider";
    }

    @Override
    public ProviderState getState() {
        // optionally indicate your provider's state (assumed to be READY if not implemented)
    }

    @Override
    public void initialize(EvaluationContext evaluationContext) throws Exception {
        // start up your provider
    }

    @Override
    public void shutdown() {
        // shut down your provider
    }

    @Override
    public ProviderEvaluation<Boolean> getBooleanEvaluation(String key, Boolean defaultValue, EvaluationContext ctx) {
        // resolve a boolean flag value
    }

    @Override
    public ProviderEvaluation<String> getStringEvaluation(String key, String defaultValue, EvaluationContext ctx) {
        // resolve a string flag value
    }

    @Override
    public ProviderEvaluation<Integer> getIntegerEvaluation(String key, Integer defaultValue, EvaluationContext ctx) {
        // resolve an int flag value
    }

    @Override
    public ProviderEvaluation<Double> getDoubleEvaluation(String key, Double defaultValue, EvaluationContext ctx) {
        // resolve a double flag value
    }

    @Override
    public ProviderEvaluation<Value> getObjectEvaluation(String key, Value defaultValue, EvaluationContext ctx) {
        // 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.

class MyEventProvider extends EventProvider {
    @Override
    public Metadata getMetadata() {
        return () -> "My Event Provider";
    }

    @Override
    public ProviderState getState() {
        // indicate your provider's state (required for EventProviders)
    }

    @Override
    public void initialize(EvaluationContext evaluationContext) throws Exception {
        // emit events when flags are changed in a hypothetical REST API
        this.restApiClient.onFlagsChanged(() -> {
            ProviderEventDetails details = ProviderEventDetails.builder().message("flags changed in API!").build();
            this.emitProviderConfigurationChanged(details);
        });
    }

    @Override
    public void shutdown() {
        // shut down your provider
    }

    // remaining provider methods...
}

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. To satisfy the interface, all methods (Before/After/Finally/Error) need to be defined. To avoid defining empty functions make use of the UnimplementedHook struct (which already implements all the empty functions).

class MyHook implements Hook {

    @Override
    public Optional before(HookContext ctx, Map hints) {
        // code that runs before the flag evaluation
    }

    @Override
    public void after(HookContext ctx, FlagEvaluationDetails details, Map hints) {
        // code that runs after the flag evaluation succeeds
    }

    @Override
    public void error(HookContext ctx, Exception error, Map hints) {
        // code that runs when there's an error during a flag evaluation
    }

    @Override
    public void finallyAfter(HookContext ctx, Map hints) {
        // 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 that has already contributed

Pictures of the folks who have contributed to the project

Made with contrib.rocks.

java-sdk's People

Contributors

renovate[bot] avatar justinabrahms avatar toddbaert avatar github-actions[bot] avatar thomaspoignant avatar kavindu-dodan avatar lopitz avatar beeme1mr avatar rgrassian-split avatar dependabot[bot] avatar liran2000 avatar thiyagu06 avatar arobertscollibra avatar akirafujiu avatar davidphirsch avatar thisthat avatar javicv avatar pbhandari9541 avatar kinyoklion avatar skyerus avatar step-security-bot avatar code4y avatar apulbere avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.