package xyz.etztech.core.web; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.ChatColor; import java.util.logging.Logger; /** * A basic class to wrap a JSON response containing a simple status and message */ public class Response { private JsonObject json; private Boolean status; private String message; private static Logger log = Logger.getLogger("Minecraft"); /** * @param httpResponse A JSON array e.g. multiple results from one call */ public Response(JsonArray httpResponse) { json = httpResponse.get(0).getAsJsonObject(); setStatus(json.get("status").getAsBoolean()); setMessage(json.get("message").getAsString()); } /** * @param httpResponse A JSON object e.g. a single result from one call */ public Response(JsonObject httpResponse) { json = httpResponse; setStatus(httpResponse.get("status").getAsBoolean()); setMessage(httpResponse.get("message").getAsString()); } /** * @param rawReponse A raw JSON array in string format */ public Response(String rawReponse) { JsonParser parser = new JsonParser(); try { json = (JsonObject) parser.parse(rawReponse); setStatus(json.get("status").getAsBoolean()); setMessage(json.get("message").getAsString()); } catch (Exception ex) { log.warning("Could not parse JSON result"); } } public JsonObject getJson() { return json; } public void setJson(JsonObject json) { this.json = json; } public Boolean getStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } /** * @return A legacy Minecraft message using color codes */ @Deprecated public String getMCMessage() { if (status) { return ChatColor.GREEN + message; } else { return ChatColor.RED + message; } } /** * @return A Spigot JSON message */ public TextComponent getMCJSON() { ComponentBuilder builder = new ComponentBuilder(message); if (status) { builder.color(net.md_5.bungee.api.ChatColor.GREEN); } else { builder.color(net.md_5.bungee.api.ChatColor.RED); } return new TextComponent(builder.create()); } }