This commit is contained in:
坏黑 2018-09-14 20:39:49 +08:00
parent e648107f1b
commit dbf319addb
12 changed files with 231 additions and 154 deletions

View File

@ -6,7 +6,7 @@
<groupId>me.skymc</groupId> <groupId>me.skymc</groupId>
<artifactId>TabooLib</artifactId> <artifactId>TabooLib</artifactId>
<version>4.27</version> <version>4.28</version>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -14,15 +14,16 @@ import com.ilummc.tlib.resources.TLocaleLoader;
import com.ilummc.tlib.util.IO; import com.ilummc.tlib.util.IO;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.fileutils.FileUtils; import me.skymc.taboolib.fileutils.FileUtils;
import me.skymc.taboolib.plugin.PluginUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.Arrays;
@Dependency(type = Dependency.Type.LIBRARY, maven = "com.zaxxer:HikariCP:3.1.0") @Dependency(type = Dependency.Type.LIBRARY, maven = "com.zaxxer:HikariCP:3.1.0")
@Dependency(type = Dependency.Type.LIBRARY, maven = "org.slf4j:slf4j-api:1.7.25") @Dependency(type = Dependency.Type.LIBRARY, maven = "org.slf4j:slf4j-api:1.7.25")
@ -58,14 +59,6 @@ public class TLib {
} }
} }
public static TLib getTLib() {
return tLib;
}
public static YamlConfiguration getInternalLanguage() {
return internalLanguage;
}
public static void init() { public static void init() {
tLib = new TLib(); tLib = new TLib();
@ -94,6 +87,11 @@ public class TLib {
} }
public static void injectPluginManager() { public static void injectPluginManager() {
if (!tLib.isInjectEnabled() || tLib.isBlackListPluginExists()) {
TLocale.Logger.fatal("TLIB.INJECTION-DISABLED");
Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> plugin != Main.getInst()).forEach(plugin -> TDependencyInjector.inject(plugin, plugin));
return;
}
try { try {
Field field = Bukkit.getServer().getClass().getDeclaredField("pluginManager"); Field field = Bukkit.getServer().getClass().getDeclaredField("pluginManager");
field.setAccessible(true); field.setAccessible(true);
@ -101,12 +99,16 @@ public class TLib {
TLocale.Logger.info("TLIB.INJECTION-SUCCESS"); TLocale.Logger.info("TLIB.INJECTION-SUCCESS");
} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException ignored) { } catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException ignored) {
TLocale.Logger.fatal("TLIB.INJECTION-FAILED"); TLocale.Logger.fatal("TLIB.INJECTION-FAILED");
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> plugin != Main.getInst()).forEach(plugin -> TDependencyInjector.inject(plugin, plugin));
if (plugin != Main.getInst()) {
TDependencyInjector.inject(plugin, plugin);
} }
} }
public static TLib getTLib() {
return tLib;
} }
public static YamlConfiguration getInternalLanguage() {
return internalLanguage;
} }
public TLogger getLogger() { public TLogger getLogger() {
@ -124,4 +126,18 @@ public class TLib {
public File getLibsFolder() { public File getLibsFolder() {
return libsFolder; return libsFolder;
} }
// *********************************
//
// Private Methods
//
// *********************************
private boolean isInjectEnabled() {
return Main.getInst().getConfig().getBoolean("PLUGIN-INJECTOR.ENABLE", true);
}
private boolean isBlackListPluginExists() {
return Main.getInst().getConfig().getStringList("PLUGIN-INJECTOR.DISABLE-ON-PLUGIN-EXISTS").stream().anyMatch(PluginUtils::isPluginExists);
}
} }

View File

@ -165,6 +165,5 @@ public class TabooLibLoader implements Listener {
static void registerMetrics() { static void registerMetrics() {
Metrics metrics = new Metrics(TabooLib.instance()); Metrics metrics = new Metrics(TabooLib.instance());
metrics.addCustomChart(new Metrics.SingleLineChart("plugins_using_taboolib", () -> Math.toIntExact(Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> plugin.getDescription().getDepend().contains("TabooLib")).count()))); metrics.addCustomChart(new Metrics.SingleLineChart("plugins_using_taboolib", () -> Math.toIntExact(Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> plugin.getDescription().getDepend().contains("TabooLib")).count())));
metrics.addCustomChart(new Metrics.AdvancedPie("plugins_using_taboolib_name", () -> Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> plugin.getDescription().getDepend().contains("TabooLib")).collect(Collectors.toMap(Plugin::getName, plugin -> 1, (a, b) -> b))));
} }
} }

