Skip to content

Commit a828e23

Browse files
committed
Cleanup and use gson
1 parent 0e7c815 commit a828e23

4 files changed

Lines changed: 77 additions & 66 deletions

File tree

eternalcode-commons-updater/build.gradle.kts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ tasks.test {
1111

1212

1313
dependencies {
14-
api("org.json:json:20240303")
14+
api("com.google.code.gson:gson:2.13.1")
1515
api(project(":eternalcode-commons-shared"))
1616

1717
api("org.jetbrains:annotations:24.1.0")

eternalcode-commons-updater/src/main/java/com/eternalcode/commons/updater/UpdateResult.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,12 @@
22

33
public record UpdateResult(Version currentVersion, Version latestVersion, String downloadUrl, String releaseUrl) {
44

5+
public static UpdateResult empty(Version currentVersion) {
6+
return new UpdateResult(currentVersion, currentVersion, null, null);
7+
}
8+
59
public boolean isUpdateAvailable() {
610
return this.latestVersion.isNewerThan(this.currentVersion);
711
}
12+
813
}

eternalcode-commons-updater/src/main/java/com/eternalcode/commons/updater/Version.java

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,60 @@
11
package com.eternalcode.commons.updater;
22

3+
import java.util.Arrays;
34
import org.jetbrains.annotations.NotNull;
45

56
public class Version implements Comparable<Version> {
7+
8+
private static final int DEFAULT_VERSION_COMPONENT_VALUE = 0;
9+
610
private final String value;
7-
private final int[] parts;
11+
private final int[] versionComponents;
812

913
public Version(String version) {
1014
if (version == null || version.trim().isEmpty()) {
1115
throw new IllegalArgumentException("Version cannot be null or empty");
1216
}
1317

1418
this.value = version.trim();
15-
this.parts = parseVersion(this.value);
19+
this.versionComponents = parseVersion(this.value);
1620
}
1721

1822
private int[] parseVersion(String version) {
19-
String cleaned = version.startsWith("v") ? version.substring(1) : version;
20-
21-
int dashIndex = cleaned.indexOf('-');
22-
if (dashIndex > 0) {
23-
cleaned = cleaned.substring(0, dashIndex);
24-
}
25-
26-
String[] stringParts = cleaned.split("\\.");
27-
int[] intParts = new int[stringParts.length];
23+
String cleaned = cleanVersion(version);
24+
String[] rawVersionComponents = cleaned.split("\\.");
25+
int[] versionComponents = new int[rawVersionComponents.length];
2826

29-
for (int i = 0; i < stringParts.length; i++) {
27+
for (int i = 0; i < rawVersionComponents.length; i++) {
3028
try {
31-
intParts[i] = Integer.parseInt(stringParts[i]);
29+
versionComponents[i] = Integer.parseInt(rawVersionComponents[i]);
3230
}
3331
catch (NumberFormatException exception) {
3432
throw new IllegalArgumentException("Invalid version format: " + version);
3533
}
3634
}
3735

38-
return intParts;
36+
return versionComponents;
3937
}
4038

41-
@Override
42-
public int compareTo(@NotNull Version other) {
43-
if (other == null) {
44-
return 1;
39+
private static String cleanVersion(String version) {
40+
String cleaned = version.startsWith("v") ? version.substring(1) : version;
41+
int dashIndex = cleaned.indexOf('-');
42+
if (dashIndex > 0) {
43+
return cleaned.substring(0, dashIndex);
4544
}
4645

47-
int maxLength = Math.max(this.parts.length, other.parts.length);
46+
return cleaned;
47+
}
48+
49+
@Override
50+
public int compareTo(@NotNull Version other) {
51+
int maxLength = Math.max(this.versionComponents.length, other.versionComponents.length);
4852

4953
for (int i = 0; i < maxLength; i++) {
50-
int thisPart = i < this.parts.length ? this.parts[i] : 0;
51-
int otherPart = i < other.parts.length ? other.parts[i] : 0;
54+
int thisComponent = getComponentAtIndex(i, this);
55+
int otherComponent = getComponentAtIndex(i, other);
5256

53-
int result = Integer.compare(thisPart, otherPart);
57+
int result = Integer.compare(thisComponent, otherComponent);
5458
if (result != 0) {
5559
return result;
5660
}
@@ -59,6 +63,12 @@ public int compareTo(@NotNull Version other) {
5963
return 0;
6064
}
6165

66+
private int getComponentAtIndex(int index, Version version) {
67+
return index < version.versionComponents.length
68+
? version.versionComponents[index]
69+
: DEFAULT_VERSION_COMPONENT_VALUE;
70+
}
71+
6272
public boolean isNewerThan(Version other) {
6373
return this.compareTo(other) > 0;
6474
}
@@ -79,7 +89,7 @@ public boolean equals(Object obj) {
7989

8090
@Override
8191
public int hashCode() {
82-
return java.util.Arrays.hashCode(parts);
92+
return Arrays.hashCode(versionComponents);
8393
}
8494

8595
@Override
Lines changed: 38 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,51 @@
11
package com.eternalcode.commons.updater.impl;
22

3-
import com.eternalcode.commons.Lazy;
43
import com.eternalcode.commons.updater.UpdateChecker;
54
import com.eternalcode.commons.updater.UpdateResult;
65
import com.eternalcode.commons.updater.Version;
6+
import com.google.gson.Gson;
7+
import com.google.gson.JsonParseException;
8+
import com.google.gson.annotations.SerializedName;
9+
import com.google.gson.reflect.TypeToken;
710
import java.net.URI;
811
import java.net.http.HttpClient;
912
import java.net.http.HttpRequest;
1013
import java.net.http.HttpResponse;
1114
import java.time.Duration;
12-
import org.json.JSONArray;
13-
import org.json.JSONException;
14-
import org.json.JSONObject;
15+
import java.util.List;
16+
import java.util.Objects;
1517

1618
public final class ModrinthUpdateChecker implements UpdateChecker {
1719

1820
private static final String API_BASE_URL = "https://api.modrinth.com/v2";
1921
private static final String MODRINTH_BASE_URL = "https://modrinth.com/plugin";
2022
private static final String USER_AGENT = "UpdateChecker/1.0";
21-
private static final Duration TIMEOUT = Duration.ofSeconds(10);
2223

23-
private final Lazy<HttpClient> client = new Lazy<>(() -> HttpClient.newBuilder().connectTimeout(TIMEOUT).build());
24+
private static final Gson GSON = new Gson();
25+
26+
private final HttpClient client = HttpClient.newBuilder()
27+
.connectTimeout(Duration.ofSeconds(60))
28+
.build();
2429

2530
@Override
2631
public UpdateResult check(String projectId, Version currentVersion) {
27-
if (projectId == null || projectId.trim().isEmpty()) {
32+
if (projectId == null || projectId.isBlank()) {
2833
throw new IllegalArgumentException("Project ID cannot be null or empty");
2934
}
3035

3136
try {
32-
String url = API_BASE_URL + "/project/" + projectId + "/version";
33-
34-
HttpRequest request =
35-
HttpRequest.newBuilder().uri(URI.create(url)).header("User-Agent", USER_AGENT).timeout(TIMEOUT).build();
36-
37-
HttpResponse<String> response = this.client.get().send(request, HttpResponse.BodyHandlers.ofString());
37+
HttpRequest request = HttpRequest.newBuilder()
38+
.uri(URI.create(API_BASE_URL + "/project/" + projectId + "/version"))
39+
.header("User-Agent", USER_AGENT)
40+
.timeout(Duration.ofSeconds(30))
41+
.build();
3842

43+
HttpResponse<String> response = this.client.send(request, HttpResponse.BodyHandlers.ofString());
3944
if (response.statusCode() != 200) {
40-
return createEmptyResult(currentVersion);
45+
return UpdateResult.empty(currentVersion);
4146
}
4247

43-
String json = response.body();
44-
if (json == null || json.trim().isEmpty()) {
45-
return createEmptyResult(currentVersion);
46-
}
47-
48-
return parseVersionResponse(json, currentVersion, projectId);
48+
return this.parseVersionResponse(response.body(), currentVersion, projectId);
4949
}
5050
catch (Exception exception) {
5151
throw new RuntimeException("Failed to check Modrinth updates for project: " + projectId, exception);
@@ -54,39 +54,35 @@ public UpdateResult check(String projectId, Version currentVersion) {
5454

5555
private UpdateResult parseVersionResponse(String json, Version currentVersion, String projectId) {
5656
try {
57-
JSONArray versions = new JSONArray(json);
58-
59-
if (versions.isEmpty()) {
60-
return createEmptyResult(currentVersion);
57+
List<ModrinthVersion> versions = GSON.fromJson(json, new TypeToken<>(){});
58+
if (versions == null || versions.isEmpty()) {
59+
return UpdateResult.empty(currentVersion);
6160
}
6261

63-
JSONObject latestVersionObj = versions.getJSONObject(0);
64-
65-
String versionNumber = latestVersionObj.optString("version_number", null);
62+
ModrinthVersion latestVersionData = versions.get(0);
63+
String versionNumber = latestVersionData.versionNumber();
6664
if (versionNumber == null || versionNumber.trim().isEmpty()) {
67-
return createEmptyResult(currentVersion);
68-
}
69-
70-
String downloadUrl = null;
71-
if (latestVersionObj.has("files")) {
72-
JSONArray files = latestVersionObj.getJSONArray("files");
73-
if (!files.isEmpty()) {
74-
JSONObject firstFile = files.getJSONObject(0);
75-
downloadUrl = firstFile.optString("url", null);
76-
}
65+
return UpdateResult.empty(currentVersion);
7766
}
7867

7968
String releaseUrl = MODRINTH_BASE_URL + "/" + projectId + "/version/" + versionNumber;
80-
Version latestVersion = new Version(versionNumber);
69+
String downloadUrl = latestVersionData.files().stream()
70+
.map(modrinthFile -> modrinthFile.url())
71+
.filter(obj -> Objects.nonNull(obj))
72+
.findFirst()
73+
.orElse(releaseUrl);
8174

75+
Version latestVersion = new Version(versionNumber);
8276
return new UpdateResult(currentVersion, latestVersion, downloadUrl, releaseUrl);
8377
}
84-
catch (JSONException exception) {
85-
return createEmptyResult(currentVersion);
78+
catch (JsonParseException exception) {
79+
return UpdateResult.empty(currentVersion);
8680
}
8781
}
8882

89-
private UpdateResult createEmptyResult(Version currentVersion) {
90-
return new UpdateResult(currentVersion, currentVersion, null, null);
83+
private record ModrinthVersion(@SerializedName("version_number") String versionNumber, List<ModrinthFile> files) {
84+
}
85+
86+
private record ModrinthFile(String url) {
9187
}
9288
}

0 commit comments

Comments
 (0)