Clavem stores your builds and answers GET /v1/releases/:productId/latest. A license that is valid for the product gets release notes and files with signed download links. Any other key gets only version and published_at. The release docs list the fields. This page is the Java side: the check, a version comparison, a download that resumes, and the install step. It reuses the HttpClient and Jackson mapper from license key validation in Java. The Java code was not compiled or run, because the JDK available for testing was Java 8 and the code needs Java 17.
Check
The snippets below belong in an Updater class that holds the HttpClient, the Jackson mapper and the base URI from the validation page. The records can be nested inside it, and platformLabel is a private static method. The Version record exists because the JDK has no semantic version type, and a library such as a semver package works as well if you already depend on one.
import com.fasterxml.jackson.databind.JsonNode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public record ReleaseFile(long id, String filename, long size, String url) {}
public record Update(State state, String version, String notes, ReleaseFile file, String reason) {
public enum State { UP_TO_DATE, AVAILABLE, LOCKED, FAILED }
}
/** MAJOR.MINOR.PATCH with an optional -prerelease. A pre-release sorts below its release. */
record Version(int major, int minor, int patch, String pre) implements Comparable<Version> {
private static final Pattern PATTERN = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?");
static Version parse(String s) {
Matcher m = PATTERN.matcher(s);
if (!m.find()) return null;
return new Version(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2)), Integer.parseInt(m.group(3)), m.group(4));
}
@Override public int compareTo(Version o) {
int c = Integer.compare(major, o.major);
if (c == 0) c = Integer.compare(minor, o.minor);
if (c == 0) c = Integer.compare(patch, o.patch);
if (c != 0) return c;
if (pre == null || o.pre == null) return pre == null ? (o.pre == null ? 0 : 1) : -1;
return pre.compareTo(o.pre);
}
}
/** The label you chose at upload, for example macos-aarch64, windows-amd64 or linux-amd64. */
static String platformLabel() {
String os = System.getProperty("os.name").toLowerCase();
String kind = os.contains("win") ? "windows" : os.contains("mac") ? "macos" : "linux";
return kind + "-" + System.getProperty("os.arch");
}
public Update checkForUpdate(long productId, String currentVersion, String licenseKey) {
String url = "/v1/releases/" + productId + "/latest?platform=" + URLEncoder.encode(platformLabel(), StandardCharsets.UTF_8);
HttpRequest.Builder request = HttpRequest.newBuilder(base.resolve(url)).timeout(Duration.ofSeconds(8)).GET();
if (licenseKey != null) request.header("X-License-Key", licenseKey); // a header keeps it out of logs
try {
HttpResponse<String> response = http.send(request.build(), HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 404) return new Update(Update.State.UP_TO_DATE, null, null, null, null); // nothing published yet
if (response.statusCode() != 200)
return new Update(Update.State.FAILED, null, null, null, "HTTP " + response.statusCode()); // 429: Retry-After 60
JsonNode release = json.readTree(response.body());
Version latest = Version.parse(release.path("version").asText(""));
Version current = Version.parse(currentVersion);
if (latest == null || current == null) return new Update(Update.State.FAILED, null, null, null, "version is not semver");
if (latest.compareTo(current) <= 0) return new Update(Update.State.UP_TO_DATE, null, null, null, null);
for (JsonNode f : release.path("files")) {
if (f.path("url").isTextual())
return new Update(Update.State.AVAILABLE, release.path("version").asText(), release.path("notes").asText(null),
new ReleaseFile(f.path("id").asLong(), f.path("filename").asText(), f.path("size").asLong(), f.path("url").asText()), null);
}
return new Update(Update.State.LOCKED, release.path("version").asText(), null, null, null); // newer, but the key is missing or not valid
} catch (IOException e) {
return new Update(Update.State.FAILED, null, null, null, "offline");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return new Update(Update.State.FAILED, null, null, null, "interrupted");
}
}
LOCKED is the useful middle case: a lapsed customer learns that a newer version exists and can be sent to renew. For the live demo product the real API answers 404 with not_found, and the code treats that as up to date. Build the label the same way you named your uploads. If you uploaded your Mac build as macos and the JVM reports aarch64, the label is macos-aarch64, and a mismatch returns only files with no label.
Download, with resume and progress
Request the link when the user clicks Update by calling checkForUpdate again, and download from that fresh response. This streams to a .part file, resumes with Range, and moves the file into place only when the size matches:
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.function.IntConsumer;
public void download(ReleaseFile file, Path destination, IntConsumer onPercent) throws IOException, InterruptedException {
Path part = destination.resolveSibling(destination.getFileName() + ".part");
long have = Files.exists(part) ? Files.size(part) : 0;
if (have > file.size()) { Files.delete(part); have = 0; }
if (have < file.size()) {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(file.url())).GET(); // no request timeout: it would cap the transfer
if (have > 0) request.header("Range", "bytes=" + have + "-");
HttpResponse<InputStream> response = http.send(request.build(), HttpResponse.BodyHandlers.ofInputStream());
int status = response.statusCode();
if (status == 403) throw new IOException("The download link expired. Check for updates again.");
if (status != 200 && status != 206) throw new IOException("Download failed: HTTP " + status);
if (status == 200) have = 0; // Range ignored: start over
try (InputStream in = response.body();
OutputStream out = Files.newOutputStream(part, status == 206 ? StandardOpenOption.APPEND : StandardOpenOption.TRUNCATE_EXISTING,
StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
byte[] buffer = new byte[64 * 1024];
int last = -1, read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
have += read;
int percent = (int) (have * 100 / file.size());
if (percent != last) { last = percent; onPercent.accept(percent); }
}
}
}
if (Files.size(part) != file.size()) throw new IOException("Size does not match. Keep the .part file and resume.");
Files.move(part, destination, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
}
The response has no checksum field, so size is the only integrity check the API gives. Sign your installers, and let the operating system verify the signature. Call download from a worker thread and pass onPercent a lambda that posts to the UI thread, for example with SwingUtilities.invokeLater.
Install
- jpackage installers. Open the downloaded
.msi,.exe,.dmgor.debwithDesktop.getDesktop().open(path.toFile()), then exit. The installer replaces the app. - Windows. A running app cannot overwrite its own files. Start the installer and call
System.exit(0). - A plain JAR. Replace the file with
Files.moveand ask the user to restart.
Limits and timing
The releases endpoint allows 120 requests a minute per IP address, counted apart from validation. Check once at launch or once a day. “Latest” is the most recently published release, not the highest version number: a backport published after 3.2.1 becomes the answer, so a customer on 3.2.1 sees nothing newer.
Doing this with Clavem
Upload each installer in the dashboard, give it a platform label and publish. The same key that turns the app on fetches the download. Licenses imported from Lemon Squeezy have no order page, so for them this endpoint is how builds are delivered. See the release docs for limits and storage.
Questions
How do I compare version strings in Java?
Parse the numbers and compare them as integers, so 3.10.0 is above 3.9.0, and rank a pre-release below its release. A library such as a semver package does this, and a small record with a compareTo method is enough for plain dotted versions.
How do I get my app's own version?
Read it from the JAR manifest with Package.getImplementationVersion, or keep it in a resource file your build fills in. Do not hard-code it in a second place, or the update check keeps offering the build the user already has.
Can a Java program replace itself?
Not while it runs on Windows, and a JVM app is usually a launcher plus JARs or a jpackage installation. Download the installer, open it, and exit. For an app you ship as a plain JAR, replace the file and ask the user to restart.