View File

@ -17,13 +17,7 @@ import java.io.IOException;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
import java.util.ArrayList; import java.util.*;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
@ -36,6 +30,15 @@ import java.util.zip.GZIPOutputStream;
*/ */
public class Metrics { public class Metrics {
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Should failed requests be logged?
private static boolean logFailedRequests;
// The uuid of the server
private static String serverUUID;
static { static {
// You can use the property to disable the check in your test environment // 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")) { if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
@ -50,18 +53,6 @@ public class Metrics {
} }
} }
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Should failed requests be logged?
private static boolean logFailedRequests;
// The uuid of the server
private static String serverUUID;
// The plugin // The plugin
private final JavaPlugin plugin; private final JavaPlugin plugin;
@ -103,7 +94,8 @@ public class Metrics {
).copyDefaults(true); ).copyDefaults(true);
try { try {
config.save(configFile); config.save(configFile);
} catch (IOException ignored) { } } catch (IOException ignored) {
}
} }
// Load the data // Load the data
@ -117,7 +109,8 @@ public class Metrics {
service.getField("B_STATS_VERSION"); // Our identifier :) service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first found = true; // We aren't the first
break; break;
} catch (NoSuchFieldException ignored) { } } catch (NoSuchFieldException ignored) {
}
} }
// Register our service // Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
@ -128,6 +121,61 @@ public class Metrics {
} }
} }
/**
* Sends the data to the bStats server.
*
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(JSONObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes("UTF-8"));
gzip.close();
return outputStream.toByteArray();
}
/** /**
* Adds a custom chart. * Adds a custom chart.
* *
@ -256,9 +304,11 @@ public class Metrics {
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) { for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try { try {
pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider())); pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider()));
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
}
}
} catch (NoSuchFieldException ignored) {
} }
} catch (NoSuchFieldException ignored) { }
} }
data.put("plugins", pluginData); data.put("plugins", pluginData);
@ -280,61 +330,6 @@ public class Metrics {
}).start(); }).start();
} }
/**
* Sends the data to the bStats server.
*
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(JSONObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes("UTF-8"));
gzip.close();
return outputStream.toByteArray();
}
/** /**
* Represents a custom chart. * Represents a custom chart.
*/ */

View File

