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, retries, logging and asynchronous calls in detail.

Install

<dependency>
  <groupId>com.calmlens</groupId>
  <artifactId>calmlens-sdk</artifactId>
  <version>0.29.0</version>
</dependency>

The JAR is a named module: add requires com.calmlens; to your module-info.java when your application uses modules. 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. CalmLensServerClient.fromEnv() reads them from the CALMLENS_API_KEY and CALMLENS_PROJECT_ID environment variables, and CALMLENS_BASE_URL when it is set. 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. Documents, websites, 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.*;
import com.calmlens.params.*;

var client = CalmLensServerClient.fromEnv();
Asset asset = client.text().classify(TextClassifyParams.builder()
    .setText("Great photo!")
    .setExternalId("comment-42")
    .build());
if (asset.getClassification().getModeration().getDecision().orElse(null) == AssetModerationDecision.ALLOWED) {
  System.out.println("Publish " + asset.getId());
}

getDecision() is empty while the decision is pending. Publish only an allowed result; serve an age-restricted one only to viewers your app allows, by setting .setViewerClaims(ViewerClaims.builder().setAgeConfirmed(true).build()) on CdnRequestParams or CdnSignAssetUrlParams, which adds them to the URL; a signed URL or your API key alone doesn't serve it. See Age-restricted assets and Reading classification results.

To configure the client in code, use the builder:

var client = CalmLensServerClient.builder()
    .apiKey(apiKey)
    .projectId(projectId)
    .appInfo("gallery-plugin", "2.1.0", "https://example.com/gallery")   // added to the User-Agent
    .build();

CalmLensServerClient.builder().fromEnv() starts from the environment, so you can set other options before build(). See Client for every builder setting.

Requests and responses

Request params live in com.calmlens.params and are immutable: build them with XParams.builder().setOption(value).build(), as with TextClassifyParams above. Path IDs are plain arguments, such as client.assets().retrieve(assetId). Unset options aren't sent, and build() throws InvalidArgumentException (sdk/invalid-argument) when a required option is missing.

Responses live in com.calmlens.models and read with getters (asset.getClassification().getModeration().getCategories(), event.getType()). A field the API always sends returns its value; an optional or nullable one returns an Optional. Timestamps are Instants, and whole numbers in metadata stay exact Longs. Statuses and other fixed sets of values are enums: a value added after your SDK version reads as UNKNOWN instead of failing, so treat a value you don't recognise as not allowed. See Responses.

Waiting for a decision

assets().waitForDecision(assetId) 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 a TimeoutException (sdk/timeout) with assetId and the last classificationStatus and moderationDecision in getDetails(). Interrupting the thread stops it with sdk/cancelled.

Asset queued = client.assets().create(AssetCreateParams.builder()
    .setName("photo.jpg")
    .setContent(Content.file(Path.of("photo.jpg"), "image/jpeg"))
    .setExternalId("post-42")
    .build());
