();
-
private static boolean hasJumpPotion(Player player) {
return player.hasPotionEffect(PotionEffectType.JUMP);
}
@@ -61,49 +60,49 @@ public class YAxisCheck {
double y1 = player.getLocation().getY();
UUID uuid = player.getUniqueId();
// Fix Y axis spam.
- if (!lastYcoord.containsKey(uuid) || !lastYtime.containsKey(uuid)
- || !yAxisLastViolation.containsKey(uuid)) {
- lastYcoord.put(uuid, y1);
- yAxisViolations.put(uuid, 0);
- yAxisLastViolation.put(uuid, 0L);
- lastYtime.put(uuid, System.currentTimeMillis());
+ if (!LAST_Y_COORD_CACHE.containsKey(uuid) || !LAST_Y_TIME.containsKey(uuid)
+ || !LAST_Y_AXIS_VIOLATION.containsKey(uuid)) {
+ LAST_Y_COORD_CACHE.put(uuid, y1);
+ Y_AXIS_VIOLATIONS.put(uuid, 0);
+ LAST_Y_AXIS_VIOLATION.put(uuid, 0L);
+ LAST_Y_TIME.put(uuid, System.currentTimeMillis());
} else {
- if (y1 > lastYcoord.get(uuid)
- && yAxisViolations.get(uuid) > AntiCheatReloaded.getManager().getBackend().getMagic()
+ if (y1 > LAST_Y_COORD_CACHE.get(uuid)
+ && Y_AXIS_VIOLATIONS.get(uuid) > AntiCheatReloaded.getManager().getBackend().getMagic()
.Y_MAXVIOLATIONS()
- && (System.currentTimeMillis() - yAxisLastViolation.get(uuid)) < AntiCheatReloaded.getManager()
+ && (System.currentTimeMillis() - LAST_Y_AXIS_VIOLATION.get(uuid)) < AntiCheatReloaded.getManager()
.getBackend().getMagic().Y_MAXVIOTIME()) {
Location g = player.getLocation();
- yAxisViolations.put(uuid, yAxisViolations.get(uuid) + 1);
- yAxisLastViolation.put(uuid, System.currentTimeMillis());
+ Y_AXIS_VIOLATIONS.put(uuid, Y_AXIS_VIOLATIONS.get(uuid) + 1);
+ LAST_Y_AXIS_VIOLATION.put(uuid, System.currentTimeMillis());
if (!AntiCheatReloaded.getManager().getBackend().silentMode()) {
- g.setY(lastYcoord.get(uuid));
+ g.setY(LAST_Y_COORD_CACHE.get(uuid));
if (g.getBlock().getType() == Material.AIR) {
player.teleport(g);
}
}
return new CheckResult(CheckResult.Result.FAILED,
- player.getName() + " tried to fly on y-axis " + yAxisViolations.get(uuid) + " times (max ="
+ player.getName() + " tried to fly on y-axis " + Y_AXIS_VIOLATIONS.get(uuid) + " times (max ="
+ AntiCheatReloaded.getManager().getBackend().getMagic().Y_MAXVIOLATIONS() + ")");
} else {
- if (yAxisViolations.get(uuid) > AntiCheatReloaded.getManager().getBackend().getMagic()
+ if (Y_AXIS_VIOLATIONS.get(uuid) > AntiCheatReloaded.getManager().getBackend().getMagic()
.Y_MAXVIOLATIONS()
- && (System.currentTimeMillis() - yAxisLastViolation.get(uuid)) > AntiCheatReloaded
+ && (System.currentTimeMillis() - LAST_Y_AXIS_VIOLATION.get(uuid)) > AntiCheatReloaded
.getManager().getBackend().getMagic().Y_MAXVIOTIME()) {
- yAxisViolations.put(uuid, 0);
- yAxisLastViolation.put(uuid, 0L);
+ Y_AXIS_VIOLATIONS.put(uuid, 0);
+ LAST_Y_AXIS_VIOLATION.put(uuid, 0L);
}
}
- long i = System.currentTimeMillis() - lastYtime.get(uuid);
+ long i = System.currentTimeMillis() - LAST_Y_TIME.get(uuid);
double diff = AntiCheatReloaded.getManager().getBackend().getMagic().Y_MAXDIFF()
+ (Utilities.isStair(player.getLocation().add(0, -1, 0).getBlock()) ? 0.5 : 0.0);
- if ((y1 - lastYcoord.get(uuid)) > diff
+ if ((y1 - LAST_Y_COORD_CACHE.get(uuid)) > diff
&& i < AntiCheatReloaded.getManager().getBackend().getMagic().Y_TIME()) {
Location g = player.getLocation();
- yAxisViolations.put(uuid, yAxisViolations.get(uuid) + 1);
- yAxisLastViolation.put(uuid, System.currentTimeMillis());
+ Y_AXIS_VIOLATIONS.put(uuid, Y_AXIS_VIOLATIONS.get(uuid) + 1);
+ LAST_Y_AXIS_VIOLATION.put(uuid, System.currentTimeMillis());
if (!AntiCheatReloaded.getManager().getBackend().silentMode()) {
- g.setY(lastYcoord.get(uuid));
+ g.setY(LAST_Y_COORD_CACHE.get(uuid));
if (g.getBlock().getType() == Material.AIR) {
player.teleport(g);
}
@@ -111,12 +110,12 @@ public class YAxisCheck {
return new CheckResult(CheckResult.Result.FAILED, player.getName() + " tried to fly on y-axis in "
+ i + " ms (min =" + AntiCheatReloaded.getManager().getBackend().getMagic().Y_TIME() + ")");
} else {
- if ((y1 - lastYcoord.get(uuid)) > AntiCheatReloaded.getManager().getBackend().getMagic().Y_MAXDIFF()
+ if ((y1 - LAST_Y_COORD_CACHE.get(uuid)) > AntiCheatReloaded.getManager().getBackend().getMagic().Y_MAXDIFF()
+ 1
- || (System.currentTimeMillis() - lastYtime.get(uuid)) > AntiCheatReloaded.getManager()
+ || (System.currentTimeMillis() - LAST_Y_TIME.get(uuid)) > AntiCheatReloaded.getManager()
.getBackend().getMagic().Y_TIME()) {
- lastYtime.put(uuid, System.currentTimeMillis());
- lastYcoord.put(uuid, y1);
+ LAST_Y_TIME.put(uuid, System.currentTimeMillis());
+ LAST_Y_COORD_CACHE.put(uuid, y1);
}
}
}
diff --git a/src/main/java/com/rammelkast/anticheatreloaded/event/EntityListener.java b/src/main/java/com/rammelkast/anticheatreloaded/event/EntityListener.java
index 3a64fe8..39f8b2e 100644
--- a/src/main/java/com/rammelkast/anticheatreloaded/event/EntityListener.java
+++ b/src/main/java/com/rammelkast/anticheatreloaded/event/EntityListener.java
@@ -29,18 +29,16 @@ import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
+import org.bukkit.event.entity.EntityShootBowEvent;
+import org.bukkit.event.entity.FoodLevelChangeEvent;
import com.rammelkast.anticheatreloaded.AntiCheatReloaded;
import com.rammelkast.anticheatreloaded.check.CheckResult;
import com.rammelkast.anticheatreloaded.check.CheckType;
import com.rammelkast.anticheatreloaded.check.combat.CriticalsCheck;
-import com.rammelkast.anticheatreloaded.check.combat.KillAuraCheck;
import com.rammelkast.anticheatreloaded.check.combat.VelocityCheck;
import com.rammelkast.anticheatreloaded.util.Distance;
-import org.bukkit.event.entity.EntityShootBowEvent;
-import org.bukkit.event.entity.FoodLevelChangeEvent;
-
public class EntityListener extends EventListener {
@EventHandler
@@ -105,9 +103,6 @@ public class EntityListener extends EventListener {
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event;
if (e.getDamager() instanceof Player) {
- if (getCheckManager().willCheck((Player)e.getDamager(), CheckType.KILLAURA)) {
- KillAuraCheck.doDamageEvent(e, (Player)e.getDamager());
- }
if (getCheckManager().willCheck((Player)e.getDamager(), CheckType.CRITICALS)) {
CriticalsCheck.doDamageEvent(e, (Player)e.getDamager());
}
@@ -118,7 +113,7 @@ public class EntityListener extends EventListener {
if (e.getDamager() instanceof Player) {
Player p = (Player) e.getDamager();
getBackend().logDamage(p, 1);
- int value = p.getInventory().getItemInHand().containsEnchantment(Enchantment.KNOCKBACK) ? 2 : 1;
+ int value = p.getInventory().getItemInMainHand().containsEnchantment(Enchantment.KNOCKBACK) ? 2 : 1;
getBackend().logDamage(player, value);
if (getCheckManager().willCheck(p, CheckType.LONG_REACH)) {
Distance distance = new Distance(player.getLocation(), p.getLocation());
diff --git a/src/main/java/com/rammelkast/anticheatreloaded/metrics/Metrics.java b/src/main/java/com/rammelkast/anticheatreloaded/metrics/Metrics.java
index bae14ee..ac47bab 100644
--- a/src/main/java/com/rammelkast/anticheatreloaded/metrics/Metrics.java
+++ b/src/main/java/com/rammelkast/anticheatreloaded/metrics/Metrics.java
@@ -19,20 +19,24 @@
package com.rammelkast.anticheatreloaded.metrics;
+import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
+import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
-import java.util.HashMap;
+import java.util.Collection;
import java.util.List;
-import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
+import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
@@ -40,28 +44,69 @@ import javax.net.ssl.HttpsURLConnection;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
+import org.bukkit.entity.Player;
+import org.bukkit.plugin.Plugin;
+import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
-import org.bukkit.plugin.java.JavaPlugin;
-import org.json.simple.JSONArray;
-import org.json.simple.JSONObject;
-//bStats.org/ to learn more about bStats!
+import com.google.gson.JsonArray;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonPrimitive;
+
+/**
+ * bStats collects some data for plugin authors.
+ *
+ * Check out https://bStats.org/ to learn more about bStats!
+ */
+@SuppressWarnings({ "WeakerAccess", "unused" })
public class Metrics {
+ static {
+ // You can use the property to disable the check in your test environment
+ if (System.getProperty("bstats.relocatecheck") == null
+ || !System.getProperty("bstats.relocatecheck").equals("false")) {
+ // Maven's Relocate is clever and changes strings, too. So we have to use this
+ // little "trick" ... :D
+ final String defaultPackage = new String(
+ new byte[] { 'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't' });
+ final String examplePackage = new String(
+ new byte[] { 'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e' });
+ // We want to make sure nobody just copy & pastes the example and use the wrong
+ // package names
+ if (Metrics.class.getPackage().getName().equals(defaultPackage)
+ || Metrics.class.getPackage().getName().equals(examplePackage)) {
+ throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
+ }
+ }
+ }
+
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
- private static final String URL = "https://bStats.org/submitData";
+ private static final String URL = "https://bStats.org/submitData/bukkit";
+
+ // Is bStats enabled on this server?
+ private boolean enabled;
// Should failed requests be logged?
private static boolean logFailedRequests;
+ // Should the sent data be logged?
+ private static boolean logSentData;
+
+ // Should the response text be logged?
+ private static boolean logResponseStatusText;
+
// The uuid of the server
private static String serverUUID;
// The plugin
- private final JavaPlugin plugin;
+ private final Plugin plugin;
+
+ // The plugin id
+ private final int pluginId;
// A list with all custom charts
private final List charts = new ArrayList<>();
@@ -69,13 +114,17 @@ public class Metrics {
/**
* Class constructor.
*
- * @param plugin The plugin which stats should be submitted.
+ * @param plugin The plugin which stats should be submitted.
+ * @param pluginId The id of the plugin. It can be found at
+ * What is my
+ * plugin id?
*/
- public Metrics(JavaPlugin plugin) {
+ public Metrics(Plugin plugin, int pluginId) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
+ this.pluginId = pluginId;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
@@ -91,6 +140,10 @@ public class Metrics {
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
config.addDefault("logFailedRequests", false);
+ // Should the sent data be logged?
+ config.addDefault("logSentData", false);
+ // Should the response text be logged?
+ config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config.options().header(
@@ -106,9 +159,13 @@ public class Metrics {
}
// Load the data
+ enabled = config.getBoolean("enabled", true);
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
- if (config.getBoolean("enabled", true)) {
+ logSentData = config.getBoolean("logSentData", false);
+ logResponseStatusText = config.getBoolean("logResponseStatusText", false);
+
+ if (enabled) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class> service : Bukkit.getServicesManager().getKnownServices()) {
@@ -128,6 +185,15 @@ public class Metrics {
}
}
+ /**
+ * Checks if bStats is enabled.
+ *
+ * @return Whether bStats is enabled or not.
+ */
+ public boolean isEnabled() {
+ return enabled;
+ }
+
/**
* Adds a custom chart.
*
@@ -156,12 +222,7 @@ public class Metrics {
// use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the
// stats collection is sync ;)
- Bukkit.getScheduler().runTask(plugin, new Runnable() {
- @Override
- public void run() {
- submitData();
- }
- });
+ Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000 * 60 * 5, 1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other
@@ -176,24 +237,25 @@ public class Metrics {
*
* @return The plugin specific data.
*/
- public JSONObject getPluginData() {
- JSONObject data = new JSONObject();
+ public JsonObject getPluginData() {
+ JsonObject data = new JsonObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
- data.put("pluginName", pluginName); // Append the name of the plugin
- data.put("pluginVersion", pluginVersion); // Append the version of the plugin
- JSONArray customCharts = new JSONArray();
+ data.addProperty("pluginName", pluginName); // Append the name of the plugin
+ data.addProperty("id", pluginId); // Append the id of the plugin
+ data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin
+ JsonArray customCharts = new JsonArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
- JSONObject chart = customChart.getRequestJsonObject();
+ JsonObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
- data.put("customCharts", customCharts);
+ data.add("customCharts", customCharts);
return data;
}
@@ -203,12 +265,23 @@ public class Metrics {
*
* @return The server specific data.
*/
- private JSONObject getServerData() {
+ private JsonObject getServerData() {
// Minecraft specific data
- int playerAmount = Bukkit.getOnlinePlayers().size();
+ int playerAmount;
+ try {
+ // Around MC 1.8 the return type was changed to a collection from an array,
+ // This fixes java.lang.NoSuchMethodError:
+ // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
+ Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
+ playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
+ ? ((Collection>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
+ : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
+ } catch (Exception e) {
+ playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
+ }
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
- String bukkitVersion = org.bukkit.Bukkit.getVersion();
- bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1);
+ String bukkitVersion = Bukkit.getVersion();
+ String bukkitName = Bukkit.getName();
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
@@ -217,19 +290,20 @@ public class Metrics {
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
- JSONObject data = new JSONObject();
+ JsonObject data = new JsonObject();
- data.put("serverUUID", serverUUID);
+ data.addProperty("serverUUID", serverUUID);
- data.put("playerAmount", playerAmount);
- data.put("onlineMode", onlineMode);
- data.put("bukkitVersion", bukkitVersion);
+ data.addProperty("playerAmount", playerAmount);
+ data.addProperty("onlineMode", onlineMode);
+ data.addProperty("bukkitVersion", bukkitVersion);
+ data.addProperty("bukkitName", bukkitName);
- data.put("javaVersion", javaVersion);
- data.put("osName", osName);
- data.put("osArch", osArch);
- data.put("osVersion", osVersion);
- data.put("coreCount", coreCount);
+ data.addProperty("javaVersion", javaVersion);
+ data.addProperty("osName", osName);
+ data.addProperty("osArch", osArch);
+ data.addProperty("osVersion", osVersion);
+ data.addProperty("coreCount", coreCount);
return data;
}
@@ -238,57 +312,77 @@ public class Metrics {
* Collects the data and sends it afterwards.
*/
private void submitData() {
- final JSONObject data = getServerData();
+ final JsonObject data = getServerData();
- JSONArray pluginData = new JSONArray();
+ JsonArray pluginData = new JsonArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
+
+ for (RegisteredServiceProvider> provider : Bukkit.getServicesManager().getRegistrations(service)) {
+ try {
+ Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
+ if (plugin instanceof JsonObject) {
+ pluginData.add((JsonObject) plugin);
+ } else { // old bstats version compatibility
+ try {
+ Class> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
+ if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
+ Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
+ jsonStringGetter.setAccessible(true);
+ String jsonString = (String) jsonStringGetter.invoke(plugin);
+ JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
+ pluginData.add(object);
+ }
+ } catch (ClassNotFoundException e) {
+ // minecraft version 1.14+
+ if (logFailedRequests) {
+ this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e);
+ }
+ }
+ }
+ } catch (NullPointerException | NoSuchMethodException | IllegalAccessException
+ | InvocationTargetException ignored) {
+ }
+ }
} catch (NoSuchFieldException ignored) {
- continue; // Continue "searching"
- }
- // Found one!
- try {
- pluginData.add(service.getMethod("getPluginData").invoke(Bukkit.getServicesManager().load(service)));
- } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
}
}
- data.put("plugins", pluginData);
+ data.add("plugins", pluginData);
// Create a new thread for the connection to the bStats server
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- // Send the data
- sendData(data);
- } catch (Exception e) {
- // Something went wrong! :(
- if (logFailedRequests) {
- plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(),
- e);
- }
+ new Thread(() -> {
+ try {
+ // Send the data
+ sendData(plugin, data);
+ } catch (Exception e) {
+ // Something went wrong! :(
+ if (logFailedRequests) {
+ plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}).start();
-
}
/**
* Sends the data to the bStats server.
*
- * @param data The data to send.
+ * @param plugin Any plugin. It's just used to get a logger instance.
+ * @param data The data to send.
* @throws Exception If the request failed.
*/
- private static void sendData(JSONObject data) throws Exception {
+ private static void sendData(Plugin plugin, JsonObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
+ if (logSentData) {
+ plugin.getLogger().info("Sending data to bStats: " + data);
+ }
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
@@ -305,12 +399,21 @@ public class Metrics {
// Send data
connection.setDoOutput(true);
- DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
- outputStream.write(compressedData);
- outputStream.flush();
- outputStream.close();
+ try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
+ outputStream.write(compressedData);
+ }
- connection.getInputStream().close(); // We don't care about the response - Just send our data :)
+ StringBuilder builder = new StringBuilder();
+ try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
+ String line;
+ while ((line = bufferedReader.readLine()) != null) {
+ builder.append(line);
+ }
+ }
+
+ if (logResponseStatusText) {
+ plugin.getLogger().info("Sent data to bStats and received response: " + builder);
+ }
}
/**
@@ -325,9 +428,9 @@ public class Metrics {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
- gzip.write(str.getBytes("UTF-8"));
- gzip.close();
+ try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
+ gzip.write(str.getBytes(StandardCharsets.UTF_8));
+ }
return outputStream.toByteArray();
}
@@ -337,30 +440,30 @@ public class Metrics {
public static abstract class CustomChart {
// The id of the chart
- protected final String chartId;
+ final String chartId;
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
- public CustomChart(String chartId) {
+ CustomChart(String chartId) {
if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!");
}
this.chartId = chartId;
}
- protected JSONObject getRequestJsonObject() {
- JSONObject chart = new JSONObject();
- chart.put("chartId", chartId);
+ private JsonObject getRequestJsonObject() {
+ JsonObject chart = new JsonObject();
+ chart.addProperty("chartId", chartId);
try {
- JSONObject data = getChartData();
+ JsonObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
- chart.put("data", data);
+ chart.add("data", data);
} catch (Throwable t) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
@@ -370,40 +473,37 @@ public class Metrics {
return chart;
}
- protected abstract JSONObject getChartData();
+ protected abstract JsonObject getChartData() throws Exception;
}
/**
* Represents a custom simple pie.
*/
- public static abstract class SimplePie extends CustomChart {
+ public static class SimplePie extends CustomChart {
+
+ private final Callable callable;
/**
* Class constructor.
*
- * @param chartId The id of the chart.
+ * @param chartId The id of the chart.
+ * @param callable The callable which is used to request the chart data.
*/
- public SimplePie(String chartId) {
+ public SimplePie(String chartId, Callable callable) {
super(chartId);
+ this.callable = callable;
}
- /**
- * Gets the value of the pie.
- *
- * @return The value of the pie.
- */
- public abstract String getValue();
-
@Override
- protected JSONObject getChartData() {
- JSONObject data = new JSONObject();
- String value = getValue();
+ protected JsonObject getChartData() throws Exception {
+ JsonObject data = new JsonObject();
+ String value = callable.call();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
- data.put("value", value);
+ data.addProperty("value", value);
return data;
}
}
@@ -411,31 +511,26 @@ public class Metrics {
/**
* Represents a custom advanced pie.
*/
- public static abstract class AdvancedPie extends CustomChart {
+ public static class AdvancedPie extends CustomChart {
+
+ private final Callable