@ -2,8 +2,8 @@ package me.skymc.taboolib.listener;
import com.ilummc.tlib.resources.TLocale; import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main; import me.skymc.taboolib.Main;
import me.skymc.taboolib.message.MsgUtils;
import me.skymc.taboolib.mysql.MysqlUtils; import me.skymc.taboolib.mysql.MysqlUtils;
import me.skymc.taboolib.mysql.hikari.HikariHandler;
import me.skymc.taboolib.mysql.protect.MySQLConnection; import me.skymc.taboolib.mysql.protect.MySQLConnection;
import me.skymc.taboolib.timecycle.TimeCycleManager; import me.skymc.taboolib.timecycle.TimeCycleManager;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
@ -12,6 +12,7 @@ import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
@TListener @TListener
@ -21,12 +22,14 @@ public class ListenerPluginDisable implements Listener {
public void disable(PluginDisableEvent e) { public void disable(PluginDisableEvent e) {
// 注销时间周期 // 注销时间周期
TimeCycleManager.cancel(e.getPlugin()); TimeCycleManager.cancel(e.getPlugin());
// 注销数据库连接
new HashSet<>(HikariHandler.getDataSource().keySet()).stream().filter(host -> e.getPlugin().equals(host.getPlugin()) && host.isAutoClose()).forEach(HikariHandler::closeDataSource);
// 获取连接 // 获取连接
List<MySQLConnection> conns = new ArrayList<>(); List<MySQLConnection> connection = new ArrayList<>();
for (MySQLConnection conn : MysqlUtils.CONNECTIONS) { for (MySQLConnection conn : MysqlUtils.CONNECTIONS) {
if (conn.getPlugin().equals(e.getPlugin())) { if (conn.getPlugin().equals(e.getPlugin())) {
conns.add(conn); connection.add(conn);
MysqlUtils.CONNECTIONS.remove(conn); MysqlUtils.CONNECTIONS.remove(conn);
} }
} }
@ -37,7 +40,7 @@ public class ListenerPluginDisable implements Listener {
@Override @Override
public void run() { public void run() {
int i = 0; int i = 0;
for (MySQLConnection conn : conns) { for (MySQLConnection conn : connection) {
conn.setFallReconnection(false); conn.setFallReconnection(false);
conn.closeConnection(); conn.closeConnection();
i++; i++;

View File

@ -18,18 +18,28 @@ public class SQLHost {
private String password; private String password;
private String database; private String database;
private Plugin plugin; private Plugin plugin;
private boolean autoClose;
public SQLHost(ConfigurationSection section, Plugin plugin) { public SQLHost(ConfigurationSection section, Plugin plugin) {
this(section, plugin, false);
}
public SQLHost(ConfigurationSection section, Plugin plugin, boolean autoClose) {
this(section.getString("host", "localhost"), section.getString("user", "root"), section.getString("port", "3306"), section.getString("password", ""), section.getString("database", "test"), plugin); this(section.getString("host", "localhost"), section.getString("user", "root"), section.getString("port", "3306"), section.getString("password", ""), section.getString("database", "test"), plugin);
} }
public SQLHost(String host, String user, String port, String password, String database, Plugin plugin) { public SQLHost(String host, String user, String port, String password, String database, Plugin plugin) {
this(host, user, port, password, database, plugin, false);
}
public SQLHost(String host, String user, String port, String password, String database, Plugin plugin, boolean autoClose) {
this.host = host; this.host = host;
this.user = user; this.user = user;
this.port = port; this.port = port;
this.password = password; this.password = password;
this.database = database; this.database = database;
this.plugin = plugin; this.plugin = plugin;
this.autoClose = false;
} }
public String getHost() { public String getHost() {
@ -56,6 +66,10 @@ public class SQLHost {
return plugin; return plugin;
} }
public boolean isAutoClose() {
return autoClose;
}
public String getConnectionUrl() { public String getConnectionUrl() {
return Strings.replaceWithOrder("jdbc:mysql://{0}:{1}/{2}?characterEncoding=utf-8&useSSL=false", this.host, this.port, this.database); return Strings.replaceWithOrder("jdbc:mysql://{0}:{1}/{2}?characterEncoding=utf-8&useSSL=false", this.host, this.port, this.database);
} }
@ -73,16 +87,18 @@ public class SQLHost {
return false; return false;
} }
SQLHost sqlHost = (SQLHost) o; SQLHost sqlHost = (SQLHost) o;
return Objects.equals(getHost(), sqlHost.getHost()) && return autoClose == sqlHost.autoClose &&
Objects.equals(getHost(), sqlHost.getHost()) &&
Objects.equals(getUser(), sqlHost.getUser()) && Objects.equals(getUser(), sqlHost.getUser()) &&
Objects.equals(getPort(), sqlHost.getPort()) && Objects.equals(getPort(), sqlHost.getPort()) &&
Objects.equals(getPassword(), sqlHost.getPassword()) && Objects.equals(getPassword(), sqlHost.getPassword()) &&
Objects.equals(getDatabase(), sqlHost.getDatabase()); Objects.equals(getDatabase(), sqlHost.getDatabase()) &&
Objects.equals(getPlugin(), sqlHost.getPlugin());
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(getHost(), getUser(), getPort(), getPassword(), getDatabase()); return Objects.hash(getHost(), getUser(), getPort(), getPassword(), getDatabase(), getPlugin(), autoClose);
} }
@Override @Override
@ -94,6 +110,7 @@ public class SQLHost {
", password='" + password + '\'' + ", password='" + password + '\'' +
", database='" + database + '\'' + ", database='" + database + '\'' +
", plugin=" + plugin + ", plugin=" + plugin +
", autoClose=" + autoClose +
'}'; '}';
} }
} }

View File

@ -26,11 +26,7 @@ public class SQLTable {
} }
public SQLTable addColumn(SQLColumn sqlColumn) { public SQLTable addColumn(SQLColumn sqlColumn) {
if (columns == null) { columns = columns == null ? new SQLColumn[] {sqlColumn} : ArrayUtils.arrayAppend(columns, sqlColumn);
columns = new SQLColumn[] {sqlColumn};
} else {
columns = ArrayUtils.arrayAppend(columns, sqlColumn);
}
return this; return this;
} }

View File

@ -89,4 +89,18 @@ public class HikariHandler {
} }
return config; return config;
} }
// *********************************
//
// Getter and Setter
//
// *********************************
public static ConcurrentHashMap<SQLHost, MapDataSource> getDataSource() {
return dataSource;
}
public static FileConfiguration getSettings() {
return settings;
}
} }

