> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Java

> Call an app from Java with a typed client generated from its contract

The Java client runs on Java 21 with no dependency beyond the JDK. `bijection
client java` writes a typed package for your app: its exposed functions as
refs, their arguments and values as records, and a `connect` that pins the app
contract. The package depends on the runtime, `com.bijection:client`.

## Install

Add the runtime to your build, or depend on the generated package, which
brings it:

```xml theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
<dependency>
  <groupId>com.bijection</groupId>
  <artifactId>client</artifactId>
  <version>0.10.0</version>
</dependency>
```

## Generate a client

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection client java --out orders-client --name com.acme.orders
```

`--name` is the Java package. The output is a Maven project (`com.acme:orders-client`)
with:

* `App.java`: `App.CONTRACT`, `App.connect(...)` and the app's tree, each
  subtree a nested class and each exposed function a ref (`App.Orders.place`
  for `orders.place`, `App.Billing.Invoices.list` for `billing.invoices.list`);
* one record per object type (`OrdersPlaceArgs`, `OrdersRecentValueItem`, …) and
  one enum per union of string literals;
* `interface.json`, the portable interface document.

The command refuses when `bijection.lock` is stale: run `bijection check --write-lock`, review the diff and commit it first. Regenerate the package
when the app's exposed functions change.

## Connect

```java theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import com.acme.orders.App;
import com.bijection.client.*;

Client client = App.connect("https://orders.example.com",
    ConnectOptions.builder().tokenSource(refresh -> session.accessToken(refresh)));
```

`token(String)` takes a fixed token (a server, a script) and `tokenSource`
asks for the current one on every call and live connection. Without a token
the caller is anonymous. `App.connect` pins `App.CONTRACT`, the `contract`
line of `bijection.lock`: an installation whose contract differs refuses every
call with `Conflict`, its message starting `ContractStale`, instead of
running a call the client was not generated for. `Bijection.connect(url,
options)` makes an unpinned client.

For a dynamic tool, pass `ConnectOptions.builder().discover().build()` to the raw connector. A pinned client refuses a path absent from its contract map before sending it.

## Calls

```java theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
Result<List<OrdersRecentValueItem>> recent =
    client.query(App.Orders.recent, new OrdersRecentArgs("c-1", Optional.of(20L)));

Result<String> placed =
    client.mutate(App.Orders.place, new OrdersPlaceArgs("A-1", 2L), MutateOptions.once(orderKey));
```

A function is addressed by its tree path: `App.Orders.place` is the ref whose
path is `orders.place`. `query` reads once; `mutate` runs one transaction.

`once` is the identity of one logical mutation. The same `once` with the same
arguments answers the original result; with other arguments it refuses
`Invalid`. Without `once`, the client mints one for that call. When a result
is `Unknown` (the reply was lost, or the outcome was withheld), call `mutate`
again with the same `once`: if the first attempt committed, the host answers
its result instead of committing twice.
An uncertain mutation carries its original request key in `Refusal.once()`.

```java theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
var options = MutateOptions.once(UUID.randomUUID().toString());
Result<String> result = client.mutate(App.Orders.place, args, options);
while (result instanceof Result.Refusal<String> r && r.code().equals(HostCode.UNKNOWN))
  result = client.mutate(App.Orders.place, args, options);
```

`queryAsync` and `mutateAsync` return `CompletableFuture`s.

## Frames

Each frame method returns a new client and leaves this one unchanged:

| Method | Meaning |
| - | - |
| `as(principalId)` | Act as that principal. Only an operator credential may. |
| `under(label)` | Act under that label: `Label.tag("access.finance")`, `Label.member("access.tenant", "acme")`, `.and(…)`, `Label.anyOf(…)`. |
| `in(world)` | Run in a world: `World.branch("plan-2027")` or `World.version(v)`. |
| `at(instant)` | Read at a valid instant. |

```java theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
var plan = client.in(World.branch("plan-2027")).under(Label.member("access.tenant", "acme"));
```

A committed mutation's result carries its `version`. Pass it as `seen` to a
later call to answer from state at least that new, so you read your own
write:

```java theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
if (placed instanceof Result.Ok<String> ok)
  client.query(App.Orders.recent, args, ReadOptions.seen(ok.version()));
```

## Results

Every call answers a `Result`: `Result.Ok(value, version)` or
`Result.Refusal(code, message, guard)`. Switch on it:

```java theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
switch (placed) {
  case Result.Ok<String> ok -> confirm(ok.value());
  case Result.Refusal<String> r when r.code().equals("OutOfStock") -> offerBackorder();
  case Result.Refusal<String> r -> show(r.message());
}
```

`code` is one of the twelve host codes (`HostCode.UNKNOWN`, `DISALLOWED`,
`FORBIDDEN`, `INVALID`, `ABSENT`, `EXISTS`, `CONFLICT`, `ERASED`, `EXPIRED`,
`WITHDRAWN`, `LIMIT`, `FAILED`) or one the function declares in `refuses`. A
declared code arrives exactly as the function refused; the generated ref lists
the declared codes, and any other kernel code folds into its host code with
the kernel code as `reason()`. A host code's `reason()` is its precise cause
(`BudgetExhausted` under `Limit`), or null, and `message()` never starts with
it. On `Forbidden`, `guard` is the
path of the guard that refused. `message` is the sentence the caller may read.

## Watch

```java theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
Watch watch = client.watch(App.Orders.recent, args, result -> render(result));
// later
watch.stop();
```

`watch` runs a query and delivers each new result, a value or a refusal, to
the listener until `stop()`. The client keeps one live connection per frame
(who acts and under what), reconnects after a lost connection and subscribes
again. In a world or at a valid instant (`in`, `at`) a watch reads once.
`client.close()` closes the live connections.

## Trial

```java theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
Trial<String> trial = client.trial(App.Orders.place, args);
trial.writes();  // [TrialWrite(verb, table, key, before, after)]
trial.tasks();   // [TrialTask(target, args, due)]
trial.validUntil(); // Instant, or null
```

`trial` runs a call in a discarded world and commits nothing: `result` is how
it would have ended (a refusing guard in its `guard`), `writes` what it would
have written and `tasks` what it would have submitted. `validUntil` is the
instant the answer is valid until: a call at the same version committed before
it is decided the same way. It is null when nothing time-dependent bounds the
answer.

## Values

| Bijection | Java |
| - | - |
| `t.int` | `Long` |
| `t.number` | `Double` (NaN, infinities and −0 kept) |
| `t.string`, keys, versions | `String` |
| `t.bytes` | `byte[]` |
| `Decimal` | `BigDecimal` |
| a date | `LocalDate` |
| an instant | `Instant` (microsecond precision) |
| a duration | `Duration` (a duration in years or months has no fixed length and is refused) |
| a list, a map | `List<T>`, `Map<String, T>` |
| an object | a record; an optional field is an `Optional` component |
| a union of string literals | an enum |
| any other union, `any` | `Object` (plain values) |

## Change entries

A query over `selection.changes` returns change entries, typed
`Change<Fact>(key, before, after, version)`: `before` is null on an insert,
`after` null on a delete, and `version` is the change's version.

## Arrow and Iceberg

`com.bijection:client-arrow` turns a query's facts into bounded Arrow batches
(`ArrowBatches.fromRows(facts, ArrowBatches.rowSchema(App.Orders.recent), …)`).
`sdks/application/java-iceberg` reads Datasets tables with Iceberg under a
read lease; see [exact reads](https://docs.bijection.com/datasets/exact-reads.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.