diff --git a/ModuleLoader/gradle/wrapper/gradle-wrapper.jar b/ModuleLoader/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/ModuleLoader/gradle/wrapper/gradle-wrapper.jar differ diff --git a/ModuleLoader/src/main/java/opg/p2vman/moduleloader/module/ModuleMannager.java b/ModuleLoader/src/main/java/opg/p2vman/moduleloader/module/ModuleMannager.java index 06e1386..30859a0 100644 --- a/ModuleLoader/src/main/java/opg/p2vman/moduleloader/module/ModuleMannager.java +++ b/ModuleLoader/src/main/java/opg/p2vman/moduleloader/module/ModuleMannager.java @@ -115,6 +115,21 @@ public class ModuleMannager { return super.visitField(access, name, updateDescriptor(descriptor), signature, value); } + @Override + public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { + return super.visitAnnotation(updateDescriptor(descriptor), visible); + } + + @Override + public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String descriptor, boolean visible) { + return super.visitTypeAnnotation(typeRef, typePath, updateDescriptor(descriptor), visible); + } + + @Override + public RecordComponentVisitor visitRecordComponent(String name, String descriptor, String signature) { + return super.visitRecordComponent(name, updateDescriptor(descriptor), signature); + } + @Override public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { MethodVisitor mv = super.visitMethod(access, name, updateDescriptor(descriptor), signature, exceptions); diff --git a/ModuleLoader/src/main/java/opg/p2vman/moduleloader/module/ModuleMeta.java b/ModuleLoader/src/main/java/opg/p2vman/moduleloader/module/ModuleMeta.java index 68df0b7..be4e16b 100644 --- a/ModuleLoader/src/main/java/opg/p2vman/moduleloader/module/ModuleMeta.java +++ b/ModuleLoader/src/main/java/opg/p2vman/moduleloader/module/ModuleMeta.java @@ -1,10 +1,6 @@ package opg.p2vman.moduleloader.module; -import java.util.List; -import java.util.Map; - public class ModuleMeta { public String main_class; public String name; - public Map> class_lookups; } diff --git a/base/build.gradle b/base/build.gradle index 7408098..e5f8960 100644 --- a/base/build.gradle +++ b/base/build.gradle @@ -3,7 +3,7 @@ plugins { } group = 'io.github.p2vman' -version = '1.3' +version = '1.4' repositories { mavenCentral() @@ -15,11 +15,6 @@ dependencies { compileOnly 'org.projectlombok:lombok:1.18.30' } -task createJar(type: Jar) { - archiveBaseName = 'base' - archiveVersion = 'marge' - from sourceSets.main.output -} tasks.withType(JavaCompile).configureEach { options.encoding = 'UTF-8' diff --git a/base/src/main/java/io/github/p2vman/updater/Updater.java b/base/src/main/java/io/github/p2vman/updater/Updater.java new file mode 100644 index 0000000..bd73efd --- /dev/null +++ b/base/src/main/java/io/github/p2vman/updater/Updater.java @@ -0,0 +1,57 @@ +package io.github.p2vman.updater; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.stream.JsonReader; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.ProtocolException; +import java.net.URL; +import java.util.Objects; + +public class Updater { + private static Updater updater; + public static Updater getInstance() { + if (updater == null) updater = new Updater(); + return updater; + } + private String id; + + public String getId() { + return id; + } + + private static final String API_URL = "https://api.spiget.org/v2/resources/"; + private static final String URL = "https://www.spigotmc.org/"; + private static final String SPIGOT_SIDE_API = "https://api.spigotmc.org/legacy/"; + + public Updater() { + try (InputStreamReader reader = new InputStreamReader(Objects.requireNonNull(Updater.class.getClassLoader().getResourceAsStream("updater.json")))) { + JsonObject jsonObject = JsonParser.parseReader(reader).getAsJsonObject(); + id = jsonObject.get("id").getAsString(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public JsonObject getLasted() throws ProtocolException, IOException { + URL url = new URL(API_URL + id + "/versions/latest"); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + conn.setRequestProperty("User-Agent", "Mozilla/5.0"); + + return JsonParser.parseReader(new BufferedReader(new InputStreamReader(conn.getInputStream()))).getAsJsonObject(); + } + + public String getVersionUrl() throws ProtocolException, IOException { + URL url = new URL(API_URL + id); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + conn.setRequestProperty("User-Agent", "Mozilla/5.0"); + + return URL+JsonParser.parseReader(new BufferedReader(new InputStreamReader(conn.getInputStream()))).getAsJsonObject().get("file").getAsJsonObject().get("url").getAsString(); + } +} diff --git a/base/src/main/java/org/eptalist/Config.java b/base/src/main/java/org/eptalist/Config.java index 896008e..be02f1a 100644 --- a/base/src/main/java/org/eptalist/Config.java +++ b/base/src/main/java/org/eptalist/Config.java @@ -21,7 +21,7 @@ public class Config { "whitelist", "base"), "org.eptalist.storge.Json", - Utils.put(new HashMap<>(), "file", "eoptalist.json"), + Utils.put(new HashMap<>(), "file", "eptalist.json"), "&6Молодой человек а вас нету в списке &4:)" ), new Mode( @@ -29,7 +29,7 @@ public class Config { "whitelist", "dev"), "org.eptalist.storge.Json", - Utils.put(new HashMap<>(), "file", "eoptalist.dev.json"), + Utils.put(new HashMap<>(), "file", "eptalist.dev.json"), "&2Сервер на тех работах" ) }; diff --git a/base/src/main/java/org/eptalist/metrics/AdvancedBarChart.java b/base/src/main/java/org/eptalist/metrics/AdvancedBarChart.java new file mode 100644 index 0000000..181ff00 --- /dev/null +++ b/base/src/main/java/org/eptalist/metrics/AdvancedBarChart.java @@ -0,0 +1,44 @@ +package org.eptalist.metrics; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} \ No newline at end of file diff --git a/base/src/main/java/org/eptalist/metrics/AdvancedPie.java b/base/src/main/java/org/eptalist/metrics/AdvancedPie.java new file mode 100644 index 0000000..2991081 --- /dev/null +++ b/base/src/main/java/org/eptalist/metrics/AdvancedPie.java @@ -0,0 +1,44 @@ +package org.eptalist.metrics; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} \ No newline at end of file diff --git a/base/src/main/java/org/eptalist/metrics/CustomChart.java b/base/src/main/java/org/eptalist/metrics/CustomChart.java new file mode 100644 index 0000000..c9d3fe5 --- /dev/null +++ b/base/src/main/java/org/eptalist/metrics/CustomChart.java @@ -0,0 +1,36 @@ +package org.eptalist.metrics; + +import java.util.function.BiConsumer; + +public abstract class CustomChart { + private final String chartId; + + protected CustomChart(String chartId) { + if (chartId == null) { + throw new IllegalArgumentException("chartId must not be null"); + } + this.chartId = chartId; + } + + public JsonObjectBuilder.JsonObject getRequestJsonObject( + BiConsumer errorLogger, boolean logErrors) { + JsonObjectBuilder builder = new JsonObjectBuilder(); + builder.appendField("chartId", chartId); + try { + JsonObjectBuilder.JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + builder.appendField("data", data); + } catch (Throwable t) { + if (logErrors) { + errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return builder.build(); + } + + protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception; +} \ No newline at end of file diff --git a/base/src/main/java/org/eptalist/metrics/DrilldownPie.java b/base/src/main/java/org/eptalist/metrics/DrilldownPie.java new file mode 100644 index 0000000..c6ef273 --- /dev/null +++ b/base/src/main/java/org/eptalist/metrics/DrilldownPie.java @@ -0,0 +1,48 @@ +package org.eptalist.metrics; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} \ No newline at end of file diff --git a/base/src/main/java/org/eptalist/metrics/JsonObjectBuilder.java b/base/src/main/java/org/eptalist/metrics/JsonObjectBuilder.java new file mode 100644 index 0000000..16da5a8 --- /dev/null +++ b/base/src/main/java/org/eptalist/metrics/JsonObjectBuilder.java @@ -0,0 +1,211 @@ +package org.eptalist.metrics; + +import java.util.Arrays; +import java.util.stream.Collectors; + + +/** + * An extremely simple JSON builder. + * + *

While this class is neither feature-rich nor the most performant one, it's sufficient enough + * for its use-case. + */ +public class JsonObjectBuilder { + + private StringBuilder builder = new StringBuilder(); + + private boolean hasAtLeastOneField = false; + + public JsonObjectBuilder() { + builder.append("{"); + } + + /** + * Appends a null field to the JSON. + * + * @param key The key of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendNull(String key) { + appendFieldUnescaped(key, "null"); + return this; + } + + /** + * Appends a string field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String value) { + if (value == null) { + throw new IllegalArgumentException("JSON value must not be null"); + } + appendFieldUnescaped(key, "\"" + escape(value) + "\""); + return this; + } + + /** + * Appends an integer field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int value) { + appendFieldUnescaped(key, String.valueOf(value)); + return this; + } + + /** + * Appends an object to the JSON. + * + * @param key The key of the field. + * @param object The object. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject object) { + if (object == null) { + throw new IllegalArgumentException("JSON object must not be null"); + } + appendFieldUnescaped(key, object.toString()); + return this; + } + + /** + * Appends a string array to the JSON. + * + * @param key The key of the field. + * @param values The string array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values) + .map(value -> "\"" + escape(value) + "\"") + .collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an integer array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an object array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends a field to the object. + * + * @param key The key of the field. + * @param escapedValue The escaped value of the field. + */ + private void appendFieldUnescaped(String key, String escapedValue) { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + if (key == null) { + throw new IllegalArgumentException("JSON key must not be null"); + } + if (hasAtLeastOneField) { + builder.append(","); + } + builder.append("\"").append(escape(key)).append("\":").append(escapedValue); + hasAtLeastOneField = true; + } + + /** + * Builds the JSON string and invalidates this builder. + * + * @return The built JSON string. + */ + public JsonObject build() { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + JsonObject object = new JsonObject(builder.append("}").toString()); + builder = null; + return object; + } + + /** + * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ + private static String escape(String value) { + final StringBuilder builder = new StringBuilder(); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '"') { + builder.append("\\\""); + } else if (c == '\\') { + builder.append("\\\\"); + } else if (c <= '\u000F') { + builder.append("\\u000").append(Integer.toHexString(c)); + } else if (c <= '\u001F') { + builder.append("\\u00").append(Integer.toHexString(c)); + } else { + builder.append(c); + } + } + return builder.toString(); + } + + /** + * A super simple representation of a JSON object. + * + *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not + * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, + * JsonObject)}. + */ + public static class JsonObject { + + private final String value; + + private JsonObject(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } + } +} \ No newline at end of file diff --git a/base/src/main/java/org/eptalist/metrics/MultiLineChart.java b/base/src/main/java/org/eptalist/metrics/MultiLineChart.java new file mode 100644 index 0000000..f44c5cb --- /dev/null +++ b/base/src/main/java/org/eptalist/metrics/MultiLineChart.java @@ -0,0 +1,44 @@ +package org.eptalist.metrics; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} \ No newline at end of file diff --git a/base/src/main/java/org/eptalist/metrics/SimpleBarChart.java b/base/src/main/java/org/eptalist/metrics/SimpleBarChart.java new file mode 100644 index 0000000..b58c8b8 --- /dev/null +++ b/base/src/main/java/org/eptalist/metrics/SimpleBarChart.java @@ -0,0 +1,34 @@ +package org.eptalist.metrics; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()}); + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} \ No newline at end of file diff --git a/base/src/main/java/org/eptalist/metrics/SimplePie.java b/base/src/main/java/org/eptalist/metrics/SimplePie.java new file mode 100644 index 0000000..b012762 --- /dev/null +++ b/base/src/main/java/org/eptalist/metrics/SimplePie.java @@ -0,0 +1,29 @@ +package org.eptalist.metrics; + +import java.util.concurrent.Callable; + +public class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } +} \ No newline at end of file diff --git a/base/src/main/java/org/eptalist/metrics/SingleLineChart.java b/base/src/main/java/org/eptalist/metrics/SingleLineChart.java new file mode 100644 index 0000000..0a15853 --- /dev/null +++ b/base/src/main/java/org/eptalist/metrics/SingleLineChart.java @@ -0,0 +1,29 @@ +package org.eptalist.metrics; + +import java.util.concurrent.Callable; + +public class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObjectBuilder.JsonObject getChartData() throws Exception { + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } +} \ No newline at end of file diff --git a/base/src/main/java/org/eptalist/storge/Mysql.java b/base/src/main/java/org/eptalist/storge/Mysql.java index 6e13011..49a901b 100644 --- a/base/src/main/java/org/eptalist/storge/Mysql.java +++ b/base/src/main/java/org/eptalist/storge/Mysql.java @@ -8,13 +8,18 @@ import java.util.Map; public class Mysql implements Data { public Connection connection; public Map data; + public String teable; + public String i; public Mysql(Map data) { this.data = data; + final String teable_profix = data.containsKey("prefix") ? "eptalist" : (String) data.get("prefix"); + this.teable = data.containsKey("teable") ? teable_profix+"_users" : teable_profix+data.get("teable"); + this.i = data.containsKey("t") ? "username" : (String) data.get("t"); try { Class.forName("com.mysql.cj.jdbc.Driver"); connection = DriverManager.getConnection((String) this.data.get("file")); try (Statement statement = connection.createStatement()) { - statement.executeUpdate("CREATE TABLE IF NOT EXISTS users (username VARCHAR(255) PRIMARY KEY)"); + statement.executeUpdate("CREATE TABLE IF NOT EXISTS "+this.teable+" ("+this.i+" VARCHAR(255) PRIMARY KEY)"); } } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); @@ -27,7 +32,7 @@ public class Mysql implements Data { return false; } try { - PreparedStatement statement = connection.prepareStatement("DELETE FROM users WHERE username = ?"); + PreparedStatement statement = connection.prepareStatement("DELETE FROM "+this.teable+" WHERE "+this.i+" = ?"); statement.setString(1, name); return statement.executeUpdate() > 0; } catch (SQLException e) { @@ -43,7 +48,7 @@ public class Mysql implements Data { return false; } try { - PreparedStatement statement = connection.prepareStatement("DELETE FROM users WHERE username = ?"); + PreparedStatement statement = connection.prepareStatement("DELETE FROM "+this.teable+" WHERE "+this.i+" = ?"); statement.setString(1, name); return statement.executeUpdate() > 0; } catch (SQLException e) { @@ -60,7 +65,7 @@ public class Mysql implements Data { connection = DriverManager.getConnection(String.format((String) this.data.get("file"))); info.add("&6The database has been reconnected"); } - PreparedStatement statement = connection.prepareStatement("SELECT user_name FROM users WHERE username = ?"); + PreparedStatement statement = connection.prepareStatement("SELECT user_name FROM "+this.teable+" WHERE "+this.i+" = ?"); statement.setString(1, name); ResultSet resultSet = statement.executeQuery(); return resultSet.next(); @@ -77,7 +82,7 @@ public class Mysql implements Data { if (connection.isClosed()) { connection = DriverManager.getConnection((String) this.data.get("file")); } - PreparedStatement statement = connection.prepareStatement("SELECT username FROM users WHERE username = ?"); + PreparedStatement statement = connection.prepareStatement("SELECT username FROM "+this.teable+" WHERE "+this.i+" = ?"); statement.setString(1, name); ResultSet resultSet = statement.executeQuery(); return resultSet.next(); @@ -94,7 +99,7 @@ public class Mysql implements Data { return false; } try { - PreparedStatement statement = connection.prepareStatement("INSERT INTO users (username) VALUES (?)"); + PreparedStatement statement = connection.prepareStatement("INSERT INTO "+this.teable+" ("+this.i+") VALUES (?)"); statement.setString(1, name); return statement.executeUpdate() > 0; } catch (SQLException e) { @@ -110,7 +115,7 @@ public class Mysql implements Data { return false; } try { - PreparedStatement statement = connection.prepareStatement("INSERT INTO users (username) VALUES (?)"); + PreparedStatement statement = connection.prepareStatement("INSERT INTO "+this.teable+" ("+this.i+") VALUES (?)"); statement.setString(1, name); return statement.executeUpdate() > 0; } catch (SQLException e) { @@ -139,11 +144,11 @@ public class Mysql implements Data { if (connection.isClosed()) { connection = DriverManager.getConnection((String) this.data.get("file")); } - String sql = "SELECT username FROM users"; + String sql = "SELECT "+this.i+" FROM "+this.teable; Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { - players.add(rs.getString("username")); + players.add(rs.getString(this.i)); } rs.close(); stmt.close(); diff --git a/base/src/main/java/org/eptalist/storge/Sqlite.java b/base/src/main/java/org/eptalist/storge/Sqlite.java index 9008801..71a73e7 100644 --- a/base/src/main/java/org/eptalist/storge/Sqlite.java +++ b/base/src/main/java/org/eptalist/storge/Sqlite.java @@ -9,12 +9,18 @@ public class Sqlite implements Data { public Connection connection; public Map data; + public String teable; + public String i; public Sqlite(Map data) { this.data = data; + final String teable_profix = data.containsKey("prefix") ? "eptalist" : (String) data.get("prefix"); + this.teable = data.containsKey("teable") ? teable_profix+"_users" : teable_profix+data.get("teable"); + this.i = data.containsKey("t") ? "username" : (String) data.get("t"); + try { connection = DriverManager.getConnection(String.format("jdbc:sqlite:%s.db", (String) this.data.get("file"))); try (Statement statement = connection.createStatement()) { - statement.executeUpdate("CREATE TABLE IF NOT EXISTS users (user_name VARCHAR(255) PRIMARY KEY)"); + statement.executeUpdate("CREATE TABLE IF NOT EXISTS "+this.teable+" ("+this.i+" VARCHAR(255) PRIMARY KEY)"); } } catch (SQLException e) { e.printStackTrace(); @@ -27,7 +33,7 @@ public class Sqlite implements Data { return false; } try { - PreparedStatement statement = connection.prepareStatement("DELETE FROM users WHERE user_name = ?"); + PreparedStatement statement = connection.prepareStatement("DELETE FROM "+this.teable+" WHERE "+this.i+" = ?"); statement.setString(1, name); return statement.executeUpdate() > 0; } catch (SQLException e) { @@ -43,7 +49,7 @@ public class Sqlite implements Data { return false; } try { - PreparedStatement statement = connection.prepareStatement("DELETE FROM users WHERE user_name = ?"); + PreparedStatement statement = connection.prepareStatement("DELETE FROM "+this.teable+" WHERE "+this.i+" = ?"); statement.setString(1, name); return statement.executeUpdate() > 0; } catch (SQLException e) { @@ -60,7 +66,7 @@ public class Sqlite implements Data { connection = DriverManager.getConnection(String.format("jdbc:sqlite:%s.db", (String) this.data.get("file"))); info.add("&6The database has been reconnected"); } - PreparedStatement statement = connection.prepareStatement("SELECT user_name FROM users WHERE user_name = ?"); + PreparedStatement statement = connection.prepareStatement("SELECT "+this.i+" FROM "+this.teable+" WHERE "+this.i+" = ?"); statement.setString(1, name); ResultSet resultSet = statement.executeQuery(); return resultSet.next(); @@ -77,7 +83,7 @@ public class Sqlite implements Data { if (connection.isClosed()) { connection = DriverManager.getConnection(String.format("jdbc:sqlite:%s.db", (String) this.data.get("file"))); } - PreparedStatement statement = connection.prepareStatement("SELECT user_name FROM users WHERE user_name = ?"); + PreparedStatement statement = connection.prepareStatement("SELECT "+this.i+" FROM "+this.teable+" WHERE "+this.i+" = ?"); statement.setString(1, name); ResultSet resultSet = statement.executeQuery(); return resultSet.next(); @@ -94,7 +100,7 @@ public class Sqlite implements Data { return false; } try { - PreparedStatement statement = connection.prepareStatement("INSERT INTO users (user_name) VALUES (?)"); + PreparedStatement statement = connection.prepareStatement("INSERT INTO "+this.teable+" ("+this.i+") VALUES (?)"); statement.setString(1, name); return statement.executeUpdate() > 0; } catch (SQLException e) { @@ -110,7 +116,7 @@ public class Sqlite implements Data { return false; } try { - PreparedStatement statement = connection.prepareStatement("INSERT INTO users (user_name) VALUES (?)"); + PreparedStatement statement = connection.prepareStatement("INSERT INTO "+this.teable+" ("+this.i+") VALUES (?)"); statement.setString(1, name); return statement.executeUpdate() > 0; } catch (SQLException e) { @@ -139,11 +145,11 @@ public class Sqlite implements Data { if (connection.isClosed()) { connection = DriverManager.getConnection(String.format("jdbc:sqlite:%s.db", (String) this.data.get("file"))); } - String sql = "SELECT user_name FROM users"; + String sql = "SELECT "+this.i+" FROM "+this.teable; Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { - players.add(rs.getString("name")); + players.add(rs.getString(this.i)); } rs.close(); stmt.close(); diff --git a/base/src/main/resources/updater.json b/base/src/main/resources/updater.json new file mode 100644 index 0000000..81c8ee5 --- /dev/null +++ b/base/src/main/resources/updater.json @@ -0,0 +1,4 @@ +{ + "id": "122225", + "source": "https://github.com/p2vman/EptaListProject" +} \ No newline at end of file diff --git a/boungecord/build.gradle b/boungecord/build.gradle index 05be848..5b5a959 100644 --- a/boungecord/build.gradle +++ b/boungecord/build.gradle @@ -1,7 +1,7 @@ apply plugin: 'java' group = 'org.eg4rerer' -version = '1.3' +version = '1.4' repositories { mavenCentral() diff --git a/boungecord/src/main/java/org/eptalist/bounge/Boungecord.java b/boungecord/src/main/java/org/eptalist/bounge/Boungecord.java index 4e3866b..47309b8 100644 --- a/boungecord/src/main/java/org/eptalist/bounge/Boungecord.java +++ b/boungecord/src/main/java/org/eptalist/bounge/Boungecord.java @@ -1,12 +1,19 @@ package org.eptalist.bounge; +import com.google.gson.JsonObject; import io.github.p2vman.Identifier; +import io.github.p2vman.Static; import io.github.p2vman.profiling.ExempleProfiler; import io.github.p2vman.profiling.Profiler; +import io.github.p2vman.updater.Updater; import net.md_5.bungee.api.plugin.Plugin; import org.eptalist.Config; +import org.eptalist.Constants; +import org.eptalist.bounge.metrics.Metrics; +import org.eptalist.metrics.SimplePie; import org.eptalist.storge.Data; +import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -44,6 +51,30 @@ public final class Boungecord extends Plugin { @Override public void onEnable() { + try { + Updater updater = Updater.getInstance(); + JsonObject obj = updater.getLasted(); + if (!getDescription().getVersion().equals(obj.get("name").getAsString())) { + LOGGER.log(Level.WARNING, "---------- Outdated Version ----------"); + LOGGER.log(Level.WARNING, ""); + LOGGER.log(Level.WARNING, "new version:"); + LOGGER.log(Level.WARNING, updater.getVersionUrl()); + LOGGER.log(Level.WARNING, ""); + LOGGER.log(Level.WARNING, "---------------------------------"); + } + } catch (Exception e) { + e.printStackTrace(); + } + File data = getDataFolder(); + if (!data.exists()) { + data.mkdirs(); + } + config = new Config.ConfigContainer(new File(data, "wh.json")); + + load(); + Metrics metrics = new Metrics(this, Constants.bstats_id); + + metrics.addCustomChart(new SimplePie("data_type", () -> mode.storage)); getProxy().getPluginManager().registerListener(this, new Event()); this.getProxy().getPluginManager().registerCommand(this, new WhiteListCommand()); } diff --git a/boungecord/src/main/java/org/eptalist/bounge/metrics/Metrics.java b/boungecord/src/main/java/org/eptalist/bounge/metrics/Metrics.java new file mode 100644 index 0000000..324d218 --- /dev/null +++ b/boungecord/src/main/java/org/eptalist/bounge/metrics/Metrics.java @@ -0,0 +1,400 @@ +package org.eptalist.bounge.metrics; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; +import javax.net.ssl.HttpsURLConnection; +import net.md_5.bungee.api.plugin.Plugin; +import net.md_5.bungee.config.Configuration; +import net.md_5.bungee.config.ConfigurationProvider; +import net.md_5.bungee.config.YamlConfiguration; +import org.eptalist.metrics.CustomChart; +import org.eptalist.metrics.JsonObjectBuilder; + +public class Metrics { + + private final Plugin plugin; + + private final MetricsBase metricsBase; + + private boolean enabled; + + private String serverUUID; + + private boolean logErrors = false; + + private boolean logSentData; + + private boolean logResponseStatusText; + + /** + * Creates a new Metrics instance. + * + * @param plugin Your plugin instance. + * @param serviceId The id of the service. It can be found at What is my plugin id? + */ + public Metrics(Plugin plugin, int serviceId) { + this.plugin = plugin; + try { + loadConfig(); + } catch (IOException e) { + // Failed to load configuration + plugin.getLogger().log(Level.WARNING, "Failed to load bStats config!", e); + metricsBase = null; + return; + } + metricsBase = + new MetricsBase( + "bungeecord", + serverUUID, + serviceId, + enabled, + this::appendPlatformData, + this::appendServiceData, + null, + () -> true, + (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), + (message) -> this.plugin.getLogger().log(Level.INFO, message), + logErrors, + logSentData, + logResponseStatusText, + false); + } + + /** Loads the bStats configuration. */ + private void loadConfig() throws IOException { + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + bStatsFolder.mkdirs(); + File configFile = new File(bStatsFolder, "config.yml"); + if (!configFile.exists()) { + writeFile( + configFile, + "# bStats (https://bStats.org) collects some basic information for plugin authors, like how", + "# many people use their plugin and their total player count. It's recommended to keep bStats", + "# enabled, but if you're not comfortable with this, you can turn this setting off. There is no", + "# performance penalty associated with having metrics enabled, and data sent to bStats is fully", + "# anonymous.", + "enabled: true", + "serverUuid: \"" + UUID.randomUUID() + "\"", + "logFailedRequests: false", + "logSentData: false", + "logResponseStatusText: false"); + } + Configuration configuration = + ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile); + // Load configuration + enabled = configuration.getBoolean("enabled", true); + serverUUID = configuration.getString("serverUuid"); + logErrors = configuration.getBoolean("logFailedRequests", false); + logSentData = configuration.getBoolean("logSentData", false); + logResponseStatusText = configuration.getBoolean("logResponseStatusText", false); + } + + private void writeFile(File file, String... lines) throws IOException { + try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file))) { + for (String line : lines) { + bufferedWriter.write(line); + bufferedWriter.newLine(); + } + } + } + + /** Shuts down the underlying scheduler service. */ + public void shutdown() { + metricsBase.shutdown(); + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + metricsBase.addCustomChart(chart); + } + + private void appendPlatformData(JsonObjectBuilder builder) { + builder.appendField("playerAmount", plugin.getProxy().getOnlineCount()); + builder.appendField("managedServers", plugin.getProxy().getServers().size()); + builder.appendField("onlineMode", plugin.getProxy().getConfig().isOnlineMode() ? 1 : 0); + builder.appendField("bungeecordVersion", plugin.getProxy().getVersion()); + builder.appendField("bungeecordName", plugin.getProxy().getName()); + builder.appendField("javaVersion", System.getProperty("java.version")); + builder.appendField("osName", System.getProperty("os.name")); + builder.appendField("osArch", System.getProperty("os.arch")); + builder.appendField("osVersion", System.getProperty("os.version")); + builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); + } + + private void appendServiceData(JsonObjectBuilder builder) { + builder.appendField("pluginVersion", plugin.getDescription().getVersion()); + } + + public static class MetricsBase { + + /** The version of the Metrics class. */ + public static final String METRICS_VERSION = "3.1.0"; + + private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; + + private final ScheduledExecutorService scheduler; + + private final String platform; + + private final String serverUuid; + + private final int serviceId; + + private final Consumer appendPlatformDataConsumer; + + private final Consumer appendServiceDataConsumer; + + private final Consumer submitTaskConsumer; + + private final Supplier checkServiceEnabledSupplier; + + private final BiConsumer errorLogger; + + private final Consumer infoLogger; + + private final boolean logErrors; + + private final boolean logSentData; + + private final boolean logResponseStatusText; + + private final Set customCharts = new HashSet<>(); + + private final boolean enabled; + + /** + * Creates a new MetricsBase class instance. + * + * @param platform The platform of the service. + * @param serviceId The id of the service. + * @param serverUuid The server uuid. + * @param enabled Whether or not data sending is enabled. + * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all platform-specific data. + * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all service-specific data. + * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be + * used to delegate the data collection to a another thread to prevent errors caused by + * concurrency. Can be {@code null}. + * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. + * @param errorLogger A consumer that accepts log message and an error. + * @param infoLogger A consumer that accepts info log messages. + * @param logErrors Whether or not errors should be logged. + * @param logSentData Whether or not the sent data should be logged. + * @param logResponseStatusText Whether or not the response status text should be logged. + * @param skipRelocateCheck Whether or not the relocate check should be skipped. + */ + public MetricsBase( + String platform, + String serverUuid, + int serviceId, + boolean enabled, + Consumer appendPlatformDataConsumer, + Consumer appendServiceDataConsumer, + Consumer submitTaskConsumer, + Supplier checkServiceEnabledSupplier, + BiConsumer errorLogger, + Consumer infoLogger, + boolean logErrors, + boolean logSentData, + boolean logResponseStatusText, + boolean skipRelocateCheck) { + ScheduledThreadPoolExecutor scheduler = + new ScheduledThreadPoolExecutor( + 1, + task -> { + Thread thread = new Thread(task, "bStats-Metrics"); + thread.setDaemon(true); + return thread; + }); + // We want delayed tasks (non-periodic) that will execute in the future to be + // cancelled when the scheduler is shutdown. + // Otherwise, we risk preventing the server from shutting down even when + // MetricsBase#shutdown() is called + scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + this.scheduler = scheduler; + this.platform = platform; + this.serverUuid = serverUuid; + this.serviceId = serviceId; + this.enabled = enabled; + this.appendPlatformDataConsumer = appendPlatformDataConsumer; + this.appendServiceDataConsumer = appendServiceDataConsumer; + this.submitTaskConsumer = submitTaskConsumer; + this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; + this.errorLogger = errorLogger; + this.infoLogger = infoLogger; + this.logErrors = logErrors; + this.logSentData = logSentData; + this.logResponseStatusText = logResponseStatusText; + if (!skipRelocateCheck) { + checkRelocation(); + } + if (enabled) { + // WARNING: Removing the option to opt-out will get your plugin banned from + // bStats + startSubmitting(); + } + } + + public void addCustomChart(CustomChart chart) { + this.customCharts.add(chart); + } + + public void shutdown() { + scheduler.shutdown(); + } + + private void startSubmitting() { + final Runnable submitTask = + () -> { + if (!enabled || !checkServiceEnabledSupplier.get()) { + // Submitting data or service is disabled + scheduler.shutdown(); + return; + } + if (submitTaskConsumer != null) { + submitTaskConsumer.accept(this::submitData); + } else { + this.submitData(); + } + }; + // Many servers tend to restart at a fixed time at xx:00 which causes an uneven + // distribution of requests on the + // bStats backend. To circumvent this problem, we introduce some randomness into + // the initial and second delay. + // WARNING: You must not modify and part of this Metrics class, including the + // submit delay or frequency! + // WARNING: Modifying this code will get your plugin banned on bStats. Just + // don't do it! + long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); + long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); + scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); + scheduler.scheduleAtFixedRate( + submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); + } + + private void submitData() { + final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); + appendPlatformDataConsumer.accept(baseJsonBuilder); + final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); + appendServiceDataConsumer.accept(serviceJsonBuilder); + JsonObjectBuilder.JsonObject[] chartData = + customCharts.stream() + .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) + .filter(Objects::nonNull) + .toArray(JsonObjectBuilder.JsonObject[]::new); + serviceJsonBuilder.appendField("id", serviceId); + serviceJsonBuilder.appendField("customCharts", chartData); + baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); + baseJsonBuilder.appendField("serverUUID", serverUuid); + baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); + JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); + scheduler.execute( + () -> { + try { + // Send the data + sendData(data); + } catch (Exception e) { + // Something went wrong! :( + if (logErrors) { + errorLogger.accept("Could not submit bStats metrics data", e); + } + } + }); + } + + private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { + if (logSentData) { + infoLogger.accept("Sent bStats metrics data: " + data.toString()); + } + String url = String.format(REPORT_URL, platform); + HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("User-Agent", "Metrics-Service/1"); + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + 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) { + infoLogger.accept("Sent data to bStats and received response: " + builder); + } + } + + /** Checks that the class was properly relocated. */ + private void checkRelocation() { + // 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'}); + final String examplePackage = + new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure no one just copy & pastes the example and uses the wrong + // package names + if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) + || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + /** + * Gzips the given string. + * + * @param str The string to gzip. + * @return The gzipped string. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + } +} \ No newline at end of file diff --git a/boungecord/src/main/resources/bungee.yml b/boungecord/src/main/resources/bungee.yml index 7737e3a..cc4b05c 100644 --- a/boungecord/src/main/resources/bungee.yml +++ b/boungecord/src/main/resources/bungee.yml @@ -1,3 +1,3 @@ -name: boungecord -version: '1.3' -main: org.eg4rerer.boungecord.Boungecord +name: EptaList +version: '1.4' +main: org.eptalist.bounge.Boungecord \ No newline at end of file diff --git a/build.gradle b/build.gradle index 76dc7ac..e4c17ea 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,18 @@ + plugins { id 'java' + id 'de.undercouch.download' version '5.4.0' apply false } +import de.undercouch.gradle.tasks.download.Download + +subprojects { + tasks.withType(JavaCompile) { + options.encoding = "UTF-8" + } +} + + allprojects { repositories { mavenCentral() @@ -12,20 +23,33 @@ allprojects { } } -version = "1.3" +version = "1.4" task mergePlugins(type: Jar) { + def io = it archiveBaseName = 'EptaList' archiveVersion = version + def projects = [':base', ':velocity', ':spigot', ":boungecord"] + def jars = { + def jr = [] + projects.forEach { + evaluationDependsOn(it) + def task = project(it).tasks.named('jar') + dependsOn task + jr.add(task.get().archiveFile.get()) + } + return jr + } + def jarPaths = [ - "C:\\Users\\User\\IdeaProjects\\EptaListProject\\velocity\\build\\libs\\velocity-"+version+".jar", - "C:\\Users\\User\\IdeaProjects\\EptaListProject\\spigot\\build\\libs\\spigot-"+version+".jar", - "C:\\Users\\User\\IdeaProjects\\EptaListProject\\base\\build\\libs\\base-"+version+".jar", - "C:\\Users\\User\\IdeaProjects\\EptaListProject\\boungecord\\build\\libs\\boungecord-"+version+".jar" + "D:\\Users\\User\\IdeaProjects\\EptaListProject\\velocity\\build\\libs\\velocity-"+version+".jar", + "D:\\Users\\User\\IdeaProjects\\EptaListProject\\spigot\\build\\libs\\spigot-"+version+".jar", + "D:\\Users\\User\\IdeaProjects\\EptaListProject\\base\\build\\libs\\base-"+version+".jar", + "D:\\Users\\User\\IdeaProjects\\EptaListProject\\boungecord\\build\\libs\\boungecord-"+version+".jar" ] - from jarPaths.collect { zipTree(it) } + from jars().collect { zipTree(it) } duplicatesStrategy = DuplicatesStrategy.INCLUDE } @@ -33,4 +57,41 @@ task mergePlugins(type: Jar) { task mergeALL() { dependsOn mergePlugins +} + +tasks.register('downloadBungeeCord', Download) { + src 'https://ci.md-5.net/job/BungeeCord/lastSuccessfulBuild/artifact/bootstrap/target/BungeeCord.jar' + dest file("$buildDir/downloads/BungeeCord.jar") + overwrite false +} + +tasks.register("RunBungeeCord") { + dependsOn mergeALL + dependsOn 'downloadBungeeCord' + + def jarFile = file("$buildDir/libs/EptaList-${version}.jar") + def targetDir = file("$buildDir/run/plugins") + + + def jarFile2 = file("$buildDir/run/plugins/EptaList-${version}.jar") + if (jarFile2.exists()) { + jarFile2.delete() + } + + targetDir.mkdirs() + copy { + from jarFile + into targetDir + } + + targetDir = file("$buildDir/run") + jarFile = file("$buildDir/downloads/BungeeCord.jar") + + doLast { + javaexec { + workingDir = targetDir + mainClass = '-jar' + args = [jarFile] + } + } } \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index da156eb..14f2595 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,4 +1,2 @@ rootProject.name = 'EptaListProject' -include ':base', ':velocity', ':spigot', ":boungecord" -include 'ModuleLoader:ExempleModule' -findProject(':ModuleLoader:ExempleModule')?.name = 'ExempleModule' \ No newline at end of file +include ':base', ':velocity', ':spigot', ":boungecord" \ No newline at end of file diff --git a/spigot/build.gradle b/spigot/build.gradle index 5382e8d..db94e55 100644 --- a/spigot/build.gradle +++ b/spigot/build.gradle @@ -3,7 +3,7 @@ plugins { } group = 'org.eg4rerer' -version = "1.3" +version = "1.4" repositories { mavenCentral() diff --git a/spigot/src/main/java/org/eptalist/spigot/EptaList.java b/spigot/src/main/java/org/eptalist/spigot/EptaList.java index e58665b..8f15f8f 100644 --- a/spigot/src/main/java/org/eptalist/spigot/EptaList.java +++ b/spigot/src/main/java/org/eptalist/spigot/EptaList.java @@ -1,18 +1,18 @@ package org.eptalist.spigot; -import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonObject; import io.github.p2vman.profiling.ExempleProfiler; import io.github.p2vman.profiling.Profiler; +import io.github.p2vman.updater.Updater; import org.eptalist.Config; import io.github.p2vman.Identifier; import org.eptalist.Constants; +import org.eptalist.metrics.SimplePie; import org.eptalist.spigot.metrics.Metrics; import org.eptalist.storge.Data; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandMap; -import org.bukkit.permissions.Permission; -import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; @@ -57,6 +57,22 @@ public final class EptaList extends JavaPlugin { @Override public void onEnable() { + try { + Updater updater = Updater.getInstance(); + JsonObject obj = updater.getLasted(); + if (!getDescription().getVersion().equals(obj.get("name").getAsString())) { + LOGGER.log(Level.WARNING, "---------- Outdated Version ----------"); + LOGGER.log(Level.WARNING, ""); + LOGGER.log(Level.WARNING, "new version:"); + LOGGER.log(Level.WARNING, updater.getVersionUrl()); + LOGGER.log(Level.WARNING, ""); + LOGGER.log(Level.WARNING, "---------------------------------"); + } + } catch (Exception e) { + e.printStackTrace(); + } + + profiler.push("init"); metrics = new Metrics(this, Constants.bstats_id); @@ -80,7 +96,7 @@ public final class EptaList extends JavaPlugin { } getServer().getPluginManager().registerEvents(new Event(), this); - metrics.addCustomChart(new Metrics.SimplePie("data_type", () -> mode.storage)); + metrics.addCustomChart(new SimplePie("data_type", () -> mode.storage)); LOGGER.log(Level.INFO, String.format("Init Plugin %sms", profiler.getElapsedTimeAndRemove(profiler.pop()))); } diff --git a/spigot/src/main/java/org/eptalist/spigot/metrics/Metrics.java b/spigot/src/main/java/org/eptalist/spigot/metrics/Metrics.java index 15cedf4..c38bbf0 100644 --- a/spigot/src/main/java/org/eptalist/spigot/metrics/Metrics.java +++ b/spigot/src/main/java/org/eptalist/spigot/metrics/Metrics.java @@ -1,22 +1,18 @@ package org.eptalist.spigot.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 org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.eptalist.metrics.CustomChart; +import org.eptalist.metrics.JsonObjectBuilder; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; import java.lang.reflect.Method; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.Callable; +import java.util.*; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; @@ -24,13 +20,7 @@ import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Level; -import java.util.stream.Collectors; import java.util.zip.GZIPOutputStream; -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; public class Metrics { @@ -402,490 +392,4 @@ public class Metrics { return outputStream.toByteArray(); } } - - public static class AdvancedBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class SimplePie extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimplePie(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - String value = callable.call(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("value", value).build(); - } - } - - public static class DrilldownPie extends CustomChart { - - private final Callable>> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public DrilldownPie(String chartId, Callable>> callable) { - super(chartId); - this.callable = callable; - } - - @Override - public JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map> map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); - boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if (!allSkipped) { - reallyAllSkipped = false; - valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); - } - } - if (reallyAllSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class SingleLineChart extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SingleLineChart(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - int value = callable.call(); - if (value == 0) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("value", value).build(); - } - } - - public static class MultiLineChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public MultiLineChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class AdvancedPie extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedPie(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public abstract static class CustomChart { - - private final String chartId; - - protected CustomChart(String chartId) { - if (chartId == null) { - throw new IllegalArgumentException("chartId must not be null"); - } - this.chartId = chartId; - } - - public JsonObjectBuilder.JsonObject getRequestJsonObject( - BiConsumer errorLogger, boolean logErrors) { - JsonObjectBuilder builder = new JsonObjectBuilder(); - builder.appendField("chartId", chartId); - try { - JsonObjectBuilder.JsonObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - builder.appendField("data", data); - } catch (Throwable t) { - if (logErrors) { - errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return builder.build(); - } - - protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception; - } - - public static class SimpleBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimpleBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()}); - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - /** - * An extremely simple JSON builder. - * - *

While this class is neither feature-rich nor the most performant one, it's sufficient enough - * for its use-case. - */ - public static class JsonObjectBuilder { - - private StringBuilder builder = new StringBuilder(); - - private boolean hasAtLeastOneField = false; - - public JsonObjectBuilder() { - builder.append("{"); - } - - /** - * Appends a null field to the JSON. - * - * @param key The key of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendNull(String key) { - appendFieldUnescaped(key, "null"); - return this; - } - - /** - * Appends a string field to the JSON. - * - * @param key The key of the field. - * @param value The value of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, String value) { - if (value == null) { - throw new IllegalArgumentException("JSON value must not be null"); - } - appendFieldUnescaped(key, "\"" + escape(value) + "\""); - return this; - } - - /** - * Appends an integer field to the JSON. - * - * @param key The key of the field. - * @param value The value of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, int value) { - appendFieldUnescaped(key, String.valueOf(value)); - return this; - } - - /** - * Appends an object to the JSON. - * - * @param key The key of the field. - * @param object The object. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, JsonObject object) { - if (object == null) { - throw new IllegalArgumentException("JSON object must not be null"); - } - appendFieldUnescaped(key, object.toString()); - return this; - } - - /** - * Appends a string array to the JSON. - * - * @param key The key of the field. - * @param values The string array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, String[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values) - .map(value -> "\"" + escape(value) + "\"") - .collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends an integer array to the JSON. - * - * @param key The key of the field. - * @param values The integer array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, int[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends an object array to the JSON. - * - * @param key The key of the field. - * @param values The integer array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, JsonObject[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends a field to the object. - * - * @param key The key of the field. - * @param escapedValue The escaped value of the field. - */ - private void appendFieldUnescaped(String key, String escapedValue) { - if (builder == null) { - throw new IllegalStateException("JSON has already been built"); - } - if (key == null) { - throw new IllegalArgumentException("JSON key must not be null"); - } - if (hasAtLeastOneField) { - builder.append(","); - } - builder.append("\"").append(escape(key)).append("\":").append(escapedValue); - hasAtLeastOneField = true; - } - - /** - * Builds the JSON string and invalidates this builder. - * - * @return The built JSON string. - */ - public JsonObject build() { - if (builder == null) { - throw new IllegalStateException("JSON has already been built"); - } - JsonObject object = new JsonObject(builder.append("}").toString()); - builder = null; - return object; - } - - /** - * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. - * - *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. - * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). - * - * @param value The value to escape. - * @return The escaped value. - */ - private static String escape(String value) { - final StringBuilder builder = new StringBuilder(); - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - if (c == '"') { - builder.append("\\\""); - } else if (c == '\\') { - builder.append("\\\\"); - } else if (c <= '\u000F') { - builder.append("\\u000").append(Integer.toHexString(c)); - } else if (c <= '\u001F') { - builder.append("\\u00").append(Integer.toHexString(c)); - } else { - builder.append(c); - } - } - return builder.toString(); - } - - /** - * A super simple representation of a JSON object. - * - *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not - * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, - * JsonObject)}. - */ - public static class JsonObject { - - private final String value; - - private JsonObject(String value) { - this.value = value; - } - - @Override - public String toString() { - return value; - } - } - } } \ No newline at end of file diff --git a/spigot/src/main/resources/plugin.yml b/spigot/src/main/resources/plugin.yml index 1321579..5ddfec7 100644 --- a/spigot/src/main/resources/plugin.yml +++ b/spigot/src/main/resources/plugin.yml @@ -1,3 +1,5 @@ name: EptaList -version: "1.2" +version: "1.4" main: org.eptalist.spigot.EptaList +softdepend: + - ModuleLoader \ No newline at end of file diff --git a/velocity/build.gradle b/velocity/build.gradle index da4c860..ade5155 100644 --- a/velocity/build.gradle +++ b/velocity/build.gradle @@ -5,7 +5,7 @@ plugins { } group = 'org.eg4rerer' -version = "1.3" +version = "1.4" repositories { mavenCentral() diff --git a/velocity/src/main/java/org/eptalist/velocity/Velocity.java b/velocity/src/main/java/org/eptalist/velocity/Velocity.java index f4ae95d..c467206 100644 --- a/velocity/src/main/java/org/eptalist/velocity/Velocity.java +++ b/velocity/src/main/java/org/eptalist/velocity/Velocity.java @@ -1,6 +1,6 @@ package org.eptalist.velocity; -import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonObject; import com.google.inject.Inject; import com.velocitypowered.api.command.CommandManager; import com.velocitypowered.api.event.ResultedEvent; @@ -13,9 +13,11 @@ import com.velocitypowered.api.proxy.ProxyServer; import io.github.p2vman.Identifier; import io.github.p2vman.profiling.ExempleProfiler; import io.github.p2vman.profiling.Profiler; +import io.github.p2vman.updater.Updater; import net.kyori.adventure.text.Component; import org.eptalist.Config; import org.eptalist.Constants; +import org.eptalist.metrics.SimplePie; import org.eptalist.storge.Data; import org.eptalist.velocity.metrics.Metrics; import org.slf4j.Logger; @@ -28,7 +30,7 @@ import java.util.List; import java.util.Map; import java.util.logging.Level; -@Plugin(id = "velocity", name = "velocity", version = BuildConstants.VERSION) +@Plugin(id = "eptalist", name = "Eptalist", version = BuildConstants.VERSION) public class Velocity { private static Metrics metrics; public static final Profiler profiler = new ExempleProfiler(); @@ -66,6 +68,20 @@ public class Velocity { @Inject public Velocity(ProxyServer server, @DataDirectory Path dataDirectory, Metrics.Factory metricsFactory) { + try { + Updater updater = Updater.getInstance(); + JsonObject obj = updater.getLasted(); + if (!BuildConstants.VERSION.equals(obj.get("name").getAsString())) { + LOGGER.log(Level.WARNING, "---------- Outdated Version ----------"); + LOGGER.log(Level.WARNING, ""); + LOGGER.log(Level.WARNING, "new version:"); + LOGGER.log(Level.WARNING, updater.getVersionUrl()); + LOGGER.log(Level.WARNING, ""); + LOGGER.log(Level.WARNING, "---------------------------------"); + } + } catch (Exception e) { + e.printStackTrace(); + } profiler.push("init"); this.metricsFactory = metricsFactory; this.dataDirectory = dataDirectory; @@ -83,13 +99,13 @@ public class Velocity { public void onProxyInitialization(ProxyInitializeEvent event) { Metrics metrics = metricsFactory.make(this, Constants.bstats_id); - metrics.addCustomChart(new Metrics.SimplePie("data_type", () -> mode.storage)); + metrics.addCustomChart(new SimplePie("data_type", () -> mode.storage)); } @Subscribe public void onLogin(LoginEvent event) { if (list.is(event.getPlayer().getUsername())) { - event.setResult(ResultedEvent.ComponentResult.denied(Component.text(""))); + event.setResult(ResultedEvent.ComponentResult.denied(Component.text(mode.kick_msg))); } } } diff --git a/velocity/src/main/java/org/eptalist/velocity/metrics/Metrics.java b/velocity/src/main/java/org/eptalist/velocity/metrics/Metrics.java index f22eba6..7c99ebf 100644 --- a/velocity/src/main/java/org/eptalist/velocity/metrics/Metrics.java +++ b/velocity/src/main/java/org/eptalist/velocity/metrics/Metrics.java @@ -20,28 +20,16 @@ import com.velocitypowered.api.plugin.PluginContainer; import com.velocitypowered.api.plugin.PluginDescription; import com.velocitypowered.api.plugin.annotation.DataDirectory; import com.velocitypowered.api.proxy.ProxyServer; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; +import org.eptalist.metrics.CustomChart; +import org.eptalist.metrics.JsonObjectBuilder; +import org.slf4j.Logger; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.Callable; +import java.util.*; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; @@ -51,8 +39,6 @@ import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.zip.GZIPOutputStream; -import javax.net.ssl.HttpsURLConnection; -import org.slf4j.Logger; public class Metrics { @@ -425,492 +411,6 @@ public class Metrics { } } - public static class AdvancedBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class SimplePie extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimplePie(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - String value = callable.call(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("value", value).build(); - } - } - - public static class DrilldownPie extends CustomChart { - - private final Callable>> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public DrilldownPie(String chartId, Callable>> callable) { - super(chartId); - this.callable = callable; - } - - @Override - public JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map> map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); - boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if (!allSkipped) { - reallyAllSkipped = false; - valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); - } - } - if (reallyAllSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class SingleLineChart extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SingleLineChart(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - int value = callable.call(); - if (value == 0) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("value", value).build(); - } - } - - public static class MultiLineChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public MultiLineChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class AdvancedPie extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedPie(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public abstract static class CustomChart { - - private final String chartId; - - protected CustomChart(String chartId) { - if (chartId == null) { - throw new IllegalArgumentException("chartId must not be null"); - } - this.chartId = chartId; - } - - public JsonObjectBuilder.JsonObject getRequestJsonObject( - BiConsumer errorLogger, boolean logErrors) { - JsonObjectBuilder builder = new JsonObjectBuilder(); - builder.appendField("chartId", chartId); - try { - JsonObjectBuilder.JsonObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - builder.appendField("data", data); - } catch (Throwable t) { - if (logErrors) { - errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return builder.build(); - } - - protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception; - } - - public static class SimpleBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimpleBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()}); - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - /** - * An extremely simple JSON builder. - * - *

While this class is neither feature-rich nor the most performant one, it's sufficient enough - * for its use-case. - */ - public static class JsonObjectBuilder { - - private StringBuilder builder = new StringBuilder(); - - private boolean hasAtLeastOneField = false; - - public JsonObjectBuilder() { - builder.append("{"); - } - - /** - * Appends a null field to the JSON. - * - * @param key The key of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendNull(String key) { - appendFieldUnescaped(key, "null"); - return this; - } - - /** - * Appends a string field to the JSON. - * - * @param key The key of the field. - * @param value The value of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, String value) { - if (value == null) { - throw new IllegalArgumentException("JSON value must not be null"); - } - appendFieldUnescaped(key, "\"" + escape(value) + "\""); - return this; - } - - /** - * Appends an integer field to the JSON. - * - * @param key The key of the field. - * @param value The value of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, int value) { - appendFieldUnescaped(key, String.valueOf(value)); - return this; - } - - /** - * Appends an object to the JSON. - * - * @param key The key of the field. - * @param object The object. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, JsonObject object) { - if (object == null) { - throw new IllegalArgumentException("JSON object must not be null"); - } - appendFieldUnescaped(key, object.toString()); - return this; - } - - /** - * Appends a string array to the JSON. - * - * @param key The key of the field. - * @param values The string array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, String[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values) - .map(value -> "\"" + escape(value) + "\"") - .collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends an integer array to the JSON. - * - * @param key The key of the field. - * @param values The integer array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, int[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends an object array to the JSON. - * - * @param key The key of the field. - * @param values The integer array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, JsonObject[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends a field to the object. - * - * @param key The key of the field. - * @param escapedValue The escaped value of the field. - */ - private void appendFieldUnescaped(String key, String escapedValue) { - if (builder == null) { - throw new IllegalStateException("JSON has already been built"); - } - if (key == null) { - throw new IllegalArgumentException("JSON key must not be null"); - } - if (hasAtLeastOneField) { - builder.append(","); - } - builder.append("\"").append(escape(key)).append("\":").append(escapedValue); - hasAtLeastOneField = true; - } - - /** - * Builds the JSON string and invalidates this builder. - * - * @return The built JSON string. - */ - public JsonObject build() { - if (builder == null) { - throw new IllegalStateException("JSON has already been built"); - } - JsonObject object = new JsonObject(builder.append("}").toString()); - builder = null; - return object; - } - - /** - * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. - * - *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. - * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). - * - * @param value The value to escape. - * @return The escaped value. - */ - private static String escape(String value) { - final StringBuilder builder = new StringBuilder(); - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - if (c == '"') { - builder.append("\\\""); - } else if (c == '\\') { - builder.append("\\\\"); - } else if (c <= '\u000F') { - builder.append("\\u000").append(Integer.toHexString(c)); - } else if (c <= '\u001F') { - builder.append("\\u00").append(Integer.toHexString(c)); - } else { - builder.append(c); - } - } - return builder.toString(); - } - - /** - * A super simple representation of a JSON object. - * - *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not - * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, - * JsonObject)}. - */ - public static class JsonObject { - - private final String value; - - private JsonObject(String value) { - this.value = value; - } - - @Override - public String toString() { - return value; - } - } - } - /** * A simple config for bStats. *