View File

@ -30,7 +30,7 @@ public class PluginUtils {
} }
public static File getPluginFile(Plugin plugin) { public static File getPluginFile(Plugin plugin) {
for (File pluginFile : Objects.requireNonNull(new File("plugins").listFiles())) { for (File pluginFile : new File("plugins").listFiles()) {
if (pluginFile.getName().endsWith(".jar")) { if (pluginFile.getName().endsWith(".jar")) {
try { try {
PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(pluginFile); PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(pluginFile);
@ -44,6 +44,21 @@ public class PluginUtils {
return null; return null;
} }
public static boolean isPluginExists(String name) {
for (File pluginFile : new File("plugins").listFiles()) {
if (pluginFile.getName().endsWith(".jar")) {
try {
PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(pluginFile);
if (desc.getName().equalsIgnoreCase(name)) {
return true;
}
} catch (Exception ignored) {
}
}
}
return false;
}
public static void enable(Plugin plugin) { public static void enable(Plugin plugin) {
if (plugin != null && !plugin.isEnabled()) { if (plugin != null && !plugin.isEnabled()) {
Bukkit.getPluginManager().enablePlugin(plugin); Bukkit.getPluginManager().enablePlugin(plugin);

View File

@ -2,7 +2,6 @@ package me.skymc.taboolib.string;
import com.ilummc.tlib.util.Strings; import com.ilummc.tlib.util.Strings;
import javax.annotation.Nullable;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
@ -20,15 +19,21 @@ import java.util.stream.IntStream;
*/ */
public class ArrayUtils { public class ArrayUtils {
public static String arrayJoin(String[] args, int start) { public static <T> int indexOf(T[] array, T obj) {
return IntStream.range(start, args.length).mapToObj(i -> args[i] + " ").collect(Collectors.joining()).trim(); return array == null || array.length == 0 ? -1 : IntStream.range(0, array.length).filter(i -> array[i] != null && array[i].equals(obj)).findFirst().orElse(-1);
}
public static <T> boolean contains(T[] array, T obj) {
return indexOf(array, obj) != -1;
} }
@SafeVarargs @SafeVarargs
public static <T> List<T> asList(T... args) { public static <T> T[] asArray(T... args) {
List<T> list = new ArrayList<>(); return args;
Collections.addAll(list, args); }
return list;
public static String arrayJoin(String[] args, int start) {
return IntStream.range(start, args.length).mapToObj(i -> args[i] + " ").collect(Collectors.joining()).trim();
} }
public static <T> T[] arrayAppend(T[] array, T obj) { public static <T> T[] arrayAppend(T[] array, T obj) {
@ -88,6 +93,13 @@ public class ArrayUtils {
return firstElement == null ? def : obj; return firstElement == null ? def : obj;
} }
@SafeVarargs
public static <T> List<T> asList(T... args) {
List<T> list = new ArrayList<>();
Collections.addAll(list, args);
return list;
}
// ********************************* // *********************************
// //
// Deprecated // Deprecated

View File

@ -24,6 +24,13 @@ LOCALE:
# 如果需要开启仍然可以在语言文件中加入 papi: true # 如果需要开启仍然可以在语言文件中加入 papi: true
USE_PAPI: false USE_PAPI: false
# 是否注入 PluginManager关闭后可能会导致部分功能出错。
PLUGIN-INJECTOR:
ENABLE: true
# 检测下面的插件并自动关闭注入
DISABLE-ON-PLUGIN-EXISTS:
- LuckPerms
# 是否启用调试模式 # 是否启用调试模式
# 启用后将收到来自其他插件的调试信息 # 启用后将收到来自其他插件的调试信息
DEBUG: false DEBUG: false

View File

@ -3,6 +3,9 @@ TLIB:
INJECTION-FAILED: INJECTION-FAILED:
- '注入失败' - '注入失败'
- '&c提前加载依赖于 TabooLib 的所有插件的相关功能' - '&c提前加载依赖于 TabooLib 的所有插件的相关功能'
INJECTION-DISABLED:
- '关闭注入'
- '&c提前加载依赖于 TabooLib 的所有插件的相关功能'
LOAD-FAIL-OFFLINE: LOAD-FAIL-OFFLINE:
- '**********************************************' - '**********************************************'
- '** TabooLib-{0} 无法在您的服务器上使用' - '** TabooLib-{0} 无法在您的服务器上使用'