---
title: "Java REST client"
description: "Build a complete Java Sandbox licensing client with verified signatures, persistent identity, private state, offline policy and safe feature gating."
slug: "/docs/v1/sdks/java"
section: "SDKs and languages"
order: 52
audience: "all"
level: "intermediate"
last_updated: "2026-10-17"
version: "v1"
related: ["/docs/v1/api/activate", "/docs/v1/security/offline-mode"]
draft: false
---
Use the real API v1 from a trusted Java process with explicit signature and policy checks before enabling [features](/docs/v1/start/glossary#feature). This REST sample is not an additional [official SDK](/docs/v1/start/glossary#official-sdk).

## What you will learn
- Activate, validate and deactivate one stable [Sandbox](/docs/v1/start/glossary#sandbox) installation.
- Preserve signed bytes and verify the trusted Ed25519 key before policy.
- Handle cache, [offline grace](/docs/v1/start/glossary#offline-grace), explicit rejection and safe user messages.

## Prerequisites
- Complete [the Sandbox quickstart](/docs/v1/start/quickstart).
- Read [authentication](/docs/v1/start/authentication) and [signed responses](/docs/v1/security/signed-responses).
- Have the [product](/docs/v1/start/glossary#product) App ID, a Sandbox [license](/docs/v1/start/glossary#license) and its matching [customer](/docs/v1/start/glossary#customer) email when supplied.
- Obtain the actual [public-key document](/docs/v1/api/public-key) over independently trusted HTTPS and distribute/pin it through controlled application configuration, not from an untrusted envelope.

## Runtime and application type
Java17+, Gson2.14.0, Bouncy Castle1.86. JVM desktop, CLI and backend processes. The complete session core uses Java HttpClient and Java NIO file locking. Keep the two pinned jars at runtime. Windows classpaths use semicolons; the POSIX shell build needs a compatible development shell or equivalent IDE configuration.

## Complete project and integrity
<!-- P7-PROJECT-PACKAGE:START -->
The complete project archive contains every client/verifier source and the exact build/dependency metadata needed by this language. Extract it with its original directory layout. Dependencies/locks are included where this runtime uses them; no hidden helper or test-only clock is required.

[kdpika-java-rest-example-1.0.0.zip](/docs/downloads/kdpika-java-rest-example-1.0.0.zip) · 9925 bytes · version 1.0.0

SHA-256: 75a1647186ff9642c3d48c7e92772f8dcae251406fb7dd439cad453bdf969aa3
<!-- P7-PROJECT-PACKAGE:END -->
Extract the entire project, preserving its samples/sdks and samples/security layout. The archive includes all first-party client/verifier sources and pinned manifests/locks; dependency downloads are development-time restoration, never extra services needed by the PHP host. Do not flatten the tree or replace the verification helper with a generic JSON reserializer.

## Install and build
1. Verify the archive SHA-256 against the current table. Expected: exact digest match; otherwise stop.
2. Extract into a clean private development directory. Expected: complete samples tree with the language project.
3. Enter samples/sdks/java. Expected: the main client and build/dependency files are present.
4. Install the stated runtime/native libraries, then run the full build command below. Expected: successful syntax check or native executable, not a registry SDK download.
```bash
sh build.sh
```
The source scripts compile the exact files and validate third-party download checksums where applicable. Compiler toolchains are development dependencies, not tools to install on KDPika shared hosting. macOS is the actual tested runtime; other targets require their own build/permission/TLS-root checks.

## Application configuration
| Variable | Required | Meaning |
| --- | --- | --- |
| KDP_APP_ID | Yes | [Public App ID](/docs/v1/start/glossary#public-app-id), not internal product ID or [developer](/docs/v1/start/glossary#developer) key |
| KDP_BASE_URL | No | HTTPS API base ending /api/v1; default https://licensing.kdpika.com/api/v1 |
| KDP_STATE_DIR | Yes | Absolute private application state root; keep it stable |
| KDP_TRUSTED_KEY_FILE | Yes | Absolute path to an independently trusted public-key document |
| KDP_LICENSE_KEY | [Activation](/docs/v1/start/glossary#activation) | Sandbox key beginning TEST; never embedded in distributed source |
| KDP_CUSTOMER_EMAIL | Optional | Actual matching customer email for email-bound activation |
| KDP_ALLOW_LOOPBACK | Local testing only | 1 permits explicit localhost/127.0.0.1 HTTP, not arbitrary HTTP hosts |

Environment is fixed to SANDBOX in this example. Unsafe URL credentials/query/fragment and nonlocal HTTP are rejected. Official SDK constructors expect the site origin; these REST programs expect /api/v1. Store state and trusted keys outside public web roots. Do not ship lmp_ developer management keys.

## Complete runnable client
```java
// Complete Sandbox REST session, Java17+, Gson2.14.0, BC1.86.
// Compile with the unchanged P5 Canonical.java/Verify.java and pinned jars.
// Run Session status|activate|check|validate|deactivate; safe JSON decisions only.
import com.google.gson.*;
import java.net.URI;
import java.net.http.*;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.MessageDigest;
import java.time.*;
import java.util.*;

public final class Session implements AutoCloseable {
    static final Gson JSON=new GsonBuilder().disableHtmlEscaping().serializeNulls().create();
    static final int MAX=1048576;
    static final class Denied extends Exception {
        private static final long serialVersionUID=1L;
        final String code,requestId;
        Denied(String code){this(code,null);} Denied(String code,String requestId){super(code);this.code=code;this.requestId=requestId;}
    }
    static final class Offline extends Exception {private static final long serialVersionUID=1L;}
    final String app,base,installation;
    final Path directory;
    final byte[] trusted;
    final FileChannel channel;
    final FileLock lock;
    final HttpClient http=HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER).build();
    static String config(String name){String value=System.getenv(name);if(value==null||value.isBlank()||value.contains("\r")||value.contains("\n"))throw new IllegalArgumentException("Missing configuration");return value;}
    static String digest(String text)throws Exception{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)));}
    static void permission(Path path,String mode)throws Exception {if(Files.getFileStore(path).supportsFileAttributeView("posix"))Files.setPosixFilePermissions(path,PosixFilePermissions.fromString(mode));}
    static byte[] read(Path file)throws Exception {if(Files.isSymbolicLink(file)||!Files.isRegularFile(file,LinkOption.NOFOLLOW_LINKS)||Files.size(file)>MAX)throw new IllegalArgumentException("Unsafe state file");return Files.readAllBytes(file);}
    static JsonObject parsed(byte[] bytes)throws Exception {Object tree=Canonical.parse(bytes);if(!(tree instanceof Map))throw new Denied("INVALID_RESPONSE");return JsonParser.parseString(Canonical.encode(tree)).getAsJsonObject();}
    static String string(JsonObject object,String name)throws Denied {var value=object.get(name);if(value==null||!value.isJsonPrimitive()||!value.getAsJsonPrimitive().isString())throw new Denied("INVALID_RESPONSE");return value.getAsString();}
    static Instant instant(String value)throws Denied {try{return OffsetDateTime.parse(value).toInstant();}catch(Exception error){throw new Denied("INVALID_TIME");}}
    Session()throws Exception {
        app=config("KDP_APP_ID");if(!app.matches("[A-Za-z0-9_-]{3,160}"))throw new IllegalArgumentException("App ID");
        var uri=URI.create(System.getenv().getOrDefault("KDP_BASE_URL","https://licensing.kdpika.com/api/v1").replaceAll("/+$",""));
        boolean local="http".equals(uri.getScheme())&&Set.of("127.0.0.1","localhost").contains(uri.getHost())&&"1".equals(System.getenv("KDP_ALLOW_LOOPBACK"));
        if(uri.getHost()==null||(!"https".equals(uri.getScheme())&&!local)||uri.getUserInfo()!=null||uri.getQuery()!=null||uri.getFragment()!=null||!"/api/v1".equals(uri.getPath()))throw new IllegalArgumentException("Unsafe URL");
        base=uri.toString();var root=Path.of(config("KDP_STATE_DIR"));var key=Path.of(config("KDP_TRUSTED_KEY_FILE"));
        if(!root.isAbsolute()||!key.isAbsolute())throw new IllegalArgumentException("Absolute paths required");trusted=read(key);
        var publicKey=parsed(trusted);if(!"Ed25519".equals(string(publicKey,"algorithm"))||!"base64url".equals(string(publicKey,"encoding")))throw new IllegalArgumentException("Trusted key");
        Files.createDirectories(root);if(Files.isSymbolicLink(root))throw new IllegalArgumentException("Root symlink");
        directory=root.resolve(digest(base+"|"+app+"|SANDBOX|java-rest-v1").substring(0,20));Files.createDirectories(directory);
        if(Files.isSymbolicLink(directory))throw new IllegalArgumentException("Namespace symlink");permission(directory,"rwx------");
        channel=FileChannel.open(directory.resolve(".lock"),StandardOpenOption.CREATE,StandardOpenOption.WRITE,LinkOption.NOFOLLOW_LINKS);permission(directory.resolve(".lock"),"rw-------");
        FileLock acquired=channel.tryLock();if(acquired==null){channel.close();throw new IllegalStateException("Busy installation");}lock=acquired;
        try {
            var identity=directory.resolve("installation.json");
            if(!Files.exists(identity,LinkOption.NOFOLLOW_LINKS)){var value=new JsonObject();value.addProperty("installation_id","lmp-install-"+UUID.randomUUID());write("installation.json",value);}
            installation=string(parsed(read(identity)),"installation_id");
            if(!installation.matches("lmp-install-[a-f0-9-]{36}"))throw new IllegalArgumentException("Invalid identity; do not reset automatically");
        }catch(Exception error){close();throw error;}
    }
    void write(String name,JsonObject value)throws Exception {
        var target=directory.resolve(name);var temporary=Files.createTempFile(directory,"write-",".tmp");permission(temporary,"rw-------");
        try(var file=FileChannel.open(temporary,StandardOpenOption.WRITE)){var bytes=ByteBuffer.wrap(JSON.toJson(value).getBytes(StandardCharsets.UTF_8));while(bytes.hasRemaining())file.write(bytes);file.force(true);}
        try{Files.move(temporary,target,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);}
        catch(AtomicMoveNotSupportedException error){Files.move(temporary,target,StandardCopyOption.REPLACE_EXISTING);}
    }
    JsonObject state()throws Exception {
        var file=directory.resolve("session.json");if(!Files.exists(file,LinkOption.NOFOLLOW_LINKS))return null;
        var value=parsed(read(file));if(!string(value,"token").matches("act_[A-Za-z0-9_-]+"))throw new IllegalArgumentException("Invalid token file");
        instant(string(value,"checkpoint"));if(!value.has("envelope")||(!value.get("envelope").isJsonNull()&&!value.get("envelope").isJsonPrimitive()))throw new IllegalArgumentException("Invalid cache");return value;
    }
    void clear()throws Exception {Files.deleteIfExists(directory.resolve("session.json"));}
    record Reply(JsonObject body,Object tree,String requestId) {}
    Reply request(String endpoint,JsonObject body,String token)throws Exception {
        var builder=HttpRequest.newBuilder(URI.create(base+endpoint)).timeout(Duration.ofSeconds(15)).header("Accept","application/json").header("Content-Type","application/json").header("User-Agent","KDPika-REST-Java-example/1.0");
        if(token==null)builder.header("X-App-ID",app).header("X-Environment","SANDBOX");else builder.header("Authorization","Bearer "+token).header("X-Installation-ID",installation);
        HttpResponse<java.io.InputStream> response;byte[] raw;
        try {
            response=http.send(builder.POST(HttpRequest.BodyPublishers.ofString(JSON.toJson(body),StandardCharsets.UTF_8)).build(),HttpResponse.BodyHandlers.ofInputStream());
            try(var input=response.body()){raw=input.readNBytes(MAX+1);}
        }catch(java.io.IOException error){throw new Offline();}
        catch(InterruptedException error){Thread.currentThread().interrupt();throw new Offline();}
        if(raw.length>MAX)throw new Denied("INVALID_RESPONSE");
        Object tree;JsonObject value;try{tree=Canonical.parse(raw);value=parsed(raw);}catch(Exception error){throw new Denied("INVALID_RESPONSE");}
        String id=value.has("request_id")&&value.get("request_id").isJsonPrimitive()?value.get("request_id").getAsString():null;
        if(id!=null&&!id.matches("req_[A-Za-z0-9_-]{1,120}"))id=null;
        if(response.statusCode()<200||response.statusCode()>=300||!new JsonPrimitive(true).equals(value.get("success"))){
            String code="HTTP_ERROR";if(value.has("error")&&value.get("error").isJsonObject()){var error=value.getAsJsonObject("error");if(error.has("code")&&error.get("code").isJsonPrimitive()&&error.get("code").getAsString().matches("[A-Z0-9_]{1,64}"))code=error.get("code").getAsString();}throw new Denied(code,id);
        }return new Reply(value,tree,id);
    }
    JsonObject decision(String envelope,String source,String checkpoint,String requestId)throws Exception {
        if(!Verify.verifyEnvelope(trusted,envelope.getBytes(StandardCharsets.UTF_8)))throw new Denied("SIGNATURE_INVALID",requestId);
        var payload=parsed(envelope.getBytes(StandardCharsets.UTF_8)).getAsJsonObject("payload");var now=Instant.now();
        if(!app.equals(string(payload,"product_id"))||!"sandbox".equals(string(payload,"environment"))||!digest(installation).equals(string(payload.getAsJsonObject("device"),"installation_hash")))throw new Denied("BINDING_MISMATCH",requestId);
        var server=instant(string(payload,"server_time"));var next=instant(string(payload,"next_validation_at"));var grace=instant(string(payload,"offline_grace_until"));
        if(next.isBefore(server)||grace.isBefore(server))throw new Denied("INVALID_TIME",requestId);
        var latest=checkpoint==null?server:instant(checkpoint);if(server.isAfter(latest))latest=server;
        if(now.plusSeconds(300).isBefore(latest))throw new Denied("CLOCK_ROLLBACK_DETECTED",requestId);
        if(!"active".equals(string(payload,"status")))throw new Denied("LICENSE_NOT_ACTIVE",requestId);
        if(payload.has("starts_at")&&!payload.get("starts_at").isJsonNull()&&now.isBefore(instant(string(payload,"starts_at"))))throw new Denied("LICENSE_NOT_STARTED",requestId);
        if(!payload.get("expires_at").isJsonNull()&&!now.isBefore(instant(string(payload,"expires_at"))))throw new Denied("LICENSE_EXPIRED",requestId);
        if(!source.equals("online")&&now.isAfter(grace))throw new Denied("OFFLINE_GRACE_EXPIRED",requestId);
        var features=payload.getAsJsonObject("features");var result=accepted(source,requestId);result.addProperty("signature_valid",true);
        result.addProperty("pdf_export_allowed",new JsonPrimitive(true).equals(features.get("pdf_export")));
        var seat=features.get("seat_count");if(seat!=null&&seat.isJsonPrimitive()&&seat.getAsJsonPrimitive().isNumber())try{long count=seat.getAsBigDecimal().longValueExact();if(count>=0&&count<=9007199254740991L)result.addProperty("seat_count",count);}catch(ArithmeticException ignored){}
        return result;
    }
    static JsonObject accepted(String source,String id){var value=new JsonObject();value.addProperty("valid",true);value.addProperty("source",source);value.addProperty("signature_valid",false);value.add("error_code",JsonNull.INSTANCE);value.addProperty("request_id",id);value.addProperty("pdf_export_allowed",false);value.add("seat_count",JsonNull.INSTANCE);value.addProperty("message","Your license is ready.");return value;}
    JsonObject run(String action)throws Exception {
        var state=state();if(action.equals("status")){var value=new JsonObject();value.addProperty("activated",state!=null);value.addProperty("installation_hash",digest(installation));value.addProperty("storage_security","permission-protected-file");return value;}
        if(action.equals("activate")){
            String license=config("KDP_LICENSE_KEY");if(!license.startsWith("TEST"))throw new IllegalArgumentException("Sandbox key required");if(state!=null)throw new Denied("ALREADY_ACTIVATED");
            var body=new JsonObject();body.addProperty("license_key",license);body.addProperty("device_id",installation);body.addProperty("device_name","Java REST example");body.addProperty("platform",System.getProperty("os.name"));body.addProperty("app_version","1.0.0");String email=System.getenv("KDP_CUSTOMER_EMAIL");if(email!=null&&!email.isBlank())body.addProperty("email",config("KDP_CUSTOMER_EMAIL"));
            var reply=request("/licenses/activate",body,null);String token=string(reply.body,"activation_token");if(!token.matches("act_[A-Za-z0-9_-]+"))throw new Denied("INVALID_RESPONSE",reply.requestId);
            try{String envelope=Canonical.encode(((Map<?,?>)reply.tree).get("license"));var result=decision(envelope,"online",null,reply.requestId);var saved=new JsonObject();saved.addProperty("token",token);saved.addProperty("envelope",envelope);saved.addProperty("checkpoint",Instant.now().toString());write("session.json",saved);return result;}
            catch(Exception error){try{request("/licenses/deactivate",new JsonObject(),token);}catch(Exception ignored){}throw error;}
        }
        if(state==null)throw new Denied("NOT_ACTIVATED");String token=string(state,"token");
        if(action.equals("deactivate")){var reply=request("/licenses/deactivate",new JsonObject(),token);if(!new JsonPrimitive(true).equals(reply.body.get("deactivated")))throw new Denied("INVALID_RESPONSE",reply.requestId);clear();var result=accepted("online",reply.requestId);result.addProperty("message","This installation has been deactivated.");return result;}
        if(action.equals("check")&&!state.get("envelope").isJsonNull())try{String envelope=string(state,"envelope");var result=decision(envelope,"cache",string(state,"checkpoint"),null);var payload=parsed(envelope.getBytes(StandardCharsets.UTF_8)).getAsJsonObject("payload");if(Instant.now().isBefore(instant(string(payload,"next_validation_at")))){state.addProperty("checkpoint",Instant.now().toString());write("session.json",state);return result;}}
        catch(Exception error){state.add("envelope",JsonNull.INSTANCE);write("session.json",state);}
        try{var reply=request("/licenses/validate",new JsonObject(),token);String envelope=Canonical.encode(((Map<?,?>)reply.tree).get("license"));var result=decision(envelope,"online",string(state,"checkpoint"),reply.requestId);state.addProperty("envelope",envelope);state.addProperty("checkpoint",Instant.now().toString());write("session.json",state);return result;}
        catch(Offline error){if(state.get("envelope").isJsonNull())throw new Denied("OFFLINE_CACHE_MISSING");var result=decision(string(state,"envelope"),"offline",string(state,"checkpoint"),null);state.addProperty("checkpoint",Instant.now().toString());write("session.json",state);return result;}
        catch(Denied error){if(Set.of("INVALID_TOKEN","DEVICE_MISMATCH","LICENSE_REVOKED","LICENSE_EXPIRED","LICENSE_CANCELLED").contains(error.code))clear();else{state.add("envelope",JsonNull.INSTANCE);write("session.json",state);}throw error;}
    }
    public void close()throws java.io.IOException {try{lock.release();}finally{channel.close();}}
    public static void main(String[] args){int exit=2;try{
        if(args.length!=1||!Set.of("status","activate","check","validate","deactivate").contains(args[0]))throw new IllegalArgumentException("Action required");
        try(var session=new Session()){try{var result=session.run(args[0]);System.out.println(JSON.toJson(result));exit=0;}
        catch(Denied error){var result=accepted("local",error.requestId);result.addProperty("valid",false);result.addProperty("error_code",error.code);result.addProperty("message",error.code.equals("INVALID_LICENSE")?"Check your license key and matching email.":"Your license could not be confirmed. Connect and try again, or contact your software provider.");System.out.println(JSON.toJson(result));exit=1;}
        catch(Offline error){var result=accepted("local",null);result.addProperty("valid",false);result.addProperty("error_code","NETWORK_ERROR");result.addProperty("message","Connect to the internet and try again.");System.out.println(JSON.toJson(result));exit=1;}}
    }catch(Exception error){System.err.println("Check application settings and private storage. Contact your software provider if the problem continues.");}System.exit(exit);}
}
```
The complete project also contains the exact verification helper. Its source and all positive/negative vectors are available in the [security verifier archive](/docs/downloads/security-verifiers.zip). Derived reusable files remove only the original standalone CLI entry point/imports that became unused; they do not change the signature algorithm or canonicalization.

## Run the lifecycle
Use java -cp "classes:deps/gson.jar:deps/bcprov.jar" Session followed by exactly one action. Preserve the same App ID, state root and origin across processes.
1. Run status. Expected: activated=false for a new namespace and only an installation hash/storage category. Token presence is not a license validity decision.
2. Set a Sandbox key and matching email, then run activate. Expected: valid=true and signature_valid=true, or a safe refusal. An existing token is not silently replaced.
3. Run check. Expected: eligible authenticated cache before next_validation_at, otherwise an online validation attempt.
4. Run validate. Expected: an online attempt; only transport failure can use an eligible verified offline cache. Explicit HTTP rejection never grants offline permission.
5. Run deactivate. Expected: server-confirmed release, token/cache removal and no feature grant. valid=true here means the release operation succeeded, not permission to run a protected feature.
6. Run status again. Expected: activated=false and the same installation hash. Cumulative activation_count is not reset.
Exit0 means accepted operation/status, exit1 means refusal or connectivity denial, exit2 means unsafe configuration/state or unexpected failure. Output is safe decision metadata: never raw keys, tokens, Authorization headers or signed customer payloads.

## API contract and signature verification
Activation sends X-App-ID and X-Environment: SANDBOX plus license_key/device_id and optional matching email. Validation uses Bearer act_ and X-Installation-ID. Deactivation releases that token. See the [endpoint reference](/docs/v1/api/conventions) for full field/response/error tables.
The response parser preserves numeric lexemes, rejects duplicate/invalid JSON through the shared tested verifier, and authenticates the exact envelope. Only a verified payload enters policy. Key ID is derived from the independently trusted raw public key; wrong algorithm/key/signature is rejected. Never repair a mismatch by stripping signed fields or using JSON.stringify-style numeric normalization.

## Binding, features and fail-closed policy
The client requires its actual product App ID, environment=sandbox, SHA-256 installation binding and active status. It checks starts_at when present, expiry when nonnull, signed validation/grace dates and the last accepted checkpoint. Invalid data, status or policy is a refusal even if the payload carries a true feature.
pdf_export is allowed only for the boolean true on a fully accepted result. seat_count is exposed only as a nonnegative integer bounded by the shared safe-integer policy; otherwise it stays null. These example feature names must match your own product configuration. Constructing a result or reading token presence never authenticates a license.

## Offline grace and time checks
Before next_validation_at, check can return a verified cache. After that instant it validates online. Only a transport failure may use the existing signed state within offline_grace_until and expires_at. An explicit HTTP refusal, bad signature, malformed success or binding mismatch cannot extend access. Selected token/revocation/[device](/docs/v1/start/glossary#device)/expiry/cancellation refusals clear the token; other refusals clear cached authorization.
The last accepted checkpoint and signed server_time bound rollback with300 seconds tolerance. Grace is based on its signed deadline, not added to next_validation_at. Validating online does not promise permission if time/status/binding rules fail. No constructor flag creates an extra offline extension.
These strict sample policies are not changes to existing SDK behavior. A person controlling the host can patch the program or restore full snapshots. Use server-side authorization for high-value online actions and do not promise absolute local anti-tamper protection.

## Private storage, concurrency and recovery
The [installation ID](/docs/v1/start/glossary#installation-id) is random, persistent and independent of MAC/serial/hardware fingerprints. A namespaced private session stores the [activation token](/docs/v1/start/glossary#activation-token), lossless [signed envelope](/docs/v1/start/glossary#signed-envelope) and checkpoint. Writes are atomic and permissions are owner-only where supported; this is not automatic encryption or an OS-vault certification.
The program serializes one namespace. Java/Kotlin, Dart, Rust and the POSIX native core use an OS lock on a stable file; Go/Ruby/Swift use exclusive lock-file ownership and require manual reconciliation after a crash. Never delete an active lock or regenerate identity to avoid a refusal. A new identity can consume another cumulative activation. Keep separate namespaces for unrelated buyers/tenants.
Review [secure token storage](/docs/v1/security/secure-token-storage) for native vault adapters. POSIX modes do not replace Windows ACL review. Do not put state under public_html, bundle a populated cache, or expose raw SDK/client methods to a renderer/browser.

## Errors and uncertain mutations
The client accepts only bounded safe error/request identifiers and shows plain user messages. Unknown errors fail closed. No automatic mutation retry is supplied. A lost activation response may already have consumed a server activation; reconcile before retrying. If a returned new token fails signature/policy acceptance, the client attempts best-effort release, which can itself remain uncertain.
Read [the complete server error table](/docs/v1/api/errors). Local example identifiers such as BINDING_MISMATCH, ALREADY_ACTIVATED, SIGNATURE_INVALID and INVALID_TIME are client policy results, not invented server emissions. Never show raw stack traces, private paths or customer payloads to end users.

## Packaging and framework integration
JVM desktop, CLI and backend processes. The complete session core uses Java HttpClient and Java NIO file locking. Keep the two pinned jars at runtime. Windows classpaths use semicolons; the POSIX shell build needs a compatible development shell or equivalent IDE configuration.
Keep stable state outside executable extraction/install directories. Include the exact verification modules and required native/runtime libraries; never embed a developer key or populated token/cache. A web route still needs application authentication, tenant authorization and CSRF protection. A desktop renderer gets narrow safe decisions only, not arbitrary file paths or token access.
Re-test real activation, cache reload, offline loss, explicit refusal and release after bundling or updating dependencies. macOS native source execution is not proof that every operating-system package, signing/notarization setup or framework UI has passed.

## Recorded verification and limits
The exact native runtime executes the real isolated Sandbox lifecycle and21 negative/positive checks: wrong email, stable cross-process identity, cache without HTTP, online validation, injected network loss, modified offline cache, rollback, explicit HTTP503, modified signed response, no-follow307, recovery, release and unsafe setup guards. Refusal/outage/redirect injections are an explicit loopback test forwarder, not a claimed production outage.
Build evidence records actual toolchain/dependency hashes. All ten fresh project archives build and the complete native clients execute real Sandbox lifecycles. All23 published signature vectors pass in every REST language. Signature authenticity is separate from current license authorization. Native Windows/Linux/mobile GUI execution is not inferred from this macOS run.

## Expected result
Your application authenticates signed state, applies binding/time/status policy and enables only verified features. A refusal or successful seat release cannot accidentally unlock a feature.

## Common mistakes
- Using the internal product ID instead of the Public App ID.
- Losing numeric tokens before verifying the signature.
- Treating a true feature or HTTP success as a validity proof.
- Sharing one installation cache between unrelated tenants or deleting identity on failure.

## Security notes
Keep HTTPS verification, independent key trust and fail-closed policy. This example does not change the platform contract, process payments or grant universal anti-tamper protection. Preserve real API/SDK boundaries and keep credentials off browser/renderer surfaces.

## Troubleshooting
| Symptom | Cause | Action |
| --- | --- | --- |
| Exit2 at startup | Unsafe URL, missing private path, bad identity or busy lock | Correct trusted configuration; do not expose raw diagnostics to users |
| INVALID_LICENSE | Key/email/App ID/environment mismatch | Use the actual matching Sandbox values |
| SIGNATURE_INVALID | Wrong key, modified state or changed canonical bytes | Deny access and run the published vectors |
| OFFLINE_CACHE_MISSING | No accepted signed state remains | Reconnect and validate; never manufacture a cache |
| CLOCK_ROLLBACK_DETECTED | System time behind trusted time | Correct the device clock and reconnect |
| Release uncertain | Lost response or network/server refusal | Preserve identity and reconcile the seat with your software provider |

## Next steps
Review [offline mode](/docs/v1/security/offline-mode), [signed responses](/docs/v1/security/signed-responses) and [API errors](/docs/v1/api/errors).

## Related
- [Activate](/docs/v1/api/activate)
- [Validate](/docs/v1/api/validate)
- [Deactivate](/docs/v1/api/deactivate)
- [Signature test vectors](/docs/v1/security/test-vectors)
