SDK Reference

Java

Thread-safe Java SDK. Optimized for JVM backends, Spring Boot, high-concurrency microservices, and standard Android Java applications.

Installation

xml
<dependency>
    <groupId>com.toggleai</groupId>
    <artifactId>sdk-java</artifactId>
    <version>1.0.0</version>
</dependency>

Basic Usage

The Java SDK works in tight synchronization with ToggleAI edge services to deliver maximum speed, concurrent safety, and background data replication:

⚡ Local In-Memory Evaluation

Upon invoking client.init(), the SDK downloads the active configuration rules via GET /sdk/config and atomic-swaps them locally. Subsequent resolutions with client.getFlag() or client.getFlagValue() execute in-memory with sub-millisecond speeds—completely eliminating network roundtrips from critical API paths.

🛰️ Edge Remote Evaluation

For high-security operations demanding real-time server-side validation bypassing cached states, client.evaluateFlagRemote() makes a direct network call to the edge gateway POST /sdk/evaluate, returning fresh determinations.

Application.java
import com.toggleai.sdk.ToggleAIClient;
import com.toggleai.sdk.ToggleAIOptions;
import com.toggleai.sdk.models.Payloads.EvaluationContext;
import com.toggleai.sdk.models.Payloads.FlagEvaluationResult;

public class Application {
    public static void main(String[] args) {
        // Instantiate Options
        ToggleAIOptions options = new ToggleAIOptions();
        options.setClientId("pk_live_xxx");
        options.setSecret("sk_live_xxx");
        options.setPollingIntervalMs(30000);

        ToggleAIClient client = new ToggleAIClient(options);
        
        // Initialize client (fetches rules, starts background thread pool)
        client.init();

        // Create evaluation context
        EvaluationContext ctx = new EvaluationContext("user_123", Map.of("plan", "premium"));

        // 1. Evaluate Feature Flag (Synchronous local evaluation)
        FlagEvaluationResult result = client.getFlag("new-checkout", ctx);
        if (result.enabled) {
            System.out.println("Show new checkout layout");
        }

        // 2. Typed Flag Value
        String buttonColor = client.getFlagValue("button-color", ctx, "#000000", String.class);

        // 3. Remote Config Value
        int timeout = client.getConfig("api_timeout_ms", 5000, Integer.class);

        // Graceful shutdown (terminates scheduler thread pools and flushes logs)
        client.close();
    }
}

Spring Boot Integration

Integrating ToggleAI into Spring Boot applications is seamless. We recommend configuring a shared singleton bean inside a Configuration class:

ToggleAIConfig.java
@Configuration
public class ToggleAIConfig {

    @Value("${toggleai.client-id}")
    private String clientId;

    @Value("${toggleai.secret}")
    private String secret;

    @Bean(destroyMethod = "close")
    public ToggleAIClient toggleAIClient() {
        ToggleAIOptions options = new ToggleAIOptions();
        options.setClientId(clientId);
        options.setSecret(secret);
        options.setPollingIntervalMs(30000);

        ToggleAIClient client = new ToggleAIClient(options);
        client.init(); // Blocks until initial config is fetched successfully
        return client;
    }
}
CheckoutController.java
@RestController
@RequestMapping("/api")
public class CheckoutController {

    @Autowired
    private ToggleAIClient client;

    @GetMapping("/checkout")
    public ResponseEntity<?> checkout(@RequestParam String userId) {
        EvaluationContext ctx = new EvaluationContext(userId, Map.of("platform", "web"));
        
        boolean showNew = client.getFlag("new-checkout", ctx).enabled;
        
        if (showNew) {
            return ResponseEntity.ok(Map.of("ui", "new"));
        }
        return ResponseEntity.ok(Map.of("ui", "legacy"));
    }
}

Error Handling

java
import com.toggleai.sdk.ToggleAIException;

try {
    client.init();
} catch (ToggleAIException e) {
    switch (e.getCode()) {
        case "INVALID_KEY":   System.err.println("Verify your API key pair."); break;
        case "NETWORK_ERROR": System.err.println("Cannot reach ToggleAI servers."); break;
        case "RATE_LIMITED":  System.err.println("Too many requests."); break;
        default:              System.err.println("Initialization failed: " + e.getMessage());
    }
}

ToggleAIOptions

Setter / MethodTypeDefault
setClientId(String)voidrequired
setSecret(String)voidrequired
setPollingIntervalMs(long)void30000
setDisableCache(boolean)voidfalse
setDefaultContext(EvaluationContext)voidnull
setTimeoutMs(long)void10000

API Reference

MethodReturnsDescription
init()voidFetch configuration, start scheduled executor pools
close()voidShutdown thread pools, close active log threads
refresh()voidManually trigger config refresh blockingly
getFlag(key, ctx)FlagEvaluationResultIn-memory local flag evaluation
evaluateFlagRemote(key, ctx)CompletableFuture<...>Server-side flag evaluation
getFlagValue(key, ctx, default, Class<T>)TIn-memory typed flag value
getConfig(key, default, Class<T>)TIn-memory typed config value
getAllConfigs()Map<String, Object>All remote config key/value pairs
hasConfig(key)booleanCheck existence of config key
getLogger()ToggleAILoggerGet attached logger instance