An asynchronous java client library for the OpenPolicyAgent REST API.
This repository has two components:
opa-async-java-client
is the actual client for the OPA REST APIrego-java
a library that models the Open Policy Agent policy language Rego
The design of the project is borrowed from Bisnode/opa-java-client, but uses an async programming model instead, which makes it suitable to be used in a reactive application stack.
This client library uses the JDK11+ HttpClient by default, but allows you to plug in your own http-client by providing an implementation for the OpaRestClient interface.
Prerequisites: Java 11 or higher
Using Gradle:
implementation "com.contentgrid.opa-java-client:opa-async-java-client:${version}"
Using Maven:
<dependency>
<groupId>com.contentgrid.opa-java-client</groupId>
<artifactId>opa-async-java-client</artifactId>
<version>${version}</version>
</dependency>
Create an OpaClient
instance:
OpaClient client = OpaClient.builder()
.url("http://localhost:8181")
.build();
client.listPolicies().thenAccept(response -> {
var policies = response.getResult();
policies.forEach(policy -> log.info("policy id: {}", policy.getId()));
});
client.getPolicy("my-policy-id").thenAccept(response -> {
AbstractSyntaxTree ast = response.getResult().getAst();
// do something with the `ast`
});
client.upsertPolicy("policy_id", "content of the policy").join();
Error handling is not yet properly supported.
When the HTTP status code is 400 or higher, the returned
CompletableFuture<T>
will fail, with HttpStatusException
as inner exception cause.
Example:
var result = client.upsertPolicy("my-policy", "invalid policy");
result.handle((response, ex) -> {
if (ex != null) {
if (ex.getCause() instanceof HttpStatusException) {
if (((HttpStatusException) ex.getCause()).getStatusCode() == 400) {
throw new IllegalArgumentException("policy content is not valid");
}
}
throw RuntimeException(ex);
}
// happy path
return response;
});