### Basic OpenFeature Java SDK Usage Example Source: https://github.com/open-feature/java-sdk/blob/main/README.md This example demonstrates how to configure an InMemoryProvider, create a client, and retrieve a boolean flag value. Ensure the provider is set and waited upon before client usage. ```java public void example(){ // flags defined in memory Map> 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(); try { api.setProviderAndWait(new InMemoryProvider(myFlags)); } catch (Exception e) { // handle initialization failure e.printStackTrace(); } // create a client Client client = api.getClient(); // get a bool flag value boolean flagValue = client.getBooleanValue("v2_enabled", false); } ``` -------------------------------- ### Use Maven Wrapper for Verification Source: https://github.com/open-feature/java-sdk/blob/main/CONTRIBUTING.md Example usage of the Maven wrapper script for running verification tasks. ```bash ./mvnw verify ``` -------------------------------- ### Get Provider State Source: https://github.com/open-feature/java-sdk/blob/main/README.md Query the current state of a provider using the OpenFeature SDK client. This is useful for understanding the operational status of registered providers. ```java OpenFeatureAPI.getInstance().getClient().getProviderState(); ``` -------------------------------- ### Check Spotless Code Formatting Source: https://github.com/open-feature/java-sdk/blob/main/CONTRIBUTING.md Verify if your code adheres to the required formatting standards without making changes. If this fails, use 'mvn spotless:apply' to fix. ```bash mvn spotless:check ``` -------------------------------- ### Apply Spotless Code Formatting Source: https://github.com/open-feature/java-sdk/blob/main/CONTRIBUTING.md Format your code according to the Palantir Java Style using the Spotless Maven plugin. Run this before committing changes. ```bash mvn spotless:apply ``` -------------------------------- ### Verify Code Styling and Static Analysis Source: https://github.com/open-feature/java-sdk/blob/main/CONTRIBUTING.md Check code styling and static analysis with Maven. Use the specified profile to exclude deployment steps. ```bash mvn verify -P !deploy ``` -------------------------------- ### Implement a Basic Feature Provider Source: https://github.com/open-feature/java-sdk/blob/main/README.md Implement the `FeatureProvider` interface to create a custom provider. This includes methods for metadata, initialization, shutdown, and evaluating different data types. ```java public class MyProvider implements FeatureProvider { @Override public Metadata getMetadata() { return () -> "My Provider"; } @Override public void initialize(EvaluationContext evaluationContext) throws Exception { // start up your provider } @Override public void shutdown() { // shut down your provider } @Override public ProviderEvaluation getBooleanEvaluation(String key, Boolean defaultValue, EvaluationContext ctx) { // resolve a boolean flag value } @Override public ProviderEvaluation getStringEvaluation(String key, String defaultValue, EvaluationContext ctx) { // resolve a string flag value } @Override public ProviderEvaluation getIntegerEvaluation(String key, Integer defaultValue, EvaluationContext ctx) { // resolve an int flag value } @Override public ProviderEvaluation getDoubleEvaluation(String key, Double defaultValue, EvaluationContext ctx) { // resolve a double flag value } @Override public ProviderEvaluation getObjectEvaluation(String key, Value defaultValue, EvaluationContext ctx) { // resolve an object flag value } } ``` -------------------------------- ### Implement an Event-Supporting Feature Provider Source: https://github.com/open-feature/java-sdk/blob/main/README.md Extend `EventProvider` to create a provider that can emit events, such as when flag configurations change. This involves overriding the `initialize` method to set up event listeners. ```java class MyEventProvider extends EventProvider { @Override public Metadata getMetadata() { return () -> "My Event Provider"; } @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... } ``` -------------------------------- ### Run JMH Benchmark for Allocations Source: https://github.com/open-feature/java-sdk/blob/main/CONTRIBUTING.md Execute the JMH benchmark suite to test memory allocations. Focus on 'totalAllocatedBytes' and 'totalAllocatedInstances' for meaningful results. ```bash mvn -P benchmark clean compile test-compile jmh:benchmark -Djmh.f=1 -Djmh.prof='dev.openfeature.sdk.benchmark.AllocationProfiler' ``` -------------------------------- ### Run Maven Tests Source: https://github.com/open-feature/java-sdk/blob/main/CONTRIBUTING.md Execute unit tests using Maven. This is a standard command for validating code changes. ```bash mvn test ``` -------------------------------- ### Registering an OpenFeature Provider Source: https://github.com/open-feature/java-sdk/blob/main/README.md This snippet shows how to register a provider with the OpenFeature SDK. Ensure the provider is added as a dependency before registration. ```java import dev.openfeature.sdk.*; public class Main { public static void main(String[] args) { OpenFeatureAPI.getInstance().setProvider(new MyProvider()); } } ``` -------------------------------- ### Configure Domain-Specific Providers Source: https://github.com/open-feature/java-sdk/blob/main/README.md Register providers to specific domains for logical association. If a domain has no provider, the global provider is used. ```java FeatureProvider scopedProvider = new MyProvider(); // registering the default provider OpenFeatureAPI.getInstance().setProvider(LocalProvider()); // registering a provider to a domain OpenFeatureAPI.getInstance().setProvider("my-domain", new CachedProvider()); // A client bound to the default provider Client clientDefault = OpenFeatureAPI.getInstance().getClient(); // A client bound to the CachedProvider provider Client domainScopedClient = OpenFeatureAPI.getInstance().getClient("my-domain"); ``` -------------------------------- ### Maven Repository for Snapshot Builds Source: https://github.com/open-feature/java-sdk/blob/main/README.md Configure this repository in your Maven settings if you need to use snapshot builds of the OpenFeature Java SDK. ```xml true sonatype Sonatype Repository https://s01.oss.sonatype.org/content/repositories/snapshots/ ``` -------------------------------- ### Handle Provider Configuration Changes Source: https://github.com/open-feature/java-sdk/blob/main/README.md Add an event handler to a client to react when the provider's flag settings change. ```java // 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 }); ``` -------------------------------- ### Register Provider Synchronously Source: https://github.com/open-feature/java-sdk/blob/main/README.md Register a provider in a blocking manner to ensure it is ready before proceeding. Handles potential initialization failures. ```java OpenFeatureAPI api = OpenFeatureAPI.getInstance(); try { api.setProviderAndWait(new MyProvider()); } catch (Exception e) { // handle initialization failure e.printStackTrace(); } ``` -------------------------------- ### Track User Actions with OpenFeature Source: https://github.com/open-feature/java-sdk/blob/main/README.md Associate user actions with feature flag evaluations for experimentation. Ensure tracking event names are not empty to avoid exceptions. ```java OpenFeatureAPI api = OpenFeatureAPI.getInstance(); api.getClient().track("visited-promo-page", new MutableTrackingEventDetails(99.77).add("currency", "USD")); ``` -------------------------------- ### Configure Multi-Provider Source: https://github.com/open-feature/java-sdk/blob/main/README.md Register multiple feature providers to delegate flag evaluation. This is useful for composing different provider implementations. ```java import dev.openfeature.sdk.OpenFeatureAPI; import dev.openfeature.sdk.Client; import dev.openfeature.sdk.FeatureProvider; import dev.openfeature.sdk.multiprovider.MultiProvider; import java.util.List; public void multiProviderExample() throws Exception { FeatureProvider primaryProvider = new MyPrimaryProvider(); FeatureProvider fallbackProvider = new MyFallbackProvider(); MultiProvider multiProvider = new MultiProvider(List.of(primaryProvider, fallbackProvider)); OpenFeatureAPI api = OpenFeatureAPI.getInstance(); api.setProviderAndWait(multiProvider); Client client = api.getClient(); boolean value = client.getBooleanValue("some-flag", false); } ``` -------------------------------- ### Run End-to-End Tests Source: https://github.com/open-feature/java-sdk/blob/main/CONTRIBUTING.md Execute the end-to-end gherkin tests using the InMemoryProvider with Maven. This requires the 'e2e' profile. ```bash mvn test -P e2e ``` -------------------------------- ### Implement a Custom Hook Source: https://github.com/open-feature/java-sdk/blob/main/README.md Conform to the `Hook` interface to create custom hooks that execute logic before, after, or during flag evaluations. This includes methods for handling success, errors, and finalization. ```java 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, FlagEvaluationDetails details, Map hints) { // code that runs regardless of success or error } }; ``` -------------------------------- ### Register Provider Asynchronously Source: https://github.com/open-feature/java-sdk/blob/main/README.md Register a provider in a non-blocking manner. This allows the application to continue execution without waiting for provider initialization. ```java OpenFeatureAPI.getInstance().setProvider(new MyProvider()); ``` -------------------------------- ### Set Targeting Context Source: https://github.com/open-feature/java-sdk/blob/main/README.md Provide dynamic input data for flag evaluation based on application or user criteria. Supports setting context globally, per-client, or per-invocation. ```java // set a value to the global context OpenFeatureAPI api = OpenFeatureAPI.getInstance(); Map 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 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 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); ``` -------------------------------- ### Handle Global Provider Stale Events Source: https://github.com/open-feature/java-sdk/blob/main/README.md Add an event handler to the global API to react when the provider's cache goes stale. ```java // add an event handler to the global API OpenFeatureAPI.getInstance().onProviderStale((EventDetails eventDetails) -> { // do something when the provider's cache goes stale }); ``` -------------------------------- ### Check Spec Compliance with Python Script Source: https://github.com/open-feature/java-sdk/blob/main/CONTRIBUTING.md Validate that the project's tests cover all specification entries using a Python script. ```bash python spec_finder.py ``` -------------------------------- ### Add Hooks for Flag Evaluation Source: https://github.com/open-feature/java-sdk/blob/main/README.md Register custom logic at different points in the flag evaluation lifecycle. Hooks can be added globally, to a specific client, or for a single flag evaluation. ```java // 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()); ``` -------------------------------- ### Maven Dependency for OpenFeature Java SDK Source: https://github.com/open-feature/java-sdk/blob/main/README.md Add this dependency to your Maven project to include the OpenFeature Java SDK. Ensure you use the latest version. ```xml dev.openfeature sdk 1.20.2 ``` -------------------------------- ### Gradle Dependency for OpenFeature Java SDK Source: https://github.com/open-feature/java-sdk/blob/main/README.md Add this dependency to your Gradle project to include the OpenFeature Java SDK. Ensure you use the latest version. ```groovy dependencies { implementation 'dev.openfeature:sdk:1.20.2' } ``` -------------------------------- ### Shut Down OpenFeature Providers Source: https://github.com/open-feature/java-sdk/blob/main/README.md Perform cleanup of all registered providers when your application is shutting down. ```java // shut down all providers OpenFeatureAPI.getInstance().shutdown(); ``` -------------------------------- ### Set Transaction Context for Flag Evaluations Source: https://github.com/open-feature/java-sdk/blob/main/README.md Add data like userId to the transaction context, which will then be automatically applied to all flag evaluations within the current transaction. ```java // adding userId to transaction context OpenFeatureAPI api = OpenFeatureAPI.getInstance(); Map transactionAttrs = new HashMap<>(); transactionAttrs.put("userId", new Value("userId")); EvaluationContext transactionCtx = new ImmutableContext(transactionAttrs); api.setTransactionContext(transactionCtx); ``` -------------------------------- ### Register ThreadLocal Transaction Context Propagator Source: https://github.com/open-feature/java-sdk/blob/main/README.md Register the ThreadLocalTransactionContextPropagator to automatically apply transaction-specific evaluation context to flag evaluations within a transaction. ```java // registering the ThreadLocalTransactionContextPropagator OpenFeatureAPI.getInstance().setTransactionContextPropagator(new ThreadLocalTransactionContextPropagator()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.