Skip to content

You’ll ask Ordainer before one paid tool runs in a Java program and watch the sixth call get blocked, then try shadow mode (record what would be denied, block nothing). Switching between shadow and enforce is a console click, with no redeploy.

The Java SDK is ai.ordainer:ordainer version 0.1.0, on Maven Central. It needs Java 11 or later, and has no runtime dependencies (the JDK’s java.net.http only). There is no servlet filter, Spring Boot integration or admin client yet: call ordainer.decide(...) from your own handler. You can still call the HTTP API with the JDK alone; that example is at the end of this page.

Do Get a test key on Your first deny, then set these two variables:

Terminal window
export ORDAINER_KEY=ord_test_... # your pilot key
export ORDAINER_BASE_URL=https://api.ordainer.dev

PowerShell 5.1:

Terminal window
$env:ORDAINER_KEY = 'ord_test_...' # your pilot key
$env:ORDAINER_BASE_URL = 'https://api.ordainer.dev'

The client reads ORDAINER_KEY and falls back to ORDAINER_API_KEY when ORDAINER_KEY is unset or empty. If both are set, ORDAINER_KEY wins. Passing apiKey(...) on the builder, or DecideOptions.builder().apiKey(...), overrides both. ORDAINER_BASE_URL sets the API address (otherwise https://api.ordainer.dev). The console’s .env download names each key after its label (for example ORDAINER_KEY_PILOT).

If you lose a key, create a new test key in Console → Keys. The console never shows a full key again, only its first characters.

You need a JDK 11 or later on your PATH (the published jar is Java 11 bytecode; it is built and tested on 11, 17 and 21). Check with java -version. If you don’t have a JDK, Eclipse Temurin is a free one for Windows, macOS and Linux (Adoptium). On macOS you can also brew install --cask temurin.

Add this dependency. Maven:

<dependency>
<groupId>ai.ordainer</groupId>
<artifactId>ordainer</artifactId>
<version>0.1.0</version>
</dependency>

Gradle (Groovy):

implementation 'ai.ordainer:ordainer:0.1.0'

Gradle (Kotlin DSL):

implementation("ai.ordainer:ordainer:0.1.0")

The artifact is on Maven Central (https://repo1.maven.org/maven2/ai/ordainer/ordainer/0.1.0/).

Create one Ordainer and share it for the life of the process (it is thread-safe; later calls reuse the connection). warmUp(true) on the builder loads the decide path and sends GET /livez (no key, no usage counted, no audit row) so the first real call doesn’t also pay for class loading, TLS and opening the connection. decide never throws for an Ordainer answer or an outage: a deny is a normal result. Branch on decision.allowed(). Call close() at shutdown (or use try-with-resources); Ordainer implements AutoCloseable.

Decide.java
import ai.ordainer.*;
public class Decide {
static String left(Decision d) {
return d.limit() == null ? "no cap" : d.remaining() + "/" + d.limit() + " left";
}
public static void main(String[] args) {
if (System.getenv("ORDAINER_KEY") == null || System.getenv("ORDAINER_BASE_URL") == null) {
System.err.println("Set ORDAINER_KEY and ORDAINER_BASE_URL first.");
System.exit(1);
}
int exit = 0;
try (Ordainer ordainer = Ordainer.builder()
.apiKey(System.getenv("ORDAINER_KEY")) // ord_test_...
.warmUp(true)
.build()) {
for (int i = 1; i <= 6; i++) {
Decision d = ordainer.decide("research.run");
if (d.allowed()) {
if (d.wouldDeny()) {
System.out.println("would deny (shadow): " + d.reason() + ", run the tool anyway (" + left(d) + ")");
} else {
System.out.println("allow: run the tool (" + left(d) + ", request_id " + d.requestId() + ")");
}
} else {
System.out.println("deny: " + d.reason() + ", don't run the tool (" + left(d)
+ ", resets " + d.resetsAt() + ", request_id " + d.requestId() + ")");
exit = 2;
break;
}
}
}
if (exit != 0) System.exit(exit);
}
}

Ordainer.fromEnv() is the same as Ordainer.builder().build(): it reads ORDAINER_KEY (then ORDAINER_API_KEY) and ORDAINER_BASE_URL, but it does not warm up unless you call ordainer.warmUp() yourself. Leaving mode unset means “do what the plan in the console says”. The sandbox plans are in enforce mode. To pin a mode in code, add .mode(Mode.SHADOW) or .mode(Mode.ENFORCE) on the builder; a pinned mode overrides the console.

decideOrThrow returns the Decision when the call may run and throws DeniedException, RejectedException, RateLimitedException or UnavailableException otherwise (all BlockedException, with decision(), response(), status() and code()). Bad options throw ConfigurationException (a RuntimeException, like every OrdainerException). DenyResponse.of(decision) gives you a status, headers and JSON body to send to your caller. Match on code(), not the message.

Put Decide.java in src/main/java of a Maven or Gradle project that has the dependency above, with the two environment variables set.

Bash, Maven:

Terminal window
mvn -q compile exec:java -Dexec.mainClass=Decide

PowerShell 5.1, Maven (quote the -D argument so PowerShell does not split it):

Terminal window
mvn -q compile exec:java "-Dexec.mainClass=Decide"

Gradle (6.4 or later): this needs a build.gradle with the application plugin and Decide as the main class. A minimal one:

build.gradle
plugins {
id 'application'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'ai.ordainer:ordainer:0.1.0'
}
application {
mainClass = 'Decide'
}

If your project already has the Gradle wrapper (gradlew and gradlew.bat in the project folder), run it from that folder.

Bash:

Terminal window
./gradlew run

PowerShell 5.1:

Terminal window
.\gradlew.bat run

If there is no wrapper yet, install Gradle and run gradle run in the same folder (the command is the same in bash and PowerShell 5.1). To add a wrapper for next time, run gradle wrapper once.

If exec:java is not already in your Maven POM, add the exec-maven-plugin or compile and run with the dependency on the classpath (javac / java -cp, using ; as the classpath separator on Windows).

With a fresh pilot key, calls 1 to 5 print allow, and call 6 prints deny: quota_exceeded and the program exits with code 2. The deny line is what to look for, because the exit code you see depends on how you ran it. Plain java shows 2 everywhere. Maven shows 2 on macOS and Linux, but on Windows mvn (mvn.cmd) reports any non-zero exit as 1, so $LASTEXITCODE is 1 there. Gradle reports the 2 as BUILD FAILED (“finished with non-zero exit value 2”), and gradle run / gradlew run itself exits 1:

allow: run the tool (4/5 left, request_id req_…)
allow: run the tool (3/5 left, request_id req_…)
allow: run the tool (2/5 left, request_id req_…)
allow: run the tool (1/5 left, request_id req_…)
allow: run the tool (0/5 left, request_id req_…)
deny: quota_exceeded, don't run the tool (0/5 left, resets 2027-01-01T00:00:00.000Z, request_id req_…)

If run 1 already denies, the pilot key is used up this month: click Reset sandbox on the welcome page or the console Overview (Run it again shows where). The console asks you to confirm: Cancel has the focus, and Cancel or Escape changes nothing. It clears the sandbox customer’s test-key counters, audit rows, idempotency keys and the sandbox rows in Recent decisions, so the pilot key gets its full allowance again (5 by default). It doesn’t reset the 1,000 test decisions a month. Live data is never touched. A returning console user may first see We’ve updated our legal documents, with Accept and Not now.

On a real product, start in shadow: we make the real decision and record it, but your tool runs even when we would say no. New plans you create in the console start in shadow. To see it on the sandbox: Console → Plans → on the pilot row, switch to shadow. Then click Reset sandbox, confirm the dialog (Cancel has the focus; Cancel or Escape changes nothing), and run the program again.

Calls 1 to 5 still print allow. Calls 6 and after print would deny (shadow) and the tool is still allowed to run (decision.allowed() is true and decision.wouldDeny() is true). With each of those lines, the SDK also writes its own shadow warning to stderr (set .logger(OrdainerLogger.NONE) in the builder to silence it):

[ordainer] shadow: would deny tool=research.run reason=quota_exceeded remaining=0/5 request_id=req_… (call allowed)
would deny (shadow): quota_exceeded, run the tool anyway (0/5 left)

Keep mode unset in the builder so a console switch to Enforce is picked up on the next call, with no redeploy. More: Shadow vs enforce.

  • Session leases: DecideOptions.builder().lease() (server default 120 seconds) or .lease(300) sends lease on decide. decision.lease() is a Lease (id(), expiresAt(), running(), limit()) or null. It is null when you didn’t ask for one, the key has no session limit (even if you asked), the answer was a deny (except a shadow concurrency_exhausted would-deny, which still takes and returns the lease), or Ordainer couldn’t be reached. Always check for null before release or extend. A fail-open runs with no lease. wrap releases in a finally block; a failed release is logged, not thrown. See Session leases.
  • Retries: the client gives every decide a fresh random idempotency key unless you pass DecideOptions.builder().idempotencyKey(...). A key replays the first answer for 24 hours. The default is one retry (retries(1)) on a timeout, network error or 503, inside a 650 ms budget, with the same key. More: Idempotency and retries.
  • Outages: if we’re slow (300 ms per attempt; at most about 650 ms with the default retry), unreachable or answer with a 5xx, the call is allowed and a warning is logged (FailMode.OPEN, the default). Use .failMode(FailMode.CLOSED) to block instead. An error answer (any 4xx, such as unknown_key) is not an outage: it’s blocked in every fail mode, except 403 subscription_inactive, which follows .billingLapse(...) (default FailMode.OPEN), and 429 safety_limit_reached, which is allowed with decision.safetyLimited() set. See Fail open vs fail closed.
  • Going live: Live keys are not available yet. Live keys open when paid plans launch. Your test keys cover everything in your beta.
  • Every field and error: Decide API reference and Errors.

If you would rather not add a dependency, the JDK’s java.net.http.HttpClient is enough to call POST /v1/decide. This file is self-contained and you can run it with java Decide.java. That path needs a JDK 17 or later (it uses a record). It does what our SDKs do on each call: a new idempotency key per real call, 300 ms per attempt, one retry with the same key on a timeout, a network error or a 503, and a GET /livez warm-up at startup.

Decide.java
// Java 17+, JDK only (java.net.http). Plain HTTP, no package.
// After ORDAINER_KEY and ORDAINER_BASE_URL are set: java Decide.java
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.time.Duration;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Decide {
static final String BASE_URL = System.getenv("ORDAINER_BASE_URL");
static final String KEY = System.getenv("ORDAINER_KEY");
// One client for the whole process: it keeps the connection open between calls.
static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofMillis(300)).build();
// 300 ms per attempt, like our Node, Python and Ruby SDKs. Pick a timeout that fits your request path.
static final Duration TIMEOUT = Duration.ofMillis(300);
// One answer from Ordainer. status is 0 when there was no answer (timeout or network error).
record Answer(int status, String body, String requestId) {}
static Answer send(String tool, String idempotencyKey) throws InterruptedException {
HttpRequest req = HttpRequest.newBuilder(URI.create(BASE_URL + "/v1/decide"))
.timeout(TIMEOUT)
.header("Authorization", "Bearer " + KEY)
.header("Content-Type", "application/json")
.header("Idempotency-Key", idempotencyKey)
.POST(HttpRequest.BodyPublishers.ofString("{\"tool\":\"" + tool + "\"}"))
.build();
try {
HttpResponse<String> res = HTTP.send(req, HttpResponse.BodyHandlers.ofString());
return new Answer(res.statusCode(), res.body(), res.headers().firstValue("X-Request-Id").orElse(""));
} catch (HttpTimeoutException e) {
return new Answer(0, "timeout", "");
} catch (IOException e) {
return new Answer(0, e.toString(), "");
}
}
// Asks once and, on no answer or a 503, retries once with the SAME idempotency key,
// so a call that reached us is answered once and counted once.
static Answer decide(String tool, String idempotencyKey) throws InterruptedException {
Answer a = send(tool, idempotencyKey);
if (a.status() == 0 || a.status() == 503) {
Thread.sleep(50);
a = send(tool, idempotencyKey);
}
return a;
}
// Warm-up at startup: opens the connection before the first real call. GET /livez needs
// no key, moves no usage counter and writes no audit row.
static void warmUp() throws InterruptedException {
HttpRequest req = HttpRequest.newBuilder(URI.create(BASE_URL + "/livez")).timeout(Duration.ofSeconds(2)).GET().build();
try {
HTTP.send(req, HttpResponse.BodyHandlers.discarding());
} catch (IOException e) {
// Nothing to do: the first real call will open the connection instead.
}
}
// A tiny reader for the fixed response shape. Use your JSON library in real code.
static String field(String json, String name) {
Matcher m = Pattern.compile("\"" + name + "\":(\"([^\"]*)\"|[^,}]*)").matcher(json);
if (!m.find()) return null;
return m.group(2) != null ? m.group(2) : m.group(1);
}
public static void main(String[] args) throws InterruptedException {
if (BASE_URL == null || KEY == null) {
System.err.println("Export ORDAINER_KEY and ORDAINER_BASE_URL first.");
System.exit(1);
}
warmUp();
// A new key for each real call. Reuse a key only to retry the same call.
Answer a = decide("research.run", "research-run-" + UUID.randomUUID());
if (a.status() != 200) {
// No answer, a 5xx, or an error answer (4xx). Branch on error.code, never on the message.
String code = a.status() == 0 ? "no_answer" : field(a.body(), "code");
System.err.println("error " + a.status() + ": " + code + " (request_id " + a.requestId() + ")");
if (a.status() == 0 || a.status() >= 500) {
// Ordainer couldn't answer. Your choice: fail open (run the tool) or fail closed (don't).
boolean failOpen = true;
if (failOpen) {
System.err.println("failing open: run the tool");
return;
}
System.err.println("failing closed: don't run the tool");
System.exit(1);
}
// A 4xx did answer: fix the key or the request, and don't run the tool.
System.exit(1);
}
String decision = field(a.body(), "decision");
String reason = field(a.body(), "reason");
String remaining = field(a.body(), "remaining");
String limit = field(a.body(), "limit");
String left = "null".equals(limit) ? "no cap" : remaining + "/" + limit + " left";
if ("allow".equals(decision)) {
System.out.println("allow: run the tool (" + left + ", request_id " + a.requestId() + ")");
} else if ("shadow".equals(field(a.body(), "mode"))) {
System.out.println("would deny (shadow): " + reason + ", run the tool anyway (" + left + ")");
} else {
System.out.println("deny: " + reason + ", don't run the tool (" + left + ", resets "
+ field(a.body(), "resets_at") + ", request_id " + a.requestId() + ")");
System.exit(2);
}
}
}

With the two environment variables set, in the directory that has this Decide.java:

Terminal window
for i in 1 2 3 4 5 6; do java Decide.java; done

PowerShell 5.1:

Terminal window
1..6 | ForEach-Object { java Decide.java }

This loop was checked on PowerShell 7 (pwsh 7.4), not yet on Windows PowerShell 5.1.

A deny exits 2. In a bash script that uses set -e, that stops the script, including this for loop if a deny happens before the last call. On a fresh pilot key the deny is the last call, so all six still run. The PowerShell loop keeps going.

When Ordainer can’t answer (a timeout, a network error or a 5xx), this example’s failOpen flag decides. Set it to true to let the tool run, or false to block it. A 4xx is different: we did answer, so fix the key or the request and don’t run the tool. More in Fail open vs fail closed.