Asset decided = client.assets().waitForDecision(queued.getId(), 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. Call setTotalSizeInBytes on the first part's AssetCreateParams 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 .setMetadata(List.of(MetadataItemParams.of("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

Call .setUploadPresetId(...) on AssetCreateParams to apply an upload preset's folder, visibility, file types, size limit, moderation policy and processing options. To let a browser upload through a preset that requires tokens, sign a single-use token on your server with client.uploadTokens().sign(UploadTokenSignParams.builder()...build()). Signing happens locally with your API key and makes no request.

CDN methods

To upload a public image for delivery, retain its content and use an API key with Create assets (assets:create) and Share assets (assets:share). Keep the image unpublished until moderation allows it, then use its rendered CDN resource. For a private image, keep visibility private and sign its URL on your server with a key that has Share assets. See Authentication.

Asset image = client.assets().classify(AssetCreateParams.builder()
    .setName("photo.jpg")
    .setContent(Content.file(Path.of("photo.jpg"), "image/jpeg"))
    .setVisibility(Visibility.PUBLIC)
    .setProcessingOptions(ProcessingOptionsParams.builder().setRetainContent(true).build())
    .build());
if (image.getClassification().getModeration().getDecision().orElse(null) == AssetModerationDecision.ALLOWED) {
  String src = client.cdn().getAssetUrl(CdnRequestParams.builder().setAssetId(image.getId()).setResource(CdnResource.RENDERED).build());
}

cdn().getAssetUrl(CdnRequestParams.builder().setAssetId(id).build()) builds the base asset URL. To load an image in a browser, select its displayable resource with .setResource(CdnResource.RENDERED). The base URL alone does not serve content. Use original for retained text or a download of the stored file; see CDN resources.

Fetch retained content directly from your backend with client.cdn().serve:

import com.calmlens.CalmLensServerClient;
import com.calmlens.CdnResponse;
import com.calmlens.models.CdnResource;
import com.calmlens.params.*;

public class Example {
  public static void example(CalmLensServerClient client) {
    try (CdnResponse result = client.cdn().serve(CdnRequestParams.builder()
        .setAssetId("asset_e5Gm2Rk8XqT3wLp9VbN4")
        .setResource(CdnResource.ORIGINAL)
        .build())) {
      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(CdnRequestParams.builder().setAssetId(asset.getId()).setResource(CdnResource.ORIGINAL).build())) {
  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 .setProcessingOptions(ProcessingOptionsParams.builder().setRetainContent(true).build()) on AssetCreateParams to retain content. The CDN delivers by the current classification.moderation.decision, and still requires available content and authorised access. See Delivery while moderation runs.

Methods

Each method takes its path IDs as arguments, then the params shown, from com.calmlens.params. Every method also has an overload that takes a trailing RequestOptions; see Request options. client.async() offers the same methods returning CompletableFutures; see Asynchronous calls. See the Java SDK reference for how each one behaves.

MethodPurpose
text().classify(TextClassifyParams)Classify text and wait for the decision. text().classify(String) is a shortcut.
assets().create(AssetCreateParams)Upload content without waiting for the decision.
assets().classify(AssetCreateParams)Upload content and wait for the decision where supported.
assets().uploadPart(id, AssetUploadPartParams)Send the next part of a multipart upload.
assets().retrieve(id)Fetch one asset.
assets().retrieveByExternalId(externalId)Fetch the asset with that external ID.
assets().waitForDecision(id[, timeout])Retrieve an asset until it is completed or failed; see Waiting for a decision.
assets().listTimeline(id, AssetListTimelineParams) / assets().iterateTimeline(...)Page or iterate through an audio or video asset's findings timeline Preview, in time order.
assets().list([AssetListParams]) / assets().iterate(AssetListParams)List one page of assets, or iterate over every matching asset.
assets().search(AssetSearchParams)Search assets by meaning and by name, ID, external ID, description and tags, best match first; see Asset search.
assets().listChildren(id[, AssetListChildrenParams]) / assets().iterateChildren(...)List an asset's extracted children.
assets().update(id, AssetUpdateParams)Update asset fields.
assets().move(id, AssetMoveParams)Move an asset to a folder, or to the project root.
assets().retry(id)Retry an eligible processing failure.
assets().decide(id, AssetDecideParams)Record a reviewer's decision (an AssetModerationDecision) with a required note. An asset pending moderation can only be blocked or purged, and purging needs setConfirmPurge(true); see POST /assets/:assetId/decision.
assets().requestReview(id[, AssetRequestReviewParams])Send an asset to the human review queue, such as when a user reports it.
assets().removeContent(id)Remove stored content and keep the asset record and report.
assets().delete(id)Delete the asset record and its content.
assets().batch(AssetBatchParams)Delete up to 500 assets or remove their stored content in one queued request; see POST /projects/:projectId/assets/batch.
folders(): list, iterate, retrieve, create, update, move, deleteManage folders, with FolderListParams, FolderCreateParams, FolderUpdateParams and FolderMoveParams. folders().list returns one page of folders with the ancestors needed to show their paths.
hashLists(): list, iterate, retrieve, create, update, deleteManage hash lists that image uploads are compared with, with HashListListParams, HashListCreateParams and HashListUpdateParams.
hashLists(): listEntries, iterateEntries, addEntry, removeEntryManage the hashes in a hash list, with HashListListEntriesParams and HashListAddEntryParams.
policies(): list, iterate, retrieve, create, update, reset, upgrade, setAutomaticUpdates, delete, retrieveAssigned, assignManage the organisation's moderation policies and choose the one the project uses, with PolicyListParams, PolicyCreateParams, PolicyUpdateParams, PolicyResetParams, PolicyUpgradeParams and PolicySetAutomaticUpdatesParams; see Policies.
events().list([EventListParams]) / events().pages(EventListParams)Read one page of the project event feed, or follow its cursor page by page.
events().retrieveAsset(event)Retrieve the asset an event or webhook delivery is about, as it is now.
lenses(): list, iterate, create, retrieve, update, deleteManage the project's lenses, with LensListParams, LensCreateParams and LensUpdateParams.
ensureLens(LensCreateParams) / ensureLenses(List<LensCreateParams>)Create lenses by identifier, or change them to the definitions sent.
cdn().getAssetUrl(CdnRequestParams) / cdn().serve(CdnRequestParams)Build a public asset URL or a resource URL beneath it, or stream content.
cdn().signAssetUrl(CdnSignAssetUrlParams)Sign a private asset's URL for browsers and apps.
cdn().getAssetInfo(url)Read an asset URL's display info (/info).
uploadTokens().sign(UploadTokenSignParams)Sign an upload token locally, without a request.
request(method, path[, query, body, requestOptions])Call an API path with the client's credentials, retries and errors; see Raw requests.

Pagination

Every list returns a page with getItems(), getNextCursor() and getHasMore(). Pass a page's next cursor to setCursor 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 setSort, a comma-separated list of fields, each descending when prefixed with -, such as "-createdAt,id".

events().list() without a cursor returns no events and a getNextCursor() for the current time. events().pages yields event pages from a cursor until getHasMore() is false; persist each page's getNextCursor() after handling it. See Reading the feed for cursor handling.

for (EventsPage page : client.events().pages(EventListParams.builder().setCursor(savedCursor).setPageSize(100).build())) {
  for (Event event : page.getItems()) handle(event);
  savedCursor = page.getNextCursor();
}

Errors and retries

Every failure is an unchecked CalmLensException from com.calmlens.exception, with a stable getCode(); com.calmlens.ErrorCodes has a constant for every public API error code. Constants are named for what the error means, not by its code: ErrorCodes.UNSUPPORTED_UPLOAD_TYPE is 415 upload/unsupported-type, ErrorCodes.DUPLICATE_EXTERNAL_ID is 409 asset/duplicate-external-id and ErrorCodes.FREE_UPLOADS_EXHAUSTED is 403 usage/free-uploads-exhausted. The Javadoc published with each release on Maven Central (calmlens-sdk-<version>-javadoc.jar) lists every constant with its code. Catch the subclass for the kind of failure you handle:

ExceptionWhen
ApiExceptionThe API answered with an error. Subclasses name the status: BadRequestException (400), AuthenticationException (401), PermissionDeniedException (403), NotFoundException (404), ConflictException (409), PayloadTooLargeException (413), UnprocessableEntityException (422), RateLimitException (429) and ServerException (500 and above).
ConnectionExceptionThe request couldn't be sent or its response couldn't be read (sdk/transport-error).
TimeoutExceptionA request, or waitForDecision, ran out of time (sdk/timeout).
CancelledExceptionThe calling thread was interrupted (sdk/cancelled).
InvalidArgumentExceptionNothing was sent: an invalid argument (sdk/invalid-argument) or upload payload, such as 413 upload/too-large for content of known size over the upload limit. ConfigurationException (sdk/invalid-config) is one, for invalid client options.
InvalidResponseExceptionThe API's response couldn't be read (sdk/invalid-response, sdk/response-too-large).
WebhookVerificationExceptionA webhook delivery didn't verify; see Webhooks.

Every exception has getStatus(), getRequestId() (the X-Request-Id header, or the error body's requestId), getHeaders(), getRetryAfter(), getDetails() (the error's details, such as validation issues) and getBody(). Log the request ID with failures and include it when contacting support. A redirect is never followed and fails with sdk/http-error and its status.

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. Everything else, sdk/cancelled and other 5xx statuses included, is false.

FailureWhat the SDK doesWhat 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 secondsOnce retries run out, retry later: isRetryable() is true
HTTP 429, 500, 502, 503, 504 or 409 idempotency/request-in-progressRetries the same requests, waiting for Retry-After (seconds or a date) when the API sends oneA Retry-After over 60 seconds is thrown to you instead: wait, then retry
waitForDecision runs out of timeThrows a TimeoutException with sdk/timeoutWait again, or rely on a webhook
Thread interruptedStops with CancelledException; never retriedNothing
Failure of another write, such as assets().update or assets().deleteNot retried, unless the call has an idempotency keyRetry only when repeating the change is safe
Streamed uploadSent onceUpload again from the start
Upload retried from another processEach upload sends a new Idempotency-Key, reused for that call's retriesPass your own with RequestOptions.builder().setIdempotencyKey(key).build()
RedirectNot followed; throws ApiException with sdk/http-error and its statusCheck baseUrl and cdnBaseUrl
cdn().serve failureRetries like an API read, then returns the response for any status but a redirectCheck response.status()

Set maxRetries(0) on the builder to turn retries off. See Retrying requests safely.

Builder settingDefaultLimits
connectTimeout10 secondsOpening a connection
timeout120 secondsEach API request attempt, its response body and text uploads included
uploadTimeoutNoneEach binary upload attempt, so large files are not cut off
maxRetries2Retries of each request, 0 to 10
maxResponseBytes32 MiBAPI response bodies
partSizeBytes8 MiBContent larger than this is uploaded in parts of this size, from 5 to 64 MiB

To change the timeouts, retries or headers of one call, pass RequestOptions as its last argument, or setDeadline to bound the whole call, retries included. To change them for every call, use client.withRequestOptions(...), which returns a client sharing the connection and lens cache. Set CALMLENS_LOG=info to log retries and failures, or debug to log every request; see Logging and request listeners.

Requests send User-Agent: calmlens-java/<version> (java/<runtime version>), followed by your appInfo when you set it.

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 (WebhookVerificationException invalid) {
  return invalid.getCode().equals(ErrorCodes.SDK_INVALID_WEBHOOK_SIGNATURE) ? 401 : 400;
}

It throws a WebhookVerificationException with sdk/invalid-webhook-signature for a forged, tampered or stale delivery (more than WEBHOOK_SIGNATURE_TOLERANCE_SECONDS, 300, from your clock) and with 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 getId(), getProjectId(), getType(), getSeverity(), getTitle(), getDescription(), getAssetId(), getAssetSequence(), getFacts() and getCreatedAt(); getDescription(), getAssetId() and getAssetSequence() are empty when the event has none. getRawJsonObject() 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. Events carry only the asset's ID, not its state: deduplicate by event ID, and call client.events().retrieveAsset(event) for the asset as it is now. It returns an empty Optional, without a request, for an event that isn't about an asset. 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.

Deduplicating by event.getId() stops a redelivery being applied twice, but it doesn't put events in order: a retry can arrive after a later event about the same asset. Store the highest getAssetSequence() you've applied for each asset, and apply an event only when CalmLensServerClient.isNewerAssetEvent(event, lastSequence) is true, so a late asset.allowed never undoes a later asset.blocked. A retrieved asset's getEventSequence() is the assetSequence of its latest event when it was read, or 0 before its first, so an event with a higher getAssetSequence() happened after the state you retrieved. See Event order.

Test webhooks locally

Your tests and CI need no CLI: the testing helpers build and sign deliveries offline, so your handler's verification runs unchanged. To forward your project's real events to a handler on your machine, install the calmlens CLI, a standalone executable for macOS, Linux and Windows:

curl -fsSL https://calmlens.com/install.sh | sh

Then run calmlens login and calmlens listen --forward-to <url>. See Local development for Windows, Homebrew, release downloads and npm, sending portal test events through a tunnel, and creating test events with calmlens trigger.

Testing

Use MockCalmLensServerClient from com.calmlens.testing for offline tests. See Java testing.

Last updated

Cookies on CalmLens

We use essential cookies for sign-in and security. With your permission, functional cookies remember your preferences and Google Analytics measures website use and signups. Optional ad measurement cookies link Google ad clicks to signups. Personalised advertising stays off. Manage cookies