Java SDK
Use the Java SDK to moderate content, manage assets and handle events from your server, with typed requests and responses. It requires Java 17 or later. The Java SDK reference covers each method, uploads, webhooks, CDN transforms, errors and retries in detail.
Install
<dependency>
<groupId>com.calmlens</groupId>
<artifactId>calmlens-sdk</artifactId>
<version>0.21.0</version>
</dependency>See Versioning and support for what each version change means and where to find the changelog.
Moderate content
Keep credentials on your server. Create an API key and copy your project ID in the portal; see Authentication for the permissions each call needs. Create one client, share it across threads and close it on shutdown. assets.create queues processing; assets.classify and text.classify wait for the decision. Audio and video always run in the background. See Waiting for the decision for supported content, webhooks and polling.
import com.calmlens.CalmLensServerClient;
import com.calmlens.Models.*;
var client = CalmLensServerClient.builder(System.getenv("CALMLENS_API_KEY"), System.getenv("CALMLENS_PROJECT_ID")).build();
Asset asset = client.text.classify(new ClassifyText("Great photo!").externalId("comment-42"));
if (asset.classification().moderation().status() == AssetModerationStatus.ALLOWED) {
System.out.println("Publish " + asset.id());
}Publish only an allowed result; serve an age-restricted one only to viewers your app allows, by setting .viewerClaims(new ViewerClaims().ageConfirmed(true)) on a CdnRequest or SignAssetUrlOptions, which adds them to the URL; a signed URL or your API key alone doesn't serve it. See Age-restricted assets. See Reading classification results.
Responses are immutable records with the API's field names as accessors (asset.classification().moderation().categories(), event.type()). Timestamps are Instants, and whole numbers in metadata stay exact Longs. A status or visibility added after your SDK version keeps its raw value (value(), with isKnown() false) instead of failing, so treat a status you don't recognise as not allowed.
Request models (SubmitAsset, ClassifyText and so on) are builders in com.calmlens.Models. Required fields have constructors; fluent setters configure optional fields. Patch.value(value) sets a field, Patch.clear() clears it, and leaving it unset preserves it.
Waiting for a decision
assets.waitForDecision returns the asset once its classification.status is completed or failed. It retrieves the asset at once, then again after 0.5 seconds, waiting 1.5 times longer each time, up to 2 seconds between checks. If there's no decision within the timeout (60 seconds by default), it throws sdk/timeout with assetId and the last classificationStatus and moderationStatus in getDetails(). Interrupting the thread stops it with sdk/cancelled.
Asset queued = client.assets.create(new SubmitAsset("photo.jpg", Content.file(java.nio.file.Path.of("photo.jpg"), "image/jpeg"))
.externalId("post-42"));
Asset decided = client.assets.waitForDecision(new WaitForDecision(queued.id()).timeout(java.time.Duration.ofSeconds(30)));Uploads
Content.file(path, mime) and Content.stream(inputStream, sizeInBytes, mime) stream uploads without reading them into memory; Content.stream(inputStream, mime) sends a stream of unknown size, and Content.bytes sends a byte array as it is.
assets.create and assets.classify send content larger than the builder's partSizeBytes (8 MiB by default) as a multipart upload for you when the client can read it again: bytes, base64 and files. Streams and text go in one request. Each part is retried on its own, and calling again with the same idempotency key resumes an upload that failed partway.
To send parts yourself, send the first part with assets.create or assets.classify and later parts with assets.uploadPart. Whether the upload was started with assets.create (queued) or assets.classify (wait for the decision) is fixed by the first part, so later parts can come from any client. Set totalSizeInBytes on the first part's SubmitAsset to have the total size checked before the remaining parts arrive.
Each upload must be a supported type within that type's size and duration limits; see Asset types and limits. Documents are PDF, DOCX, DOC, RTF and ODT files, spreadsheets (XLSX, XLSM, XLS, ODS) and presentations (PPTX, PPTM, PPT, ODP). Keynote and Numbers files are refused with 415 upload/unsupported-type.
Metadata is a list of {id, value} items, such as .metadata(List.of(new MetadataItem("campaign.id", "launch-2026"))). The value can be any JSON value. To filter or group assets by an item in the portal, use the ID of a metadata field defined there; see Asset metadata.
Upload presets
Pass .uploadPresetId(...) on SubmitAsset to apply an upload preset's folder, visibility, file types and size limit. To let a browser upload through a preset that requires tokens, sign a single-use token on your server with client.uploadTokens.sign(new SignUploadToken(...)). Signing happens locally with your API key and makes no request.
CDN methods
Fetch retained content directly from your backend with client.cdn.serve:
import com.calmlens.CalmLensServerClient;
import com.calmlens.Models.*;
public class Example {
public static void example(CalmLensServerClient client) {
try (var result = client.cdn.serve(new CdnRequest("asset_5Gm2Rk8XqT3wLp9VbN4c").resource("original"))) {
System.out.println(result.status());
}
}
}cdn.serve streams raw content bytes, not the asset report, and returns a closeable response for any status but a redirect, retrying failures like an API read. Check the status before using the body; for text assets (such as those created by text.classify), decode the body as UTF-8 text.
try (CdnResponse response = client.cdn.serve(new CdnRequest(asset.id()))) {
if (response.status() == 200) response.transferTo(outputStream);
}The request uses your server API key; private reads require Download assets permission. For private content in browsers, sign the asset URL with cdn.signAssetUrl instead (see Signed asset URLs).
Upload with .processingOptions(new ProcessingOptions().keepContentAfterProcessing(true)) on SubmitAsset to retain content. The CDN delivers by the current classification.moderation.status, and still requires available content and authorised access. See Delivery while moderation runs.
Methods
Each method takes the request model shown, from com.calmlens.Models. See the Java SDK reference for how each one behaves.
| Method | Purpose |
|---|---|
text.classify(ClassifyText) | Classify text and wait for the decision. text.classify(String) is a shortcut. |
assets.create(SubmitAsset) | Upload content without waiting for the decision. |
assets.classify(SubmitAsset) | Upload content and wait for the decision where supported. |
assets.uploadPart(UploadPart) | Send the next part of a multipart upload. |
assets.retrieve(AssetId) | Fetch one asset. |
assets.waitForDecision(WaitForDecision) | Retrieve an asset until it is completed or failed; see Waiting for a decision. |
assets.listTimeline(ListTimeline) / assets.iterateTimeline(ListTimeline) | Page or iterate through an audio or video asset's findings timeline Preview, in time order. |
assets.list(ListAssets) / assets.iterate(ListAssets) | List one page of assets, or iterate over every matching asset. |
assets.search(SearchAssets) | Search assets by meaning and by name, ID, external ID, description and tags, best match first; see Asset search. |
assets.listChildren(ListChildren) / assets.iterateChildren(ListChildren) | List an asset's extracted children. |
assets.update(UpdateAsset) | Update asset fields. |
assets.move(MoveAsset) | Move an asset to a folder, or to the project root. |
assets.retry(AssetId) | Retry an eligible processing failure. |
assets.explain(ExplainAsset) | Fetch the full policy evidence for a decision (which rules and findings produced it), or with rerun moderate the asset again under the current policy. |
assets.decide(DecideAsset) | Record a reviewer's decision (an AssetModerationDecision) with a required note. An asset pending moderation can only be blocked or purged, and purging needs confirmPurge(true); see POST /. |
assets.removeContent(AssetId) | Remove stored content and keep the asset record and report. |
assets.delete(AssetId) | Delete the asset record and its content. |
assets.batch(BatchAssets) | Delete up to 500 assets or remove their stored content in one queued request; see POST /. |
folders.list, iterate, retrieve, create, update, move, delete | Manage folders, with ListFolders, FolderId, CreateFolder, UpdateFolder and MoveFolder. folders.list returns one page of folders with the ancestors needed to show their paths. |
hashLists.list, iterate, retrieve, create, update, delete | Manage hash lists that image uploads are compared with, with ListHashLists, HashListId, CreateHashList and UpdateHashList. |
hashLists.listEntries, iterateEntries, addEntry, removeEntry | Manage the hashes in a hash list, with ListHashListEntries, AddHashListEntry and HashListEntryId. |
policies.list, iterate, retrieve, create, update, reset, upgrade, setAutomaticUpdates, delete, retrieveAssigned, assign | Manage the organisation's moderation policies and choose the one the project uses, with ListPolicies, PolicyId, CreatePolicy, UpdatePolicy, ResetPolicy, UpgradePolicy and SetPolicyAutomaticUpdates; see Policies. |
events.list(ListEvents) / events.pages(ListEvents) | Read one page of the project event feed, or follow its cursor page by page. |
lenses.list, iterate, create, retrieve, update, delete | Manage the project's lenses, with ListLenses, LensDefinition, LensId and UpdateLens. |
ensureLens(LensDefinition) / ensureLenses(EnsureLenses) | Create lenses by identifier, or change them to the definitions sent. |
cdn.getAssetUrl(CdnRequest) / cdn.serve(CdnRequest) | Build a public asset URL or a resource URL beneath it, or stream content. |
cdn.signAssetUrl(SignAssetUrlOptions) | Sign a private asset's URL for browsers and apps. |
cdn.getAssetInfo(url) | Read an asset URL's display info (/info). |
uploadTokens.sign(SignUploadToken) | Sign an upload token locally, without a request. |
Pagination
Every list returns a page with items(), nextCursor() and hasMore(). Pass a page's nextCursor() as cursor to get the next one, and treat it as opaque. Each list's iterate method, such as assets.iterate or policies.iterate, goes through every page for you. Lists take sort, a comma-separated list of fields, each descending when prefixed with -, such as "-createdAt,id".
events.list(new ListEvents()) without a cursor returns no events and a nextCursor() for the current time. events.pages yields event pages from a cursor until hasMore() is false; persist each page's nextCursor() after handling it. See Reading the feed for cursor handling.
for (EventsPage page : client.events.pages(new ListEvents().cursor(savedCursor).pageSize(100))) {
for (Event event : page.items()) handle(event);
savedCursor = page.nextCursor();
}Errors and retries
Every failure is an unchecked CalmLensException with a stable getCode(); ErrorCodes has a constant for every public API error code.
ApiException: the API answered with an error. It carriesgetStatus(),getRequestId()(theX-Request-Idheader, or the error body'srequestId),getHeaders(),getRetryAfter()andgetDetails()(the error's details, such as validation issues). A redirect is never followed and fails withsdk/http-errorand its status.TransportException: the request could not be sent or its response could not be read (sdk/transport-error), with the original exception as its cause.RequestTimeoutException(sdk/timeout) is one: a request that ran out of time.waitForDecision's deadline throws a plainCalmLensExceptionwithsdk/timeout, not aRequestTimeoutException. CheckgetCode()rather than the class.- Invalid arguments use
sdk/invalid-argument, invalid client optionssdk/invalid-config, and upload payload problems theirupload/*codes, such as 413 upload/too-large for content of known size over the upload limit. Nothing is sent for these.
isRetryable() is true when repeating the request may succeed: sdk/transport-error, sdk/timeout (including waitForDecision's deadline), 409 idempotency/request-in-progress and HTTP 429, 500, 502, 503 and 504, whichever exception class carries them. Everything else, sdk/cancelled and other 5xx statuses included, is false.
| Failure | What the SDK does | What you do |
|---|---|---|
Network failure (sdk/transport-error) or timeout (sdk/timeout) | Retries reads and uploads twice by default, with jittered exponential backoff from 0.5 to 8 seconds | Once retries run out, retry later: isRetryable() is true |
HTTP 429, 500, 502, 503, 504 or 409 idempotency/request-in-progress | Retries the same requests, waiting for Retry-After (seconds or a date) when the API sends one | A Retry-After over 60 seconds is thrown to you instead: wait, then retry |
waitForDecision runs out of time | Throws a CalmLensException with sdk/timeout | Wait again, or rely on a webhook |
| Thread interrupted | Stops with sdk/cancelled; never retried | Nothing |
Failure of another write, such as assets.update or assets.delete | Not retried | Retry only when repeating the change is safe |
| Streamed upload | Sent once | Upload again from the start |
| Upload retried from another process | Each upload sends a new Idempotency-Key, reused for that call's retries | Pass your own with new RequestOptions().idempotencyKey(key) |
| Redirect | Not followed; throws ApiException with sdk/http-error and its status | Check baseUrl and cdnBaseUrl |
cdn.serve failure | Retries like an API read, then returns the response for any status but a redirect | Check response.status() |
Set maxRetries(0) on the builder to turn retries off. See Retrying requests safely.
| Builder setting | Default | Limits |
|---|---|---|
connectTimeout | 10 seconds | Opening a connection |
timeout | 120 seconds | Each API request attempt, its response body and text uploads included |
uploadTimeout | None | Each binary upload attempt, so large files are not cut off |
maxResponseBytes | 32 MiB | API response bodies |
partSizeBytes | 8 MiB | Content larger than this is uploaded in parts of this size, from 5 to 64 MiB |
To override timeout, uploadTimeout and maxRetries for every call, use client.withRequestOptions(...), which returns a client sharing the connection and lens cache. Uploads (assets.create, assets.classify, assets.uploadPart), text.classify and cdn.serve also take RequestOptions for a single call.
Requests send User-Agent: calmlens-java/<version> (java/<runtime version>).
Webhooks
Read the request body as raw bytes and pass them to parseWebhookEvent, which verifies the signature and timestamp before parsing. Never pass a body your framework has already parsed. In Spring, declare the body as @RequestBody byte[] body; in a servlet, read request.getInputStream().
WebhookEventPayload event;
try {
event = CalmLensServerClient.parseWebhookEvent(body,
request.getHeader(CalmLensServerClient.WEBHOOK_SIGNATURE_HEADER),
request.getHeader(CalmLensServerClient.WEBHOOK_TIMESTAMP_HEADER),
System.getenv("CALMLENS_WEBHOOK_SECRET"));
} catch (CalmLensException invalid) {
return invalid.getCode().equals(ErrorCodes.SDK_INVALID_WEBHOOK_SIGNATURE) ? 401 : 400;
}It throws sdk/invalid-webhook-signature for a forged, tampered or stale delivery (more than WEBHOOK_SIGNATURE_TOLERANCE_SECONDS, 300, from your clock) and sdk/invalid-webhook-payload for a verified body that is not a CalmLens event. The body is the event exactly as events.list returns it, so the payload has id(), projectId(), type(), severity(), title(), description(), assetId(), the asset() snapshot, facts() and createdAt(); description, assetId and asset are null when the event has none. json() holds the whole body as received, including fields this SDK version doesn't model, CalmLensServerClient.isTestWebhookEvent(event) tells test sends apart, and CalmLensServerClient.getEventFact(event, "flagged-categories") and getEventFacts(event) read the event's facts by key. Deduplicate by event ID, and retrieve the asset for its current state rather than trusting the snapshot. verifyWebhookSignature returns a boolean instead. With the request's headers as a map, parseWebhookRequest(headers, body, secret) and verifyWebhookRequest(headers, body, secret) find the signature and timestamp in any letter case and join repeated headers. See Webhooks.
Command-line tool
See Local development to install the CLI, forward signed events and trigger test uploads.
Testing
Use com.calmlens.MockCalmLensServerClient for offline tests. See Java testing.