From 0002cdbf62419c0e4934e8596aa928ca3bc73af6 Mon Sep 17 00:00:00 2001 From: p2vman Date: Tue, 28 Jan 2025 16:32:15 +0200 Subject: [PATCH] Initial commit --- .gitignore | 42 + base/build.gradle | 24 + base/settings.gradle | 1 + .../java/io/github/p2vman/Identifier.java | 156 +++ .../main/java/io/github/p2vman/Static.java | 7 + .../src/main/java/io/github/p2vman/Utils.java | 14 + .../java/io/github/p2vman/data/Codec.java | 17 + .../java/io/github/p2vman/data/Decoder.java | 6 + .../github/p2vman/data/DecoderException.java | 16 + .../java/io/github/p2vman/data/Encoder.java | 5 + .../github/p2vman/data/EncoderException.java | 19 + .../p2vman/profiling/ExempleProfiler.java | 53 + .../io/github/p2vman/profiling/Profiler.java | 41 + base/src/main/java/org/eptalist/Config.java | 90 ++ .../main/java/org/eptalist/storge/Data.java | 14 + .../main/java/org/eptalist/storge/Json.java | 127 ++ .../main/java/org/eptalist/storge/Mysql.java | 155 +++ .../main/java/org/eptalist/storge/Sqlite.java | 155 +++ build.gradle | 24 + gradlew | 234 ++++ gradlew.bat | 89 ++ settings.gradle | 2 + spigot/build.gradle | 56 + spigot/settings.gradle | 2 + .../java/org/eptalist/spigot/EptaList.java | 94 ++ .../main/java/org/eptalist/spigot/Event.java | 24 + .../org/eptalist/spigot/WhiteListCommand.java | 239 ++++ .../org/eptalist/spigot/metrics/Metrics.java | 891 ++++++++++++++ spigot/src/main/resources/plugin.yml | 3 + velocity/build.gradle | 57 + velocity/settings.gradle | 2 + .../java/org/eptalist/velocity/Velocity.java | 94 ++ .../eptalist/velocity/WhiteListCommand.java | 146 +++ .../eptalist/velocity/metrics/Metrics.java | 1071 +++++++++++++++++ .../org/eptalist/velocity/BuildConstants.java | 7 + 35 files changed, 3977 insertions(+) create mode 100644 .gitignore create mode 100644 base/build.gradle create mode 100644 base/settings.gradle create mode 100644 base/src/main/java/io/github/p2vman/Identifier.java create mode 100644 base/src/main/java/io/github/p2vman/Static.java create mode 100644 base/src/main/java/io/github/p2vman/Utils.java create mode 100644 base/src/main/java/io/github/p2vman/data/Codec.java create mode 100644 base/src/main/java/io/github/p2vman/data/Decoder.java create mode 100644 base/src/main/java/io/github/p2vman/data/DecoderException.java create mode 100644 base/src/main/java/io/github/p2vman/data/Encoder.java create mode 100644 base/src/main/java/io/github/p2vman/data/EncoderException.java create mode 100644 base/src/main/java/io/github/p2vman/profiling/ExempleProfiler.java create mode 100644 base/src/main/java/io/github/p2vman/profiling/Profiler.java create mode 100644 base/src/main/java/org/eptalist/Config.java create mode 100644 base/src/main/java/org/eptalist/storge/Data.java create mode 100644 base/src/main/java/org/eptalist/storge/Json.java create mode 100644 base/src/main/java/org/eptalist/storge/Mysql.java create mode 100644 base/src/main/java/org/eptalist/storge/Sqlite.java create mode 100644 build.gradle create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle create mode 100644 spigot/build.gradle create mode 100644 spigot/settings.gradle create mode 100644 spigot/src/main/java/org/eptalist/spigot/EptaList.java create mode 100644 spigot/src/main/java/org/eptalist/spigot/Event.java create mode 100644 spigot/src/main/java/org/eptalist/spigot/WhiteListCommand.java create mode 100644 spigot/src/main/java/org/eptalist/spigot/metrics/Metrics.java create mode 100644 spigot/src/main/resources/plugin.yml create mode 100644 velocity/build.gradle create mode 100644 velocity/settings.gradle create mode 100644 velocity/src/main/java/org/eptalist/velocity/Velocity.java create mode 100644 velocity/src/main/java/org/eptalist/velocity/WhiteListCommand.java create mode 100644 velocity/src/main/java/org/eptalist/velocity/metrics/Metrics.java create mode 100644 velocity/src/main/templates/org/eptalist/velocity/BuildConstants.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b63da45 --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/base/build.gradle b/base/build.gradle new file mode 100644 index 0000000..27e0c8b --- /dev/null +++ b/base/build.gradle @@ -0,0 +1,24 @@ +plugins { + id 'java' +} + +group = 'io.github.p2vman' +version = '1.0' + +repositories { + mavenCentral() +} + +dependencies { + implementation "com.google.code.gson:gson:2.8.9" +} + +task createJar(type: Jar) { + archiveBaseName = 'base' + archiveVersion = 'marge' + from sourceSets.main.output +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' +} diff --git a/base/settings.gradle b/base/settings.gradle new file mode 100644 index 0000000..51acd10 --- /dev/null +++ b/base/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'base' \ No newline at end of file diff --git a/base/src/main/java/io/github/p2vman/Identifier.java b/base/src/main/java/io/github/p2vman/Identifier.java new file mode 100644 index 0000000..a57aace --- /dev/null +++ b/base/src/main/java/io/github/p2vman/Identifier.java @@ -0,0 +1,156 @@ +package io.github.p2vman; + +public class Identifier implements Comparable { + public static final char NAMESPACE_SEPARATOR = ':'; + public static final String DEFAULT_NAMESPACE = "minecraft"; + private final String namespace; + private final String path; + public Identifier(String namespace, String path) { + this.namespace = namespace; + this.path = path; + } + private Identifier(String[] id) { + this(id[0], id[1]); + } + + public Identifier(String id) { + this(split(id, NAMESPACE_SEPARATOR)); + } + + public static Identifier splitOn(String id, char delimiter) { + return new Identifier(split(id, delimiter)); + } + + public static Identifier tryParse(String id) { + try { + return new Identifier(id); + } catch (RuntimeException var2) { + return null; + } + } + + public static Identifier of(String namespace, String path) { + try { + return new Identifier(namespace, path); + } catch (RuntimeException var3) { + return null; + } + } + + protected static String[] split(String id, char delimiter) { + String[] strings = new String[]{DEFAULT_NAMESPACE, id}; + int i = id.indexOf(delimiter); + if (i >= 0) { + strings[1] = id.substring(i + 1); + if (i >= 1) { + strings[0] = id.substring(0, i); + } + } + + return strings; + } + + public String getPath() { + return this.path; + } + + public String getNamespace() { + return this.namespace; + } + + public String toString() { + return this.namespace + NAMESPACE_SEPARATOR + this.path; + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } else if (!(o instanceof Identifier)) { + return false; + } else { + Identifier identifier = (Identifier)o; + return this.namespace.equals(identifier.namespace) && this.path.equals(identifier.path); + } + } + + public int hashCode() { + return 31 * this.namespace.hashCode() + this.path.hashCode(); + } + + public int compareTo(Identifier identifier) { + int i = this.path.compareTo(identifier.path); + if (i == 0) { + i = this.namespace.compareTo(identifier.namespace); + } + + return i; + } + + public String toUnderscoreSeparatedString() { + return this.toString().replace('/', '_').replace(NAMESPACE_SEPARATOR, '_'); + } + + public String toTranslationKey() { + return this.namespace + "." + this.path; + } + + public String toShortTranslationKey() { + return this.namespace.equals(DEFAULT_NAMESPACE) ? this.path : this.toTranslationKey(); + } + + public String toTranslationKey(String prefix) { + return prefix + "." + this.toTranslationKey(); + } + + public String toTranslationKey(String prefix, String suffix) { + return prefix + "." + this.toTranslationKey() + "." + suffix; + } + + public static boolean isCharValid(char c) { + return c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c == '_' || c == ':' || c == '/' || c == '.' || c == '-'; + } + + public static boolean isPathValid(String path) { + for(int i = 0; i < path.length(); ++i) { + if (!isPathCharacterValid(path.charAt(i))) { + return false; + } + } + + return true; + } + + public static boolean isNamespaceValid(String namespace) { + for(int i = 0; i < namespace.length(); ++i) { + if (!isNamespaceCharacterValid(namespace.charAt(i))) { + return false; + } + } + + return true; + } + + private static String validateNamespace(String namespace, String path) { + if (!isNamespaceValid(namespace)) { + throw new RuntimeException("Non [a-z0-9_.-] character in namespace of location: " + namespace + NAMESPACE_SEPARATOR + path); + } else { + return namespace; + } + } + + public static boolean isPathCharacterValid(char character) { + return character == '_' || character == '-' || character >= 'a' && character <= 'z' || character >= '0' && character <= '9' || character == '/' || character == '.'; + } + + private static boolean isNamespaceCharacterValid(char character) { + return character == '_' || character == '-' || character >= 'a' && character <= 'z' || character >= '0' && character <= '9' || character == '.'; + } + + private static String validatePath(String namespace, String path) { + if (!isPathValid(path)) { + throw new RuntimeException("Non [a-z0-9/._-] character in path of location: " + namespace + NAMESPACE_SEPARATOR + path); + } else { + return path; + } + } +} \ No newline at end of file diff --git a/base/src/main/java/io/github/p2vman/Static.java b/base/src/main/java/io/github/p2vman/Static.java new file mode 100644 index 0000000..005fd5b --- /dev/null +++ b/base/src/main/java/io/github/p2vman/Static.java @@ -0,0 +1,7 @@ +package io.github.p2vman; + +import com.google.gson.Gson; + +public class Static { + public static final Gson GSON = new Gson(); +} diff --git a/base/src/main/java/io/github/p2vman/Utils.java b/base/src/main/java/io/github/p2vman/Utils.java new file mode 100644 index 0000000..3ffae95 --- /dev/null +++ b/base/src/main/java/io/github/p2vman/Utils.java @@ -0,0 +1,14 @@ +package io.github.p2vman; + +import java.util.Map; + +public class Utils { + public static boolean len(T[] t, int l) { + return t.length > l; + } + + public static Map put(Map map, K k, V v) { + map.put(k, v); + return map; + } +} diff --git a/base/src/main/java/io/github/p2vman/data/Codec.java b/base/src/main/java/io/github/p2vman/data/Codec.java new file mode 100644 index 0000000..80cd7da --- /dev/null +++ b/base/src/main/java/io/github/p2vman/data/Codec.java @@ -0,0 +1,17 @@ +package io.github.p2vman.data; + +public interface Codec extends Encoder, Decoder { + static Codec of(final Encoder encoder, final Decoder decoder) { + return new Codec() { + @Override + public T decode(I input) throws DecoderException { + return decoder.decode(input); + } + + @Override + public void encode(O out, T obj) throws EncoderException { + encoder.encode(out, obj); + } + }; + } +} diff --git a/base/src/main/java/io/github/p2vman/data/Decoder.java b/base/src/main/java/io/github/p2vman/data/Decoder.java new file mode 100644 index 0000000..017d0c9 --- /dev/null +++ b/base/src/main/java/io/github/p2vman/data/Decoder.java @@ -0,0 +1,6 @@ +package io.github.p2vman.data; + +@FunctionalInterface +public interface Decoder { + R decode(I input) throws DecoderException; +} diff --git a/base/src/main/java/io/github/p2vman/data/DecoderException.java b/base/src/main/java/io/github/p2vman/data/DecoderException.java new file mode 100644 index 0000000..945bd34 --- /dev/null +++ b/base/src/main/java/io/github/p2vman/data/DecoderException.java @@ -0,0 +1,16 @@ +package io.github.p2vman.data; + +public class DecoderException extends Exception { + public DecoderException() { + super(); + } + public DecoderException(final String message) { + super(message); + } + public DecoderException(final String message, final Throwable cause) { + super(message, cause); + } + public DecoderException(final Throwable cause) { + super(cause); + } +} diff --git a/base/src/main/java/io/github/p2vman/data/Encoder.java b/base/src/main/java/io/github/p2vman/data/Encoder.java new file mode 100644 index 0000000..f4bd3ba --- /dev/null +++ b/base/src/main/java/io/github/p2vman/data/Encoder.java @@ -0,0 +1,5 @@ +package io.github.p2vman.data; + +public interface Encoder { + void encode(O out, T obj) throws EncoderException; +} diff --git a/base/src/main/java/io/github/p2vman/data/EncoderException.java b/base/src/main/java/io/github/p2vman/data/EncoderException.java new file mode 100644 index 0000000..0d7bebb --- /dev/null +++ b/base/src/main/java/io/github/p2vman/data/EncoderException.java @@ -0,0 +1,19 @@ +package io.github.p2vman.data; + +public class EncoderException extends Exception { + public EncoderException() { + super(); + } + + public EncoderException(final String message) { + super(message); + } + + public EncoderException(final String message, final Throwable cause) { + super(message, cause); + } + + public EncoderException(final Throwable cause) { + super(cause); + } +} diff --git a/base/src/main/java/io/github/p2vman/profiling/ExempleProfiler.java b/base/src/main/java/io/github/p2vman/profiling/ExempleProfiler.java new file mode 100644 index 0000000..3ed0635 --- /dev/null +++ b/base/src/main/java/io/github/p2vman/profiling/ExempleProfiler.java @@ -0,0 +1,53 @@ +package io.github.p2vman.profiling; + +import java.util.HashMap; +import java.util.Map; +import java.util.Stack; + +public class ExempleProfiler implements Profiler { + private final Map totalTimes = new HashMap<>(); + private final Stack stack = new Stack<>(); + private final Map startTimes = new HashMap<>(); + + public void push(String name) { + stack.push(name); + startTimes.put(name, System.nanoTime()); + } + + public String pop() { + if (stack.isEmpty()) { + throw new IllegalStateException("Нет активных блоков для остановки."); + } + String name = stack.pop(); + Long startTime = startTimes.remove(name); + if (startTime == null) { + throw new IllegalStateException("Блок " + name + " не был запущен."); + } + long elapsedTime = System.nanoTime() - startTime; + totalTimes.put(name, totalTimes.getOrDefault(name, 0L) + elapsedTime); + return name; + } + + public String peek() { + if (stack.isEmpty()) { + throw new IllegalStateException("Нет активных блоков."); + } + return stack.peek(); + } + + public long getElapsedTimeAndRemove(String name) { + Long elapsedTime = totalTimes.remove(name); + if (elapsedTime == null) { + throw new IllegalStateException("Блок " + name + " не найден."); + } + return elapsedTime / 1_000_000; + } + + public long getElapsedTime(String name) { + Long elapsedTime = totalTimes.get(name); + if (elapsedTime == null) { + throw new IllegalStateException("Блок " + name + " не найден."); + } + return elapsedTime / 1_000_000; + } +} diff --git a/base/src/main/java/io/github/p2vman/profiling/Profiler.java b/base/src/main/java/io/github/p2vman/profiling/Profiler.java new file mode 100644 index 0000000..d61acc3 --- /dev/null +++ b/base/src/main/java/io/github/p2vman/profiling/Profiler.java @@ -0,0 +1,41 @@ +package io.github.p2vman.profiling; + + +public interface Profiler { + /** + * Запускает отсчет времени для нового блока. + * + * @param name название блока кода + */ + void push(String name); + + /** + * Останавливает отсчет времени для последнего блока. + * + * @return название блока, который был остановлен + */ + String pop(); + + /** + * Возвращает название текущего активного блока без остановки его выполнения. + * + * @return название текущего блока + */ + String peek(); + + /** + * Получает общее время выполнения для указанного блока и удаляет запись. + * + * @param name название блока кода + * @return время в миллисекундах + */ + long getElapsedTimeAndRemove(String name); + + /** + * Получает общее время выполнения для указанного блока без удаления записи. + * + * @param name название блока кода + * @return время в миллисекундах + */ + long getElapsedTime(String name); +} \ No newline at end of file diff --git a/base/src/main/java/org/eptalist/Config.java b/base/src/main/java/org/eptalist/Config.java new file mode 100644 index 0000000..42fe9d9 --- /dev/null +++ b/base/src/main/java/org/eptalist/Config.java @@ -0,0 +1,90 @@ +package org.eptalist; + +import com.google.gson.annotations.SerializedName; +import io.github.p2vman.Identifier; +import io.github.p2vman.Static; +import io.github.p2vman.Utils; + +import java.io.*; +import java.util.HashMap; +import java.util.Map; + +public class Config { + public boolean enable = false; + public boolean skip_to_op = true; + public Identifier curent = new Identifier("whitelist", "base"); + public Mode[] modes = new Mode[] { + new Mode( + new Identifier( + "whitelist", + "base"), + "org.eptalist.storge.Json", + Utils.put(new HashMap<>(), "file", "eoptalist.json"), + "&6Молодой человек а вас нету в списке &4:)" + ), + new Mode( + new Identifier( + "whitelist", + "dev"), + "org.eptalist.storge.Json", + Utils.put(new HashMap<>(), "file", "eoptalist.dev.json"), + "&2Сервер на тех работах" + ) + }; + + public static class Mode { + public Identifier id; + public String storage; + + public Map data; + @SerializedName("msg") + public String kick_msg; + public Mode(Identifier id, String storage, Map data, String kick_msg) { + this.id = id; + this.storage = storage; + this.data = data; + this.kick_msg = kick_msg; + } + } + + public static class ConfigContainer { + private File config; + private Config cfg = null; + public ConfigContainer(File config) { + this.config = config; + } + + public Config get() { + if (cfg == null) { + load(); + } + return cfg; + } + + public void load() { + try { + if (!config.exists()) { + this.cfg = new Config(); + try (FileWriter writer =new FileWriter(this.config)) { + Static.GSON.toJson(cfg, writer); + } + } + else { + try (FileReader reader = new FileReader(this.config)) { + cfg = Static.GSON.fromJson(reader, Config.class); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void save() { + try (FileWriter writer = new FileWriter(this.config)) { + Static.GSON.toJson(cfg, writer); + } catch (Exception e) { + e.printStackTrace(); + } + } + } +} diff --git a/base/src/main/java/org/eptalist/storge/Data.java b/base/src/main/java/org/eptalist/storge/Data.java new file mode 100644 index 0000000..80272ec --- /dev/null +++ b/base/src/main/java/org/eptalist/storge/Data.java @@ -0,0 +1,14 @@ +package org.eptalist.storge; + +import java.io.Closeable; +import java.util.List; + +public interface Data extends Closeable { + boolean addUser(T name); + boolean removeUser(T name); + boolean is(T name); + List toList(); + boolean addUser(T name, List info); + boolean removeUser(T name, List info); + boolean is(T name, List info); +} diff --git a/base/src/main/java/org/eptalist/storge/Json.java b/base/src/main/java/org/eptalist/storge/Json.java new file mode 100644 index 0000000..dd77dee --- /dev/null +++ b/base/src/main/java/org/eptalist/storge/Json.java @@ -0,0 +1,127 @@ +package org.eptalist.storge; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import io.github.p2vman.Static; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.*; + +public class Json extends ArrayList implements Data { + @Override + public void close() throws IOException { + save(); + } + + @Override + public boolean addUser(String name) { + if (is(name)) { + return false; + } + return add(name); + } + + @Override + public boolean is(String name) { + return contains(name); + } + + @Override + public boolean removeUser(String name) { + if (!is(name)) { + + return false; + } + return remove(name); + } + + public Map data; + + public Json(Map data) { + this.data = data; + if (!(size()>0)) { + load(); + } + } + + public void load() { + clear(); + try { + JsonArray array = Static.GSON.fromJson(new InputStreamReader(new FileInputStream((String) this.data.get("file"))), JsonArray.class); + Iterator iterator = array.iterator(); + while (iterator.hasNext()) { + add(iterator.next().getAsString()); + } + } catch (Exception e) { + e.printStackTrace(); + save(); + } + } + + public void save() { + try { + OutputStream stream = new FileOutputStream((String) this.data.get("file")); + stream.write(Static.GSON.toJson(this).getBytes(StandardCharsets.UTF_8)); + stream.flush(); + stream.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public boolean add(String s) { + if (super.add(s)) { + save(); + return true; + } + else { + return false; + } + } + + @Override + public boolean remove(Object o) { + if (super.remove(o)) { + save(); + return true; + } else { + return false; + } + } + + @Override + public void sort(Comparator c) { + super.sort(c); + save(); + } + + @Override + public List toList() { + return this; + } + + @Override + public boolean is(String name, List info) { + return contains(name); + } + + @Override + public boolean removeUser(String name, List info) { + if (!is(name)) { + info.add("&r" + name + "is not in the whitelist"); + return false; + } + return remove(name); + } + + @Override + public boolean addUser(String name, List info) { + if (is(name)) { + info.add("&r" + name + "is already on the whitelist"); + return false; + } + return add(name); + } +} diff --git a/base/src/main/java/org/eptalist/storge/Mysql.java b/base/src/main/java/org/eptalist/storge/Mysql.java new file mode 100644 index 0000000..6e13011 --- /dev/null +++ b/base/src/main/java/org/eptalist/storge/Mysql.java @@ -0,0 +1,155 @@ +package org.eptalist.storge; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Mysql implements Data { + public Connection connection; + public Map data; + public Mysql(Map data) { + this.data = data; + 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)"); + } + } catch (SQLException | ClassNotFoundException e) { + e.printStackTrace(); + } + } + + @Override + public boolean removeUser(String name) { + if (!is(name)) { + return false; + } + try { + PreparedStatement statement = connection.prepareStatement("DELETE FROM users WHERE username = ?"); + statement.setString(1, name); + return statement.executeUpdate() > 0; + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + } + + @Override + public boolean removeUser(String name, List info) { + if (!is(name)) { + info.add("&r" + name + "is not in the whitelist"); + return false; + } + try { + PreparedStatement statement = connection.prepareStatement("DELETE FROM users WHERE username = ?"); + statement.setString(1, name); + return statement.executeUpdate() > 0; + } catch (SQLException e) { + e.printStackTrace(); + info.add("&rThere was an error in the database"); + return false; + } + } + + @Override + public boolean is(String name, List info) { + try { + if (connection.isClosed()) { + 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 = ?"); + statement.setString(1, name); + ResultSet resultSet = statement.executeQuery(); + return resultSet.next(); + } catch (SQLException e) { + e.printStackTrace(); + info.add("&rThere was an error in the database"); + return false; + } + } + + @Override + public boolean is(String name) { + try { + if (connection.isClosed()) { + connection = DriverManager.getConnection((String) this.data.get("file")); + } + PreparedStatement statement = connection.prepareStatement("SELECT username FROM users WHERE username = ?"); + statement.setString(1, name); + ResultSet resultSet = statement.executeQuery(); + return resultSet.next(); + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + } + + @Override + public boolean addUser(String name, List info) { + if (is(name)) { + info.add("&r" + name + "is already on the whitelist"); + return false; + } + try { + PreparedStatement statement = connection.prepareStatement("INSERT INTO users (username) VALUES (?)"); + statement.setString(1, name); + return statement.executeUpdate() > 0; + } catch (SQLException e) { + e.printStackTrace(); + info.add("&rThere was an error in the database"); + return false; + } + } + + @Override + public boolean addUser(String name) { + if (is(name)) { + return false; + } + try { + PreparedStatement statement = connection.prepareStatement("INSERT INTO users (username) VALUES (?)"); + statement.setString(1, name); + return statement.executeUpdate() > 0; + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + } + + public void close() { + try { + if (connection != null) { + if (!connection.isClosed()) { + connection.close(); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Override + public List toList() { + + List players = new ArrayList<>(); + try { + if (connection.isClosed()) { + connection = DriverManager.getConnection((String) this.data.get("file")); + } + String sql = "SELECT username FROM users"; + Statement stmt = connection.createStatement(); + ResultSet rs = stmt.executeQuery(sql); + while (rs.next()) { + players.add(rs.getString("username")); + } + rs.close(); + stmt.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return players; + } +} diff --git a/base/src/main/java/org/eptalist/storge/Sqlite.java b/base/src/main/java/org/eptalist/storge/Sqlite.java new file mode 100644 index 0000000..9008801 --- /dev/null +++ b/base/src/main/java/org/eptalist/storge/Sqlite.java @@ -0,0 +1,155 @@ +package org.eptalist.storge; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Sqlite implements Data { + + public Connection connection; + public Map data; + public Sqlite(Map data) { + this.data = data; + 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)"); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Override + public boolean removeUser(String name) { + if (!is(name)) { + return false; + } + try { + PreparedStatement statement = connection.prepareStatement("DELETE FROM users WHERE user_name = ?"); + statement.setString(1, name); + return statement.executeUpdate() > 0; + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + } + + @Override + public boolean removeUser(String name, List info) { + if (!is(name)) { + info.add("&r" + name + "is not in the whitelist"); + return false; + } + try { + PreparedStatement statement = connection.prepareStatement("DELETE FROM users WHERE user_name = ?"); + statement.setString(1, name); + return statement.executeUpdate() > 0; + } catch (SQLException e) { + e.printStackTrace(); + info.add("&rThere was an error in the database"); + return false; + } + } + + @Override + public boolean is(String name, List info) { + try { + if (connection.isClosed()) { + 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 = ?"); + statement.setString(1, name); + ResultSet resultSet = statement.executeQuery(); + return resultSet.next(); + } catch (SQLException e) { + e.printStackTrace(); + info.add("&rThere was an error in the database"); + return false; + } + } + + @Override + public boolean is(String name) { + try { + 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 = ?"); + statement.setString(1, name); + ResultSet resultSet = statement.executeQuery(); + return resultSet.next(); + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + } + + @Override + public boolean addUser(String name, List info) { + if (is(name)) { + info.add("&r" + name + "is already on the whitelist"); + return false; + } + try { + PreparedStatement statement = connection.prepareStatement("INSERT INTO users (user_name) VALUES (?)"); + statement.setString(1, name); + return statement.executeUpdate() > 0; + } catch (SQLException e) { + e.printStackTrace(); + info.add("&rThere was an error in the database"); + return false; + } + } + + @Override + public boolean addUser(String name) { + if (is(name)) { + return false; + } + try { + PreparedStatement statement = connection.prepareStatement("INSERT INTO users (user_name) VALUES (?)"); + statement.setString(1, name); + return statement.executeUpdate() > 0; + } catch (SQLException e) { + e.printStackTrace(); + return false; + } + } + + public void close() { + try { + if (connection != null) { + if (!connection.isClosed()) { + connection.close(); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Override + public List toList() { + + List players = new ArrayList<>(); + try { + if (connection.isClosed()) { + connection = DriverManager.getConnection(String.format("jdbc:sqlite:%s.db", (String) this.data.get("file"))); + } + String sql = "SELECT user_name FROM users"; + Statement stmt = connection.createStatement(); + ResultSet rs = stmt.executeQuery(sql); + while (rs.next()) { + players.add(rs.getString("name")); + } + rs.close(); + stmt.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return players; + } +} \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..724fd45 --- /dev/null +++ b/build.gradle @@ -0,0 +1,24 @@ +plugins { + id 'java' +} + +allprojects { + repositories { + mavenCentral() + } +} + +task mergeJars(type: Jar) { + archiveBaseName = 'EptaList' + archiveVersion = '1.1-release' + + def jarPaths = [ + "C:\\Users\\User\\IdeaProjects\\EptaListProject\\velocity\\build\\libs\\velocity-1.0.jar", + "C:\\Users\\User\\IdeaProjects\\EptaListProject\\spigot\\build\\libs\\spigot-1.0.jar", + "C:\\Users\\User\\IdeaProjects\\EptaListProject\\base\\build\\libs\\base-1.0.jar" + ] + + from jarPaths.collect { zipTree(it) } + + duplicatesStrategy = DuplicatesStrategy.INCLUDE +} \ No newline at end of file diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..d34a558 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'EptaListProject' +include ':base', ':velocity', ':spigot' \ No newline at end of file diff --git a/spigot/build.gradle b/spigot/build.gradle new file mode 100644 index 0000000..b328063 --- /dev/null +++ b/spigot/build.gradle @@ -0,0 +1,56 @@ +plugins { + id 'java' +} + +group = 'org.eg4rerer' +version = "1.0" + +repositories { + mavenCentral() + maven { + name = "spigotmc-repo" + url = "https://hub.spigotmc.org/nexus/content/repositories/snapshots/" + } + maven { + name = "sonatype" + url = "https://oss.sonatype.org/content/groups/public/" + } +} + +dependencies { + compileOnly("org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT") + compileOnly project(':base') +} + +def targetJavaVersion = 17 +java { + def javaVersion = JavaVersion.toVersion(targetJavaVersion) + sourceCompatibility = javaVersion + targetCompatibility = javaVersion + if (JavaVersion.current() < javaVersion) { + toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) + } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + + if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) { + options.release.set(targetJavaVersion) + } +} + +processResources { + def props = [version: version] + inputs.properties props + filteringCharset 'UTF-8' + filesMatching('plugin.yml') { + expand props + } +} + +task createJar(type: Jar) { + archiveBaseName = 'spigot' + archiveVersion = 'marge' + from sourceSets.main.output +} \ No newline at end of file diff --git a/spigot/settings.gradle b/spigot/settings.gradle new file mode 100644 index 0000000..b15b492 --- /dev/null +++ b/spigot/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'spigot' +include ':base' \ No newline at end of file diff --git a/spigot/src/main/java/org/eptalist/spigot/EptaList.java b/spigot/src/main/java/org/eptalist/spigot/EptaList.java new file mode 100644 index 0000000..4a82154 --- /dev/null +++ b/spigot/src/main/java/org/eptalist/spigot/EptaList.java @@ -0,0 +1,94 @@ +package org.eptalist.spigot; + +import com.google.gson.reflect.TypeToken; +import io.github.p2vman.profiling.ExempleProfiler; +import io.github.p2vman.profiling.Profiler; +import org.eptalist.Config; +import io.github.p2vman.Identifier; +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; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +public final class EptaList extends JavaPlugin { + private static Metrics metrics; + public static final Profiler profiler = new ExempleProfiler(); + public static final Logger LOGGER = Logger.getLogger("EptaList"); + + public static Config.ConfigContainer config; + public static Data list; + public static Config.Mode mode; + public static List identifiers = new ArrayList<>(); + + public static void load() { + profiler.push("load"); + config.load(); + identifiers.clear(); + for (Config.Mode mode1 : config.get().modes) { + identifiers.add(mode1.id); + } + { + Identifier id = config.get().curent; + for (Config.Mode mode1 : config.get().modes) if (mode1.id.equals(id)) { + mode = mode1; + break; + } + } + try { + list = (Data) Class.forName(mode.storage).getConstructor(Map.class).newInstance(mode.data); + } catch (Exception e) { + e.printStackTrace(); + } + LOGGER.log(Level.INFO, String.format("Load Plugin Configuration %sms", profiler.getElapsedTimeAndRemove(profiler.pop()))); + } + + @Override + public void onEnable() { + profiler.push("init"); + metrics = new Metrics(this, 24527); + + File data = getDataFolder(); + if (!data.exists()) { + data.mkdirs(); + } + config = new Config.ConfigContainer(new File(data, "wh.json")); + load(); + + try { + Field commandMapField = Bukkit.getServer().getClass().getDeclaredField("commandMap"); + commandMapField.setAccessible(true); + CommandMap map = (CommandMap)commandMapField.get(Bukkit.getServer()); + + Command command = new WhiteListCommand(); + + map.register("minecraft", command); + } catch (Exception e) { + e.printStackTrace(); + } + + getServer().getPluginManager().registerEvents(new Event(), this); + metrics.addCustomChart(new Metrics.SimplePie("data_type", () -> mode.storage)); + LOGGER.log(Level.INFO, String.format("Init Plugin %sms", profiler.getElapsedTimeAndRemove(profiler.pop()))); + } + + @Override + public void onDisable() { + try { + if (list != null) list.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/spigot/src/main/java/org/eptalist/spigot/Event.java b/spigot/src/main/java/org/eptalist/spigot/Event.java new file mode 100644 index 0000000..00aba18 --- /dev/null +++ b/spigot/src/main/java/org/eptalist/spigot/Event.java @@ -0,0 +1,24 @@ +package org.eptalist.spigot; + +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerLoginEvent; +import org.eptalist.Config; + +public class Event implements Listener { + @EventHandler(priority = EventPriority.MONITOR) + public void onConnect(PlayerLoginEvent e) { + Player p = e.getPlayer(); + if (p != null) { + Config config = EptaList.config.get(); + if (config.enable) { + if (!((config.skip_to_op && p.isOp()) || EptaList.list.is(p.getName()))) { + e.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, ChatColor.translateAlternateColorCodes('&', EptaList.mode.kick_msg)); + } + } + } + } +} diff --git a/spigot/src/main/java/org/eptalist/spigot/WhiteListCommand.java b/spigot/src/main/java/org/eptalist/spigot/WhiteListCommand.java new file mode 100644 index 0000000..7e377b0 --- /dev/null +++ b/spigot/src/main/java/org/eptalist/spigot/WhiteListCommand.java @@ -0,0 +1,239 @@ +package org.eptalist.spigot; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang.Validate; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; +import org.bukkit.util.StringUtil; +import io.github.p2vman.Identifier; +import io.github.p2vman.Utils; + +import java.util.*; +import java.util.function.Function; + +public class WhiteListCommand extends Command { + private final String[] w1 = new String[] { + "off", + "on", + "add", + "remove", + "list", + "help", + "mode", + "kick_nolisted", + "reload" + }; + private final Permission permission_enable; + private final Permission permission_add; + private final Permission permission_remove; + private final Permission permission_reload; + private final Permission permission_mode; + private final Permission permission_outher; + private final Permission permission_list; + + + public WhiteListCommand() { + super("eptalist"); + Function recal = (p) -> { + p.recalculatePermissibles(); + return p; + }; + + permission_enable = recal.apply(new Permission("eptalist.enable", PermissionDefault.OP)); + permission_add = recal.apply(new Permission("eptalist.add", PermissionDefault.OP)); + permission_remove = recal.apply(new Permission("eptalist.remove", PermissionDefault.OP)); + permission_reload = recal.apply(new Permission("eptalist.reload", PermissionDefault.OP)); + permission_mode = recal.apply(new Permission("eptalist.mode", PermissionDefault.OP)); + permission_list = recal.apply(new Permission("eptalist.list", PermissionDefault.OP)); + permission_outher = recal.apply(new Permission("eptalist.outher", PermissionDefault.OP)); + } + + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + if (!(args.length > 0)) { + sender.sendMessage(String.format("/%s (%s)", getName(), String.join("/", w1))); + return false; + } + switch (args[0]) { + case "off": if (testPermission(sender, permission_enable)) { + EptaList.config.get().enable = false; + EptaList.config.save(); + sender.sendMessage("Whitelist disabled."); + } + break; + case "on": if (testPermission(sender, permission_enable)) { + EptaList.config.get().enable = true; + EptaList.config.save(); + sender.sendMessage("Whitelist enabled."); + } + break; + case "add": if (testPermission(sender, permission_add)) { + List info = new ArrayList<>(); + if (!Utils.len(args, 1)) { + sender.sendMessage("Usage: /" + commandLabel + " add "); + } else if (EptaList.list.addUser(args[1], info)) { + sender.sendMessage("User added to the whitelist: " + args[1]); + } else { + for (String line : info) { + sender.sendMessage(ChatColor.translateAlternateColorCodes('&', line)); + } + } + } + break; + case "remove": if (testPermission(sender, permission_remove)) { + List info = new ArrayList<>(); + if (!Utils.len(args, 1)) { + sender.sendMessage("Usage: /" + commandLabel + " remove "); + } else if (EptaList.list.removeUser(args[1], info)) { + sender.sendMessage("User removed from the whitelist: " + args[1]); + } else { + for (String line : info) { + sender.sendMessage(ChatColor.translateAlternateColorCodes('&', line)); + } + } + } + break; + case "list": if (testPermission(sender, permission_list)) { + sender.sendMessage("Whitelisted players: " + EptaList.list.toList().toString()); + } + break; + case "mode": if (testPermission(sender, permission_mode)) { + if (!Utils.len(args, 1)) { + sender.sendMessage("Usage: /" + commandLabel + " mode "); + } else { + Identifier id = Identifier.tryParse(args[1]); + if (id != null && EptaList.identifiers.contains(id)) { + EptaList.config.get().curent = id; + EptaList.config.save(); + EptaList.load(); + sender.sendMessage("Mode set to: " + id); + } else { + sender.sendMessage("Invalid mode ID!"); + } + } + } + break; + case "kick_nolisted": if (testPermission(sender, permission_outher)) { + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + if (!EptaList.list.is(player.getName())) { + player.kickPlayer(EptaList.mode.kick_msg); + } + } + sender.sendMessage("Non-whitelisted players have been kicked."); + } + break; + case "help": { + sender.sendMessage(new String[]{ + String.format("1: /%s add - Add user to whitelist", getName()), + String.format("2: /%s remove - Remove user from whitelist", getName()), + String.format("3: /%s list - Display whitelisted players", getName()), + String.format("4: /%s on - Enable whitelist", getName()), + String.format("5: /%s off - Disable whitelist", getName()), + String.format("6: /%s mode - Set list data mode", getName()), + String.format("7: /%s kick_nolisted - Kick non-whitelisted players", getName()), + String.format("8: /%s reload - Reload the whitelist configuration", getName()), + }); + } + break; + case "reload": if (testPermission(sender, permission_reload)) { + try { + EptaList.load(); + sender.sendMessage("Configuration reloaded successfully."); + } catch (Exception e) { + e.printStackTrace(); + sender.sendMessage("Failed to reload the configuration."); + } + } + break; + } + return true; + } + + + + @Override + public List tabComplete(CommandSender sender, String alias, String[] args, Location location) throws IllegalArgumentException { + Validate.notNull(sender, "Sender cannot be null"); + Validate.notNull(args, "Arguments cannot be null"); + Validate.notNull(alias, "Alias cannot be null"); + + if (args.length == 0) { + return ImmutableList.of(); + } else if (args.length == 1) { + String lastWord = args[args.length - 1]; + ArrayList matchedPlayers = new ArrayList(); + Iterator var7 = Arrays.stream(w1).iterator(); + while(var7.hasNext()) { + String name = (String)var7.next(); + if (StringUtil.startsWithIgnoreCase(name, lastWord)) { + matchedPlayers.add(name); + } + } + + Collections.sort(matchedPlayers, String.CASE_INSENSITIVE_ORDER); + return matchedPlayers; + } else if (args.length == 2) { + if (args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("remove")) { + String lastWord = args[args.length - 1]; + + Player senderPlayer = sender instanceof Player ? (Player) sender : null; + + ArrayList matchedPlayers = new ArrayList(); + for (Player player : sender.getServer().getOnlinePlayers()) { + String name = player.getName(); + if ((senderPlayer == null || senderPlayer.canSee(player)) && StringUtil.startsWithIgnoreCase(name, lastWord)) { + matchedPlayers.add(name); + } + } + + Collections.sort(matchedPlayers, String.CASE_INSENSITIVE_ORDER); + return matchedPlayers; + } else if (args[0].equalsIgnoreCase("mode")) { + String lastWord = args[args.length - 1]; + ArrayList matchedPlayers = new ArrayList(); + Iterator var7 = EptaList.identifiers.iterator(); + while(var7.hasNext()) { + String name = var7.next().toString(); + if (StringUtil.startsWithIgnoreCase(name, lastWord)) { + matchedPlayers.add(name); + } + } + + Collections.sort(matchedPlayers, String.CASE_INSENSITIVE_ORDER); + return matchedPlayers; + } + } else if (args.length == 3) { + if (args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("remove")) { + String lastWord = args[args.length - 1]; + ArrayList matchedPlayers = new ArrayList(); + Iterator var7 = EptaList.identifiers.iterator(); + while (var7.hasNext()) { + String name = var7.next().toString(); + if (StringUtil.startsWithIgnoreCase(name, lastWord)) { + matchedPlayers.add(name); + } + } + + Collections.sort(matchedPlayers, String.CASE_INSENSITIVE_ORDER); + return matchedPlayers; + } + } + + return ImmutableList.of(); + } + + public boolean testPermission(CommandSender target, Permission permission) { + if (target.hasPermission(permission.getName())) { + return true; + } else { + target.sendMessage(ChatColor.RED + "You don't have permission to perform this command."); + return false; + } + } +} diff --git a/spigot/src/main/java/org/eptalist/spigot/metrics/Metrics.java b/spigot/src/main/java/org/eptalist/spigot/metrics/Metrics.java new file mode 100644 index 0000000..15cedf4 --- /dev/null +++ b/spigot/src/main/java/org/eptalist/spigot/metrics/Metrics.java @@ -0,0 +1,891 @@ +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 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.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.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 { + + private final Plugin plugin; + + private final MetricsBase metricsBase; + + /** + * 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; + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + if (!config.isSet("serverUuid")) { + config.addDefault("enabled", true); + config.addDefault("serverUuid", UUID.randomUUID().toString()); + config.addDefault("logFailedRequests", false); + config.addDefault("logSentData", false); + config.addDefault("logResponseStatusText", false); + // Inform the server owners about bStats + config + .options() + .header( + "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" + + "many people use their plugin and their total player count. It's recommended to keep bStats\n" + + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" + + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" + + "anonymous.") + .copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + // Load the data + boolean enabled = config.getBoolean("enabled", true); + String serverUUID = config.getString("serverUuid"); + boolean logErrors = config.getBoolean("logFailedRequests", false); + boolean logSentData = config.getBoolean("logSentData", false); + boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); + boolean isFolia = false; + try { + isFolia = Class.forName("io.papermc.paper.threadedregions.RegionizedServer") != null; + } catch (Exception e) { + } + metricsBase = + new // See https://github.com/Bastian/bstats-metrics/pull/126 + // See https://github.com/Bastian/bstats-metrics/pull/126 + // See https://github.com/Bastian/bstats-metrics/pull/126 + // See https://github.com/Bastian/bstats-metrics/pull/126 + // See https://github.com/Bastian/bstats-metrics/pull/126 + // See https://github.com/Bastian/bstats-metrics/pull/126 + // See https://github.com/Bastian/bstats-metrics/pull/126 + MetricsBase( + "bukkit", + serverUUID, + serviceId, + enabled, + this::appendPlatformData, + this::appendServiceData, + isFolia + ? null + : submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), + plugin::isEnabled, + (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), + (message) -> this.plugin.getLogger().log(Level.INFO, message), + logErrors, + logSentData, + logResponseStatusText, + false); + } + + /** 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", getPlayerAmount()); + builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); + builder.appendField("bukkitVersion", Bukkit.getVersion()); + builder.appendField("bukkitName", Bukkit.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()); + } + + private int getPlayerAmount() { + try { + // Around MC 1.8 the return type was changed from an array to a collection, + // This fixes java.lang.NoSuchMethodError: + // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + return onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + // Just use the new method if the reflection failed + return Bukkit.getOnlinePlayers().size(); + } + } + + 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(); + } + } + + 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 new file mode 100644 index 0000000..3020c54 --- /dev/null +++ b/spigot/src/main/resources/plugin.yml @@ -0,0 +1,3 @@ +name: EptaList +version: "1.1-release" +main: org.eptalist.spigot.EptaList diff --git a/velocity/build.gradle b/velocity/build.gradle new file mode 100644 index 0000000..41400ae --- /dev/null +++ b/velocity/build.gradle @@ -0,0 +1,57 @@ +plugins { + id 'java' + id 'eclipse' + id 'org.jetbrains.gradle.plugin.idea-ext' version '1.1.8' +} + +group = 'org.eg4rerer' +version = "1.1-release" + +repositories { + mavenCentral() + maven { + name = "papermc-repo" + url = "https://repo.papermc.io/repository/maven-public/" + } + maven { + name = "sonatype" + url = "https://oss.sonatype.org/content/groups/public/" + } +} + +dependencies { + compileOnly("com.velocitypowered:velocity-api:3.4.0-SNAPSHOT") + annotationProcessor("com.velocitypowered:velocity-api:3.4.0-SNAPSHOT") + compileOnly project(':base') +} + +def targetJavaVersion = 17 +java { + toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + options.release.set(targetJavaVersion) +} + +def templateSource = file('src/main/templates') +def templateDest = layout.buildDirectory.dir('generated/sources/templates') +def generateTemplates = tasks.register('generateTemplates', Copy) { task -> + def props = ['version': project.version] + task.inputs.properties props + + task.from templateSource + task.into templateDest + task.expand props +} + +sourceSets.main.java.srcDir(generateTemplates.map { it.outputs }) + +//project.idea.project.settings.taskTriggers.afterSync generateTemplates +project.eclipse.synchronizationTasks(generateTemplates) +task createJar(type: Jar) { + archiveBaseName = 'velocity' + archiveVersion = 'marge' + from sourceSets.main.output +} \ No newline at end of file diff --git a/velocity/settings.gradle b/velocity/settings.gradle new file mode 100644 index 0000000..a6ae672 --- /dev/null +++ b/velocity/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'velocity' +include ':base' \ No newline at end of file diff --git a/velocity/src/main/java/org/eptalist/velocity/Velocity.java b/velocity/src/main/java/org/eptalist/velocity/Velocity.java new file mode 100644 index 0000000..12816a4 --- /dev/null +++ b/velocity/src/main/java/org/eptalist/velocity/Velocity.java @@ -0,0 +1,94 @@ +package org.eptalist.velocity; + +import com.google.gson.reflect.TypeToken; +import com.google.inject.Inject; +import com.velocitypowered.api.command.CommandManager; +import com.velocitypowered.api.event.ResultedEvent; +import com.velocitypowered.api.event.connection.LoginEvent; +import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; +import com.velocitypowered.api.event.Subscribe; +import com.velocitypowered.api.plugin.Plugin; +import com.velocitypowered.api.plugin.annotation.DataDirectory; +import com.velocitypowered.api.proxy.ProxyServer; +import io.github.p2vman.Identifier; +import io.github.p2vman.profiling.ExempleProfiler; +import io.github.p2vman.profiling.Profiler; +import net.kyori.adventure.text.Component; +import org.eptalist.Config; +import org.eptalist.storge.Data; +import org.eptalist.velocity.metrics.Metrics; +import org.slf4j.Logger; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; + +@Plugin(id = "velocity", name = "velocity", version = BuildConstants.VERSION) +public class Velocity { + private static Metrics metrics; + public static final Profiler profiler = new ExempleProfiler(); + public static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger("EptaList"); + @Inject + private Logger logger; + public static Config.ConfigContainer config; + private Path dataDirectory; + private final Metrics.Factory metricsFactory; + + public static Data list; + public static Config.Mode mode; + public static List identifiers = new ArrayList<>(); + public static void load() { + profiler.push("load"); + config.load(); + identifiers.clear(); + for (Config.Mode mode1 : config.get().modes) { + identifiers.add(mode1.id); + } + { + Identifier id = config.get().curent; + for (Config.Mode mode1 : config.get().modes) if (mode1.id.equals(id)) { + mode = mode1; + break; + } + } + try { + list = (Data) Class.forName(mode.storage).getConstructor(Map.class).newInstance(mode.data); + } catch (Exception e) { + e.printStackTrace(); + } + LOGGER.log(Level.INFO, String.format("Load Plugin Configuration %sms", profiler.getElapsedTimeAndRemove(profiler.pop()))); + } + + @Inject + public Velocity(ProxyServer server, @DataDirectory Path dataDirectory, Metrics.Factory metricsFactory) { + profiler.push("init"); + this.metricsFactory = metricsFactory; + this.dataDirectory = dataDirectory; + if (!Files.exists(dataDirectory)) { + dataDirectory.toFile().mkdirs(); + } + config = new Config.ConfigContainer(new File(dataDirectory.toFile(), "config.json")); + load(); + CommandManager commandManager = server.getCommandManager(); + commandManager.register("eptalist", new WhiteListCommand(logger)); + LOGGER.log(Level.INFO, String.format("Load Plugin Configuration %sms", profiler.getElapsedTimeAndRemove(profiler.pop()))); + } + + @Subscribe + public void onProxyInitialization(ProxyInitializeEvent event) { + Metrics metrics = metricsFactory.make(this, 24527); + + metrics.addCustomChart(new Metrics.SimplePie("data_type", () -> mode.storage)); + } + + @Subscribe + public void onLogin(LoginEvent event) { + if (list.is(event.getPlayer().getUsername())) { + event.setResult(ResultedEvent.ComponentResult.denied(Component.text(""))); + } + } +} diff --git a/velocity/src/main/java/org/eptalist/velocity/WhiteListCommand.java b/velocity/src/main/java/org/eptalist/velocity/WhiteListCommand.java new file mode 100644 index 0000000..87e80eb --- /dev/null +++ b/velocity/src/main/java/org/eptalist/velocity/WhiteListCommand.java @@ -0,0 +1,146 @@ +package org.eptalist.velocity; + +import com.google.common.collect.ImmutableList; +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import io.github.p2vman.Identifier; +import net.kyori.adventure.text.Component; +import org.slf4j.Logger; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class WhiteListCommand implements SimpleCommand { + private final String[] w1 = new String[]{ + "off", + "on", + "add", + "remove", + "list", + "help", + "mode", + "reload" + }; + + private Logger logger; + + public WhiteListCommand(Logger logger) { + this.logger = logger; + } + + @Override + public void execute(Invocation invocation) { + CommandSource sender = invocation.source(); + String[] args = invocation.arguments(); + + if (args.length == 0) { + sender.sendMessage(Component.text(String.format("/eptalist (%s)", String.join("/", w1)))); + return; + } + + switch (args[0].toLowerCase()) { + case "off": + Velocity.config.get().enable = false; + Velocity.config.save(); + sender.sendMessage(Component.text("Whitelist disabled.")); + break; + + case "on": + Velocity.config.get().enable = true; + Velocity.config.save(); + sender.sendMessage(Component.text("Whitelist enabled.")); + break; + + case "add": + if (args.length < 2) { + sender.sendMessage(Component.text("Usage: /eptalist add ")); + break; + } + String usernameToAdd = args[1]; + List infoAdd = new ArrayList<>(); + if (Velocity.list.addUser(usernameToAdd, infoAdd)) { + sender.sendMessage(Component.text("User added to the whitelist: " + usernameToAdd)); + } else { + infoAdd.forEach(line -> sender.sendMessage(Component.text(line))); + } + break; + + case "remove": + if (args.length < 2) { + sender.sendMessage(Component.text("Usage: /eptalist remove ")); + break; + } + String usernameToRemove = args[1]; + List infoRemove = new ArrayList<>(); + if (Velocity.list.removeUser(usernameToRemove, infoRemove)) { + sender.sendMessage(Component.text("User removed from the whitelist: " + usernameToRemove)); + } else { + infoRemove.forEach(line -> sender.sendMessage(Component.text(line))); + } + break; + + case "list": + sender.sendMessage(Component.text("Whitelisted players: " + Velocity.list.toList())); + break; + + case "mode": + if (args.length < 2) { + sender.sendMessage(Component.text("Usage: /eptalist mode ")); + break; + } + Identifier id = Identifier.tryParse(args[1]); + if (id != null && Velocity.identifiers.contains(id)) { + Velocity.config.get().curent = id; + Velocity.config.save(); + Velocity.load(); + sender.sendMessage(Component.text("Mode set to: " + id)); + } else { + sender.sendMessage(Component.text("Invalid mode ID!")); + } + break; + case "help": + sender.sendMessage(Component.text(String.join("\n", + "1: /eptalist add - Add user to whitelist", + "2: /eptalist remove - Remove user from whitelist", + "3: /eptalist list - Display whitelisted players", + "4: /eptalist on - Enable whitelist", + "5: /eptalist off - Disable whitelist", + "6: /eptalist mode - Set list data mode", + "7: /eptalist kick_nolisted - Kick non-whitelisted players", + "8: /eptalist reload - Reload the whitelist configuration" + ))); + break; + + case "reload": + try { + Velocity.load(); + sender.sendMessage(Component.text("Configuration reloaded successfully.")); + } catch (Exception e) { + logger.error("Failed to reload the configuration.", e); + sender.sendMessage(Component.text("Failed to reload the configuration.")); + } + break; + + default: + sender.sendMessage(Component.text("Unknown command. Use /eptalist help for the list of commands.")); + break; + } + } + + @Override + public List suggest(Invocation invocation) { + String[] args = invocation.arguments(); + + if (args.length == 0) { + return ImmutableList.of(); + } else if (args.length == 1) { + return Arrays.stream(w1) + .filter(cmd -> cmd.startsWith(args[0].toLowerCase())) + .sorted(String.CASE_INSENSITIVE_ORDER) + .collect(Collectors.toList()); + } + return ImmutableList.of(); + } +} diff --git a/velocity/src/main/java/org/eptalist/velocity/metrics/Metrics.java b/velocity/src/main/java/org/eptalist/velocity/metrics/Metrics.java new file mode 100644 index 0000000..f22eba6 --- /dev/null +++ b/velocity/src/main/java/org/eptalist/velocity/metrics/Metrics.java @@ -0,0 +1,1071 @@ +package org.eptalist.velocity.metrics; + +/* + * This Metrics class was auto-generated and can be copied into your project if you are + * not using a build tool like Gradle or Maven for dependency management. + * + * IMPORTANT: You are not allowed to modify this class, except changing the package. + * + * Disallowed modifications include but are not limited to: + * - Remove the option for users to opt-out + * - Change the frequency for data submission + * - Obfuscate the code (every obfuscator should allow you to make an exception for specific files) + * - Reformat the code (if you use a linter, add an exception) + * + * Violations will result in a ban of your plugin and account from bStats. + */ + +import com.google.inject.Inject; +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 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.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.regex.Pattern; +import java.util.stream.Collectors; +import java.util.zip.GZIPOutputStream; +import javax.net.ssl.HttpsURLConnection; +import org.slf4j.Logger; + +public class Metrics { + + /** A factory to create new Metrics classes. */ + public static class Factory { + + private final ProxyServer server; + + private final Logger logger; + + private final Path dataDirectory; + + // The constructor is not meant to be called by the user. + // The instance is created using Dependency Injection + @Inject + private Factory(ProxyServer server, Logger logger, @DataDirectory Path dataDirectory) { + this.server = server; + this.logger = logger; + this.dataDirectory = dataDirectory; + } + + /** + * Creates a new Metrics class. + * + * @param plugin The plugin instance. + * @param serviceId The id of the service. It can be found at What is my plugin id? + *

Not to be confused with Velocity's {@link PluginDescription#getId()} method! + * @return A Metrics instance that can be used to register custom charts. + *

The return value can be ignored, when you do not want to register custom charts. + */ + public Metrics make(Object plugin, int serviceId) { + return new Metrics(plugin, server, logger, dataDirectory, serviceId); + } + } + + private final PluginContainer pluginContainer; + + private final ProxyServer server; + + private MetricsBase metricsBase; + + private Metrics( + Object plugin, ProxyServer server, Logger logger, Path dataDirectory, int serviceId) { + pluginContainer = + server + .getPluginManager() + .fromInstance(plugin) + .orElseThrow( + () -> new IllegalArgumentException("The provided instance is not a plugin")); + this.server = server; + File configFile = dataDirectory.getParent().resolve("bStats").resolve("config.txt").toFile(); + MetricsConfig config; + try { + config = new MetricsConfig(configFile, true); + } catch (IOException e) { + logger.error("Failed to create bStats config", e); + return; + } + metricsBase = + new MetricsBase( + "velocity", + config.getServerUUID(), + serviceId, + config.isEnabled(), + this::appendPlatformData, + this::appendServiceData, + task -> server.getScheduler().buildTask(plugin, task).schedule(), + () -> true, + logger::warn, + logger::info, + config.isLogErrorsEnabled(), + config.isLogSentDataEnabled(), + config.isLogResponseStatusTextEnabled(), + false); + if (!config.didExistBefore()) { + // Send an info message when the bStats config file gets created for the first time + logger.info( + "Velocity and some of its plugins collect metrics and send them to bStats (https://bStats.org)."); + logger.info( + "bStats collects some basic information for plugin authors, like how many people use"); + logger.info( + "their plugin and their total player count. It's recommend to keep bStats enabled, but"); + logger.info( + "if you're not comfortable with this, you can opt-out by editing the config.txt file in"); + logger.info("the '/plugins/bStats/' folder and setting enabled to false."); + } + } + + /** 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) { + if (metricsBase != null) { + metricsBase.addCustomChart(chart); + } + } + + private void appendPlatformData(JsonObjectBuilder builder) { + builder.appendField("playerAmount", server.getPlayerCount()); + builder.appendField("managedServers", server.getAllServers().size()); + builder.appendField("onlineMode", server.getConfiguration().isOnlineMode() ? 1 : 0); + builder.appendField("velocityVersionVersion", server.getVersion().getVersion()); + builder.appendField("velocityVersionName", server.getVersion().getName()); + builder.appendField("velocityVersionVendor", server.getVersion().getVendor()); + 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", pluginContainer.getDescription().getVersion().orElse("unknown")); + } + + 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(); + } + } + + 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. + * + *

This class is not used by every platform. + */ + public static class MetricsConfig { + + private final File file; + + private final boolean defaultEnabled; + + private String serverUUID; + + private boolean enabled; + + private boolean logErrors; + + private boolean logSentData; + + private boolean logResponseStatusText; + + private boolean didExistBefore = true; + + public MetricsConfig(File file, boolean defaultEnabled) throws IOException { + this.file = file; + this.defaultEnabled = defaultEnabled; + setupConfig(); + } + + public String getServerUUID() { + return serverUUID; + } + + public boolean isEnabled() { + return enabled; + } + + public boolean isLogErrorsEnabled() { + return logErrors; + } + + public boolean isLogSentDataEnabled() { + return logSentData; + } + + public boolean isLogResponseStatusTextEnabled() { + return logResponseStatusText; + } + + /** + * Checks whether the config file did exist before or not. + * + * @return If the config did exist before. + */ + public boolean didExistBefore() { + return didExistBefore; + } + + /** Creates the config file if it does not exist and read its content. */ + private void setupConfig() throws IOException { + if (!file.exists()) { + // Looks like it's the first time we create it (or someone deleted it). + didExistBefore = false; + writeConfig(); + } + readConfig(); + if (serverUUID == null) { + // Found a malformed config file with no UUID. Let's recreate it. + writeConfig(); + readConfig(); + } + } + + /** Creates a config file with teh default content. */ + private void writeConfig() throws IOException { + List configContent = new ArrayList<>(); + configContent.add( + "# bStats (https://bStats.org) collects some basic information for plugin authors, like"); + configContent.add( + "# how many people use their plugin and their total player count. It's recommended to keep"); + configContent.add( + "# bStats enabled, but if you're not comfortable with this, you can turn this setting off."); + configContent.add( + "# There is no performance penalty associated with having metrics enabled, and data sent to"); + configContent.add("# bStats is fully anonymous."); + configContent.add("enabled=" + defaultEnabled); + configContent.add("server-uuid=" + UUID.randomUUID().toString()); + configContent.add("log-errors=false"); + configContent.add("log-sent-data=false"); + configContent.add("log-response-status-text=false"); + writeFile(file, configContent); + } + + /** Reads the content of the config file. */ + private void readConfig() throws IOException { + List lines = readFile(file); + if (lines == null) { + throw new AssertionError("Content of newly created file is null"); + } + enabled = getConfigValue("enabled", lines).map("true"::equals).orElse(true); + serverUUID = getConfigValue("server-uuid", lines).orElse(null); + logErrors = getConfigValue("log-errors", lines).map("true"::equals).orElse(false); + logSentData = getConfigValue("log-sent-data", lines).map("true"::equals).orElse(false); + logResponseStatusText = + getConfigValue("log-response-status-text", lines).map("true"::equals).orElse(false); + } + + /** + * Gets a config setting from the given list of lines of the file. + * + * @param key The key for the setting. + * @param lines The lines of the file. + * @return The value of the setting. + */ + private Optional getConfigValue(String key, List lines) { + return lines.stream() + .filter(line -> line.startsWith(key + "=")) + .map(line -> line.replaceFirst(Pattern.quote(key + "="), "")) + .findFirst(); + } + + /** + * Reads the text content of the given file. + * + * @param file The file to read. + * @return The lines of the given file. + */ + private List readFile(File file) throws IOException { + if (!file.exists()) { + return null; + } + try (FileReader fileReader = new FileReader(file); + BufferedReader bufferedReader = new BufferedReader(fileReader)) { + return bufferedReader.lines().collect(Collectors.toList()); + } + } + + /** + * Writes the given lines to the given file. + * + * @param file The file to write to. + * @param lines The lines to write. + */ + private void writeFile(File file, List lines) throws IOException { + if (!file.exists()) { + file.getParentFile().mkdirs(); + file.createNewFile(); + } + try (FileWriter fileWriter = new FileWriter(file); + BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) { + for (String line : lines) { + bufferedWriter.write(line); + bufferedWriter.newLine(); + } + } + } + } +} \ No newline at end of file diff --git a/velocity/src/main/templates/org/eptalist/velocity/BuildConstants.java b/velocity/src/main/templates/org/eptalist/velocity/BuildConstants.java new file mode 100644 index 0000000..dcf9f9a --- /dev/null +++ b/velocity/src/main/templates/org/eptalist/velocity/BuildConstants.java @@ -0,0 +1,7 @@ +package org.eptalist.velocity; + +// The constants are replaced before compilation +public class BuildConstants { + + public static final String VERSION = "${version}"; +}