Skip to content

Commit

Permalink
Changed to GSON
Browse files Browse the repository at this point in the history
  • Loading branch information
Lvmostwanted committed May 31, 2023
1 parent 9aa27b8 commit 0bd149f
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 154 deletions.
6 changes: 0 additions & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,5 @@
<version>1.18.28</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230227</version>
</dependency>
</dependencies>

</project>
76 changes: 41 additions & 35 deletions src/main/java/cc/projectnexus/adapters/java/api/ApiInteraction.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@
import cc.projectnexus.adapters.java.NexusClient;
import cc.projectnexus.adapters.java.datamodels.GuildSettings;
import cc.projectnexus.adapters.java.datamodels.Infraction;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;

import static cc.projectnexus.adapters.java.utils.JavaScriptUtils.*;

public class ApiInteraction {

Expand Down Expand Up @@ -54,7 +55,7 @@ public static String sendRequest(String method, String url) throws IOException {
return response.toString();
}

private static String sendRequestData(String method, String url, JSONObject payload) throws IOException {
private static String sendRequestData(String method, String url, String payload) throws IOException {
HttpURLConnection connection = null;
BufferedReader reader = null;
OutputStream outputStream = null;
Expand Down Expand Up @@ -113,15 +114,13 @@ public static boolean test() {
public static GuildSettings[] getAllGuilds() {
try {
String res = sendRequest("GET", uri + "/guilds");
JSONObject json = new JSONObject(res);
Gson gson = new Gson();

JSONArray jsonArray = json.getJSONArray("guilds");
List<GuildSettings> guilds = new ArrayList<>();
TypeToken<List<GuildSettings>> token = new TypeToken<List<GuildSettings>>() {};
List<GuildSettings> guilds = gson.fromJson(res, token.getType());

for (int i = 0; i < jsonArray.length(); i++) {
JSONObject guild = jsonArray.getJSONObject(i);
GuildSettings guildSettings = GuildSettings.fromJson(guild);
guilds.add(guildSettings);
for (GuildSettings guild : guilds) {
setTimestampFields(guild, gson.toJson(guild));
}

return guilds.toArray(new GuildSettings[0]);
Expand All @@ -134,9 +133,11 @@ public static GuildSettings[] getAllGuilds() {
public static GuildSettings getGuild(String guildId) {
if (guildId == null) return null;
try {
Gson gson = new Gson();
String res = sendRequest("GET", uri + "/guilds/" + guildId);
JSONObject json = new JSONObject(res);
return GuildSettings.fromJson(json);
GuildSettings guildSettings = gson.fromJson(res, GuildSettings.class);
setTimestampFields(guildSettings, res);
return guildSettings;
} catch (IOException e) {
e.printStackTrace();
return null;
Expand All @@ -146,10 +147,12 @@ public static GuildSettings getGuild(String guildId) {
public static GuildSettings createGuild(String guildId) {
if (guildId == null) return null;
try {
JSONObject payload = new JSONObject("{\"guildId\": \"" + guildId + "\"}");
Gson gson = new Gson();
String payload = gson.toJson("{\"guildId\": \"" + guildId + "\"}");
String res = sendRequestData("POST", uri + "/guilds/", payload);
JSONObject json = new JSONObject(res);
return GuildSettings.fromJson(json);
GuildSettings guildSettings = gson.fromJson(res, GuildSettings.class);
setTimestampFields(guildSettings, res);
return guildSettings;
} catch (IOException e) {
e.printStackTrace();
return null;
Expand All @@ -170,10 +173,12 @@ public static boolean deleteGuild(GuildSettings guildSettings) {
public static GuildSettings updateGuild(GuildSettings guildSettings) {
if (guildSettings == null) return null;
try {
JSONObject payload = new JSONObject(guildSettings.toJson());
Gson gson = new Gson();
String payload = gson.toJson(guildSettings);
String res = sendRequestData("PUT", uri + "/guilds/" + guildSettings.getGuildId(), payload);
JSONObject json = new JSONObject(res);
return GuildSettings.fromJson(json);
GuildSettings updatedGuildSettings = gson.fromJson(res, GuildSettings.class);
setTimestampFields(updatedGuildSettings, res);
return updatedGuildSettings;
} catch (IOException e) {
e.printStackTrace();
return null;
Expand All @@ -183,16 +188,13 @@ public static GuildSettings updateGuild(GuildSettings guildSettings) {
public static Infraction[] getAllInfractions() {
try {
String res = sendRequest("GET", uri + "/infractions");
JSONObject json = new JSONObject(res);

JSONArray jsonArray = json.getJSONArray("infractions");
List<Infraction> infractions = new ArrayList<>();
Gson gson = new Gson();

for (int i = 0; i < jsonArray.length(); i++) {
JSONObject infractionJson = jsonArray.getJSONObject(i);
Infraction infraction = Infraction.fromJson(infractionJson);
TypeToken<List<Infraction>> token = new TypeToken<List<Infraction>>() {};
List<Infraction> infractions = gson.fromJson(res, token.getType());

infractions.add(infraction);
for (Infraction infraction : infractions) {
setTimestampFields(infraction, gson.toJson(infraction));
}

return infractions.toArray(new Infraction[0]);
Expand All @@ -205,9 +207,11 @@ public static Infraction[] getAllInfractions() {
public static Infraction getInfraction(Long infractionId) {
if (infractionId == null) return null;
try {
Gson gson = new Gson();
String res = sendRequest("GET", uri + "/infractions/" + infractionId);
JSONObject json = new JSONObject(res);
return Infraction.fromJson(json);
Infraction infraction = gson.fromJson(res, Infraction.class);
setTimestampFields(infraction, res);
return infraction;
} catch (IOException e) {
e.printStackTrace();
return null;
Expand All @@ -217,10 +221,10 @@ public static Infraction getInfraction(Long infractionId) {
public static Infraction createInfraction(Infraction infraction) {
if (infraction == null) return null;
try {
JSONObject payload = infraction.toJson();
Gson gson = new Gson();
String payload = gson.toJson(infraction);
String res = sendRequestData("POST", uri + "/infractions/", payload);
JSONObject json = new JSONObject(res);
return Infraction.fromJson(json);
return gson.fromJson(res, Infraction.class);
} catch (IOException e) {
e.printStackTrace();
return null;
Expand All @@ -241,10 +245,12 @@ public static boolean deleteInfraction(Infraction infraction) {
public static Infraction updateInfraction(Infraction infraction) {
if (infraction == null) return null;
try {
JSONObject payload = new JSONObject(infraction.toJson());
Gson gson = new Gson();
String payload = gson.toJson(infraction);
String res = sendRequestData("PUT", uri + "/infractions/" + infraction.getId(), payload);
JSONObject json = new JSONObject(res);
return Infraction.fromJson(json);
Infraction updatedInfraction = gson.fromJson(res, Infraction.class);
setTimestampFields(updatedInfraction, res);
return updatedInfraction;
} catch (IOException e) {
e.printStackTrace();
return null;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
package cc.projectnexus.adapters.java.datamodels;

import cc.projectnexus.adapters.java.utils.JavaScriptUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.Timestamp;
import java.util.Objects;

@Data
@NoArgsConstructor
Expand All @@ -23,57 +19,11 @@ public class GuildSettings {
private Timestamp lastUpdated;
private Region[] enabledRegions;

// Convert this object to a JSON object
public JSONObject toJson() {
JSONObject json = new JSONObject();

json.put("id", id);
json.put("guildId", guildId);
json.put("auto_ban", autoBan);
json.put("auto_unban", autoUnban);
json.put("logs_channel", logsChannel);
json.put("createdAt", createdAt.toString());
json.put("lastUpdated", lastUpdated.toString());

JSONArray regions = new JSONArray();
for (Region region : enabledRegions) {
regions.put(region.toString());
}

json.put("enabled_regions", regions);

return json;
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}

// Convert a JSON object to this object
public static GuildSettings fromJson(JSONObject json) {
GuildSettings guildSettings = new GuildSettings();

guildSettings.id = json.optLong("id");
guildSettings.guildId = json.optString("guildId");
guildSettings.autoBan = json.optBoolean("auto_ban");
guildSettings.autoUnban = json.optBoolean("auto_unban");
guildSettings.logsChannel = json.optString("logs_channel");
guildSettings.createdAt = Timestamp.valueOf(
Objects.requireNonNull(JavaScriptUtils.timestampJsToJava(
json.optString("createdAt")
))
);
guildSettings.lastUpdated = Timestamp.valueOf(
Objects.requireNonNull(JavaScriptUtils.timestampJsToJava(
json.optString("updatedAt")
))
);

JSONArray regionsArray = json.optJSONArray("enabled_regions");
if (regionsArray != null) {
Region[] regions = new Region[regionsArray.length()];
for (int i = 0; i < regionsArray.length(); i++) {
regions[i] = Region.valueOf(regionsArray.optString(i));
}
guildSettings.enabledRegions = regions;
}

return guildSettings;
public void setUpdatedAt(Timestamp updatedAt) {
this.lastUpdated = updatedAt;
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
package cc.projectnexus.adapters.java.datamodels;

import cc.projectnexus.adapters.java.utils.JavaScriptUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.Timestamp;
import java.util.Objects;

@Data
@NoArgsConstructor
Expand All @@ -22,55 +18,13 @@ public class Infraction {
private Long executorId;
private Boolean active;
private Timestamp createdAt;
private Timestamp updatedAt;
private Timestamp lastUpdated;

// Convert this object to a JSON object.
public JSONObject toJson() {
JSONObject json = new JSONObject();

json.put("id", id);
json.put("infractionUserId", userId);

JSONArray regionsArray = new JSONArray();
for (Region region : regions) {
regionsArray.put(region.toString());
}

json.put("regions", regionsArray);

json.put("reason", infractionReason);
json.put("proof", infractionProof);
json.put("executor", executorId);
json.put("active", active);
json.put("createdAt", createdAt.toString());
json.put("updatedAt", updatedAt.toString());

return json;
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}

// Convert a JSON object to this object
public static Infraction fromJson(JSONObject json) {
Infraction infraction = new Infraction();

infraction.id = json.optLong("id");
infraction.userId = json.optLong("infractionUserId");

JSONArray regionsArray = json.optJSONArray("regions");
if (regionsArray != null) {
Region[] regions = new Region[regionsArray.length()];
for (int i = 0; i < regionsArray.length(); i++) {
regions[i] = Region.valueOf(regionsArray.optString(i));
}
infraction.regions = regions;
}

infraction.infractionReason = json.optString("reason");
infraction.infractionProof = json.optString("proof");
infraction.executorId = json.optLong("executor");
infraction.active = json.optBoolean("active");
infraction.createdAt = Timestamp.valueOf(Objects.requireNonNull(JavaScriptUtils.timestampJsToJava(json.optString("createdAt"))));
infraction.updatedAt = Timestamp.valueOf(Objects.requireNonNull(JavaScriptUtils.timestampJsToJava(json.optString("updatedAt"))));

return infraction;
public void setUpdatedAt(Timestamp updatedAt) {
this.lastUpdated = updatedAt;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
import cc.projectnexus.adapters.java.NexusClient;
import cc.projectnexus.adapters.java.api.ApiInteraction;
import cc.projectnexus.adapters.java.datamodels.GuildSettings;
import cc.projectnexus.adapters.java.datamodels.Infraction;
import cc.projectnexus.adapters.java.datamodels.Region;

import java.util.*;
import java.util.function.Predicate;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,49 @@
package cc.projectnexus.adapters.java.utils;

import cc.projectnexus.adapters.java.datamodels.GuildSettings;
import cc.projectnexus.adapters.java.datamodels.Infraction;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class JavaScriptUtils {

public static String timestampJsToJava(String jsTimestamp) {
public static Timestamp timestampJsToJava(String jsTimestamp) {
DateTimeFormatter jsFormatter = DateTimeFormatter.ISO_INSTANT;
DateTimeFormatter javaFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String javaTimestampString;

try {
Instant instant = Instant.from(jsFormatter.parse(jsTimestamp));
LocalDateTime javaDateTime = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
javaTimestampString = javaDateTime.format(javaFormatter);
return Timestamp.valueOf(javaDateTime);
} catch (Exception e) {
e.printStackTrace();
return null; // or return an empty string, depending on your preference
return null; // or handle the error as needed
}
}

public static void setTimestampFields(GuildSettings guildSettings, String response) {
JsonObject responseJson = new Gson().fromJson(response, JsonObject.class);

String createdAt = responseJson.get("createdAt").getAsString();
String updatedAt = responseJson.get("lastUpdated").getAsString();

guildSettings.setCreatedAt(timestampJsToJava(createdAt));
guildSettings.setUpdatedAt(timestampJsToJava(updatedAt));
}

public static void setTimestampFields(Infraction infraction, String response) {
JsonObject responseJson = new Gson().fromJson(response, JsonObject.class);

String createdAt = responseJson.get("createdAt").getAsString();
String updatedAt = responseJson.get("lastUpdated").getAsString();

return javaTimestampString;
infraction.setCreatedAt(timestampJsToJava(createdAt));
infraction.setUpdatedAt(timestampJsToJava(updatedAt));
}

}

0 comments on commit 0bd149f

Please sign in to comment.