From 2131be3079ee8061678d4e631c865b652bdca136 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9D=8F=E9=BB=91?= Date: Sat, 19 May 2018 11:46:55 +0800 Subject: [PATCH 1/9] =?UTF-8?q?=E7=89=88=E6=9C=AC=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=87=B3=EF=BC=9A4.03=20=E6=96=B0=E5=A2=9E=EF=BC=9ATabooLib=20?= =?UTF-8?q?=E7=A6=BB=E7=BA=BF=E7=89=88=20=E6=96=B0=E5=A2=9E=EF=BC=9A?= =?UTF-8?q?=E9=98=BB=E6=AD=A2=E5=9C=A8=E7=BA=BF=E7=89=88=E5=9C=A8=E6=97=A0?= =?UTF-8?q?=E4=BA=92=E8=81=94=E7=BD=91=E4=B8=94=E6=97=A0=E4=BE=9D=E8=B5=96?= =?UTF-8?q?=E5=BA=93=E7=9A=84=E6=9C=8D=E5=8A=A1=E5=99=A8=E4=B8=8A=E5=90=AF?= =?UTF-8?q?=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- src/main/java/com/ilummc/tlib/TLib.java | 8 +- .../ilummc/tlib/dependency/TDependency.java | 4 +- .../tlib/inject/TDependencyInjector.java | 27 +- .../ilummc/tlib/resources/TLocaleLoader.java | 3 +- src/main/java/me/skymc/taboolib/Main.java | 277 +++++++++++------- src/main/java/me/skymc/taboolib/TabooLib.java | 7 +- .../skymc/taboolib/fileutils/FileUtils.java | 29 ++ .../taboolib/mysql/builder/SQLColumn.java | 5 - src/main/resources/config.yml | 5 +- src/main/resources/lang/zh_CN.yml | 11 +- 11 files changed, 235 insertions(+), 143 deletions(-) diff --git a/pom.xml b/pom.xml index 14b6dc3..07bb135 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ me.skymc TabooLib - 4.02 + 4.03 UTF-8 diff --git a/src/main/java/com/ilummc/tlib/TLib.java b/src/main/java/com/ilummc/tlib/TLib.java index a4643ee..9c64381 100644 --- a/src/main/java/com/ilummc/tlib/TLib.java +++ b/src/main/java/com/ilummc/tlib/TLib.java @@ -13,6 +13,7 @@ import com.ilummc.tlib.resources.TLocale; import com.ilummc.tlib.resources.TLocaleLoader; import com.ilummc.tlib.util.IO; import me.skymc.taboolib.Main; +import me.skymc.taboolib.fileutils.FileUtils; import org.bukkit.Bukkit; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; @@ -49,7 +50,7 @@ public class TLib { libsFolder.mkdirs(); } try { - String yamlText = new String(IO.readFully(TLib.class.getResourceAsStream("/lang/internal.yml")), Charset.forName("utf-8")); + String yamlText = new String(IO.readFully(FileUtils.getResource("lang/internal.yml")), Charset.forName("utf-8")); internalLanguage = new YamlConfiguration(); internalLanguage.loadFromString(yamlText); } catch (IOException | InvalidConfigurationException ignored) { @@ -71,13 +72,14 @@ public class TLib { TLocaleLoader.init(); PlaceholderHook.init(); TLocaleLoader.load(Main.getInst(), false); - TDependencyInjector.inject(Main.getInst(), tLib); + } + public static void initPost() { + TDependencyInjector.inject(Main.getInst(), TLib.getTLib()); try { Pool.init(); } catch (Throwable ignored) { } - } public static void unload() { diff --git a/src/main/java/com/ilummc/tlib/dependency/TDependency.java b/src/main/java/com/ilummc/tlib/dependency/TDependency.java index 193f115..2decabc 100644 --- a/src/main/java/com/ilummc/tlib/dependency/TDependency.java +++ b/src/main/java/com/ilummc/tlib/dependency/TDependency.java @@ -52,8 +52,8 @@ public class TDependency { } private static boolean downloadMaven(String url, String groupId, String artifactId, String version, File target, String dl) { - if (Main.getInst().getConfig().getBoolean("OFFLINE-MODE")) { - TLocale.Logger.warn("DEPENDENCY.OFFLINE-DEPENDENCY-WARN"); + if (Main.isOfflineVersion()) { + TLocale.Logger.warn("DEPENDENCY.DOWNLOAD-OFFLINE"); return false; } AtomicBoolean failed = new AtomicBoolean(false); diff --git a/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java b/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java index def8e07..d8298a9 100644 --- a/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java +++ b/src/main/java/com/ilummc/tlib/inject/TDependencyInjector.java @@ -13,9 +13,23 @@ import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.lang.reflect.Field; +import java.util.HashMap; public class TDependencyInjector { + public static Dependency[] getDependencies(Object o) { + Dependency[] dependencies = new Dependency[0]; + Dependencies d = o.getClass().getAnnotation(Dependencies.class); + if (d != null) { + dependencies = d.value(); + } + Dependency d2 = o.getClass().getAnnotation(Dependency.class); + if (d2 != null) { + dependencies = new Dependency[]{d2}; + } + return dependencies; + } + public static void inject(Plugin plugin, Object o) { TLocaleLoader.load(plugin, true); injectDependencies(plugin, o); @@ -135,17 +149,7 @@ public class TDependencyInjector { } private static void injectDependencies(Plugin plugin, Object o) { - Dependency[] dependencies = new Dependency[0]; - { - Dependencies d = o.getClass().getAnnotation(Dependencies.class); - if (d != null) { - dependencies = d.value(); - } - Dependency d2 = o.getClass().getAnnotation(Dependency.class); - if (d2 != null) { - dependencies = new Dependency[]{d2}; - } - } + Dependency[] dependencies = getDependencies(o); if (dependencies.length != 0) { TLocale.Logger.info("DEPENDENCY.LOADING-START", plugin.getName()); for (Dependency dependency : dependencies) { @@ -167,5 +171,4 @@ public class TDependencyInjector { TLocale.Logger.info("DEPENDENCY.LOAD-COMPLETE"); } } - } diff --git a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java index 31ddcad..c9f6bcb 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java @@ -10,6 +10,7 @@ import me.skymc.taboocode.TabooCodeLang; import me.skymc.taboolib.Main; import me.skymc.taboolib.TabooLib; import me.skymc.taboolib.fileutils.ConfigUtils; +import me.skymc.taboolib.fileutils.FileUtils; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; @@ -140,7 +141,7 @@ public class TLocaleLoader { } private static YamlConfiguration getLocaleAtStream(Plugin plugin, File localeFile) { - InputStream localeInputSteam = plugin.getClass().getResourceAsStream("/lang/" + localeFile.getName()); + InputStream localeInputSteam = FileUtils.getResource("lang/" + localeFile.getName()); try { String yamlText = new String(IO.readFully(localeInputSteam), Charset.forName("utf-8")); YamlConfiguration yaml = new YamlConfiguration(); diff --git a/src/main/java/me/skymc/taboolib/Main.java b/src/main/java/me/skymc/taboolib/Main.java index 5eefd71..611e1d2 100644 --- a/src/main/java/me/skymc/taboolib/Main.java +++ b/src/main/java/me/skymc/taboolib/Main.java @@ -1,7 +1,8 @@ package me.skymc.taboolib; import com.ilummc.tlib.TLib; -import com.ilummc.tlib.inject.TConfigWatcher; +import com.ilummc.tlib.annotations.Dependency; +import com.ilummc.tlib.inject.TDependencyInjector; import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.anvil.AnvilContainerAPI; import me.skymc.taboolib.bstats.Metrics; @@ -17,12 +18,12 @@ import me.skymc.taboolib.database.PlayerDataManager; import me.skymc.taboolib.economy.EcoUtils; import me.skymc.taboolib.entity.EntityUtils; import me.skymc.taboolib.fileutils.ConfigUtils; +import me.skymc.taboolib.fileutils.FileUtils; import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.inventory.speciaitem.SpecialItem; import me.skymc.taboolib.javashell.JavaShell; import me.skymc.taboolib.listener.*; import me.skymc.taboolib.message.ChatCatcher; -import me.skymc.taboolib.message.MsgUtils; import me.skymc.taboolib.mysql.hikari.HikariHandler; import me.skymc.taboolib.mysql.protect.MySQLConnection; import me.skymc.taboolib.nms.item.DabItemUtils; @@ -50,6 +51,8 @@ import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; import java.io.File; +import java.io.InputStream; +import java.net.InetAddress; import java.util.Random; /** @@ -57,6 +60,14 @@ import java.util.Random; */ public class Main extends JavaPlugin implements Listener { + public Main() { + inst = this; + } + + public enum StorageType { + LOCAL, SQL + } + private static Plugin inst; private static net.milkbowl.vault.economy.Economy Economy; @@ -65,7 +76,7 @@ public class Main extends JavaPlugin implements Listener { private static File serverDataFolder; - private static StorageType storageType; + private static StorageType storageType = StorageType.LOCAL; private static boolean disable = false; @@ -75,60 +86,10 @@ public class Main extends JavaPlugin implements Listener { private static boolean started; + private static boolean isInternetOnline = false; + private FileConfiguration config = null; - public static Plugin getInst() { - return inst; - } - - public static String getPrefix() { - return "§8[§3§lTabooLib§8] §7"; - } - - public static net.milkbowl.vault.economy.Economy getEconomy() { - return Economy; - } - - public static void setEconomy(net.milkbowl.vault.economy.Economy economy) { - Economy = economy; - } - - public static File getPlayerDataFolder() { - return playerDataFolder; - } - - public static File getServerDataFolder() { - return serverDataFolder; - } - - public static StorageType getStorageType() { - return storageType; - } - - public static boolean isDisable() { - return disable; - } - - public static MySQLConnection getConnection() { - return connection; - } - - public static Language2 getExampleLanguage2() { - return exampleLanguage2; - } - - public static boolean isStarted() { - return started; - } - - public static Random getRandom() { - return NumberUtils.getRandom(); - } - - public static String getTablePrefix() { - return inst.getConfig().getString("MYSQL.PREFIX"); - } - @Override public FileConfiguration getConfig() { return config; @@ -150,71 +111,31 @@ public class Main extends JavaPlugin implements Listener { @Override public void onLoad() { - inst = this; disable = false; - // 载入配置 saveDefaultConfig(); - - // 加载依赖 + // 载入牛逼玩意儿 TLib.init(); TLib.injectPluginManager(); - - // 载入目录 + // 网络检测 + testInternet(); + // 创建文件夹 setupDataFolder(); - // 注册配置 - DataUtils.addPluginData("TabooLibrary", null); - - // 启用数据库 - if (getConfig().getBoolean("MYSQL.ENABLE")) { - // 连接数据库 - connection = new MySQLConnection(getConfig().getString("MYSQL.HOST"), getConfig().getString("MYSQL.USER"), getConfig().getString("MYSQL.POST"), getConfig().getString("MYSQL.PASSWORD"), getConfig().getString("MYSQL.DATABASE"), 30, this); - // 连接成功 - if (connection.isConnection()) { - // 创建表 - connection.createTable(getTablePrefix() + "_playerdata", "username", "configuration"); - connection.createTable(getTablePrefix() + "_plugindata", "name", "variable", "upgrade"); - connection.createTable(getTablePrefix() + "_serveruuid", "uuid", "hash"); - - // 如果没有数据 - if (!connection.isExists(getTablePrefix() + "_serveruuid", "uuid", TabooLib.getServerUID())) { - connection.intoValue(getTablePrefix() + "_serveruuid", TabooLib.getServerUID(), StringUtils.hashKeyForDisk(getDataFolder().getPath())); - } else { - String hash = connection.getValue(getTablePrefix() + "_serveruuid", "uuid", TabooLib.getServerUID(), "hash").toString(); - // 如果这个值和我的值不同 - if (!hash.equals(StringUtils.hashKeyForDisk(getDataFolder().getPath()))) { - TLocale.Logger.error("NOTIFY.ERROR-SERVER-KEY"); - // 重新生成序列号 - TabooLib.resetServerUID(); - // 关服 - Bukkit.shutdown(); - } - } - } else { - // 提示 - TLocale.Logger.error("NOTIFY.ERROR-CONNECTION-FAIL"); - // 关服 - Bukkit.shutdown(); - } - // 储存方式 - storageType = StorageType.SQL; - } else { - // 储存方式 - storageType = StorageType.LOCAL; - } + // 创建数据库 + setupDatabase(); + // 载入离线库文件 + setupLibraries(); + // 载入牛逼玩意儿 + TLib.initPost(); } @Override public void onEnable() { - // 注册指令 - getCommand("language2").setExecutor(new Language2Command()); - getCommand("taboolibrarymodule").setExecutor(new TLMCommands()); - getCommand("tabooliblocale").setExecutor(new TabooLibLocaleCommand()); - BaseMainCommand.createCommandExecutor("taboolib", new TabooLibMainCommand()); - BaseMainCommand.createCommandExecutor("taboolibplugin", new TabooLibPluginMainCommand()); - + // 注册命令 + registerCommands(); // 注册监听 registerListener(); + // 载入经济 EcoUtils.setupEconomy(); // 载入权限 @@ -243,6 +164,7 @@ public class Main extends JavaPlugin implements Listener { // 文件保存 Bukkit.getScheduler().runTaskTimerAsynchronously(this, DataUtils::saveAllCaches, 20, 20 * 120); Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> PlayerDataManager.saveAllCaches(true, false), 20, 20 * 60); + // 文件监控 TLib.getTLib().getConfigWatcher().addListener(new File(getDataFolder(), "config.yml"), null, obj -> { reloadConfig(); @@ -254,9 +176,11 @@ public class Main extends JavaPlugin implements Listener { @Override public void run() { + // 载入 PlaceholderAPI 扩展 if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { new SupportPlaceholder(getInst(), "taboolib").hook(); } + // 载入 ProtocolLib 扩展 if (PacketUtils.isProtocolLibEnabled()) { TagAPI.inst(); } @@ -328,12 +252,29 @@ public class Main extends JavaPlugin implements Listener { connection.closeConnection(); } + // 卸载牛逼玩意儿 TLib.unload(); // 关闭服务器 Bukkit.shutdown(); } + private void testInternet() { + try { + InetAddress inetAddress = InetAddress.getByName(getConfig().getString("TEST-URL", "aliyun.com")); + isInternetOnline = inetAddress.isReachable(10000); + } catch (Exception ignored) { + } + if (!isInternetOnline() && !isOfflineVersion() && !isLibrariesExists()) { + TLocale.Logger.error("TLIB.LOAD-FAIL-OFFLINE", getDescription().getVersion()); + // 死锁 + try { + Thread.sleep(Long.MAX_VALUE); + } catch (Exception ignored) { + } + } + } + private void setupDataFolder() { playerDataFolder = new File(getConfig().getString("DATAURL.PLAYER-DATA")); if (!playerDataFolder.exists()) { @@ -345,6 +286,56 @@ public class Main extends JavaPlugin implements Listener { } } + private void setupLibraries() { + if (!isOfflineVersion()) { + return; + } + for (Dependency dependency : TDependencyInjector.getDependencies(TLib.getTLib())) { + if (dependency.type() == Dependency.Type.LIBRARY && dependency.maven().matches(".*:.*:.*")) { + String fileName = String.join("-", dependency.maven().split(":")) + ".jar"; + File targetFile = FileUtils.file(TLib.getTLib().getLibsFolder(), fileName); + InputStream inputStream = FileUtils.getResource("libs/" + fileName); + if (!targetFile.exists() && inputStream != null) { + FileUtils.inputStreamToFile(inputStream, FileUtils.file(TLib.getTLib().getLibsFolder(), fileName)); + } + } + } + } + + private void setupDatabase() { + DataUtils.addPluginData("TabooLibrary", null); + if (getConfig().getBoolean("MYSQL.ENABLE")) { + connection = new MySQLConnection(getConfig().getString("MYSQL.HOST"), getConfig().getString("MYSQL.USER"), getConfig().getString("MYSQL.POST"), getConfig().getString("MYSQL.PASSWORD"), getConfig().getString("MYSQL.DATABASE"), 30, this); + if (connection.isConnection()) { + connection.createTable(getTablePrefix() + "_playerdata", "username", "configuration"); + connection.createTable(getTablePrefix() + "_plugindata", "name", "variable", "upgrade"); + connection.createTable(getTablePrefix() + "_serveruuid", "uuid", "hash"); + if (!connection.isExists(getTablePrefix() + "_serveruuid", "uuid", TabooLib.getServerUID())) { + connection.intoValue(getTablePrefix() + "_serveruuid", TabooLib.getServerUID(), StringUtils.hashKeyForDisk(getDataFolder().getPath())); + } else { + String hash = connection.getValue(getTablePrefix() + "_serveruuid", "uuid", TabooLib.getServerUID(), "hash").toString(); + if (!hash.equals(StringUtils.hashKeyForDisk(getDataFolder().getPath()))) { + TLocale.Logger.error("NOTIFY.ERROR-SERVER-KEY"); + TabooLib.resetServerUID(); + Bukkit.shutdown(); + } + } + } else { + TLocale.Logger.error("NOTIFY.ERROR-CONNECTION-FAIL"); + Bukkit.shutdown(); + } + storageType = StorageType.SQL; + } + } + + private void registerCommands() { + getCommand("language2").setExecutor(new Language2Command()); + getCommand("taboolibrarymodule").setExecutor(new TLMCommands()); + getCommand("tabooliblocale").setExecutor(new TabooLibLocaleCommand()); + BaseMainCommand.createCommandExecutor("taboolib", new TabooLibMainCommand()); + BaseMainCommand.createCommandExecutor("taboolibplugin", new TabooLibPluginMainCommand()); + } + private void registerListener() { getServer().getPluginManager().registerEvents(this, this); getServer().getPluginManager().registerEvents(new ListenerPlayerCommand(), this); @@ -368,7 +359,73 @@ public class Main extends JavaPlugin implements Listener { } } - public enum StorageType { - LOCAL, SQL + // ********************************* + // + // Getter and Setter + // + // ********************************* + + public static Plugin getInst() { + return inst; + } + + public static String getPrefix() { + return "§8[§3§lTabooLib§8] §7"; + } + + public static net.milkbowl.vault.economy.Economy getEconomy() { + return Economy; + } + + public static void setEconomy(net.milkbowl.vault.economy.Economy economy) { + Economy = economy; + } + + public static File getPlayerDataFolder() { + return playerDataFolder; + } + + public static File getServerDataFolder() { + return serverDataFolder; + } + + public static StorageType getStorageType() { + return storageType; + } + + public static boolean isDisable() { + return disable; + } + + public static MySQLConnection getConnection() { + return connection; + } + + public static Language2 getExampleLanguage2() { + return exampleLanguage2; + } + + public static boolean isStarted() { + return started; + } + + public static Random getRandom() { + return NumberUtils.getRandom(); + } + + public static String getTablePrefix() { + return inst.getConfig().getString("MYSQL.PREFIX"); + } + + public static boolean isInternetOnline() { + return isInternetOnline; + } + + public static boolean isOfflineVersion() { + return inst.getResource("libs") != null; + } + + public static boolean isLibrariesExists() { + return TLib.getTLib().getLibsFolder().listFiles().length > 0; } } diff --git a/src/main/java/me/skymc/taboolib/TabooLib.java b/src/main/java/me/skymc/taboolib/TabooLib.java index beceeff..1e3c84c 100644 --- a/src/main/java/me/skymc/taboolib/TabooLib.java +++ b/src/main/java/me/skymc/taboolib/TabooLib.java @@ -1,5 +1,6 @@ package me.skymc.taboolib; +import me.skymc.taboolib.other.NumberUtils; import me.skymc.taboolib.playerdata.DataUtils; import net.md_5.bungee.api.ChatColor; import org.bukkit.Bukkit; @@ -37,11 +38,7 @@ public class TabooLib { } public static double getPluginVersion() { - try { - return Double.valueOf(Main.getInst().getDescription().getVersion()); - } catch (Exception e) { - return 0D; - } + return NumberUtils.getDouble(Main.getInst().getDescription().getVersion()); } public static String getVersion() { diff --git a/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java b/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java index 19d2587..a3040e4 100644 --- a/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java +++ b/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java @@ -1,6 +1,8 @@ package me.skymc.taboolib.fileutils; import ch.njol.util.Closeable; +import com.ilummc.tlib.util.IO; +import me.skymc.taboolib.Main; import org.apache.commons.io.IOUtils; import java.io.*; @@ -8,7 +10,9 @@ import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.nio.channels.FileChannel; +import java.nio.charset.Charset; import java.util.Objects; +import java.util.logging.Level; public class FileUtils { @@ -43,6 +47,31 @@ public class FileUtils { } } + public static InputStream getResource(String filename) { + try { + URL url = Main.class.getClassLoader().getResource(filename); + if (url == null) { + return null; + } else { + URLConnection connection = url.openConnection(); + connection.setUseCaches(false); + return connection.getInputStream(); + } + } catch (IOException ignored) { + return null; + } + } + + public static void inputStreamToFile(InputStream inputStream, File file) { + try { + String text = new String(IO.readFully(inputStream), Charset.forName("utf-8")); + FileWriter fileWriter = new FileWriter(FileUtils.createNewFile(file)); + fileWriter.write(text); + fileWriter.close(); + } catch (IOException ignored) { + } + } + /** * 检测文件并创建 * diff --git a/src/main/java/me/skymc/taboolib/mysql/builder/SQLColumn.java b/src/main/java/me/skymc/taboolib/mysql/builder/SQLColumn.java index cf5da50..c209065 100644 --- a/src/main/java/me/skymc/taboolib/mysql/builder/SQLColumn.java +++ b/src/main/java/me/skymc/taboolib/mysql/builder/SQLColumn.java @@ -10,11 +10,6 @@ import java.util.Arrays; */ public class SQLColumn { - public static void main(String[] args) { - SQLColumn column2 = new SQLColumn(SQLColumnType.INT, "player_title", "无"); - System.out.println(column2.convertToCommand()); - } - /** * 类型 */ diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 93de0ee..91a40b6 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -17,9 +17,8 @@ DATAURL: # 启用后将收到来自其他插件的调试信息 DEBUG: false -# 是否启用离线模式 -# 离线模式下将不会下载依赖 -OFFLINE-MODE: false +# 网络连接测试地址 +TEST-URL: 'aliyun.com' # 下载依赖时启用的线程数 DOWNLOAD-POOL-SIZE: 4 diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index a236c96..87c8819 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -1,9 +1,18 @@ TLIB: INJECTION-SUCCESS: '注入成功' INJECTION-FAILED: '注入失败' + LOAD-FAIL-OFFLINE: + - '**********************************************' + - '** TabooLib-{0} 无法在您的服务器上使用' + - '**' + - '** 您的服务器尚未连接互联网导致本插件无法正常载入' + - '** 请使用离线版本或是手动下载依赖库文件' + - '**' + - '** 详情查阅: https://github.com/Bkm016/TabooLib' + - '**********************************************' DEPENDENCY: - OFFLINE-DEPENDENCY-WARN: '已启用离线模式, 将不会下载第三方依赖库' + DOWNLOAD-OFFLINE: '已启用离线模式, 将不会下载第三方依赖库' DOWNLOAD-CONNECTED: ' 正在下载 {0} 大小 {1}' DOWNLOAD-PROGRESS: ' 下载速度 {0} 进度 {1}' DOWNLOAD-SUCCESS: ' 下载 {0} 完成' From ffa2d616c42d6352cb0d8ee6aee75dac14348c40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9D=8F=E9=BB=91?= Date: Sat, 19 May 2018 23:46:07 +0800 Subject: [PATCH 2/9] Update README.md --- README.md | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 8031631..5ff24bb 100644 --- a/README.md +++ b/README.md @@ -8,25 +8,17 @@ [![](https://img.shields.io/github/stars/Bkm016/TabooLib.svg?style=flat-square&label=Stars)](https://github.com/Bkm016/TabooLib) [![](https://jitpack.io/v/Bkm016/TabooLib.svg)](https://jitpack.io/#Bkm016/TabooLib) -## 安装 TabooLib - -#### 服务器有网络: -1. 在[这里](https://github.com/bkm016/TabooLib/releases)下载最新版的 **TabooLib** -2. 正常步骤安装 - -#### 服务器无网络: -1. 重复上面步骤 -2. 在[这里](https://skymc.oss-cn-shanghai.aliyuncs.com/plugins/libs.rar)下载 **TabooLib** 所需要的第三方库 -3. 解压后覆盖 **"plugins"** 文件夹(注意不是丢到 **"plugins"** 文件夹里) - -#### 服务端为 1.7.10 版本 -1. 重复上面步骤 -2. 查阅[文档](https://blog.yumc.pw/posts/Fix-Thermos-Load-Plugin-Class-Not-Found/), 获取解决办法 - ## 插件文档 [TabooLib 文档](https://bkm016.github.io/TabooLib/#/) +## 下载 TabooLib 插件 + +在 [这里](https://github.com/bkm016/TabooLib/releases) 根据您服务器的网络状态下载**在线**或**离线**版本 +离线版为 **offline** 结尾的 **jar** 文件 + +如果你的服务器是 **1.7.10** 版本,在 [这里](https://pcd.ac.cn/2018/05/19/71/) 修复因 **SpecialSource** 版本过低导致插件无法载入的问题 + ## 添加 TabooLib 为库 ### Maven From 0acf324b152a397edd9bda82199b497a0340abfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9D=8F=E9=BB=91?= Date: Wed, 23 May 2018 04:36:51 +0800 Subject: [PATCH 3/9] =?UTF-8?q?=E7=89=88=E6=9C=AC=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=87=B3=EF=BC=9A4.04=20=E8=B0=83=E6=95=B4=EF=BC=9A=E5=91=BD?= =?UTF-8?q?=E4=BB=A4=E5=B8=AE=E5=8A=A9=E7=9A=84=E6=A0=BC=E5=BC=8F=E7=8E=B0?= =?UTF-8?q?=E5=9C=A8=E5=8F=AF=E4=BB=A5=E5=9C=A8=E8=AF=AD=E8=A8=80=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E4=B8=AD=E6=9B=B4=E6=94=B9=E4=BA=86=E3=80=82=20?= =?UTF-8?q?=E8=B0=83=E6=95=B4=EF=BC=9A@CommandRegister=20=E7=8E=B0?= =?UTF-8?q?=E5=9C=A8=E5=8F=AF=E4=BB=A5=E7=9B=B4=E6=8E=A5=E6=A0=87=E6=B3=A8?= =?UTF-8?q?=E5=9C=A8=20BaseSubCommand=20=E6=88=90=E5=91=98=E5=8F=98?= =?UTF-8?q?=E9=87=8F=E4=B8=8A=E8=BF=9B=E8=A1=8C=E6=B3=A8=E5=86=8C=E4=BA=86?= =?UTF-8?q?=EF=BC=88=E8=AF=A6=E8=A7=81=20TabooLibPluginMainCommand=20?= =?UTF-8?q?=E5=86=99=E6=B3=95=EF=BC=89=E3=80=82=20=E8=B0=83=E6=95=B4?= =?UTF-8?q?=EF=BC=9ATagAPI=EF=BC=8CTagManager=20=E4=BD=9C=E5=BA=9F?= =?UTF-8?q?=EF=BC=8C=E4=BD=86=E9=83=A8=E5=88=86=E6=96=B9=E6=B3=95=E4=BB=8D?= =?UTF-8?q?=E5=8F=AF=E4=BD=BF=E7=94=A8=E3=80=82=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=EF=BC=9ABaseSubCommand=20=E7=B1=BB=E6=96=B0=E5=A2=9E=20getPerm?= =?UTF-8?q?ission=20=E6=96=B9=E6=B3=95=E7=94=A8=E4=BA=8E=E5=88=A4=E6=96=AD?= =?UTF-8?q?=E5=AD=90=E5=91=BD=E4=BB=A4=E6=9D=83=E9=99=90=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=EF=BC=9ATagDataHandler=20=E7=B1=BB=E7=94=A8=E4=BA=8E?= =?UTF-8?q?=E4=BB=A3=E6=9B=BF=20TagManager=20=E7=B1=BB=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=EF=BC=9ATagPacket=20=E7=B1=BB=E7=94=A8=E4=BA=8E?= =?UTF-8?q?=E4=BB=A3=E6=9B=BF=20TagAPI=20=E7=B1=BB=20=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=EF=BC=9A=E5=89=8D=E5=90=8E=E7=BC=80=E4=BB=A5=E5=8F=8A=E6=98=B5?= =?UTF-8?q?=E7=A7=B0=E7=9A=84=E5=90=84=E7=A7=8D=E4=B8=8D=E5=85=BC=E5=AE=B9?= =?UTF-8?q?=E9=97=AE=E9=A2=98=20=E4=BF=AE=E5=A4=8D=EF=BC=9AItemUtils=20?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E8=BD=BD=E5=85=A5=E7=89=A9=E5=93=81=E6=97=B6?= =?UTF-8?q?=E5=9B=A0=20material=20=E5=80=BC=E4=B8=8D=E5=AD=98=E5=9C=A8?= =?UTF-8?q?=E8=80=8C=E5=AF=BC=E8=87=B4=E7=9A=84=E6=8A=A5=E9=94=99=20?= =?UTF-8?q?=E5=88=A0=E9=99=A4=EF=BC=9Ame.skymc.taboolib.team.TagUtils=20?= =?UTF-8?q?=E7=B1=BB=E6=B0=B8=E4=B9=85=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ilummc/tlib/dependency/TDependency.java | 2 +- .../ilummc/tlib/inject/TConfigInjector.java | 188 +-- src/main/java/me/skymc/taboolib/Main.java | 18 +- .../me/skymc/taboolib/bstats/Metrics.java | 2 +- .../commands/TabooLibMainCommand.java | 1124 ++++++++--------- .../commands/internal/BaseMainCommand.java | 31 +- .../commands/internal/BaseSubCommand.java | 23 +- .../commands/internal/TBaseCommand.java | 19 + .../internal/type/CommandArgument.java | 4 +- .../commands/internal/type/CommandField.java | 26 + .../internal/type/CommandRegister.java | 2 +- .../plugin/TabooLibPluginMainCommand.java | 383 +++--- .../commands/taboolib/SaveCommand.java | 2 +- .../commands/taboolib/TagDeleteCommand.java | 6 +- .../commands/taboolib/TagDisplayCommand.java | 8 +- .../commands/taboolib/TagPrefixCommand.java | 46 +- .../commands/taboolib/TagSuffixCommand.java | 12 +- .../skymc/taboolib/inventory/ItemUtils.java | 821 ++++++------ .../taboolib/itagapi/TagDataHandler.java | 191 +++ .../me/skymc/taboolib/itagapi/TagPacket.java | 136 ++ .../skymc/taboolib/itagapi/TagPlayerData.java | 84 ++ .../me/skymc/taboolib/itagapi/TagUtils.java | 62 + .../java/me/skymc/taboolib/nms/NMSUtil18.java | 20 +- .../java/me/skymc/taboolib/nms/NMSUtil19.java | 22 +- .../string/language2/Language2Format.java | 219 ++-- .../java/me/skymc/taboolib/team/TagAPI.java | 117 +- .../me/skymc/taboolib/team/TagManager.java | 138 +- .../java/me/skymc/taboolib/team/TagUtils.java | 131 -- src/main/resources/lang/zh_CN.yml | 3 + 29 files changed, 1996 insertions(+), 1844 deletions(-) create mode 100644 src/main/java/me/skymc/taboolib/commands/internal/TBaseCommand.java create mode 100644 src/main/java/me/skymc/taboolib/commands/internal/type/CommandField.java create mode 100644 src/main/java/me/skymc/taboolib/itagapi/TagDataHandler.java create mode 100644 src/main/java/me/skymc/taboolib/itagapi/TagPacket.java create mode 100644 src/main/java/me/skymc/taboolib/itagapi/TagPlayerData.java create mode 100644 src/main/java/me/skymc/taboolib/itagapi/TagUtils.java delete mode 100644 src/main/java/me/skymc/taboolib/team/TagUtils.java diff --git a/src/main/java/com/ilummc/tlib/dependency/TDependency.java b/src/main/java/com/ilummc/tlib/dependency/TDependency.java index 2decabc..50d7494 100644 --- a/src/main/java/com/ilummc/tlib/dependency/TDependency.java +++ b/src/main/java/com/ilummc/tlib/dependency/TDependency.java @@ -84,4 +84,4 @@ public class TDependency { private static int getDownloadPoolSize() { return Main.getInst().getConfig().getInt("DOWNLOAD-POOL-SIZE", 4); } -} +} \ No newline at end of file diff --git a/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java b/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java index d7f788d..6d2e4bf 100644 --- a/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java +++ b/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java @@ -1,113 +1,61 @@ package com.ilummc.tlib.inject; +import com.google.common.collect.Lists; import com.google.common.io.Files; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.ilummc.tlib.annotations.TConfig; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.fileutils.ConfigUtils; +import com.google.gson.annotations.SerializedName; +import com.ilummc.tlib.TLib; +import com.ilummc.tlib.annotations.Config; +import com.ilummc.tlib.bean.Property; import org.apache.commons.lang3.Validate; -import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.configuration.serialization.ConfigurationSerialization; import org.bukkit.plugin.Plugin; import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.IOException; +import java.lang.reflect.Array; import java.lang.reflect.Field; import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.Map; +import java.util.*; +import java.util.stream.Collectors; public class TConfigInjector { - public static void fixUnicode(YamlConfiguration configuration) { - try { - Field field = YamlConfiguration.class.getDeclaredField("yamlOptions"); - field.setAccessible(true); - field.set(configuration, NoUnicodeDumperOption.INSTANCE); - } catch (NoSuchFieldException | IllegalAccessException e) { - e.printStackTrace(); - } - } - - private static final class NoUnicodeDumperOption extends DumperOptions { - - private static final NoUnicodeDumperOption INSTANCE = new NoUnicodeDumperOption(); - - @Override - public void setAllowUnicode(boolean allowUnicode) { - super.setAllowUnicode(false); - } - - @Override - public boolean isAllowUnicode() { - return false; - } - - @Override - public void setLineBreak(LineBreak lineBreak) { - super.setLineBreak(LineBreak.getPlatformLineBreak()); - } - } - public static Object loadConfig(Plugin plugin, Class clazz) { try { - TConfig config = clazz.getAnnotation(TConfig.class); + Config config = clazz.getAnnotation(Config.class); Validate.notNull(config); File file = new File(plugin.getDataFolder(), config.name()); - if (!file.exists()) { - if (config.fromJar()) { - plugin.saveResource(config.name(), true); - } else { - saveConfig(plugin, clazz.newInstance()); - } - } - Object obj = unserialize(plugin, clazz); - if (config.readOnly()) { - saveConfig(plugin, obj); - } - return obj; + if (!file.exists()) if (config.fromJar()) plugin.saveResource(config.name(), true); + else saveConfig(plugin, clazz.newInstance()); + return unserialize(plugin, clazz); } catch (NullPointerException e) { - TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), clazz.getSimpleName()); + TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败:没有 @Config 注解"); } catch (Exception e) { - TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName()); + TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败"); } return null; } - public static void reloadConfig(Plugin plugin, Object object) { - try { - TConfig config = object.getClass().getAnnotation(TConfig.class); - Validate.notNull(config); - File file = new File(plugin.getDataFolder(), config.name()); - Map map = ConfigUtils.confToMap(ConfigUtils.loadYaml(plugin, file)); - Object obj = ConfigUtils.mapToObj(map, object); - if (config.readOnly()) { - saveConfig(plugin, obj); - } - } catch (NullPointerException e) { - TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName()); - } catch (Exception e) { - TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), object.getClass().getSimpleName()); - } - } - public static Object unserialize(Plugin plugin, Class clazz) { try { - TConfig config = clazz.getAnnotation(TConfig.class); + Config config = clazz.getAnnotation(Config.class); Validate.notNull(config); - return ConfigUtils.confToObj( - ConfigUtils.mapToConf( - ConfigUtils.yamlToMap( - Files.toString(new File(plugin.getDataFolder(), config.name()), Charset.forName(config.charset())))), clazz); + return new GsonBuilder().disableHtmlEscaping().excludeFieldsWithModifiers(config.excludeModifiers()) + .create().fromJson(new Gson().toJson(new Yaml() + .dump(Files.toString(new File(plugin.getDataFolder(), config.name()), Charset.forName(config.charset())))), clazz); } catch (NullPointerException e) { - TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-FILE", plugin.toString(), clazz.getSimpleName()); + TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败:没有 @Config 注解或文件不存在"); return null; } catch (Exception e) { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e1) { - TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName()); + TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败"); return null; } } @@ -115,29 +63,95 @@ public class TConfigInjector { public static Map serialize(Plugin plugin, Object object) { try { - TConfig config = object.getClass().getAnnotation(TConfig.class); + Config config = object.getClass().getAnnotation(Config.class); Validate.notNull(config); - return ConfigUtils.objToMap(ConfigUtils.objToConf(object).getValues(false), config.excludeModifiers()); + return new Serializer(new LinkedHashMap<>(), object, config.excludeModifiers()).get(); } catch (NullPointerException e) { - TLocale.Logger.warn("CONFIG.SAVE-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName()); + TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + object.getClass().getSimpleName() + " 序列化失败:没有 @Config 注解"); } catch (Exception e) { - TLocale.Logger.warn("CONFIG.SAVE-FAIL", plugin.toString(), object.getClass().getSimpleName()); + TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + object.getClass().getSimpleName() + " 序列化失败"); } return null; } public static void saveConfig(Plugin plugin, Object object) throws IOException, NullPointerException { - TConfig config = object.getClass().getAnnotation(TConfig.class); + Config config = object.getClass().getAnnotation(Config.class); Validate.notNull(config); - Gson gson = new GsonBuilder().disableHtmlEscaping().create(); - Map map = gson.fromJson(gson.toJson(object), HashMap.class); - YamlConfiguration configuration = (YamlConfiguration) ConfigUtils.mapToConf(map); + Object obj = serialize(plugin, object); + Validate.notNull(obj); File target = new File(plugin.getDataFolder(), config.name()); - if (!target.exists()) { - target.createNewFile(); - } - byte[] arr = configuration.saveToString().getBytes(config.charset()); + if (!target.exists()) target.createNewFile(); + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Yaml yaml = new Yaml(options); + String str = yaml.dump(obj); + byte[] arr = str.getBytes(config.charset()); Files.write(arr, target); } + private static final List> primitiveType = Lists.newArrayList(Integer.class, + Double.class, Float.class, Boolean.class, Short.class, Byte.class, Character.class, Long.class, String.class); + + private static class Serializer { + + private HashMap map; + private Object o; + private int modifiers; + + private Serializer(HashMap map, Object o, int modifiers) { + this.map = map; + this.o = o; + this.modifiers = modifiers; + } + + private HashMap get() { + for (Field field : o.getClass().getDeclaredFields()) { + if ((field.getModifiers() & modifiers) == 0 && !field.isSynthetic()) + try { + SerializedName node = field.getAnnotation(SerializedName.class); + if (!field.isAccessible()) field.setAccessible(true); + Object obj = field.get(o); + map.put(node == null ? field.getName() : node.value(), serialize(obj)); + } catch (Exception ignored) { + } + } + return map; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private Object serialize(Object o) { + try { + if (o.getClass().isPrimitive() || primitiveType.contains(o.getClass())) { + return o; + } else if (o.getClass().isArray()) { + List list = new ArrayList<>(); + int len = (int) o.getClass().getField("length").get(o); + for (int i = 0; i < len; i++) { + list.add(serialize(Array.get(o, i))); + } + return list; + } else if (o instanceof Collection) { + return ((Collection) o).stream().map(this::serialize).collect(Collectors.toList()); + } else if (o instanceof Map) { + Map map = new LinkedHashMap<>(); + ((Map) o).forEach((o1, o2) -> map.put((String) o1, serialize(o2))); + return map; + } else if (o instanceof ConfigurationSerializable) { + Map map = new LinkedHashMap<>(); + map.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, + ConfigurationSerialization.getAlias((Class) o.getClass())); + map.putAll(((ConfigurationSerializable) o).serialize()); + return map; + } else if (o instanceof Property) { + return serialize(((Property) o).get()); + } else { + return new Serializer(new HashMap<>(), o, modifiers).get(); + } + } catch (Exception ignored) { + return null; + } + } + + } + } diff --git a/src/main/java/me/skymc/taboolib/Main.java b/src/main/java/me/skymc/taboolib/Main.java index 611e1d2..a181285 100644 --- a/src/main/java/me/skymc/taboolib/Main.java +++ b/src/main/java/me/skymc/taboolib/Main.java @@ -8,6 +8,7 @@ import me.skymc.taboolib.anvil.AnvilContainerAPI; import me.skymc.taboolib.bstats.Metrics; import me.skymc.taboolib.commands.TabooLibMainCommand; import me.skymc.taboolib.commands.internal.BaseMainCommand; +import me.skymc.taboolib.commands.internal.TBaseCommand; import me.skymc.taboolib.commands.language.Language2Command; import me.skymc.taboolib.commands.locale.TabooLibLocaleCommand; import me.skymc.taboolib.commands.plugin.TabooLibPluginMainCommand; @@ -21,6 +22,7 @@ import me.skymc.taboolib.fileutils.ConfigUtils; import me.skymc.taboolib.fileutils.FileUtils; import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.inventory.speciaitem.SpecialItem; +import me.skymc.taboolib.itagapi.TagDataHandler; import me.skymc.taboolib.javashell.JavaShell; import me.skymc.taboolib.listener.*; import me.skymc.taboolib.message.ChatCatcher; @@ -28,7 +30,6 @@ import me.skymc.taboolib.mysql.hikari.HikariHandler; import me.skymc.taboolib.mysql.protect.MySQLConnection; import me.skymc.taboolib.nms.item.DabItemUtils; import me.skymc.taboolib.other.NumberUtils; -import me.skymc.taboolib.packet.PacketUtils; import me.skymc.taboolib.permission.PermissionUtils; import me.skymc.taboolib.playerdata.DataUtils; import me.skymc.taboolib.sign.SignUtils; @@ -36,8 +37,6 @@ import me.skymc.taboolib.skript.SkriptHandler; import me.skymc.taboolib.string.StringUtils; import me.skymc.taboolib.string.language2.Language2; import me.skymc.taboolib.support.SupportPlaceholder; -import me.skymc.taboolib.team.TagAPI; -import me.skymc.taboolib.team.TagUtils; import me.skymc.taboolib.timecycle.TimeCycleManager; import me.skymc.taboolib.update.UpdateTask; import me.skymc.tlm.TLM; @@ -150,6 +149,8 @@ public class Main extends JavaPlugin implements Listener { JavaShell.javaShellSetup(); // 注册脚本 SkriptHandler.getInst(); + // 注册头衔 + TagDataHandler.init(this); // 载入语言文件 exampleLanguage2 = new Language2("Language2", this); @@ -180,10 +181,6 @@ public class Main extends JavaPlugin implements Listener { if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { new SupportPlaceholder(getInst(), "taboolib").hook(); } - // 载入 ProtocolLib 扩展 - if (PacketUtils.isProtocolLibEnabled()) { - TagAPI.inst(); - } // 载入 SpecialItem 接口 SpecialItem.getInst().loadItems(); // 载入 TLM 接口 @@ -244,9 +241,6 @@ public class Main extends JavaPlugin implements Listener { // 提示信息 TLocale.Logger.error("NOTIFY.SUCCESS-DISABLE"); - // 清理头衔 - TagUtils.delete(); - // 结束连接 if (connection != null && connection.isConnection()) { connection.closeConnection(); @@ -332,8 +326,8 @@ public class Main extends JavaPlugin implements Listener { getCommand("language2").setExecutor(new Language2Command()); getCommand("taboolibrarymodule").setExecutor(new TLMCommands()); getCommand("tabooliblocale").setExecutor(new TabooLibLocaleCommand()); - BaseMainCommand.createCommandExecutor("taboolib", new TabooLibMainCommand()); - BaseMainCommand.createCommandExecutor("taboolibplugin", new TabooLibPluginMainCommand()); + TBaseCommand.registerCommand("taboolib", new TabooLibMainCommand()); + TBaseCommand.registerCommand("taboolibplugin", new TabooLibPluginMainCommand()); } private void registerListener() { diff --git a/src/main/java/me/skymc/taboolib/bstats/Metrics.java b/src/main/java/me/skymc/taboolib/bstats/Metrics.java index da4da6a..8866d16 100644 --- a/src/main/java/me/skymc/taboolib/bstats/Metrics.java +++ b/src/main/java/me/skymc/taboolib/bstats/Metrics.java @@ -224,7 +224,7 @@ public class Metrics { playerAmount = Bukkit.getOnlinePlayers().size(); } int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = org.bukkit.Bukkit.getVersion(); + String bukkitVersion = Bukkit.getVersion(); bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1); // OS/Java specific data diff --git a/src/main/java/me/skymc/taboolib/commands/TabooLibMainCommand.java b/src/main/java/me/skymc/taboolib/commands/TabooLibMainCommand.java index a036026..2db286c 100644 --- a/src/main/java/me/skymc/taboolib/commands/TabooLibMainCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/TabooLibMainCommand.java @@ -22,765 +22,705 @@ public class TabooLibMainCommand extends BaseMainCommand { } @CommandRegister(priority = 1) - void save() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand save = new BaseSubCommand() { - @Override - public String getLabel() { - return "save"; - } + @Override + public String getLabel() { + return "save"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.SAVE.DESCRIPTION"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.SAVE.DESCRIPTION"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.SAVE.ARGUMENTS.0"))}; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.SAVE.ARGUMENTS.0"))}; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new SaveCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new SaveCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 2) - void item() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand item = new BaseSubCommand() { - @Override - public String getLabel() { - return "item"; - } + @Override + public String getLabel() { + return "item"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.ITEM.DESCRIPTION"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.ITEM.DESCRIPTION"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{ - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.ITEM.ARGUMENTS.0")), - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.ITEM.ARGUMENTS.1"), false), - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.ITEM.ARGUMENTS.2"), false) - }; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{ + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.ITEM.ARGUMENTS.0")), + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.ITEM.ARGUMENTS.1"), false), + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.ITEM.ARGUMENTS.2"), false) + }; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new ItemCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new ItemCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 3) - void itemInfo() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand itemInfo = new BaseSubCommand() { - @Override - public String getLabel() { - return "itemInfo"; - } + @Override + public String getLabel() { + return "itemInfo"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.ITEMLIST.DESCRIPTION"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.ITEMLIST.DESCRIPTION"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[0]; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new InfoCommand(sender, args); - } - }); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new InfoCommand(sender, args); + } + }; @CommandRegister(priority = 3.1) - void infoList() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand infoList = new BaseSubCommand() { - @Override - public String getLabel() { - return "itemList"; - } + @Override + public String getLabel() { + return "itemList"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.ITEMLIST.DESCRIPTION"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.ITEMLIST.DESCRIPTION"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[0]; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new ItemListCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new ItemListCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 4) - void itemReload() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand itemReload = new BaseSubCommand() { - @Override - public String getLabel() { - return "itemReload"; - } + @Override + public String getLabel() { + return "itemReload"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.ITEMRELOAD.DESCRIPTION"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.ITEMRELOAD.DESCRIPTION"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[0]; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - ItemUtils.reloadItemCache(); - ItemUtils.reloadItemName(); - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEMRELOAD.SUCCESS-RELOAD"); - } - }); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + ItemUtils.reloadItemCache(); + ItemUtils.reloadItemName(); + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEMRELOAD.SUCCESS-RELOAD"); + } + }; @CommandRegister(priority = 5) - void emptyLine1() { - registerSubCommand(null); - } + BaseSubCommand emptyLine1 = null; @CommandRegister(priority = 6) - void attributes() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand attributes = new BaseSubCommand() { - @Override - public String getLabel() { - return "attributes"; - } + @Override + public String getLabel() { + return "attributes"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.ATTRIBUTES.DESCRIPTION"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.ATTRIBUTES.DESCRIPTION"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[0]; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new AttributesCommand(sender, args); - } - }); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new AttributesCommand(sender, args); + } + }; @CommandRegister(priority = 7) - void enchants() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand enchants = new BaseSubCommand() { - @Override - public String getLabel() { - return "enchants"; - } + @Override + public String getLabel() { + return "enchants"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.ENCHANTS.DESCRIPTION"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.ENCHANTS.DESCRIPTION"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[0]; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new EnchantCommand(sender, args); - } - }); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new EnchantCommand(sender, args); + } + }; @CommandRegister(priority = 8) - void potions() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand potions = new BaseSubCommand() { - @Override - public String getLabel() { - return "potions"; - } + @Override + public String getLabel() { + return "potions"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.POTIONS.DESCRIPTION"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.POTIONS.DESCRIPTION"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[0]; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new PotionCommand(sender, args); - } - }); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new PotionCommand(sender, args); + } + }; @CommandRegister(priority = 9) - void flags() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand flags = new BaseSubCommand() { - @Override - public String getLabel() { - return "flags"; - } + @Override + public String getLabel() { + return "flags"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.FLAGS.DESCRIPTION"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.FLAGS.DESCRIPTION"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[0]; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new FlagCommand(sender, args); - } - }); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new FlagCommand(sender, args); + } + }; @CommandRegister(priority = 10) - void slots() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand slots = new BaseSubCommand() { - @Override - public String getLabel() { - return "slots"; - } + @Override + public String getLabel() { + return "slots"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.SLOTS.DESCRIPTION"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.SLOTS.DESCRIPTION"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[0]; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new AttributesCommand(sender, args); - } - }); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new AttributesCommand(sender, args); + } + }; @CommandRegister(priority = 11) - void sounds() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand sounds = new BaseSubCommand() { - @Override - public String getLabel() { - return "sounds"; - } + @Override + public String getLabel() { + return "sounds"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.DESCRIPTION"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.DESCRIPTION"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[0]; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new SoundsCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new SoundsCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 12) - void emptyLine2() { - registerSubCommand(null); - } + BaseSubCommand emptyLine2 = null; @CommandRegister(priority = 13) - void getVariable() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand getVariable = new BaseSubCommand() { - @Override - public String getLabel() { - return "getVariable"; - } + @Override + public String getLabel() { + return "getVariable"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.DESCRIPTION.GET"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.DESCRIPTION.GET"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{ - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.ARGUMENTS.GET.0")), - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.ARGUMENTS.GET.1")) - }; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{ + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.ARGUMENTS.GET.0")), + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.ARGUMENTS.GET.1")) + }; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new VariableGetCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new VariableGetCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 13.1) - void setVariable() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand setVariable = new BaseSubCommand() { - @Override - public String getLabel() { - return "setVariable"; - } + @Override + public String getLabel() { + return "setVariable"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.DESCRIPTION.SET"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.DESCRIPTION.SET"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{ - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.ARGUMENTS.SET.0")), - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.ARGUMENTS.SET.1")), - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.ARGUMENTS.SET.2")) - }; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{ + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.ARGUMENTS.SET.0")), + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.ARGUMENTS.SET.1")), + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.VARIABLE.ARGUMENTS.SET.2")) + }; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new VariableSetCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new VariableSetCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 13.2) - void emptyLine3() { - registerSubCommand(null); - } + BaseSubCommand getEmptyLine3 = null; @CommandRegister(priority = 13.3) - void cycleList() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand cycleList = new BaseSubCommand() { - @Override - public String getLabel() { - return "cycleList"; - } + @Override + public String getLabel() { + return "cycleList"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.DESCRIPTION.LIST"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.DESCRIPTION.LIST"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[0]; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new CycleListCommand(sender, args); - } - }); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new CycleListCommand(sender, args); + } + }; @CommandRegister(priority = 14) - void cycleInfo() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand cycleInfo = new BaseSubCommand() { - @Override - public String getLabel() { - return "cycleInfo"; - } + @Override + public String getLabel() { + return "cycleInfo"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.DESCRIPTION.INFO"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.DESCRIPTION.INFO"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{ - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.ARGUMENTS.INFO.0")) - }; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{ + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.ARGUMENTS.INFO.0")) + }; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new CycleInfoCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new CycleInfoCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 15) - void cycleReset() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand cycleReset = new BaseSubCommand() { - @Override - public String getLabel() { - return "cycleReset"; - } + @Override + public String getLabel() { + return "cycleReset"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.DESCRIPTION.RESET"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.DESCRIPTION.RESET"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{ - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.ARGUMENTS.RESET.0")) - }; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{ + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.ARGUMENTS.RESET.0")) + }; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new CycleResetCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new CycleResetCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 16) - void cycleUpdate() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand cycleUpdate = new BaseSubCommand() { - @Override - public String getLabel() { - return "cycleUpdate"; - } + @Override + public String getLabel() { + return "cycleUpdate"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.DESCRIPTION.UPDATE"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.DESCRIPTION.UPDATE"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{ - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.ARGUMENTS.UPDATE.0")) - }; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{ + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.ARGUMENTS.UPDATE.0")) + }; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new CycleUpdateCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new CycleUpdateCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 17) - void emptyLine4() { - registerSubCommand(null); - } + BaseSubCommand getEmptyLine4 = null; @CommandRegister(priority = 18) - void shellLoad() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand shellLoad = new BaseSubCommand() { - @Override - public String getLabel() { - return "shellLoad"; - } + @Override + public String getLabel() { + return "shellLoad"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.JAVASHELL.DESCRIPTION.LOAD"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.JAVASHELL.DESCRIPTION.LOAD"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{ - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.JAVASHELL.ARGUMENTS.LOAD.0")) - }; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{ + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.JAVASHELL.ARGUMENTS.LOAD.0")) + }; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new ShellLoadCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new ShellLoadCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 19) - void shellUnload() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand shellUnload = new BaseSubCommand() { - @Override - public String getLabel() { - return "shellUnload"; - } + @Override + public String getLabel() { + return "shellUnload"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.JAVASHELL.DESCRIPTION.UNLOAD"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.JAVASHELL.DESCRIPTION.UNLOAD"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{ - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.JAVASHELL.ARGUMENTS.UNLOAD.0")) - }; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{ + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.JAVASHELL.ARGUMENTS.UNLOAD.0")) + }; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new ShellUnloadCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new ShellUnloadCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 20) - void emptyLine5() { - registerSubCommand(null); - } + BaseSubCommand getEmptyLine5 = null; @CommandRegister(priority = 20.5) - void tagDisplay() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand tagDisplay = new BaseSubCommand() { - @Override - public String getLabel() { - return "tagDisplay"; - } + @Override + public String getLabel() { + return "tagDisplay"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.DESCRIPTION.DISPLAY"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.DESCRIPTION.DISPLAY"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{ - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.DISPLAY.0")), - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.DISPLAY.1")) - }; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{ + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.DISPLAY.0")), + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.DISPLAY.1")) + }; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new TagDisplayCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new TagDisplayCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 21) - void tagPrefix() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand tagPrefix = new BaseSubCommand() { - @Override - public String getLabel() { - return "tagPrefix"; - } + @Override + public String getLabel() { + return "tagPrefix"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.DESCRIPTION.PREFIX"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.DESCRIPTION.PREFIX"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{ - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.PREFIX.0")), - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.PREFIX.1")) - }; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{ + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.PREFIX.0")), + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.PREFIX.1")) + }; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new TagPrefixCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new TagPrefixCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 22) - void tagSuffix() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand tagSuffix = new BaseSubCommand() { - @Override - public String getLabel() { - return "tagSuffix"; - } + @Override + public String getLabel() { + return "tagSuffix"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.DESCRIPTION.SUFFIX"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.DESCRIPTION.SUFFIX"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{ - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.SUFFIX.0")), - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.SUFFIX.1")) - }; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{ + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.SUFFIX.0")), + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.SUFFIX.1")) + }; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new TagSuffixCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new TagSuffixCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 23) - void tagDelete() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand tagDelete = new BaseSubCommand() { - @Override - public String getLabel() { - return "tagDelete"; - } + @Override + public String getLabel() { + return "tagDelete"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.DESCRIPTION.DELETE"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.DESCRIPTION.DELETE"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{ - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.DELETE.0")) - }; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{ + new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.PLAYERTAG.ARGUMENTS.DELETE.0")) + }; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new TagDeleteCommand(sender, args); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new TagDeleteCommand(sender, args); + } - @Override - public boolean ignoredLabel() { - return false; - } - }); - } + @Override + public boolean ignoredLabel() { + return false; + } + }; @CommandRegister(priority = 24) - void emptyLine6() { - registerSubCommand(null); - } + BaseSubCommand getEmptyLine6 = null; @CommandRegister(priority = 25) - void importData() { - registerSubCommand(new BaseSubCommand() { + BaseSubCommand importData = new BaseSubCommand() { - @Override - public String getLabel() { - return "importData"; - } + @Override + public String getLabel() { + return "importData"; + } - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.IMPORTDATA.DESCRIPTION"); - } + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.IMPORTDATA.DESCRIPTION"); + } - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[0]; + } - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new ImportCommand(sender, args); - } - }); - } + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + new ImportCommand(sender, args); + } + }; } diff --git a/src/main/java/me/skymc/taboolib/commands/internal/BaseMainCommand.java b/src/main/java/me/skymc/taboolib/commands/internal/BaseMainCommand.java index 9116be8..c2669d9 100644 --- a/src/main/java/me/skymc/taboolib/commands/internal/BaseMainCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/internal/BaseMainCommand.java @@ -2,10 +2,9 @@ package me.skymc.taboolib.commands.internal; import com.google.common.base.Preconditions; import com.ilummc.tlib.resources.TLocale; -import com.ilummc.tlib.resources.TLocaleLoader; -import com.ilummc.tlib.util.Ref; import me.skymc.taboolib.Main; import me.skymc.taboolib.TabooLib; +import me.skymc.taboolib.commands.internal.type.CommandField; import me.skymc.taboolib.commands.internal.type.CommandRegister; import me.skymc.taboolib.commands.internal.type.CommandType; import me.skymc.taboolib.string.ArrayUtils; @@ -47,6 +46,7 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor, public static void loadCommandRegister(BaseMainCommand baseMainCommand) { List methods = new ArrayList<>(); + List fields = new ArrayList<>(); baseMainCommand.getLinkClasses().forEach(clazz -> Arrays.stream(clazz.getDeclaredMethods()).filter(method -> method.getAnnotation(CommandRegister.class) != null).forEach(methods::add)); if (methods.size() > 0) { methods.sort(Comparator.comparingDouble(a -> a.getAnnotation(CommandRegister.class).priority())); @@ -58,8 +58,19 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor, } }); } - if (methods.size() > 0) { - TLocale.Logger.info("COMMANDS.INTERNAL.COMMAND-REGISTER", baseMainCommand.getRegisterCommand().getPlugin().getName(), baseMainCommand.getRegisterCommand().getName(), String.valueOf(methods.size())); + baseMainCommand.getLinkClasses().forEach(clazz -> Arrays.stream(clazz.getDeclaredFields()).filter(field -> field.getAnnotation(CommandRegister.class) != null && field.getType().equals(BaseSubCommand.class)).forEach(field -> fields.add(new CommandField(field, clazz)))); + if (fields.size() > 0) { + fields.sort(Comparator.comparingDouble(commandField -> commandField.getField().getAnnotation(CommandRegister.class).priority())); + fields.forEach(commandField -> { + try { + commandField.getField().setAccessible(true); + baseMainCommand.registerSubCommand((BaseSubCommand) commandField.getField().get(commandField.getParent().newInstance())); + } catch (Exception ignored) { + } + }); + } + if (methods.size() + fields.size() > 0) { + TLocale.Logger.info("COMMANDS.INTERNAL.COMMAND-REGISTER", baseMainCommand.getRegisterCommand().getPlugin().getName(), baseMainCommand.getRegisterCommand().getName(), String.valueOf(methods.size() + fields.size())); } } @@ -94,7 +105,7 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor, helpCommand(sender, label); } else { for (BaseSubCommand subCommand : subCommands) { - if (subCommand == null || !args[0].equalsIgnoreCase(subCommand.getLabel())) { + if (subCommand == null || !args[0].equalsIgnoreCase(subCommand.getLabel()) || !hasPermission(sender, subCommand)) { continue; } if (!isConfirmType(sender, subCommand.getType())) { @@ -113,7 +124,7 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor, @Override public void run() { - List commandCompute = subCommands.stream().filter(Objects::nonNull).sorted((b, a) -> Double.compare(StringUtils.similarDegree(args[0], a.getLabel()), StringUtils.similarDegree(args[0], b.getLabel()))).collect(Collectors.toList()); + List commandCompute = subCommands.stream().filter(x -> x != null && hasPermission(sender, x)).sorted((b, a) -> Double.compare(StringUtils.similarDegree(args[0], a.getLabel()), StringUtils.similarDegree(args[0], b.getLabel()))).collect(Collectors.toList()); if (commandCompute.size() > 0) { TLocale.sendTo(sender, "COMMANDS.INTERNAL.ERROR-COMMAND", args[0], commandCompute.get(0).getCommandString(label).trim()); } @@ -125,7 +136,7 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor, @Override public List onTabComplete(CommandSender commandSender, Command command, String s, String[] args) { - return args.length == 1 ? subCommands.stream().filter(internalCommandExecutor -> internalCommandExecutor != null && (args[0].isEmpty() || internalCommandExecutor.getLabel().toLowerCase().startsWith(args[0].toLowerCase()))).map(ISubCommand::getLabel).collect(Collectors.toList()) : null; + return args.length == 1 ? subCommands.stream().filter(subCommand -> subCommand != null && hasPermission(commandSender, subCommand) && (args[0].isEmpty() || subCommand.getLabel().toLowerCase().startsWith(args[0].toLowerCase()))).map(ISubCommand::getLabel).collect(Collectors.toList()) : null; } @Override @@ -162,7 +173,7 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor, sender.sendMessage(getEmptyLine()); sender.sendMessage(getCommandTitle()); sender.sendMessage(getEmptyLine()); - subCommands.stream().map(subCommand -> subCommand == null ? getEmptyLine() : subCommand.getCommandString(label)).forEach(sender::sendMessage); + subCommands.stream().filter(subCommands -> hasPermission(sender, subCommands)).map(subCommand -> subCommand == null ? getEmptyLine() : subCommand.getCommandString(label)).forEach(sender::sendMessage); sender.sendMessage(getEmptyLine()); } @@ -178,4 +189,8 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor, } catch (Exception ignored) { } } + + private boolean hasPermission(CommandSender sender, BaseSubCommand baseSubCommand) { + return baseSubCommand == null || baseSubCommand.getPermission() == null || sender.hasPermission(baseSubCommand.getPermission()); + } } diff --git a/src/main/java/me/skymc/taboolib/commands/internal/BaseSubCommand.java b/src/main/java/me/skymc/taboolib/commands/internal/BaseSubCommand.java index a7307b1..d8531eb 100644 --- a/src/main/java/me/skymc/taboolib/commands/internal/BaseSubCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/internal/BaseSubCommand.java @@ -1,8 +1,10 @@ package me.skymc.taboolib.commands.internal; -import me.skymc.taboolib.commands.internal.type.CommandArgument; +import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.commands.internal.type.CommandType; +import java.util.Arrays; +import java.util.stream.Collectors; import java.util.stream.IntStream; /** @@ -23,23 +25,16 @@ public abstract class BaseSubCommand implements ISubCommand { return false; } + public String getPermission() { + return null; + } + public boolean isParameterConform(String[] args) { return IntStream.range(0, getArguments().length).noneMatch(i -> getArguments()[i].isRequired() && (args == null || args.length <= i)); } public String getCommandString(String label) { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(" §f/"); - stringBuilder.append(label); - stringBuilder.append(" "); - stringBuilder.append(getLabel()); - stringBuilder.append(" "); - for (CommandArgument parameter : getArguments()) { - stringBuilder.append(parameter.toString()); - stringBuilder.append(" "); - } - stringBuilder.append("§6- §e"); - stringBuilder.append(getDescription()); - return stringBuilder.toString(); + String stringBuilder = Arrays.stream(getArguments()).map(parameter -> parameter.toString() + " ").collect(Collectors.joining()); + return TLocale.asString("COMMANDS.INTERNAL.COMMAND-HELP", label, getLabel(), stringBuilder.trim(), getDescription()); } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/commands/internal/TBaseCommand.java b/src/main/java/me/skymc/taboolib/commands/internal/TBaseCommand.java new file mode 100644 index 0000000..5d09a2d --- /dev/null +++ b/src/main/java/me/skymc/taboolib/commands/internal/TBaseCommand.java @@ -0,0 +1,19 @@ +package me.skymc.taboolib.commands.internal; + +/** + * @Author sky + * @Since 2018-05-23 2:43 + */ +public class TBaseCommand { + + /** + * 向服务端注册 BaseMainCommand 类 + * + * @param command 命令全称(需在 plugin.yml 内注册) + * @param baseMainCommand 命令对象 + * @return {@link BaseMainCommand} + */ + public static BaseMainCommand registerCommand(String command, BaseMainCommand baseMainCommand) { + return BaseMainCommand.createCommandExecutor(command, baseMainCommand); + } +} diff --git a/src/main/java/me/skymc/taboolib/commands/internal/type/CommandArgument.java b/src/main/java/me/skymc/taboolib/commands/internal/type/CommandArgument.java index bbd52ac..410df75 100644 --- a/src/main/java/me/skymc/taboolib/commands/internal/type/CommandArgument.java +++ b/src/main/java/me/skymc/taboolib/commands/internal/type/CommandArgument.java @@ -1,5 +1,7 @@ package me.skymc.taboolib.commands.internal.type; +import com.ilummc.tlib.resources.TLocale; + import java.util.Objects; /** @@ -30,7 +32,7 @@ public class CommandArgument { @Override public String toString() { - return required ? "§7[§8" + name + "§7]" : "§7<§8" + name + "§7>"; + return required ? TLocale.asString("COMMANDS.INTERNAL.COMMAND-ARGUMENT-REQUIRE", name) : TLocale.asString("COMMANDS.INTERNAL.COMMAND-ARGUMENT", name); } @Override diff --git a/src/main/java/me/skymc/taboolib/commands/internal/type/CommandField.java b/src/main/java/me/skymc/taboolib/commands/internal/type/CommandField.java new file mode 100644 index 0000000..77dd269 --- /dev/null +++ b/src/main/java/me/skymc/taboolib/commands/internal/type/CommandField.java @@ -0,0 +1,26 @@ +package me.skymc.taboolib.commands.internal.type; + +import java.lang.reflect.Field; + +/** + * @Author sky + * @Since 2018-05-23 3:07 + */ +public class CommandField { + + private final Field field; + private final Class parent; + + public CommandField(Field field, Class parent) { + this.field = field; + this.parent = parent; + } + + public Field getField() { + return field; + } + + public Class getParent() { + return parent; + } +} \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/commands/internal/type/CommandRegister.java b/src/main/java/me/skymc/taboolib/commands/internal/type/CommandRegister.java index 7463738..8f10049 100644 --- a/src/main/java/me/skymc/taboolib/commands/internal/type/CommandRegister.java +++ b/src/main/java/me/skymc/taboolib/commands/internal/type/CommandRegister.java @@ -9,7 +9,7 @@ import java.lang.annotation.Target; * @Author sky * @Since 2018-05-09 22:38 */ -@Target(ElementType.METHOD) +@Target({ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface CommandRegister { diff --git a/src/main/java/me/skymc/taboolib/commands/plugin/TabooLibPluginMainCommand.java b/src/main/java/me/skymc/taboolib/commands/plugin/TabooLibPluginMainCommand.java index d3d12b4..4f80d08 100644 --- a/src/main/java/me/skymc/taboolib/commands/plugin/TabooLibPluginMainCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/plugin/TabooLibPluginMainCommand.java @@ -6,6 +6,7 @@ import me.skymc.taboolib.commands.internal.BaseMainCommand; import me.skymc.taboolib.commands.internal.BaseSubCommand; import me.skymc.taboolib.commands.internal.ISubCommand; import me.skymc.taboolib.commands.internal.type.CommandArgument; +import me.skymc.taboolib.commands.internal.type.CommandRegister; import me.skymc.taboolib.plugin.PluginUtils; import me.skymc.taboolib.string.ArrayUtils; import org.bukkit.Bukkit; @@ -13,7 +14,6 @@ import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.plugin.Plugin; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @@ -24,12 +24,9 @@ import java.util.stream.Collectors; */ public class TabooLibPluginMainCommand extends BaseMainCommand { - public TabooLibPluginMainCommand() { - listCommand(); - infoCommand(); - loadCommand(); - unloadCommand(); - reloadCommand(); + @Override + public String getCommandTitle() { + return TLocale.asString("COMMANDS.TPLUGIN.COMMAND-TITLE"); } @Override @@ -43,195 +40,191 @@ public class TabooLibPluginMainCommand extends BaseMainCommand { } } + @CommandRegister(priority = 1) + BaseSubCommand load = new BaseSubCommand() { + + @Override + public String getLabel() { + return "load"; + } + + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TPLUGIN.LOAD.DESCRIPTION"); + } + + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.LOAD.ARGUMENTS.0"), true)}; + } + + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + String name = ArrayUtils.arrayJoin(args, 0); + if (PluginUtils.getPluginByName(name) != null) { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-PLUGIN", name); + } else { + switch (PluginUtils.load(name)) { + case "loaded": { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-SUCCESS", name); + break; + } + default: { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-FAIL", name); + } + } + } + } + }; + + @CommandRegister(priority = 2) + BaseSubCommand unload = new BaseSubCommand() { + + @Override + public String getLabel() { + return "unload"; + } + + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TPLUGIN.UNLOAD.DESCRIPTION"); + } + + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.UNLOAD.ARGUMENTS.0"), true)}; + } + + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + String name = ArrayUtils.arrayJoin(args, 0); + Plugin plugin = PluginUtils.getPluginByName(name); + if (plugin == null) { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN", name); + } else if (PluginUtils.isIgnored(plugin)) { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN-IGNORED", name); + } else { + switch (PluginUtils.unload(plugin)) { + case "unloaded": { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-SUCCESS", name); + break; + } + default: { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-FAIL", name); + } + } + } + } + }; + + @CommandRegister(priority = 3) + BaseSubCommand reload = new BaseSubCommand() { + + @Override + public String getLabel() { + return "reload"; + } + + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TPLUGIN.RELOAD.DESCRIPTION"); + } + + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.RELOAD.ARGUMENTS.0"), true)}; + } + + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + String name = ArrayUtils.arrayJoin(args, 0); + Plugin plugin = PluginUtils.getPluginByName(name); + if (plugin == null) { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.INVALID-PLUGIN", name); + } else if (PluginUtils.isIgnored(plugin)) { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.INVALID-PLUGIN-IGNORED", name); + } else { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.TRY-RELOAD"); + PluginUtils.reload(plugin); + } + } + }; + + @CommandRegister(priority = 4) + BaseSubCommand info = new BaseSubCommand() { + + @Override + public String getLabel() { + return "info"; + } + + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TPLUGIN.INFO.DESCRIPTION"); + } + + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.INFO.ARGUMENTS.0"), true)}; + } + + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + String name = ArrayUtils.arrayJoin(args, 0); + Plugin plugin = PluginUtils.getPluginByName(name); + if (plugin == null) { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-PLUGIN", name); + } else { + try { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INFO-PLUGIN", + plugin.getName(), + String.valueOf(plugin.getDescription().getDescription()), + String.valueOf(plugin.getDescription().getAuthors()), + String.valueOf(plugin.getDescription().getDepend()), + String.valueOf(plugin.getDescription().getSoftDepend()), + String.valueOf(plugin.getDescription().getMain()), + String.valueOf(plugin.getDescription().getVersion()), + String.valueOf(plugin.getDescription().getWebsite()), + String.valueOf(plugin.getDescription().getCommands().keySet())); + } catch (Exception ignored) { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-PLUGIN", name); + } + } + } + }; + + @CommandRegister(priority = 5) + BaseSubCommand list = new BaseSubCommand() { + + @Override + public String getLabel() { + return "list"; + } + + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TPLUGIN.LIST.DESCRIPTION"); + } + + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[0]; + } + + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + List pluginList = Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(Plugin::getName).sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.toList()); + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LIST.LIST-PLUGIN", String.valueOf(Bukkit.getPluginManager().getPlugins().length), Joiner.on(", ").join(pluginList)); + } + }; + + // ********************************* + // + // Private Methods + // + // ********************************* + private boolean isPluginCommand(String label) { return "info".equalsIgnoreCase(label) || "load".equalsIgnoreCase(label) || "unload".equalsIgnoreCase(label) || "reload".equalsIgnoreCase(label); } - - @Override - public String getCommandTitle() { - return TLocale.asString("COMMANDS.TPLUGIN.COMMAND-TITLE"); - } - - void loadCommand() { - registerSubCommand(new BaseSubCommand() { - - @Override - public String getLabel() { - return "load"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TPLUGIN.LOAD.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.LOAD.ARGUMENTS.0"), true)}; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - String name = ArrayUtils.arrayJoin(args, 0); - if (PluginUtils.getPluginByName(name) != null) { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-PLUGIN", name); - } else { - switch (PluginUtils.load(name)) { - case "loaded": { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-SUCCESS", name); - break; - } - default: { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-FAIL", name); - } - } - } - } - }); - } - - void unloadCommand() { - registerSubCommand(new BaseSubCommand() { - - @Override - public String getLabel() { - return "unload"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TPLUGIN.UNLOAD.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.UNLOAD.ARGUMENTS.0"), true)}; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - String name = ArrayUtils.arrayJoin(args, 0); - Plugin plugin = PluginUtils.getPluginByName(name); - if (plugin == null) { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN", name); - } else if (PluginUtils.isIgnored(plugin)) { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN-IGNORED", name); - } else { - switch (PluginUtils.unload(plugin)) { - case "unloaded": { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-SUCCESS", name); - break; - } - default: { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-FAIL", name); - } - } - } - } - }); - } - - void reloadCommand() { - registerSubCommand(new BaseSubCommand() { - - @Override - public String getLabel() { - return "reload"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TPLUGIN.RELOAD.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.RELOAD.ARGUMENTS.0"), true)}; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - String name = ArrayUtils.arrayJoin(args, 0); - Plugin plugin = PluginUtils.getPluginByName(name); - if (plugin == null) { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.INVALID-PLUGIN", name); - } else if (PluginUtils.isIgnored(plugin)) { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.INVALID-PLUGIN-IGNORED", name); - } else { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.RELOAD.TRY-RELOAD"); - PluginUtils.reload(plugin); - } - } - }); - } - - void infoCommand() { - registerSubCommand(new BaseSubCommand() { - - @Override - public String getLabel() { - return "info"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TPLUGIN.INFO.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[]{new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.INFO.ARGUMENTS.0"), true)}; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - String name = ArrayUtils.arrayJoin(args, 0); - Plugin plugin = PluginUtils.getPluginByName(name); - if (plugin == null) { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-PLUGIN", name); - } else { - try { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INFO-PLUGIN", - plugin.getName(), - String.valueOf(plugin.getDescription().getDescription()), - String.valueOf(plugin.getDescription().getAuthors()), - String.valueOf(plugin.getDescription().getDepend()), - String.valueOf(plugin.getDescription().getSoftDepend()), - String.valueOf(plugin.getDescription().getMain()), - String.valueOf(plugin.getDescription().getVersion()), - String.valueOf(plugin.getDescription().getWebsite()), - String.valueOf(plugin.getDescription().getCommands().keySet())); - } catch (Exception ignored) { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-PLUGIN", name); - } - } - } - }); - } - - void listCommand() { - registerSubCommand(new BaseSubCommand() { - - @Override - public String getLabel() { - return "list"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TPLUGIN.LIST.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - List pluginList = Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(Plugin::getName).sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.toList()); - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LIST.LIST-PLUGIN", String.valueOf(Bukkit.getPluginManager().getPlugins().length), Joiner.on(", ").join(pluginList)); - } - }); - } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/commands/taboolib/SaveCommand.java b/src/main/java/me/skymc/taboolib/commands/taboolib/SaveCommand.java index 37946e4..667d84a 100644 --- a/src/main/java/me/skymc/taboolib/commands/taboolib/SaveCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/taboolib/SaveCommand.java @@ -49,7 +49,7 @@ public class SaveCommand extends SubCommand { return; } - ChatCatcher.call((Player) sender, new ChatCatcher.Catcher() { + ChatCatcher.call((Player) sender, new Catcher() { @Override public void cancel() { diff --git a/src/main/java/me/skymc/taboolib/commands/taboolib/TagDeleteCommand.java b/src/main/java/me/skymc/taboolib/commands/taboolib/TagDeleteCommand.java index 5dbcbda..1e7d565 100644 --- a/src/main/java/me/skymc/taboolib/commands/taboolib/TagDeleteCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/taboolib/TagDeleteCommand.java @@ -2,8 +2,7 @@ package me.skymc.taboolib.commands.taboolib; import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.commands.SubCommand; -import me.skymc.taboolib.team.TagAPI; -import me.skymc.taboolib.team.TagManager; +import me.skymc.taboolib.itagapi.TagDataHandler; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -27,8 +26,7 @@ public class TagDeleteCommand extends SubCommand { return; } - TagManager.getInst().unloadData(player); - TagAPI.removePlayerDisplayName(player); + TagDataHandler.getHandler().reset(player); if (sender instanceof Player) { TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-DELETE", args[1]); diff --git a/src/main/java/me/skymc/taboolib/commands/taboolib/TagDisplayCommand.java b/src/main/java/me/skymc/taboolib/commands/taboolib/TagDisplayCommand.java index d093513..6dd46a0 100644 --- a/src/main/java/me/skymc/taboolib/commands/taboolib/TagDisplayCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/taboolib/TagDisplayCommand.java @@ -3,6 +3,7 @@ package me.skymc.taboolib.commands.taboolib; import com.ilummc.tlib.resources.TLocale; import me.clip.placeholderapi.PlaceholderAPI; import me.skymc.taboolib.commands.SubCommand; +import me.skymc.taboolib.itagapi.TagDataHandler; import me.skymc.taboolib.team.TagAPI; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; @@ -27,12 +28,9 @@ public class TagDisplayCommand extends SubCommand { return; } - String value = getArgs(2).replace("&", "§"); - if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { - value = PlaceholderAPI.setPlaceholders(player, value); - } + String value = TLocale.Translate.setPlaceholders(player, getArgs(2)); + TagDataHandler.getHandler().setDisplay(player, value); - TagAPI.setPlayerDisplayName(player, value); if (sender instanceof Player) { TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-DISPLAY-SET", args[1], value); } diff --git a/src/main/java/me/skymc/taboolib/commands/taboolib/TagPrefixCommand.java b/src/main/java/me/skymc/taboolib/commands/taboolib/TagPrefixCommand.java index f52533f..895be34 100644 --- a/src/main/java/me/skymc/taboolib/commands/taboolib/TagPrefixCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/taboolib/TagPrefixCommand.java @@ -1,9 +1,8 @@ package me.skymc.taboolib.commands.taboolib; import com.ilummc.tlib.resources.TLocale; -import me.clip.placeholderapi.PlaceholderAPI; import me.skymc.taboolib.commands.SubCommand; -import me.skymc.taboolib.team.TagManager; +import me.skymc.taboolib.itagapi.TagDataHandler; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -14,28 +13,25 @@ import org.bukkit.entity.Player; */ public class TagPrefixCommand extends SubCommand { - public TagPrefixCommand(CommandSender sender, String[] args) { - super(sender, args); - if (args.length < 3) { - TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN"); - return; - } - - Player player = Bukkit.getPlayerExact(args[1]); - if (player == null) { - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.INVALID-PLAYER", args[1]); - return; - } - - String value = getArgs(2).replace("&", "§"); - if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { - value = PlaceholderAPI.setPlaceholders(player, value); - } - - TagManager.getInst().setPrefix(player, value); - if (sender instanceof Player) { - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-PREFIX-SET", args[1], value); - } - } + public TagPrefixCommand(CommandSender sender, String[] args) { + super(sender, args); + if (args.length < 3) { + TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN"); + return; + } + + Player player = Bukkit.getPlayerExact(args[1]); + if (player == null) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.INVALID-PLAYER", args[1]); + return; + } + + String value = TLocale.Translate.setPlaceholders(player, getArgs(2)); + TagDataHandler.getHandler().setPrefix(player, value); + + if (sender instanceof Player) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-PREFIX-SET", args[1], value); + } + } } diff --git a/src/main/java/me/skymc/taboolib/commands/taboolib/TagSuffixCommand.java b/src/main/java/me/skymc/taboolib/commands/taboolib/TagSuffixCommand.java index 39aa825..08d5b9f 100644 --- a/src/main/java/me/skymc/taboolib/commands/taboolib/TagSuffixCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/taboolib/TagSuffixCommand.java @@ -1,9 +1,8 @@ package me.skymc.taboolib.commands.taboolib; import com.ilummc.tlib.resources.TLocale; -import me.clip.placeholderapi.PlaceholderAPI; import me.skymc.taboolib.commands.SubCommand; -import me.skymc.taboolib.team.TagManager; +import me.skymc.taboolib.itagapi.TagDataHandler; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -27,12 +26,9 @@ public class TagSuffixCommand extends SubCommand { return; } - String value = getArgs(2).replace("&", "§"); - if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { - value = PlaceholderAPI.setPlaceholders(player, value); - } - - TagManager.getInst().setSuffix(player, value); + String value = TLocale.Translate.setPlaceholders(player, getArgs(2)); + TagDataHandler.getHandler().setSuffix(player, value); + if (sender instanceof Player) { TLocale.sendTo(sender, "COMMANDS.TABOOLIB.PLAYERTAG.SUCCESS-SUFFIX-SET", args[1], value); } diff --git a/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java b/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java index 54008d0..5f4420b 100644 --- a/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java +++ b/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java @@ -1,6 +1,6 @@ package me.skymc.taboolib.inventory; -import com.ilummc.tlib.resources.TLocale; +import lombok.Getter; import me.clip.placeholderapi.PlaceholderAPI; import me.skymc.taboolib.Main; import me.skymc.taboolib.TabooLib; @@ -9,6 +9,7 @@ import me.skymc.taboolib.itemnbtapi.NBTItem; import me.skymc.taboolib.itemnbtapi.NBTList; import me.skymc.taboolib.itemnbtapi.NBTListCompound; import me.skymc.taboolib.itemnbtapi.NBTType; +import me.skymc.taboolib.message.MsgUtils; import me.skymc.taboolib.other.NumberUtils; import me.skymc.taboolib.string.Language; import org.bukkit.Color; @@ -28,235 +29,226 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import java.io.File; -import java.util.Arrays; -import java.util.Collections; +import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; -import java.util.stream.IntStream; public class ItemUtils { - - private static FileConfiguration itemdir = null; - - private static FileConfiguration itemCache = null; - - private static File finalItemsFolder; - - private static LinkedHashMap itemlib = new LinkedHashMap<>(); - - private static LinkedHashMap itemCaches = new LinkedHashMap<>(); - - private static LinkedHashMap itemCachesFinal = new LinkedHashMap<>(); - - public static FileConfiguration getItemdir() { - return itemdir; - } - - public static FileConfiguration getItemCache() { - return itemCache; - } - - public static File getFinalItemsFolder() { - return finalItemsFolder; - } - - public static LinkedHashMap getItemlib() { - return itemlib; - } - - public static LinkedHashMap getItemCaches() { - return itemCaches; - } - - public static LinkedHashMap getItemCachesFinal() { - return itemCachesFinal; - } - - /** - * 获取物品缓存 - * 检测顺序: - * 1. 固定物品库 - * 2. 动态物品库 - * - * @param name 物品名称 - * @return - */ - public static ItemStack getCacheItem(String name) { - // 检测固定物品库是否存在该物品 - if (itemCachesFinal.containsKey(name)) { - return itemCachesFinal.get(name); - } - // 返回动态物品库 - return itemCaches.get(name); - } - - public static boolean isExists(String name) { - return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name); - } - - public static void LoadLib() { - try { - reloadItemName(); - reloadItemCache(); - itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR"))); - } catch (Exception e) { - TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ITEMS", e.toString()); - } - } - - public static void loadItemsFile(File file, boolean finalFile) { - FileConfiguration conf = ConfigUtils.load(Main.getInst(), file); - for (String name : conf.getConfigurationSection("").getKeys(false)) { - if (isExists(name)) { - TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ITEMS", name); - } else if (finalFile) { - itemCachesFinal.put(name, loadItem(conf, name)); - } else { - itemCaches.put(name, loadItem(conf, name)); - } - } - } - - public static void reloadItemCache() { - itemCaches.clear(); - itemCachesFinal.clear(); - loadItemsFile(getItemCacheFile(), false); - // 创建固定物品库 - finalItemsFolder = new File(Main.getInst().getDataFolder(), "FinalItems"); - if (!finalItemsFolder.exists()) { - finalItemsFolder.mkdir(); - } - // 检查固定物品库中的物品 - Arrays.stream(finalItemsFolder.listFiles()).forEach(file -> loadItemsFile(file, true)); - TLocale.Logger.info("ITEM-UTILS.SUCCESS-LOAD-CACHES", String.valueOf(itemCaches.size() + itemCachesFinal.size())); - } - - public static void reloadItemName() { - FileConfiguration conf = new Language("ITEM_NAME", Main.getInst(), true).getConfiguration(); - itemlib.clear(); - conf.getConfigurationSection("").getKeys(false).forEach(a -> itemlib.put(a, conf.getString(a))); - TLocale.Logger.info("ITEM-UTILS.SUCCESS-LOAD-NAMES", String.valueOf(itemlib.size())); - } - - public static File getItemCacheFile() { - File itemCacheFile = new File(Main.getInst().getDataFolder(), "items.yml"); - if (!itemCacheFile.exists()) { - Main.getInst().saveResource("items.yml", true); - } - return itemCacheFile; - } - - public static String getCustomName(ItemStack item) { - if (item == null || item.getType().equals(Material.AIR)) { - return TLocale.asString("ITEM-UTILS.EMPTY-ITEM"); - } - int data = item.getType().getMaxDurability() == 0 ? item.getDurability() : 0; - return item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : itemlib.get(item.getType() + ":" + data) == null ? item.getType().toString() : itemlib.get(item.getType() + ":" + data); - } - - public static ItemStack getItemFromDir(String name) { - if (itemdir != null) { - return itemdir.getItemStack("item." + name); - } - return null; - } - - @SuppressWarnings("deprecation") + + @Getter + private static FileConfiguration itemdir = null; + + @Getter + private static FileConfiguration itemCache = null; + + @Getter + private static File finalItemsFolder; + + @Getter + private static LinkedHashMap itemlib = new LinkedHashMap<>(); + + @Getter + private static LinkedHashMap itemCaches = new LinkedHashMap<>(); + + @Getter + private static LinkedHashMap itemCachesFinal = new LinkedHashMap<>(); + + /** + * 获取物品缓存 + * 检测顺序: + * 1. 固定物品库 + * 2. 动态物品库 + * + * @param name 物品名称 + * @return + */ + public static ItemStack getCacheItem(String name) { + // 检测固定物品库是否存在该物品 + if (itemCachesFinal.containsKey(name)) { + return itemCachesFinal.get(name); + } + // 返回动态物品库 + return itemCaches.get(name); + } + + public static boolean isExists(String name) { + return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name); + } + + public static void LoadLib() { + try { + reloadItemName(); + reloadItemCache(); + itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR"))); + } catch (Exception e) { + MsgUtils.warn("物品库载入失败: &4" + e.getMessage()); + } + } + + public static void loadItemsFile(File file, boolean finalFile) { + FileConfiguration conf = ConfigUtils.load(Main.getInst(), file); + for (String name : conf.getConfigurationSection("").getKeys(false)) { + if (isExists(name)) { + MsgUtils.warn("无法载入载入物品 &4" + name + "&c, 因为它已经存在了"); + } else if (finalFile) { + itemCachesFinal.put(name, loadItem(conf, name)); + } else { + itemCaches.put(name, loadItem(conf, name)); + } + } + } + + public static void reloadItemCache() { + itemCaches.clear(); + itemCachesFinal.clear(); + loadItemsFile(getItemCacheFile(), false); + // 创建固定物品库 + finalItemsFolder = new File(Main.getInst().getDataFolder(), "FinalItems"); + if (!finalItemsFolder.exists()) { + finalItemsFolder.mkdir(); + } + // 检查固定物品库中的物品 + for (File file : finalItemsFolder.listFiles()) { + loadItemsFile(file, true); + } + MsgUtils.send("载入 " + (itemCaches.size() + itemCachesFinal.size()) + " 项缓存物品"); + } + + public static void reloadItemName() { + FileConfiguration conf = new Language("ITEM_NAME", Main.getInst(), true).getConfiguration(); + itemlib.clear(); + for (String a : conf.getConfigurationSection("").getKeys(false)) { + itemlib.put(a, conf.getString(a)); + } + MsgUtils.send("载入 " + itemlib.size() + " 项物品名称"); + } + + public static File getItemCacheFile() { + File itemCacheFile = new File(Main.getInst().getDataFolder(), "items.yml"); + if (!itemCacheFile.exists()) { + Main.getInst().saveResource("items.yml", true); + } + return itemCacheFile; + } + + public static String getCustomName(ItemStack item) { + if (item == null || item.getType().equals(Material.AIR)) { + return "空"; + } + int data = item.getType().getMaxDurability() == 0 ? item.getDurability() : 0; + return item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : itemlib.get(item.getType() + ":" + data) == null ? item.getType().toString() : itemlib.get(item.getType() + ":" + data); + } + + public static ItemStack getItemFromDir(String name) { + if (itemdir != null) { + return itemdir.getItemStack("item." + name); + } + return null; + } + + @SuppressWarnings("deprecation") public static ItemStack item(int n, int a, int d) { return new ItemStack(n, a, (short) d); } - + public static ItemStack setName(ItemStack i, String n) { ItemMeta meta = i.getItemMeta(); meta.setDisplayName(n); i.setItemMeta(meta); return i; } - + public static ItemStack Enchant(ItemStack i, Enchantment e, int l) { ItemMeta meta = i.getItemMeta(); meta.addEnchant(e, l, false); i.setItemMeta(meta); return i; } - + public static ItemStack addFlag(ItemStack i, ItemFlag f) { ItemMeta meta = i.getItemMeta(); meta.addItemFlags(f); i.setItemMeta(meta); return i; } - + public static boolean isNull(ItemStack item) { - return item == null || item.getType().equals(Material.AIR); + return item == null || item.getType().equals(Material.AIR); } - + public static boolean isName(ItemStack i, String a) { return isNamed(i) && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null && i.getItemMeta().getDisplayName().equals(a); } - + public static boolean isNameAs(ItemStack i, String a) { return isNamed(i) && i.getItemMeta().getDisplayName().contains(a); } - + public static String asString(String args, Player placeholderPlayer) { - if (placeholderPlayer == null) { - return args.replace("&", "§"); - } - return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§")); + if (placeholderPlayer == null) { + return args.replace("&", "§"); + } + return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§")); } - + public static List asString(List args, Player placeholderPlayer) { - IntStream.range(0, args.size()).forEach(i -> args.set(i, asString(args.get(i), placeholderPlayer))); - return args; + for (int i = 0 ; i < args.size() ; i ++) { + args.set(i, asString(args.get(i), placeholderPlayer)); + } + return args; } - + public static ItemFlag asItemFlag(String flag) { - try { - return ItemFlag.valueOf(flag); - } catch (Exception e) { - return null; - } + try { + return ItemFlag.valueOf(flag); + } + catch (Exception e) { + return null; + } } - + @SuppressWarnings("deprecation") - public static Material asMaterial(String args) { - try { - Material material = Material.getMaterial(args); - return material != null ? material : Material.getMaterial(Integer.valueOf(args)); - } catch (Exception e) { - return Material.STONE; - } + public static Material asMaterial(String args) { + try { + Material material = Material.getMaterial(args); + return material != null ? material : Material.getMaterial(Integer.valueOf(args)); + } + catch (Exception e) { + return Material.STONE; + } + } + + @SuppressWarnings({ "deprecation" }) + public static Enchantment asEnchantment(String enchant) { + try { + Enchantment enchantment = Enchantment.getByName(enchant); + return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant)); + } + catch (Exception e) { + return null; + } } - - @SuppressWarnings({"deprecation"}) - public static Enchantment asEnchantment(String enchant) { - try { - Enchantment enchantment = Enchantment.getByName(enchant); - return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant)); - } catch (Exception e) { - return null; - } - } - + @SuppressWarnings("deprecation") - public static PotionEffectType asPotionEffectType(String potion) { - try { - PotionEffectType type = PotionEffectType.getByName(potion); - return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion)); - } catch (Exception e) { - return null; - } + public static PotionEffectType asPotionEffectType(String potion) { + try { + PotionEffectType type = PotionEffectType.getByName(potion); + return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion)); + } + catch (Exception e) { + return null; + } } - + public static Color asColor(String color) { - try { - return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2])); - } catch (Exception e) { - return Color.fromBGR(0, 0, 0); - } + try { + return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2])); + } + catch (Exception e) { + return Color.fromBGR(0, 0, 0); + } } - + public static String asAttribute(String name) { switch (name.toLowerCase()) { case "damage": @@ -273,292 +265,321 @@ public class ItemUtils { return "generic.armor"; case "luck": return "generic.luck"; - default: - return null; } + return null; } - + /** * 包含介绍 - * + * * @param i 物品 * @param a 关键字 */ public static boolean hasLore(ItemStack i, String a) { return isLored(i) && i.getItemMeta().getLore().toString().contains(a); } - + /** * 如果已描述 - * + * * @param i * @return */ public static boolean isLored(ItemStack i) { return i != null && i.getItemMeta() != null && i.getItemMeta().getLore() != null; } - + /** * 如果已命名 - * + * * @param i * @return */ - public static boolean isNamed(ItemStack i) { + public static boolean isNamed(ItemStack i) { return i != null && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null; } - + /** * 添加描述 - * - * @param is 物品 + * + * @param is 物品 * @param lore 描述 */ public static ItemStack addLore(ItemStack is, String lore) { - ItemMeta meta = is.getItemMeta(); - - List _lore = meta.hasLore() ? meta.getLore() : Collections.emptyList(); - _lore.add(lore.replaceAll("&", "§")); - + ItemMeta meta = is.getItemMeta(); + + List _lore = meta.hasLore() ? meta.getLore() : new ArrayList<>(); + _lore.add(lore.replaceAll("&", "§")); + is.setItemMeta(meta); return is; } - + /** * 移除描述 - * - * @param is 物品 + * + * @param is 物品 * @param line 行数 */ public static ItemStack delLore(ItemStack is, int line) { - ItemMeta meta = is.getItemMeta(); + ItemMeta meta = is.getItemMeta(); if (meta.hasLore()) { - List l = meta.getLore(); - if (l.size() >= line) { - l.remove(line); - meta.setLore(l); - is.setItemMeta(meta); - } + List l = meta.getLore(); + if (l.size() >= line) { + l.remove(line); + meta.setLore(l); + is.setItemMeta(meta); + } } return is; } - + /** * 获取介绍所在行数 - * + * * @param i 物品 * @param a 关键字 */ public static int getLore(ItemStack i, String a) { - return isLored(i) ? IntStream.range(0, i.getItemMeta().getLore().size()).filter(j -> i.getItemMeta().getLore().get(j).contains(a)).findFirst().orElse(0) : 0; + if (isLored(i)) { + for (int j = 0; j < i.getItemMeta().getLore().size() ; j++) { + if (i.getItemMeta().getLore().get(j).contains(a)) { + return j; + } + } + } + return 0; } - + /** * 添加耐久 - * + * * @param i 物品 * @param d 耐久 */ public static ItemStack addDurability(ItemStack i, int d) { - i.setDurability((short) (i.getDurability() + d)); - int min = i.getDurability(); - int max = i.getType().getMaxDurability(); - if (min >= max) { - i.setType(Material.AIR); - } - return i; + i.setDurability((short) (i.getDurability() + d)); + int min = i.getDurability(); + int max = i.getType().getMaxDurability(); + if (min >= max) { + i.setType(Material.AIR); + } + return i; } - + /** * 替换描述 - * - * @param i 物品 + * + * @param i 物品 * @param l1 关键字1 * @param l2 关键字2 */ public static ItemStack repalceLore(ItemStack i, String l1, String l2) { - if (!isLored(i)) { - return i; - } else { - ItemMeta meta = i.getItemMeta(); - List lore = meta.getLore(); - IntStream.range(0, lore.size()).forEach(j -> lore.set(j, lore.get(j).replace(l1, l2))); - meta.setLore(lore); - i.setItemMeta(meta); - } - return i; + if (!isLored(i)) { + return i; + } + else { + ItemMeta meta = i.getItemMeta(); + List lore = meta.getLore(); + for (int j = 0 ; j < lore.size() ; j++) { + lore.set(j, lore.get(j).replace(l1, l2)); + } + meta.setLore(lore); + i.setItemMeta(meta); + } + return i; } - + public static ItemStack loadItem(FileConfiguration f, String s) { - return loadItem(f, s, null); + return loadItem(f, s, null); } - + public static ItemStack loadItem(FileConfiguration f, String s, Player papiPlayer) { - return loadItem(f.getConfigurationSection(s), papiPlayer); + return loadItem(f.getConfigurationSection(s), papiPlayer); } - + public static ItemStack loadItem(ConfigurationSection section, Player papiPlayer) { - if (section.get("bukkit") instanceof ItemStack) { - return section.getItemStack("bukkit"); - } - // 材质 - ItemStack item = new ItemStack(asMaterial(section.get("material").toString())); - // 数量 - item.setAmount(section.contains("amount") ? section.getInt("amount") : 1); - // 耐久 - item.setDurability((short) section.getInt("data")); - // 元数据 - ItemMeta meta = item.getItemMeta(); - // 展示名 - if (section.contains("name")) { - meta.setDisplayName(asString(section.getString("name"), papiPlayer)); - } - // 描述 - if (section.contains("lore")) { - meta.setLore(asString(section.getStringList("lore"), papiPlayer)); - } - // 附魔 - if (section.contains("enchants")) { - for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) { - Enchantment enchant = asEnchantment(preEnchant); - if (enchant != null) { - meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true); - } else { - TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ENCHANTS", preEnchant); - } - } - } - // 标签 - if (section.contains("flags") && TabooLib.getVerint() > 10700) { - for (String preFlag : section.getStringList("flags")) { - ItemFlag flag = asItemFlag(preFlag); - if (flag != null) { - meta.addItemFlags(flag); - } else { - TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-FLAG", preFlag); - } - } - } - // 皮革 - if (meta instanceof LeatherArmorMeta && section.contains("color")) { - ((LeatherArmorMeta) meta).setColor(asColor(section.getString("color"))); - } - // 药水 - if (meta instanceof PotionMeta && section.contains("potions")) { - PotionMeta potionMeta = (PotionMeta) meta; - for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) { - PotionEffectType potionEffectType = asPotionEffectType(prePotionName); - if (potionEffectType != null) { - potionMeta.addCustomEffect(new PotionEffect( - potionEffectType, - NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]), - NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true); - } else { - TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", prePotionName); - } - } - } - // 元数据 - item.setItemMeta(meta); - // 数据 - NBTItem nbt = new NBTItem(item); - // 物品标签 - if (section.contains("nbt")) { - for (String name : section.getConfigurationSection("nbt").getKeys(false)) { - Object obj = section.get("nbt." + name); - if (obj instanceof String) { - nbt.setString(name, obj.toString()); - } else if (obj instanceof Double) { - nbt.setDouble(name, Double.valueOf(obj.toString())); - } else if (obj instanceof Integer) { - nbt.setInteger(name, Integer.valueOf(obj.toString())); - } else if (obj instanceof Long) { - nbt.setLong(name, Long.valueOf(obj.toString())); - } else { - nbt.setObject(name, obj); - } - } - } - // 物品属性 - if (section.contains("attributes")) { - NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); - for (String hand : section.getConfigurationSection("attributes").getKeys(false)) { - for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) { - if (asAttribute(name) != null) { - try { - NBTListCompound _attr = attr.addCompound(); - Object num = section.get("attributes." + hand + "." + name); - if (num.toString().contains("%")) { - _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); - _attr.setInteger("Operation", 1); - } else { - _attr.setDouble("Amount", Double.valueOf(num.toString())); - _attr.setInteger("Operation", 0); - } - _attr.setString("AttributeName", asAttribute(name)); - _attr.setInteger("UUIDMost", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE)); - _attr.setInteger("UUIDLeast", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE)); - _attr.setString("Name", asAttribute(name)); - if (!"all".equals(hand)) { - _attr.setString("Slot", hand); - } - } catch (Exception ignored) { - } - } else { - TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", name); - } - } - } - } - return nbt.getItem(); + if (section.get("bukkit") instanceof ItemStack) { + return section.getItemStack("bukkit"); + } + // 材质 + ItemStack item = new ItemStack(asMaterial(section.get("material").toString())); + // 数量 + item.setAmount(section.contains("amount") ? section.getInt("amount") : 1); + // 耐久 + item.setDurability((short) section.getInt("data")); + // 元数据 + ItemMeta meta = item.getItemMeta(); + // 展示名 + if (section.contains("name")) { + meta.setDisplayName(asString(section.getString("name"), papiPlayer)); + } + // 描述 + if (section.contains("lore")) { + meta.setLore(asString(section.getStringList("lore"), papiPlayer)); + } + // 附魔 + if (section.contains("enchants")) { + for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) { + Enchantment enchant = asEnchantment(preEnchant); + if (enchant != null) { + meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true); + } + else { + MsgUtils.warn("&8" + preEnchant + " &c不是一个有效的附魔名称"); + MsgUtils.warn("&c输入 &4/taboolib enchants&c 查看所有附魔"); + } + } + } + // 标签 + if (section.contains("flags") && TabooLib.getVerint() > 10700) { + for (String preFlag : section.getStringList("flags")) { + ItemFlag flag = asItemFlag(preFlag); + if (flag != null) { + meta.addItemFlags(flag); + } + else { + MsgUtils.warn("&8" + preFlag + " &c不是一个有效的标签名称"); + MsgUtils.warn("&c输入 &4/taboolib flags&c 查看所有标签"); + } + } + } + // 皮革 + if (meta instanceof LeatherArmorMeta && section.contains("color")) { + ((LeatherArmorMeta) meta).setColor(asColor(section.getString("color"))); + } + // 药水 + if (meta instanceof PotionMeta && section.contains("potions")) { + PotionMeta potionMeta = (PotionMeta) meta; + for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) { + PotionEffectType potionEffectType = asPotionEffectType(prePotionName); + if (potionEffectType != null) { + potionMeta.addCustomEffect(new PotionEffect( + potionEffectType, + NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]), + NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true); + } + else { + MsgUtils.warn("&8" + potionEffectType + " &c不是一个有效的药水名称"); + MsgUtils.warn("&c输入 &4/taboolib potions&c 查看所有药水"); + } + } + } + // 元数据 + item.setItemMeta(meta); + // 数据 + NBTItem nbt = new NBTItem(item); + // 物品标签 + if (section.contains("nbt")) { + for (String name : section.getConfigurationSection("nbt").getKeys(false)) { + Object obj = section.get("nbt." + name); + if (obj instanceof String) { + nbt.setString(name, obj.toString()); + } + else if (obj instanceof Double) { + nbt.setDouble(name, Double.valueOf(obj.toString())); + } + else if (obj instanceof Integer) { + nbt.setInteger(name, Integer.valueOf(obj.toString())); + } + else if (obj instanceof Long) { + nbt.setLong(name, Long.valueOf(obj.toString())); + } + else { + nbt.setObject(name, obj); + } + } + } + // 物品属性 + if (section.contains("attributes")) { + NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); + for (String hand : section.getConfigurationSection("attributes").getKeys(false)) { + for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) { + if (asAttribute(name) != null) { + try { + NBTListCompound _attr = attr.addCompound(); + Object num = section.get("attributes." + hand + "." + name); + if (num.toString().contains("%")) { + _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); + _attr.setInteger("Operation", 1); + } + else { + _attr.setDouble("Amount", Double.valueOf(num.toString())); + _attr.setInteger("Operation", 0); + } + _attr.setString("AttributeName", asAttribute(name)); + _attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); + _attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); + _attr.setString("Name", asAttribute(name)); + if (!hand.equals("all")) { + _attr.setString("Slot", hand); + } + } + catch (Exception e) { + MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage()); + } + } + else { + MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称"); + MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性"); + } + } + } + } + return nbt.getItem(); } - + public static NBTItem setAttribute(NBTItem nbt, String name, Object num, String hand) { - NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); - if (asAttribute(name) != null) { - try { - NBTListCompound _attr = null; - for (int i = 0; i < attr.size(); i++) { - NBTListCompound nlc = attr.getCompound(i); - if (nlc.getString("AttributeName").equals(asAttribute(name))) { - _attr = nlc; - } - } - if (_attr == null) { - _attr = attr.addCompound(); - } - if (num.toString().contains("%")) { - _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); - _attr.setInteger("Operation", 1); - } else { - _attr.setDouble("Amount", Double.valueOf(num.toString())); - _attr.setInteger("Operation", 0); - } - _attr.setString("AttributeName", asAttribute(name)); - _attr.setInteger("UUIDMost", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE)); - _attr.setInteger("UUIDLeast", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE)); - _attr.setString("Name", asAttribute(name)); - if (!"all".equals(hand)) { - _attr.setString("Slot", hand); - } - } catch (NumberFormatException ignored) { - } - } else { - TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", name); - } - return nbt; + NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); + if (asAttribute(name) != null) { + try { + NBTListCompound _attr = null; + for (int i = 0 ; i < attr.size() ; i++) { + NBTListCompound nlc = attr.getCompound(i); + if (nlc.getString("AttributeName").equals(asAttribute(name))) { + _attr = nlc; + } + } + if (_attr == null) { + _attr = attr.addCompound(); + } + if (num.toString().contains("%")) { + _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); + _attr.setInteger("Operation", 1); + } + else { + _attr.setDouble("Amount", Double.valueOf(num.toString())); + _attr.setInteger("Operation", 0); + } + _attr.setString("AttributeName", asAttribute(name)); + _attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); + _attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); + _attr.setString("Name", asAttribute(name)); + if (!hand.equals("all")) { + _attr.setString("Slot", hand); + } + } + catch (Exception e) { + MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage()); + } + } + else { + MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称"); + MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性"); + } + return nbt; } - + @Deprecated public static void putO(ItemStack item, Inventory inv, int i) { - inv.setItem(i, item); - inv.setItem(i + 1, item); - inv.setItem(i + 2, item); - inv.setItem(i + 9, item); - inv.setItem(i + 10, null); - inv.setItem(i + 11, item); - inv.setItem(i + 18, item); - inv.setItem(i + 19, item); - inv.setItem(i + 20, item); - } + inv.setItem(i, item); + inv.setItem(i+1, item); + inv.setItem(i+2, item); + inv.setItem(i+9, item); + inv.setItem(i+10, null); + inv.setItem(i+11, item); + inv.setItem(i+18, item); + inv.setItem(i+19, item); + inv.setItem(i+20, item); + } } diff --git a/src/main/java/me/skymc/taboolib/itagapi/TagDataHandler.java b/src/main/java/me/skymc/taboolib/itagapi/TagDataHandler.java new file mode 100644 index 0000000..8d58ea8 --- /dev/null +++ b/src/main/java/me/skymc/taboolib/itagapi/TagDataHandler.java @@ -0,0 +1,191 @@ +package me.skymc.taboolib.itagapi; + +import com.google.common.base.Preconditions; +import me.skymc.taboolib.Main; +import me.skymc.taboolib.packet.PacketUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.plugin.Plugin; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.scoreboard.Team; + +import java.util.HashMap; +import java.util.UUID; + +/** + * @Author sky + * @Since 2018-05-23 0:37 + */ +public class TagDataHandler implements Listener { + + private static TagDataHandler handler; + private HashMap playersData = new HashMap<>(); + + public static void init(Plugin plugin) { + Preconditions.checkArgument(handler == null, "TagDataHandler is already instanced!"); + handler = new TagDataHandler(); + // 注册监听 + Bukkit.getPluginManager().registerEvents(handler, plugin); + // 启动相关功能 + new BukkitRunnable() { + + @Override + public void run() { + if (PacketUtils.isProtocolLibEnabled()) { + TagPacket.inst(); + } + } + }.runTask(plugin); + } + + public TagPlayerData unregisterPlayerData(Player player) { + return playersData.remove(player.getUniqueId()); + } + + public TagPlayerData getPlayerData(Player player) { + return playersData.get(player.getUniqueId()); + } + + public TagPlayerData getPlayerDataComputeIfAbsent(Player player) { + return playersData.computeIfAbsent(player.getUniqueId(), x -> new TagPlayerData(player)); + } + + public String getPrefix(Player player) { + return getPlayerDataComputeIfAbsent(player).getPrefix(); + } + + public String getSuffix(Player player) { + return getPlayerDataComputeIfAbsent(player).getSuffix(); + } + + public String getDisplay(Player player) { + return getPlayerDataComputeIfAbsent(player).getNameDisplay(); + } + + public void setPrefix(Player player, String prefix) { + updatePlayerVariable(getPlayerDataComputeIfAbsent(player).setPrefix(prefix)); + updatePlayerListName(player); + } + + public void setSuffix(Player player, String suffix) { + updatePlayerVariable(getPlayerDataComputeIfAbsent(player).setSuffix(suffix)); + updatePlayerListName(player); + } + + public void setPrefixAndSuffix(Player player, String prefix, String suffix) { + updatePlayerVariable(getPlayerDataComputeIfAbsent(player).setPrefix(prefix).setSuffix(suffix)); + updatePlayerListName(player); + } + + public void setDisplay(Player player, String display) { + TagPlayerData playerData = getPlayerDataComputeIfAbsent(player); + cancelPlayerVariable(player, playerData); + player.setDisplayName(playerData.setNameDisplay(display).getNameDisplay()); + updatePlayerVariable(playerData); + updatePlayerListName(player); + Bukkit.getScheduler().runTask(Main.getInst(), () -> TagPacket.refreshPlayer(player)); + } + + public void resetVariable(Player player) { + updatePlayerVariable(getPlayerDataComputeIfAbsent(player).reset()); + updatePlayerListName(player); + } + + public void resetDisplay(Player player) { + setDisplay(player, player.getName()); + } + + public void reset(Player player) { + updatePlayerVariable(getPlayerDataComputeIfAbsent(player).reset()); + setDisplay(player, player.getName()); + } + + // ********************************* + // + // Private Methods + // + // ********************************* + + private void downloadPlayerVariable(Player player) { + Scoreboard scoreboard = TagUtils.getScoreboardComputeIfAbsent(player); + playersData.values().forEach(playerData -> updateTeamVariable(scoreboard, playerData)); + } + + private void updatePlayerVariable(TagPlayerData playerData) { + Bukkit.getOnlinePlayers().forEach(online -> updateTeamVariable(TagUtils.getScoreboardComputeIfAbsent(online), playerData)); + } + + private void updatePlayerListName(Player player) { + TagPlayerData playerData = getPlayerDataComputeIfAbsent(player); + player.setPlayerListName(!playerData.getNameDisplay().equals(player.getName()) ? playerData.getPrefix() + playerData.getNameDisplay() + playerData.getSuffix() : playerData.getNameDisplay()); + } + + private void updateTeamVariable(Scoreboard scoreboard, TagPlayerData playerData) { + Team entryTeam = TagUtils.getTeamComputeIfAbsent(scoreboard, playerData.getTeamHash()); + entryTeam.addEntry(playerData.getNameDisplay()); + entryTeam.setPrefix(playerData.getPrefix()); + entryTeam.setSuffix(playerData.getSuffix()); + TagUtils.cleanEmptyTeamInScoreboard(scoreboard); + } + + private void cancelPlayerVariable(Player player, TagPlayerData playerData) { + if (playerData == null) { + return; + } + for (Player online : Bukkit.getOnlinePlayers()) { + Scoreboard scoreboard = TagUtils.getScoreboardComputeIfAbsent(player); + TagUtils.cleanEntryInScoreboard(scoreboard, playerData.getNameDisplay()); + TagUtils.cleanEmptyTeamInScoreboard(scoreboard); + } + } + + // ********************************* + // + // Listeners + // + // ********************************* + + @EventHandler + public void onJoin(PlayerJoinEvent e) { + downloadPlayerVariable(e.getPlayer()); + } + + @EventHandler + public void onQuit(PlayerQuitEvent e) { + cancelPlayerVariable(e.getPlayer(), unregisterPlayerData(e.getPlayer())); + } + + @EventHandler + public void onCommand(PlayerCommandPreprocessEvent e) { + if (e.getMessage().equalsIgnoreCase("/scoreboardinfo") && e.getPlayer().hasPermission("itagapi.info")) { + e.setCancelled(true); + + e.getPlayer().sendMessage("§7计分板信息:"); + Scoreboard scoreboard = TagUtils.getScoreboardComputeIfAbsent(e.getPlayer()); + + for (Team team : scoreboard.getTeams()) { + e.getPlayer().sendMessage("§7队伍: §f" + team.getName()); + e.getPlayer().sendMessage("§f - §7前缀: §f" + team.getPrefix()); + e.getPlayer().sendMessage("§f - §7后缀: §f" + team.getSuffix()); + e.getPlayer().sendMessage("§f - §7成员: §f"); + team.getEntries().forEach(entry -> e.getPlayer().sendMessage("§f - §f" + entry)); + } + } + } + + // ********************************* + // + // Getter and Setter + // + // ********************************* + + public static TagDataHandler getHandler() { + return handler; + } +} diff --git a/src/main/java/me/skymc/taboolib/itagapi/TagPacket.java b/src/main/java/me/skymc/taboolib/itagapi/TagPacket.java new file mode 100644 index 0000000..595106c --- /dev/null +++ b/src/main/java/me/skymc/taboolib/itagapi/TagPacket.java @@ -0,0 +1,136 @@ +package me.skymc.taboolib.itagapi; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.events.PacketAdapter; +import com.comphenix.protocol.events.PacketEvent; +import com.comphenix.protocol.wrappers.EnumWrappers; +import com.comphenix.protocol.wrappers.PlayerInfoData; +import com.comphenix.protocol.wrappers.WrappedGameProfile; +import com.google.common.base.Preconditions; +import me.skymc.taboolib.Main; +import me.skymc.taboolib.events.itag.AsyncPlayerReceiveNameTagEvent; +import me.skymc.taboolib.events.itag.PlayerReceiveNameTagEvent; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +import java.util.*; +import java.util.stream.IntStream; + +/** + * @Author sky + * @Since 2018-05-09 21:03 + */ +class TagPacket implements Listener { + + private static final int[] uuidSplit = new int[]{0, 8, 12, 16, 20, 32}; + + private static boolean loaded = false; + private static HashMap entityIdMap = new HashMap<>(); + + TagPacket() { + } + + public static void inst() { + assert !loaded : "TagAPI is already instanced!"; + loaded = true; + + Bukkit.getServer().getOnlinePlayers().forEach(player -> entityIdMap.put(player.getEntityId(), player)); + Bukkit.getPluginManager().registerEvents(new TagPacket(), Main.getInst()); + ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(Main.getInst(), PacketType.Play.Server.PLAYER_INFO) { + + @Override + public void onPacketSending(PacketEvent event) { + if (event.getPacket().getPlayerInfoAction().read(0) != EnumWrappers.PlayerInfoAction.ADD_PLAYER) { + return; + } + + List newPlayerInfo = new ArrayList<>(); + for (PlayerInfoData playerInfo : event.getPacket().getPlayerInfoDataLists().read(0)) { + Player player; + if (playerInfo == null || playerInfo.getProfile() == null || (player = Bukkit.getServer().getPlayer(playerInfo.getProfile().getUUID())) == null) { + // Unknown Player + newPlayerInfo.add(playerInfo); + continue; + } + newPlayerInfo.add(new PlayerInfoData(getSentName(player.getEntityId(), playerInfo.getProfile(), event.getPlayer()), playerInfo.getPing(), playerInfo.getGameMode(), playerInfo.getDisplayName())); + } + event.getPacket().getPlayerInfoDataLists().write(0, newPlayerInfo); + } + }); + } + + static String getPlayerDisplayName(Player player) { + return TagDataHandler.getHandler().getPlayerDataComputeIfAbsent(player).getNameDisplay(); + } + + static void refreshPlayer(Player player) { + Preconditions.checkState(Main.getInst().isEnabled(), "Not Enabled!"); + Preconditions.checkNotNull(player, "player"); + player.getWorld().getPlayers().forEach(playerFor -> refreshPlayer(player, playerFor)); + } + + static void refreshPlayer(final Player player, final Player forWhom) { + Preconditions.checkState(Main.getInst().isEnabled(), "Not Enabled!"); + Preconditions.checkNotNull(player, "player"); + Preconditions.checkNotNull(forWhom, "forWhom"); + + if (player != forWhom && player.getWorld() == forWhom.getWorld() && forWhom.canSee(player)) { + forWhom.hidePlayer(player); + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Main.getInst(), () -> forWhom.showPlayer(player), 2); + } + } + + static void refreshPlayer(Player player, Set forWhom) { + Preconditions.checkState(Main.getInst().isEnabled(), "Not Enabled!"); + Preconditions.checkNotNull(player, "player"); + Preconditions.checkNotNull(forWhom, "forWhom"); + + forWhom.forEach(playerFor -> refreshPlayer(player, playerFor)); + } + + private static WrappedGameProfile getSentName(int sentEntityId, WrappedGameProfile sent, Player destinationPlayer) { + Preconditions.checkState(Bukkit.getServer().isPrimaryThread(), "Can only process events on main thread."); + + Player namedPlayer = entityIdMap.get(sentEntityId); + if (namedPlayer == null) { + // They probably were dead when we reloaded + return sent; + } + + PlayerReceiveNameTagEvent oldEvent = new PlayerReceiveNameTagEvent(destinationPlayer, namedPlayer, sent.getName()); + Bukkit.getServer().getPluginManager().callEvent(oldEvent); + + StringBuilder builtUUID = new StringBuilder(); + if (!sent.getId().contains("-")) { + IntStream.range(0, uuidSplit.length - 1).forEach(i -> builtUUID.append(sent.getId(), uuidSplit[i], uuidSplit[i + 1]).append("-")); + } else { + builtUUID.append(sent.getId()); + } + + AsyncPlayerReceiveNameTagEvent newEvent = new AsyncPlayerReceiveNameTagEvent(destinationPlayer, namedPlayer, getPlayerDisplayName(namedPlayer), UUID.fromString(builtUUID.toString())); + Bukkit.getServer().getPluginManager().callEvent(newEvent); + + return new WrappedGameProfile(newEvent.getUUID(), newEvent.getTag().substring(0, Math.min(newEvent.getTag().length(), 16))); + } + + // ********************************* + // + // Listeners + // + // ********************************* + + @EventHandler + public void onJoin(PlayerJoinEvent event) { + entityIdMap.put(event.getPlayer().getEntityId(), event.getPlayer()); + } + + @EventHandler + public void onQuit(PlayerQuitEvent event) { + entityIdMap.remove(event.getPlayer().getEntityId()); + } +} diff --git a/src/main/java/me/skymc/taboolib/itagapi/TagPlayerData.java b/src/main/java/me/skymc/taboolib/itagapi/TagPlayerData.java new file mode 100644 index 0000000..9718614 --- /dev/null +++ b/src/main/java/me/skymc/taboolib/itagapi/TagPlayerData.java @@ -0,0 +1,84 @@ +package me.skymc.taboolib.itagapi; + +import com.ilummc.tlib.util.Strings; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.Objects; +import java.util.UUID; + +/** + * @Author sky + * @Since 2018-05-21 15:07 + */ +public class TagPlayerData { + + private final UUID uuid; + private String nameDisplay; + private String prefix; + private String suffix; + + public TagPlayerData(Player player) { + this.uuid = player.getUniqueId(); + this.nameDisplay = player.getName(); + this.prefix = ""; + this.suffix = ""; + } + + public String getTeamHash() { + return String.valueOf(Objects.hash(prefix)); + } + + public TagPlayerData reset() { + this.nameDisplay = getNameOrigin(); + this.prefix = ""; + this.suffix = ""; + return this; + } + + @Override + public String toString() { + return Strings.replaceWithOrder("TagPlayerData'{'uuid={0}, nameDisplay=''{1}'', prefix=''{2}'', suffix=''{3}'''}'", uuid, nameDisplay, prefix, suffix); + } + + // ********************************* + // + // Getter and Setter + // + // ********************************* + + public UUID getUUID() { + return uuid; + } + + public String getNameOrigin() { + return Bukkit.getPlayer(uuid).getName(); + } + + public String getNameDisplay() { + return nameDisplay == null ? "" : nameDisplay; + } + + public String getPrefix() { + return prefix == null ? "" : prefix; + } + + public String getSuffix() { + return suffix == null ? "" : suffix; + } + + public TagPlayerData setNameDisplay(String nameDisplay) { + this.nameDisplay = nameDisplay.length() > 16 ? nameDisplay.substring(0, 16) : nameDisplay; + return this; + } + + public TagPlayerData setPrefix(String prefix) { + this.prefix = prefix.length() > 16 ? prefix.substring(0, 16) : prefix; + return this; + } + + public TagPlayerData setSuffix(String suffix) { + this.suffix = suffix.length() > 16 ? suffix.substring(0, 16) : suffix; + return this; + } +} diff --git a/src/main/java/me/skymc/taboolib/itagapi/TagUtils.java b/src/main/java/me/skymc/taboolib/itagapi/TagUtils.java new file mode 100644 index 0000000..e0bcb8d --- /dev/null +++ b/src/main/java/me/skymc/taboolib/itagapi/TagUtils.java @@ -0,0 +1,62 @@ +package me.skymc.taboolib.itagapi; + +import com.ilummc.tlib.logger.TLogger; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.scoreboard.Team; + +import java.util.Optional; + +/** + * @Author sky + * @Since 2018-05-21 15:09 + */ +public class TagUtils { + + public static void cleanTeamInScoreboard(Scoreboard scoreboard) { + try { + scoreboard.getTeams().forEach(Team::unregister); + } catch (Exception e) { + TLogger.getGlobalLogger().error("TagUtils.cleanTeamInScoreboard() 异常: " + e.toString()); + } + } + + public static void cleanEntryInScoreboard(Scoreboard scoreboard, String entry) { + try { + Optional.ofNullable(scoreboard.getEntryTeam(entry)).ifPresent(x -> x.removeEntry(entry)); + } catch (Exception e) { + TLogger.getGlobalLogger().error("TagUtils.cleanEntryInScoreboard() 异常: " + e.toString()); + } + } + + public static void cleanEmptyTeamInScoreboard(Scoreboard scoreboard) { + try { + scoreboard.getTeams().stream().filter(team -> team.getEntries().size() == 0).forEach(Team::unregister); + } catch (Exception e) { + TLogger.getGlobalLogger().error("TagUtils.cleanEmptyTeamInScoreboard() 异常: " + e.toString()); + } + } + + public static Scoreboard getScoreboardComputeIfAbsent(Player player) { + Scoreboard scoreboard = player.getScoreboard(); + if (scoreboard == null) { + player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + } + return player.getScoreboard(); + } + + public static Scoreboard getScoreboardAndCleanTeams(Player player) { + Scoreboard scoreboard = getScoreboardComputeIfAbsent(player); + cleanTeamInScoreboard(scoreboard); + return scoreboard; + } + + public static Team getTeamComputeIfAbsent(Scoreboard scoreboard, String teamName) { + Team team = scoreboard.getTeam(teamName); + if (team == null) { + scoreboard.registerNewTeam(teamName); + } + return scoreboard.getTeam(teamName); + } +} diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java b/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java index 4151333..849d117 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java @@ -313,7 +313,7 @@ public class NMSUtil18 { class_NBTTagCompound_getByteMethod = class_NBTTagCompound.getMethod("getByte", String.class); class_NBTTagCompound_getByteArrayMethod = class_NBTTagCompound.getMethod("getByteArray", String.class); class_NBTTagCompound_getListMethod = class_NBTTagCompound.getMethod("getList", String.class, Integer.TYPE); - class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", org.bukkit.inventory.ItemStack.class); + class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", ItemStack.class); class_CraftItemStack_asBukkitCopyMethod = class_CraftItemStack.getMethod("asBukkitCopy", class_ItemStack); class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack); class_ItemStack_createStackMethod = class_ItemStack.getMethod("createStack", class_NBTTagCompound); @@ -526,7 +526,7 @@ public class NMSUtil18 { return NMSUtil18.class.getClassLoader().loadClass(className); } - public static Object getHandle(org.bukkit.inventory.ItemStack stack) { + public static Object getHandle(ItemStack stack) { Object handle = null; try { handle = class_CraftItemStack_getHandleField.get(stack); @@ -536,7 +536,7 @@ public class NMSUtil18 { return handle; } - public static Object getHandle(org.bukkit.World world) { + public static Object getHandle(World world) { if (world == null) { return null; } @@ -549,7 +549,7 @@ public class NMSUtil18 { return handle; } - public static Object getHandle(org.bukkit.entity.Entity entity) { + public static Object getHandle(Entity entity) { if (entity == null) { return null; } @@ -575,7 +575,7 @@ public class NMSUtil18 { return handle; } - public static boolean isDone(org.bukkit.Chunk chunk) { + public static boolean isDone(Chunk chunk) { Object chunkHandle = getHandle(chunk); boolean done = false; try { @@ -586,7 +586,7 @@ public class NMSUtil18 { return done; } - public static Object getHandle(org.bukkit.Chunk chunk) { + public static Object getHandle(Chunk chunk) { Object handle = null; try { handle = class_CraftChunk_getHandleMethod.invoke(chunk); @@ -596,7 +596,7 @@ public class NMSUtil18 { return handle; } - public static Object getHandle(org.bukkit.entity.Player player) { + public static Object getHandle(Player player) { Object handle = null; try { handle = class_CraftPlayer_getHandleMethod.invoke(player); @@ -652,17 +652,17 @@ public class NMSUtil18 { return dir; } - public static org.bukkit.entity.Entity getBukkitEntity(Object entity) { + public static Entity getBukkitEntity(Object entity) { if (entity == null) { return null; } try { Method getMethod = entity.getClass().getMethod("getBukkitEntity"); Object bukkitEntity = getMethod.invoke(entity); - if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) { + if (!(bukkitEntity instanceof Entity)) { return null; } - return (org.bukkit.entity.Entity) bukkitEntity; + return (Entity) bukkitEntity; } catch (Throwable ex) { ex.printStackTrace(); } diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java b/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java index efc8234..db241bc 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java @@ -377,7 +377,7 @@ public class NMSUtil19 { class_NBTTagCompound_getByteMethod = class_NBTTagCompound.getMethod("getByte", String.class); class_NBTTagCompound_getByteArrayMethod = class_NBTTagCompound.getMethod("getByteArray", String.class); class_NBTTagCompound_getListMethod = class_NBTTagCompound.getMethod("getList", String.class, Integer.TYPE); - class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", org.bukkit.inventory.ItemStack.class); + class_CraftItemStack_copyMethod = class_CraftItemStack.getMethod("asNMSCopy", ItemStack.class); class_CraftItemStack_asBukkitCopyMethod = class_CraftItemStack.getMethod("asBukkitCopy", class_ItemStack); class_CraftItemStack_mirrorMethod = class_CraftItemStack.getMethod("asCraftMirror", class_ItemStack); class_World_addEntityMethod = class_World.getMethod("addEntity", class_Entity, CreatureSpawnEvent.SpawnReason.class); @@ -931,7 +931,7 @@ public class NMSUtil19 { return NMSUtils.class.getClassLoader().loadClass(className); } - public static Object getHandle(org.bukkit.Server server) { + public static Object getHandle(Server server) { Object handle = null; try { handle = class_CraftServer_getServerMethod.invoke(server); @@ -941,7 +941,7 @@ public class NMSUtil19 { return handle; } - public static Object getHandle(org.bukkit.inventory.ItemStack stack) { + public static Object getHandle(ItemStack stack) { Object handle = null; try { handle = class_CraftItemStack_getHandleField.get(stack); @@ -951,7 +951,7 @@ public class NMSUtil19 { return handle; } - public static Object getHandle(org.bukkit.World world) { + public static Object getHandle(World world) { if (world == null) { return null; } @@ -964,7 +964,7 @@ public class NMSUtil19 { return handle; } - public static Object getHandle(org.bukkit.entity.Entity entity) { + public static Object getHandle(Entity entity) { if (entity == null) { return null; } @@ -990,7 +990,7 @@ public class NMSUtil19 { return handle; } - public static boolean isDone(org.bukkit.Chunk chunk) { + public static boolean isDone(Chunk chunk) { Object chunkHandle = getHandle(chunk); boolean done = false; try { @@ -1001,7 +1001,7 @@ public class NMSUtil19 { return done; } - public static Object getHandle(org.bukkit.Chunk chunk) { + public static Object getHandle(Chunk chunk) { Object handle = null; try { handle = class_CraftChunk_getHandleMethod.invoke(chunk); @@ -1011,7 +1011,7 @@ public class NMSUtil19 { return handle; } - public static Object getHandle(org.bukkit.entity.Player player) { + public static Object getHandle(Player player) { Object handle = null; try { handle = class_CraftPlayer_getHandleMethod.invoke(player); @@ -1068,7 +1068,7 @@ public class NMSUtil19 { return dir; } - public static org.bukkit.entity.Entity getBukkitEntity(Object entity) + public static Entity getBukkitEntity(Object entity) { if (entity == null) { return null; @@ -1076,10 +1076,10 @@ public class NMSUtil19 { try { Method getMethod = entity.getClass().getMethod("getBukkitEntity"); Object bukkitEntity = getMethod.invoke(entity); - if (!(bukkitEntity instanceof org.bukkit.entity.Entity)) { + if (!(bukkitEntity instanceof Entity)) { return null; } - return (org.bukkit.entity.Entity)bukkitEntity; + return (Entity)bukkitEntity; } catch (Throwable ex) { ex.printStackTrace(); } diff --git a/src/main/java/me/skymc/taboolib/string/language2/Language2Format.java b/src/main/java/me/skymc/taboolib/string/language2/Language2Format.java index 6fba600..ccb1dff 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/Language2Format.java +++ b/src/main/java/me/skymc/taboolib/string/language2/Language2Format.java @@ -1,6 +1,9 @@ package me.skymc.taboolib.string.language2; +import lombok.Getter; import me.skymc.taboolib.string.language2.value.*; + +import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.util.ArrayList; @@ -12,101 +15,97 @@ import java.util.List; * @since 2018-03-08 22:45:56 */ public class Language2Format implements Language2Line { - - private Language2Value language2Value; - private List language2Lines = new ArrayList<>(); - - public Language2Format(Player player, Language2Value value) { - language2Value = value; - // 语言类型 - Language2Type type = Language2Type.TEXT; - // 递交数据 - List values = new LinkedList<>(); - - // 遍历内容 - for (String line : value.getLanguageValue()) { - // 文本类型 - if (line.contains("[text]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.TEXT; - } - // 大标题 - else if (line.contains("[title]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.TITLE; - } - // 小标题 - else if (line.contains("[action]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.ACTION; - } - // JSON - else if (line.contains("[json]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.JSON; - } - // JSON2 - else if (line.contains("[json2]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.JSON2; - } - // 音效 - else if (line.contains("[sound]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.SOUND; - } - // 书本 - else if (line.contains("[book]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.BOOK; - } else if (line.contains("[return]")) { - // 递交数据 - parseValue(player, values, type); - } - // 默认 - else { - // 追加内容 - values.add(line); - } - } - } - - public Language2Value getLanguage2Value() { - return language2Value; - } - - public List getLanguage2Lines() { - return language2Lines; - } - - /** - * 识别内容 - * - * @param player 玩家 - * @param list 数据 - * @param type 类型 - */ - private void parseValue(Player player, List list, Language2Type type) { - if (list.size() == 0) { - return; - } - // 变量转换 - List listPlaceholder = language2Value.setPlaceholder(list, player); - // 大标题 + + @Getter + private Language2Value language2Value = null; + + @Getter + private List language2Lines = new ArrayList<>(); + + public Language2Format(Player player, Language2Value value) { + language2Value = value; + // 语言类型 + Language2Type type = Language2Type.TEXT; + // 递交数据 + List values = new LinkedList<>(); + + // 遍历内容 + for (String line : value.getLanguageValue()) { + // 文本类型 + if (line.contains("[text]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.TEXT; + } + // 大标题 + else if (line.contains("[title]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.TITLE; + } + // 小标题 + else if (line.contains("[action]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.ACTION; + } + // JSON + else if (line.contains("[json]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.JSON; + } + // JSON2 + else if (line.contains("[json2]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.JSON2; + } + // 音效 + else if (line.contains("[sound]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.SOUND; + } + // 书本 + else if (line.contains("[book]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.BOOK; + } + else if (line.contains("[return]")) { + // 递交数据 + parseValue(player, values, type); + } + // 默认 + else { + // 追加内容 + values.add(line); + } + } + } + + /** + * 识别内容 + * + * @param player 玩家 + * @param list 数据 + * @param type 类型 + */ + private void parseValue(Player player, List list, Language2Type type) { + if (list.size() == 0) { + return; + } + // 变量转换 + List listPlaceholder = language2Value.setPlaceholder(list, player); + // 大标题 switch (type) { case TITLE: language2Lines.add(new Language2Title(this, listPlaceholder)); @@ -134,19 +133,23 @@ public class Language2Format implements Language2Line { default: language2Lines.add(new Language2Text(this, listPlaceholder)); break; - } - // 清理数据 - list.clear(); - listPlaceholder.clear(); - } + } + // 清理数据 + list.clear(); + listPlaceholder.clear(); + } - @Override - public void send(Player player) { - language2Lines.forEach(line -> line.send(player)); - } + @Override + public void send(Player player) { + for (Language2Line line : language2Lines) { + line.send(player); + } + } - @Override - public void console() { - language2Lines.forEach(Language2Line::console); - } + @Override + public void console() { + for (Language2Line line : language2Lines) { + line.console(); + } + } } diff --git a/src/main/java/me/skymc/taboolib/team/TagAPI.java b/src/main/java/me/skymc/taboolib/team/TagAPI.java index 893c977..5afb4da 100644 --- a/src/main/java/me/skymc/taboolib/team/TagAPI.java +++ b/src/main/java/me/skymc/taboolib/team/TagAPI.java @@ -1,90 +1,41 @@ package me.skymc.taboolib.team; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketEvent; -import com.comphenix.protocol.wrappers.EnumWrappers; -import com.comphenix.protocol.wrappers.PlayerInfoData; -import com.comphenix.protocol.wrappers.WrappedGameProfile; import com.google.common.base.Preconditions; -import com.ilummc.tlib.bungee.api.ChatColor; import me.skymc.taboolib.Main; -import me.skymc.taboolib.events.itag.AsyncPlayerReceiveNameTagEvent; -import me.skymc.taboolib.events.itag.PlayerReceiveNameTagEvent; +import me.skymc.taboolib.itagapi.TagDataHandler; import org.bukkit.Bukkit; import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import java.util.*; -import java.util.stream.IntStream; +import java.util.Set; /** * @Author sky * @Since 2018-05-09 21:03 */ -public class TagAPI implements Listener { +@Deprecated +public class TagAPI { - private static final int[] uuidSplit = new int[]{0, 8, 12, 16, 20, 32}; - - private static boolean loaded = false; - private static HashMap entityIdMap = new HashMap<>(); - private static HashMap playerData = new HashMap<>(); + /** + * 该工具于 2018年5月23日02:31:14 失效 + * 新工具类: {@link TagDataHandler} + */ TagAPI() { } public static void inst() { - assert !loaded : "TagAPI is already instanced!"; - loaded = true; - - Bukkit.getServer().getOnlinePlayers().forEach(player -> entityIdMap.put(player.getEntityId(), player)); - Bukkit.getPluginManager().registerEvents(new TagAPI(), Main.getInst()); - ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(Main.getInst(), PacketType.Play.Server.PLAYER_INFO) { - - @Override - public void onPacketSending(PacketEvent event) { - if (event.getPacket().getPlayerInfoAction().read(0) != EnumWrappers.PlayerInfoAction.ADD_PLAYER) { - return; - } - - List newPlayerInfo = new ArrayList<>(); - for (PlayerInfoData playerInfo : event.getPacket().getPlayerInfoDataLists().read(0)) { - Player player; - if (playerInfo == null || playerInfo.getProfile() == null || (player = Bukkit.getServer().getPlayer(playerInfo.getProfile().getUUID())) == null) { - // Unknown Player - newPlayerInfo.add(playerInfo); - continue; - } - newPlayerInfo.add(new PlayerInfoData(getSentName(player.getEntityId(), playerInfo.getProfile(), event.getPlayer()), playerInfo.getPing(), playerInfo.getGameMode(), playerInfo.getDisplayName())); - } - event.getPacket().getPlayerInfoDataLists().write(0, newPlayerInfo); - } - }); } public static String getPlayerDisplayName(Player player) { - return playerData.getOrDefault(player.getUniqueId(), player.getName()); + return TagDataHandler.getHandler().getDisplay(player); } public static void setPlayerDisplayName(Player player, String name) { - String nameColored = ChatColor.translateAlternateColorCodes('&', name); - player.setDisplayName(nameColored); - player.setPlayerListName(nameColored); - playerData.put(player.getUniqueId(), nameColored); - - Bukkit.getScheduler().runTask(Main.getInst(), () -> refreshPlayer(player)); + TagDataHandler.getHandler().setDisplay(player, name); } public static void removePlayerDisplayName(Player player) { - player.setDisplayName(null); - player.setPlayerListName(null); - playerData.remove(player.getUniqueId()); - - Bukkit.getScheduler().runTask(Main.getInst(), () -> refreshPlayer(player)); + TagDataHandler.getHandler().setDisplay(player, player.getName()); } public static void refreshPlayer(Player player) { @@ -112,50 +63,4 @@ public class TagAPI implements Listener { forWhom.forEach(playerFor -> refreshPlayer(player, playerFor)); } - - private static WrappedGameProfile getSentName(int sentEntityId, WrappedGameProfile sent, Player destinationPlayer) { - Preconditions.checkState(Bukkit.getServer().isPrimaryThread(), "Can only process events on main thread."); - - Player namedPlayer = entityIdMap.get(sentEntityId); - if (namedPlayer == null) { - // They probably were dead when we reloaded - return sent; - } - - PlayerReceiveNameTagEvent oldEvent = new PlayerReceiveNameTagEvent(destinationPlayer, namedPlayer, sent.getName()); - Bukkit.getServer().getPluginManager().callEvent(oldEvent); - - StringBuilder builtUUID = new StringBuilder(); - if (!sent.getId().contains("-")) { - IntStream.range(0, uuidSplit.length - 1).forEach(i -> builtUUID.append(sent.getId(), uuidSplit[i], uuidSplit[i + 1]).append("-")); - } else { - builtUUID.append(sent.getId()); - } - - AsyncPlayerReceiveNameTagEvent newEvent = new AsyncPlayerReceiveNameTagEvent(destinationPlayer, namedPlayer, getPlayerDisplayName(namedPlayer), UUID.fromString(builtUUID.toString())); - Bukkit.getServer().getPluginManager().callEvent(newEvent); - - updatePlayerTag(namedPlayer, newEvent); - return new WrappedGameProfile(newEvent.getUUID(), newEvent.getTag().substring(0, Math.min(newEvent.getTag().length(), 16))); - } - - @EventHandler - public void onJoin(PlayerJoinEvent event) { - entityIdMap.put(event.getPlayer().getEntityId(), event.getPlayer()); - } - - @EventHandler - public void onQuit(PlayerQuitEvent event) { - entityIdMap.remove(event.getPlayer().getEntityId()); - } - - private static void updatePlayerTag(Player namedPlayer, AsyncPlayerReceiveNameTagEvent newEvent) { - TagManager.PlayerData playerData = TagManager.getInst().getPlayerData(namedPlayer); - if (playerData.isEmpty()) { - return; - } - TagManager.getInst().unloadData(namedPlayer); - playerData.setName(newEvent.getTag()); - TagManager.getInst().uploadData(namedPlayer); - } } diff --git a/src/main/java/me/skymc/taboolib/team/TagManager.java b/src/main/java/me/skymc/taboolib/team/TagManager.java index 161a87d..7c78340 100644 --- a/src/main/java/me/skymc/taboolib/team/TagManager.java +++ b/src/main/java/me/skymc/taboolib/team/TagManager.java @@ -2,6 +2,7 @@ package me.skymc.taboolib.team; import com.ilummc.tlib.util.Strings; import me.skymc.taboolib.Main; +import me.skymc.taboolib.itagapi.TagDataHandler; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -18,16 +19,16 @@ import java.util.UUID; * @author sky * @since 2018-03-17 21:43:49 */ -public class TagManager implements Listener { +@Deprecated +public class TagManager { + + /** + * 该工具于 2018年5月23日02:31:14 失效 + * 新工具类: {@link TagDataHandler} + */ private static TagManager inst; - private HashMap playerData = new HashMap<>(); - - private TagManager() { - Bukkit.getPluginManager().registerEvents(this, Main.getInst()); - } - public static TagManager getInst() { synchronized (TagManager.class) { if (inst == null) { @@ -38,146 +39,37 @@ public class TagManager implements Listener { } public HashMap getPlayerData() { - return playerData; + return new HashMap<>(0); } - /** - * 设置玩家前缀 - * - * @param player 名称 - * @param prefix 前缀 - */ public void setPrefix(Player player, String prefix) { - getPlayerData(player).setPrefix(prefix); - uploadData(player); + TagDataHandler.getHandler().setPrefix(player, prefix); } - /** - * 设置玩家后缀 - * - * @param player 玩家 - * @param suffix 后缀 - */ public void setSuffix(Player player, String suffix) { - getPlayerData(player).setSuffix(suffix); - uploadData(player); + TagDataHandler.getHandler().setSuffix(player, suffix); } - /** - * 获取玩家前缀 - * - * @param player 玩家 - * @return String - */ public String getPrefix(Player player) { - return getPlayerData(player).getPrefix(); + return TagDataHandler.getHandler().getPrefix(player); } - /** - * 获取玩家后缀 - * - * @param player 玩家 - * @return String - */ public String getSuffix(Player player) { - return getPlayerData(player).getSuffix(); + return TagDataHandler.getHandler().getSuffix(player); } - /** - * 获取玩家数据 - * - * @param player 玩家 - * @return {@link PlayerData} - */ public PlayerData getPlayerData(Player player) { - return playerData.computeIfAbsent(player.getUniqueId(), k -> new PlayerData(player)); + return new PlayerData(player); } - /** - * 注销称号数据 - * - * @param targetPlayer - */ public void unloadData(Player targetPlayer) { - PlayerData data = getPlayerData(targetPlayer); - for (Player player : Bukkit.getOnlinePlayers()) { - Scoreboard scoreboard = getScoreboard(player); - Team team = scoreboard.getTeam(data.getName()); - if (team != null) { - team.unregister(); - } - } - data.reset(); + TagDataHandler.getHandler().resetVariable(targetPlayer); } - /** - * 将该玩家的数据向服务器所有玩家更新 - * - * @param targetPlayer 玩家 - */ public void uploadData(Player targetPlayer) { - PlayerData data = getPlayerData(targetPlayer); - String prefix = data.getPrefix().length() > 16 ? data.getPrefix().substring(0, 16) : data.getPrefix(); - String suffix = data.getSuffix().length() > 16 ? data.getSuffix().substring(0, 16) : data.getSuffix(); - // 如果没有称号数据 - if (prefix.isEmpty() && suffix.isEmpty()) { - unloadData(targetPlayer); - return; - } - for (Player player : Bukkit.getOnlinePlayers()) { - Scoreboard scoreboard = getScoreboard(player); - Team team = getTeam(scoreboard, data); - team.setPrefix(prefix); - team.setSuffix(suffix); - } } - /** - * 下载服务器内的称号数据到该玩家 - * - * @param targetPlayer 玩家 - */ public void downloadData(Player targetPlayer) { - Scoreboard scoreboard = getScoreboard(targetPlayer); - for (Player player : Bukkit.getOnlinePlayers()) { - PlayerData data = getPlayerData(player); - String prefix = data.getPrefix().length() > 16 ? data.getPrefix().substring(0, 16) : data.getPrefix(); - String suffix = data.getSuffix().length() > 16 ? data.getSuffix().substring(0, 16) : data.getSuffix(); - // 如果没有称号数据 - if (prefix.isEmpty() && suffix.isEmpty()) { - continue; - } - Team team = getTeam(scoreboard, data); - team.setPrefix(prefix); - team.setSuffix(suffix); - } - } - - @EventHandler - public void onJoin(PlayerJoinEvent e) { - downloadData(e.getPlayer()); - } - - @EventHandler - public void onQuit(PlayerQuitEvent e) { - unloadData(e.getPlayer()); - } - - private Scoreboard getScoreboard(Player player) { - Scoreboard scoreboard = player.getScoreboard(); - if (scoreboard == null) { - player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - } - return scoreboard; - } - - private Team getTeam(Scoreboard scoreboard, PlayerData data) { - Team team = scoreboard.getTeam(String.valueOf(data.getPrefix())); - if (team == null) { - team = scoreboard.registerNewTeam(String.valueOf(data.getPrefix())); - team.addEntry(data.getName()); - } - return team; } static class PlayerData { diff --git a/src/main/java/me/skymc/taboolib/team/TagUtils.java b/src/main/java/me/skymc/taboolib/team/TagUtils.java deleted file mode 100644 index 1ebca72..0000000 --- a/src/main/java/me/skymc/taboolib/team/TagUtils.java +++ /dev/null @@ -1,131 +0,0 @@ -package me.skymc.taboolib.team; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.scoreboard.Scoreboard; -import org.bukkit.scoreboard.Team; - -/** - * @author sky - * @since 2018-03-17 21:36:52 - */ -public class TagUtils { - - /** - * 设置玩家前后缀 - * - * @param p 玩家 - * @param prefix 前缀 - * @param suffix 后缀 - */ - public static void setTag(Player p, String prefix, String suffix) { - // 判断长度 - if (prefix.length() > 16) { - prefix = prefix.substring(0, 16); - } - if (suffix.length() > 16) { - suffix = suffix.substring(0, 16); - } - - // 获取计分板 - Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); - Team t = board.getTeam(p.getName()); - if (t == null) { - t = board.registerNewTeam(p.getName()); - } - - // 更新称号 - t.setPrefix(prefix); - t.setSuffix(suffix); - t.addEntry(p.getName()); - - // 更新玩家 - for (Player o : Bukkit.getOnlinePlayers()) { - if (!board.equals(o.getScoreboard())) { - o.setScoreboard(board); - } - } - } - - /** - * 注销玩家前后缀 - * - * @param p 玩家 - */ - public static void unregisterTag(Player p) { - Team team = Bukkit.getScoreboardManager().getMainScoreboard().getTeam(p.getName()); - if (team != null) { - team.unregister(); - } - } - - /** - * 注销所有在线玩家前后缀 - */ - public static void unregisterAll() { - for (Player o : Bukkit.getOnlinePlayers()) { - unregisterTag(o); - } - } - - /** - * 删除所有前后缀 - */ - public static void delete() { - for (Team t : Bukkit.getScoreboardManager().getMainScoreboard().getTeams()) { - t.unregister(); - } - } - - /** - * 设置全服玩家前后缀 - * - * @param prefix 前缀 - * @param suffix 后缀 - */ - public static void registerAll(String prefix, String suffix) { - for (Player o : Bukkit.getOnlinePlayers()) { - setTag(o, prefix, suffix); - } - } - - /** - * 刷新计分板数据 - */ - public static void refresh() { - Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); - for (Player o : Bukkit.getOnlinePlayers()) { - o.setScoreboard(board); - } - } - - /** - * 获取玩家前缀 - * - * @param p 玩家 - * @return String - */ - public static String getPrefix(Player p) { - Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); - Team t = board.getTeam(p.getName()); - if (t != null) { - return t.getPrefix(); - } - return null; - } - - /** - * 获取玩玩家后缀 - * - * @param p 玩家 - * @return String - */ - public static String getSuffix(Player p) { - Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard(); - Team t = board.getTeam(p.getName()); - if (t != null) { - return t.getSuffix(); - } - return null; - } -} diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 87c8819..6555707 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -164,6 +164,9 @@ COMMANDS: - '&8[&3&lTabooLib&8] &7你可能想要:' - '&8[&3&lTabooLib&8] &7{1}' COMMAND-REGISTER: '&7自动为插件 &f{0} &7的命令 &f{1} &7注册 &f{2} &7条子命令' + COMMAND-HELP: ' §f/{0} {1} {2} §6- §e{3}' + COMMAND-ARGUMENT: '§7<§8{0}§7>' + COMMAND-ARGUMENT-REQUIRE: '§7[§8{0}§7]' PARAMETER: UNKNOWN: '&8[&3&lTabooLib&8] &4指令错误' INSUFFICIENT: '&8[&3&lTabooLib&8] &4参数不足' From fb38ef8977dcac29747e089eeccd5a7814331269 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9D=8F=E9=BB=91?= Date: Wed, 23 May 2018 21:32:48 +0800 Subject: [PATCH 4/9] =?UTF-8?q?=E5=9B=A0=20Idea=20=E5=86=85=E7=BD=AE=20Git?= =?UTF-8?q?hub=20=E5=AE=A2=E6=88=B7=E7=AB=AF=E7=9A=84=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E5=AF=BC=E8=87=B4=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81=E5=87=BA?= =?UTF-8?q?=E9=94=99=20=E4=BB=A5=E4=B8=8B=E7=B1=BB=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=9B=9E=E6=A1=A3=E8=87=B3=E4=B8=8A=E6=AC=A1?= =?UTF-8?q?=E6=8F=90=E4=BA=A4=E6=97=B6=E9=97=B4=EF=BC=9A=20-=20ItemUtils?= =?UTF-8?q?=20-=20TConfigInjector=20-=20Langauge2Format?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ilummc/tlib/inject/TConfigInjector.java | 188 ++-- .../skymc/taboolib/inventory/ItemUtils.java | 821 +++++++++--------- .../string/language2/Language2Format.java | 219 +++-- 3 files changed, 595 insertions(+), 633 deletions(-) diff --git a/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java b/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java index 6d2e4bf..d7f788d 100644 --- a/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java +++ b/src/main/java/com/ilummc/tlib/inject/TConfigInjector.java @@ -1,61 +1,113 @@ package com.ilummc.tlib.inject; -import com.google.common.collect.Lists; import com.google.common.io.Files; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.google.gson.annotations.SerializedName; -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.annotations.Config; -import com.ilummc.tlib.bean.Property; +import com.ilummc.tlib.annotations.TConfig; +import com.ilummc.tlib.resources.TLocale; +import me.skymc.taboolib.fileutils.ConfigUtils; import org.apache.commons.lang3.Validate; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.IOException; -import java.lang.reflect.Array; import java.lang.reflect.Field; import java.nio.charset.Charset; -import java.util.*; -import java.util.stream.Collectors; +import java.util.HashMap; +import java.util.Map; public class TConfigInjector { + public static void fixUnicode(YamlConfiguration configuration) { + try { + Field field = YamlConfiguration.class.getDeclaredField("yamlOptions"); + field.setAccessible(true); + field.set(configuration, NoUnicodeDumperOption.INSTANCE); + } catch (NoSuchFieldException | IllegalAccessException e) { + e.printStackTrace(); + } + } + + private static final class NoUnicodeDumperOption extends DumperOptions { + + private static final NoUnicodeDumperOption INSTANCE = new NoUnicodeDumperOption(); + + @Override + public void setAllowUnicode(boolean allowUnicode) { + super.setAllowUnicode(false); + } + + @Override + public boolean isAllowUnicode() { + return false; + } + + @Override + public void setLineBreak(LineBreak lineBreak) { + super.setLineBreak(LineBreak.getPlatformLineBreak()); + } + } + public static Object loadConfig(Plugin plugin, Class clazz) { try { - Config config = clazz.getAnnotation(Config.class); + TConfig config = clazz.getAnnotation(TConfig.class); Validate.notNull(config); File file = new File(plugin.getDataFolder(), config.name()); - if (!file.exists()) if (config.fromJar()) plugin.saveResource(config.name(), true); - else saveConfig(plugin, clazz.newInstance()); - return unserialize(plugin, clazz); + if (!file.exists()) { + if (config.fromJar()) { + plugin.saveResource(config.name(), true); + } else { + saveConfig(plugin, clazz.newInstance()); + } + } + Object obj = unserialize(plugin, clazz); + if (config.readOnly()) { + saveConfig(plugin, obj); + } + return obj; } catch (NullPointerException e) { - TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败:没有 @Config 注解"); + TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), clazz.getSimpleName()); } catch (Exception e) { - TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败"); + TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName()); } return null; } + public static void reloadConfig(Plugin plugin, Object object) { + try { + TConfig config = object.getClass().getAnnotation(TConfig.class); + Validate.notNull(config); + File file = new File(plugin.getDataFolder(), config.name()); + Map map = ConfigUtils.confToMap(ConfigUtils.loadYaml(plugin, file)); + Object obj = ConfigUtils.mapToObj(map, object); + if (config.readOnly()) { + saveConfig(plugin, obj); + } + } catch (NullPointerException e) { + TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName()); + } catch (Exception e) { + TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), object.getClass().getSimpleName()); + } + } + public static Object unserialize(Plugin plugin, Class clazz) { try { - Config config = clazz.getAnnotation(Config.class); + TConfig config = clazz.getAnnotation(TConfig.class); Validate.notNull(config); - return new GsonBuilder().disableHtmlEscaping().excludeFieldsWithModifiers(config.excludeModifiers()) - .create().fromJson(new Gson().toJson(new Yaml() - .dump(Files.toString(new File(plugin.getDataFolder(), config.name()), Charset.forName(config.charset())))), clazz); + return ConfigUtils.confToObj( + ConfigUtils.mapToConf( + ConfigUtils.yamlToMap( + Files.toString(new File(plugin.getDataFolder(), config.name()), Charset.forName(config.charset())))), clazz); } catch (NullPointerException e) { - TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败:没有 @Config 注解或文件不存在"); + TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-FILE", plugin.toString(), clazz.getSimpleName()); return null; } catch (Exception e) { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e1) { - TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + clazz.getSimpleName() + " 加载失败"); + TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName()); return null; } } @@ -63,95 +115,29 @@ public class TConfigInjector { public static Map serialize(Plugin plugin, Object object) { try { - Config config = object.getClass().getAnnotation(Config.class); + TConfig config = object.getClass().getAnnotation(TConfig.class); Validate.notNull(config); - return new Serializer(new LinkedHashMap<>(), object, config.excludeModifiers()).get(); + return ConfigUtils.objToMap(ConfigUtils.objToConf(object).getValues(false), config.excludeModifiers()); } catch (NullPointerException e) { - TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + object.getClass().getSimpleName() + " 序列化失败:没有 @Config 注解"); + TLocale.Logger.warn("CONFIG.SAVE-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName()); } catch (Exception e) { - TLib.getTLib().getLogger().warn("插件 " + plugin + " 的配置类 " + object.getClass().getSimpleName() + " 序列化失败"); + TLocale.Logger.warn("CONFIG.SAVE-FAIL", plugin.toString(), object.getClass().getSimpleName()); } return null; } public static void saveConfig(Plugin plugin, Object object) throws IOException, NullPointerException { - Config config = object.getClass().getAnnotation(Config.class); + TConfig config = object.getClass().getAnnotation(TConfig.class); Validate.notNull(config); - Object obj = serialize(plugin, object); - Validate.notNull(obj); + Gson gson = new GsonBuilder().disableHtmlEscaping().create(); + Map map = gson.fromJson(gson.toJson(object), HashMap.class); + YamlConfiguration configuration = (YamlConfiguration) ConfigUtils.mapToConf(map); File target = new File(plugin.getDataFolder(), config.name()); - if (!target.exists()) target.createNewFile(); - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - Yaml yaml = new Yaml(options); - String str = yaml.dump(obj); - byte[] arr = str.getBytes(config.charset()); + if (!target.exists()) { + target.createNewFile(); + } + byte[] arr = configuration.saveToString().getBytes(config.charset()); Files.write(arr, target); } - private static final List> primitiveType = Lists.newArrayList(Integer.class, - Double.class, Float.class, Boolean.class, Short.class, Byte.class, Character.class, Long.class, String.class); - - private static class Serializer { - - private HashMap map; - private Object o; - private int modifiers; - - private Serializer(HashMap map, Object o, int modifiers) { - this.map = map; - this.o = o; - this.modifiers = modifiers; - } - - private HashMap get() { - for (Field field : o.getClass().getDeclaredFields()) { - if ((field.getModifiers() & modifiers) == 0 && !field.isSynthetic()) - try { - SerializedName node = field.getAnnotation(SerializedName.class); - if (!field.isAccessible()) field.setAccessible(true); - Object obj = field.get(o); - map.put(node == null ? field.getName() : node.value(), serialize(obj)); - } catch (Exception ignored) { - } - } - return map; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - private Object serialize(Object o) { - try { - if (o.getClass().isPrimitive() || primitiveType.contains(o.getClass())) { - return o; - } else if (o.getClass().isArray()) { - List list = new ArrayList<>(); - int len = (int) o.getClass().getField("length").get(o); - for (int i = 0; i < len; i++) { - list.add(serialize(Array.get(o, i))); - } - return list; - } else if (o instanceof Collection) { - return ((Collection) o).stream().map(this::serialize).collect(Collectors.toList()); - } else if (o instanceof Map) { - Map map = new LinkedHashMap<>(); - ((Map) o).forEach((o1, o2) -> map.put((String) o1, serialize(o2))); - return map; - } else if (o instanceof ConfigurationSerializable) { - Map map = new LinkedHashMap<>(); - map.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, - ConfigurationSerialization.getAlias((Class) o.getClass())); - map.putAll(((ConfigurationSerializable) o).serialize()); - return map; - } else if (o instanceof Property) { - return serialize(((Property) o).get()); - } else { - return new Serializer(new HashMap<>(), o, modifiers).get(); - } - } catch (Exception ignored) { - return null; - } - } - - } - } diff --git a/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java b/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java index 5f4420b..349eedb 100644 --- a/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java +++ b/src/main/java/me/skymc/taboolib/inventory/ItemUtils.java @@ -1,6 +1,6 @@ package me.skymc.taboolib.inventory; -import lombok.Getter; +import com.ilummc.tlib.resources.TLocale; import me.clip.placeholderapi.PlaceholderAPI; import me.skymc.taboolib.Main; import me.skymc.taboolib.TabooLib; @@ -9,7 +9,6 @@ import me.skymc.taboolib.itemnbtapi.NBTItem; import me.skymc.taboolib.itemnbtapi.NBTList; import me.skymc.taboolib.itemnbtapi.NBTListCompound; import me.skymc.taboolib.itemnbtapi.NBTType; -import me.skymc.taboolib.message.MsgUtils; import me.skymc.taboolib.other.NumberUtils; import me.skymc.taboolib.string.Language; import org.bukkit.Color; @@ -29,226 +28,235 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import java.io.File; -import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; +import java.util.stream.IntStream; public class ItemUtils { - - @Getter - private static FileConfiguration itemdir = null; - - @Getter - private static FileConfiguration itemCache = null; - - @Getter - private static File finalItemsFolder; - - @Getter - private static LinkedHashMap itemlib = new LinkedHashMap<>(); - - @Getter - private static LinkedHashMap itemCaches = new LinkedHashMap<>(); - - @Getter - private static LinkedHashMap itemCachesFinal = new LinkedHashMap<>(); - - /** - * 获取物品缓存 - * 检测顺序: - * 1. 固定物品库 - * 2. 动态物品库 - * - * @param name 物品名称 - * @return - */ - public static ItemStack getCacheItem(String name) { - // 检测固定物品库是否存在该物品 - if (itemCachesFinal.containsKey(name)) { - return itemCachesFinal.get(name); - } - // 返回动态物品库 - return itemCaches.get(name); - } - - public static boolean isExists(String name) { - return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name); - } - - public static void LoadLib() { - try { - reloadItemName(); - reloadItemCache(); - itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR"))); - } catch (Exception e) { - MsgUtils.warn("物品库载入失败: &4" + e.getMessage()); - } - } - - public static void loadItemsFile(File file, boolean finalFile) { - FileConfiguration conf = ConfigUtils.load(Main.getInst(), file); - for (String name : conf.getConfigurationSection("").getKeys(false)) { - if (isExists(name)) { - MsgUtils.warn("无法载入载入物品 &4" + name + "&c, 因为它已经存在了"); - } else if (finalFile) { - itemCachesFinal.put(name, loadItem(conf, name)); - } else { - itemCaches.put(name, loadItem(conf, name)); - } - } - } - - public static void reloadItemCache() { - itemCaches.clear(); - itemCachesFinal.clear(); - loadItemsFile(getItemCacheFile(), false); - // 创建固定物品库 - finalItemsFolder = new File(Main.getInst().getDataFolder(), "FinalItems"); - if (!finalItemsFolder.exists()) { - finalItemsFolder.mkdir(); - } - // 检查固定物品库中的物品 - for (File file : finalItemsFolder.listFiles()) { - loadItemsFile(file, true); - } - MsgUtils.send("载入 " + (itemCaches.size() + itemCachesFinal.size()) + " 项缓存物品"); - } - - public static void reloadItemName() { - FileConfiguration conf = new Language("ITEM_NAME", Main.getInst(), true).getConfiguration(); - itemlib.clear(); - for (String a : conf.getConfigurationSection("").getKeys(false)) { - itemlib.put(a, conf.getString(a)); - } - MsgUtils.send("载入 " + itemlib.size() + " 项物品名称"); - } - - public static File getItemCacheFile() { - File itemCacheFile = new File(Main.getInst().getDataFolder(), "items.yml"); - if (!itemCacheFile.exists()) { - Main.getInst().saveResource("items.yml", true); - } - return itemCacheFile; - } - - public static String getCustomName(ItemStack item) { - if (item == null || item.getType().equals(Material.AIR)) { - return "空"; - } - int data = item.getType().getMaxDurability() == 0 ? item.getDurability() : 0; - return item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : itemlib.get(item.getType() + ":" + data) == null ? item.getType().toString() : itemlib.get(item.getType() + ":" + data); - } - - public static ItemStack getItemFromDir(String name) { - if (itemdir != null) { - return itemdir.getItemStack("item." + name); - } - return null; - } - - @SuppressWarnings("deprecation") + + private static FileConfiguration itemdir = null; + + private static FileConfiguration itemCache = null; + + private static File finalItemsFolder; + + private static LinkedHashMap itemlib = new LinkedHashMap<>(); + + private static LinkedHashMap itemCaches = new LinkedHashMap<>(); + + private static LinkedHashMap itemCachesFinal = new LinkedHashMap<>(); + + public static FileConfiguration getItemdir() { + return itemdir; + } + + public static FileConfiguration getItemCache() { + return itemCache; + } + + public static File getFinalItemsFolder() { + return finalItemsFolder; + } + + public static LinkedHashMap getItemlib() { + return itemlib; + } + + public static LinkedHashMap getItemCaches() { + return itemCaches; + } + + public static LinkedHashMap getItemCachesFinal() { + return itemCachesFinal; + } + + /** + * 获取物品缓存 + * 检测顺序: + * 1. 固定物品库 + * 2. 动态物品库 + * + * @param name 物品名称 + * @return + */ + public static ItemStack getCacheItem(String name) { + // 检测固定物品库是否存在该物品 + if (itemCachesFinal.containsKey(name)) { + return itemCachesFinal.get(name); + } + // 返回动态物品库 + return itemCaches.get(name); + } + + public static boolean isExists(String name) { + return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name); + } + + public static void LoadLib() { + try { + reloadItemName(); + reloadItemCache(); + itemdir = YamlConfiguration.loadConfiguration(new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR"))); + } catch (Exception e) { + TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ITEMS", e.toString()); + } + } + + public static void loadItemsFile(File file, boolean finalFile) { + FileConfiguration conf = ConfigUtils.load(Main.getInst(), file); + for (String name : conf.getConfigurationSection("").getKeys(false)) { + if (isExists(name)) { + TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ITEMS", name); + } else if (finalFile) { + itemCachesFinal.put(name, loadItem(conf, name)); + } else { + itemCaches.put(name, loadItem(conf, name)); + } + } + } + + public static void reloadItemCache() { + itemCaches.clear(); + itemCachesFinal.clear(); + loadItemsFile(getItemCacheFile(), false); + // 创建固定物品库 + finalItemsFolder = new File(Main.getInst().getDataFolder(), "FinalItems"); + if (!finalItemsFolder.exists()) { + finalItemsFolder.mkdir(); + } + // 检查固定物品库中的物品 + Arrays.stream(finalItemsFolder.listFiles()).forEach(file -> loadItemsFile(file, true)); + TLocale.Logger.info("ITEM-UTILS.SUCCESS-LOAD-CACHES", String.valueOf(itemCaches.size() + itemCachesFinal.size())); + } + + public static void reloadItemName() { + FileConfiguration conf = new Language("ITEM_NAME", Main.getInst(), true).getConfiguration(); + itemlib.clear(); + conf.getConfigurationSection("").getKeys(false).forEach(a -> itemlib.put(a, conf.getString(a))); + TLocale.Logger.info("ITEM-UTILS.SUCCESS-LOAD-NAMES", String.valueOf(itemlib.size())); + } + + public static File getItemCacheFile() { + File itemCacheFile = new File(Main.getInst().getDataFolder(), "items.yml"); + if (!itemCacheFile.exists()) { + Main.getInst().saveResource("items.yml", true); + } + return itemCacheFile; + } + + public static String getCustomName(ItemStack item) { + if (item == null || item.getType().equals(Material.AIR)) { + return TLocale.asString("ITEM-UTILS.EMPTY-ITEM"); + } + int data = item.getType().getMaxDurability() == 0 ? item.getDurability() : 0; + return item.getItemMeta().hasDisplayName() ? item.getItemMeta().getDisplayName() : itemlib.get(item.getType() + ":" + data) == null ? item.getType().toString() : itemlib.get(item.getType() + ":" + data); + } + + public static ItemStack getItemFromDir(String name) { + if (itemdir != null) { + return itemdir.getItemStack("item." + name); + } + return null; + } + + @SuppressWarnings("deprecation") public static ItemStack item(int n, int a, int d) { return new ItemStack(n, a, (short) d); } - + public static ItemStack setName(ItemStack i, String n) { ItemMeta meta = i.getItemMeta(); meta.setDisplayName(n); i.setItemMeta(meta); return i; } - + public static ItemStack Enchant(ItemStack i, Enchantment e, int l) { ItemMeta meta = i.getItemMeta(); meta.addEnchant(e, l, false); i.setItemMeta(meta); return i; } - + public static ItemStack addFlag(ItemStack i, ItemFlag f) { ItemMeta meta = i.getItemMeta(); meta.addItemFlags(f); i.setItemMeta(meta); return i; } - + public static boolean isNull(ItemStack item) { - return item == null || item.getType().equals(Material.AIR); + return item == null || item.getType().equals(Material.AIR); } - + public static boolean isName(ItemStack i, String a) { return isNamed(i) && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null && i.getItemMeta().getDisplayName().equals(a); } - + public static boolean isNameAs(ItemStack i, String a) { return isNamed(i) && i.getItemMeta().getDisplayName().contains(a); } - + public static String asString(String args, Player placeholderPlayer) { - if (placeholderPlayer == null) { - return args.replace("&", "§"); - } - return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§")); + if (placeholderPlayer == null) { + return args.replace("&", "§"); + } + return PlaceholderAPI.setPlaceholders(placeholderPlayer, args.replace("&", "§")); } - + public static List asString(List args, Player placeholderPlayer) { - for (int i = 0 ; i < args.size() ; i ++) { - args.set(i, asString(args.get(i), placeholderPlayer)); - } - return args; + IntStream.range(0, args.size()).forEach(i -> args.set(i, asString(args.get(i), placeholderPlayer))); + return args; } - + public static ItemFlag asItemFlag(String flag) { - try { - return ItemFlag.valueOf(flag); - } - catch (Exception e) { - return null; - } + try { + return ItemFlag.valueOf(flag); + } catch (Exception e) { + return null; + } } - + @SuppressWarnings("deprecation") - public static Material asMaterial(String args) { - try { - Material material = Material.getMaterial(args); - return material != null ? material : Material.getMaterial(Integer.valueOf(args)); - } - catch (Exception e) { - return Material.STONE; - } - } - - @SuppressWarnings({ "deprecation" }) - public static Enchantment asEnchantment(String enchant) { - try { - Enchantment enchantment = Enchantment.getByName(enchant); - return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant)); - } - catch (Exception e) { - return null; - } + public static Material asMaterial(String args) { + try { + Material material = Material.getMaterial(args); + return material != null ? material : Material.getMaterial(Integer.valueOf(args)); + } catch (Exception e) { + return Material.STONE; + } } - + + @SuppressWarnings({"deprecation"}) + public static Enchantment asEnchantment(String enchant) { + try { + Enchantment enchantment = Enchantment.getByName(enchant); + return enchantment != null ? enchantment : Enchantment.getById(Integer.valueOf(enchant)); + } catch (Exception e) { + return null; + } + } + @SuppressWarnings("deprecation") - public static PotionEffectType asPotionEffectType(String potion) { - try { - PotionEffectType type = PotionEffectType.getByName(potion); - return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion)); - } - catch (Exception e) { - return null; - } + public static PotionEffectType asPotionEffectType(String potion) { + try { + PotionEffectType type = PotionEffectType.getByName(potion); + return type != null ? type : PotionEffectType.getById(Integer.valueOf(potion)); + } catch (Exception e) { + return null; + } } - + public static Color asColor(String color) { - try { - return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2])); - } - catch (Exception e) { - return Color.fromBGR(0, 0, 0); - } + try { + return Color.fromBGR(Integer.valueOf(color.split("-")[0]), Integer.valueOf(color.split("-")[1]), Integer.valueOf(color.split("-")[2])); + } catch (Exception e) { + return Color.fromBGR(0, 0, 0); + } } - + public static String asAttribute(String name) { switch (name.toLowerCase()) { case "damage": @@ -265,321 +273,292 @@ public class ItemUtils { return "generic.armor"; case "luck": return "generic.luck"; + default: + return null; } - return null; } - + /** * 包含介绍 - * + * * @param i 物品 * @param a 关键字 */ public static boolean hasLore(ItemStack i, String a) { return isLored(i) && i.getItemMeta().getLore().toString().contains(a); } - + /** * 如果已描述 - * + * * @param i * @return */ public static boolean isLored(ItemStack i) { return i != null && i.getItemMeta() != null && i.getItemMeta().getLore() != null; } - + /** * 如果已命名 - * + * * @param i * @return */ - public static boolean isNamed(ItemStack i) { + public static boolean isNamed(ItemStack i) { return i != null && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null; } - + /** * 添加描述 - * - * @param is 物品 + * + * @param is 物品 * @param lore 描述 */ public static ItemStack addLore(ItemStack is, String lore) { - ItemMeta meta = is.getItemMeta(); - - List _lore = meta.hasLore() ? meta.getLore() : new ArrayList<>(); - _lore.add(lore.replaceAll("&", "§")); - + ItemMeta meta = is.getItemMeta(); + + List _lore = meta.hasLore() ? meta.getLore() : Collections.emptyList(); + _lore.add(lore.replaceAll("&", "§")); + is.setItemMeta(meta); return is; } - + /** * 移除描述 - * - * @param is 物品 + * + * @param is 物品 * @param line 行数 */ public static ItemStack delLore(ItemStack is, int line) { - ItemMeta meta = is.getItemMeta(); + ItemMeta meta = is.getItemMeta(); if (meta.hasLore()) { - List l = meta.getLore(); - if (l.size() >= line) { - l.remove(line); - meta.setLore(l); - is.setItemMeta(meta); - } + List l = meta.getLore(); + if (l.size() >= line) { + l.remove(line); + meta.setLore(l); + is.setItemMeta(meta); + } } return is; } - + /** * 获取介绍所在行数 - * + * * @param i 物品 * @param a 关键字 */ public static int getLore(ItemStack i, String a) { - if (isLored(i)) { - for (int j = 0; j < i.getItemMeta().getLore().size() ; j++) { - if (i.getItemMeta().getLore().get(j).contains(a)) { - return j; - } - } - } - return 0; + return isLored(i) ? IntStream.range(0, i.getItemMeta().getLore().size()).filter(j -> i.getItemMeta().getLore().get(j).contains(a)).findFirst().orElse(0) : 0; } - + /** * 添加耐久 - * + * * @param i 物品 * @param d 耐久 */ public static ItemStack addDurability(ItemStack i, int d) { - i.setDurability((short) (i.getDurability() + d)); - int min = i.getDurability(); - int max = i.getType().getMaxDurability(); - if (min >= max) { - i.setType(Material.AIR); - } - return i; + i.setDurability((short) (i.getDurability() + d)); + int min = i.getDurability(); + int max = i.getType().getMaxDurability(); + if (min >= max) { + i.setType(Material.AIR); + } + return i; } - + /** * 替换描述 - * - * @param i 物品 + * + * @param i 物品 * @param l1 关键字1 * @param l2 关键字2 */ public static ItemStack repalceLore(ItemStack i, String l1, String l2) { - if (!isLored(i)) { - return i; - } - else { - ItemMeta meta = i.getItemMeta(); - List lore = meta.getLore(); - for (int j = 0 ; j < lore.size() ; j++) { - lore.set(j, lore.get(j).replace(l1, l2)); - } - meta.setLore(lore); - i.setItemMeta(meta); - } - return i; + if (!isLored(i)) { + return i; + } else { + ItemMeta meta = i.getItemMeta(); + List lore = meta.getLore(); + IntStream.range(0, lore.size()).forEach(j -> lore.set(j, lore.get(j).replace(l1, l2))); + meta.setLore(lore); + i.setItemMeta(meta); + } + return i; } - + public static ItemStack loadItem(FileConfiguration f, String s) { - return loadItem(f, s, null); + return loadItem(f, s, null); } - + public static ItemStack loadItem(FileConfiguration f, String s, Player papiPlayer) { - return loadItem(f.getConfigurationSection(s), papiPlayer); + return loadItem(f.getConfigurationSection(s), papiPlayer); } - + public static ItemStack loadItem(ConfigurationSection section, Player papiPlayer) { - if (section.get("bukkit") instanceof ItemStack) { - return section.getItemStack("bukkit"); - } - // 材质 - ItemStack item = new ItemStack(asMaterial(section.get("material").toString())); - // 数量 - item.setAmount(section.contains("amount") ? section.getInt("amount") : 1); - // 耐久 - item.setDurability((short) section.getInt("data")); - // 元数据 - ItemMeta meta = item.getItemMeta(); - // 展示名 - if (section.contains("name")) { - meta.setDisplayName(asString(section.getString("name"), papiPlayer)); - } - // 描述 - if (section.contains("lore")) { - meta.setLore(asString(section.getStringList("lore"), papiPlayer)); - } - // 附魔 - if (section.contains("enchants")) { - for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) { - Enchantment enchant = asEnchantment(preEnchant); - if (enchant != null) { - meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true); - } - else { - MsgUtils.warn("&8" + preEnchant + " &c不是一个有效的附魔名称"); - MsgUtils.warn("&c输入 &4/taboolib enchants&c 查看所有附魔"); - } - } - } - // 标签 - if (section.contains("flags") && TabooLib.getVerint() > 10700) { - for (String preFlag : section.getStringList("flags")) { - ItemFlag flag = asItemFlag(preFlag); - if (flag != null) { - meta.addItemFlags(flag); - } - else { - MsgUtils.warn("&8" + preFlag + " &c不是一个有效的标签名称"); - MsgUtils.warn("&c输入 &4/taboolib flags&c 查看所有标签"); - } - } - } - // 皮革 - if (meta instanceof LeatherArmorMeta && section.contains("color")) { - ((LeatherArmorMeta) meta).setColor(asColor(section.getString("color"))); - } - // 药水 - if (meta instanceof PotionMeta && section.contains("potions")) { - PotionMeta potionMeta = (PotionMeta) meta; - for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) { - PotionEffectType potionEffectType = asPotionEffectType(prePotionName); - if (potionEffectType != null) { - potionMeta.addCustomEffect(new PotionEffect( - potionEffectType, - NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]), - NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true); - } - else { - MsgUtils.warn("&8" + potionEffectType + " &c不是一个有效的药水名称"); - MsgUtils.warn("&c输入 &4/taboolib potions&c 查看所有药水"); - } - } - } - // 元数据 - item.setItemMeta(meta); - // 数据 - NBTItem nbt = new NBTItem(item); - // 物品标签 - if (section.contains("nbt")) { - for (String name : section.getConfigurationSection("nbt").getKeys(false)) { - Object obj = section.get("nbt." + name); - if (obj instanceof String) { - nbt.setString(name, obj.toString()); - } - else if (obj instanceof Double) { - nbt.setDouble(name, Double.valueOf(obj.toString())); - } - else if (obj instanceof Integer) { - nbt.setInteger(name, Integer.valueOf(obj.toString())); - } - else if (obj instanceof Long) { - nbt.setLong(name, Long.valueOf(obj.toString())); - } - else { - nbt.setObject(name, obj); - } - } - } - // 物品属性 - if (section.contains("attributes")) { - NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); - for (String hand : section.getConfigurationSection("attributes").getKeys(false)) { - for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) { - if (asAttribute(name) != null) { - try { - NBTListCompound _attr = attr.addCompound(); - Object num = section.get("attributes." + hand + "." + name); - if (num.toString().contains("%")) { - _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); - _attr.setInteger("Operation", 1); - } - else { - _attr.setDouble("Amount", Double.valueOf(num.toString())); - _attr.setInteger("Operation", 0); - } - _attr.setString("AttributeName", asAttribute(name)); - _attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); - _attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); - _attr.setString("Name", asAttribute(name)); - if (!hand.equals("all")) { - _attr.setString("Slot", hand); - } - } - catch (Exception e) { - MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage()); - } - } - else { - MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称"); - MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性"); - } - } - } - } - return nbt.getItem(); + if (section.get("bukkit") instanceof ItemStack) { + return section.getItemStack("bukkit"); + } + // 材质 + ItemStack item = new ItemStack(asMaterial(section.getString("material"))); + // 数量 + item.setAmount(section.contains("amount") ? section.getInt("amount") : 1); + // 耐久 + item.setDurability((short) section.getInt("data")); + // 元数据 + ItemMeta meta = item.getItemMeta(); + // 展示名 + if (section.contains("name")) { + meta.setDisplayName(asString(section.getString("name"), papiPlayer)); + } + // 描述 + if (section.contains("lore")) { + meta.setLore(asString(section.getStringList("lore"), papiPlayer)); + } + // 附魔 + if (section.contains("enchants")) { + for (String preEnchant : section.getConfigurationSection("enchants").getKeys(false)) { + Enchantment enchant = asEnchantment(preEnchant); + if (enchant != null) { + meta.addEnchant(enchant, section.getInt("enchants." + preEnchant), true); + } else { + TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ENCHANTS", preEnchant); + } + } + } + // 标签 + if (section.contains("flags") && TabooLib.getVerint() > 10700) { + for (String preFlag : section.getStringList("flags")) { + ItemFlag flag = asItemFlag(preFlag); + if (flag != null) { + meta.addItemFlags(flag); + } else { + TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-FLAG", preFlag); + } + } + } + // 皮革 + if (meta instanceof LeatherArmorMeta && section.contains("color")) { + ((LeatherArmorMeta) meta).setColor(asColor(section.getString("color"))); + } + // 药水 + if (meta instanceof PotionMeta && section.contains("potions")) { + PotionMeta potionMeta = (PotionMeta) meta; + for (String prePotionName : section.getConfigurationSection("potions").getKeys(false)) { + PotionEffectType potionEffectType = asPotionEffectType(prePotionName); + if (potionEffectType != null) { + potionMeta.addCustomEffect(new PotionEffect( + potionEffectType, + NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[0]), + NumberUtils.getInteger(section.getString("potions." + prePotionName).split("-")[1]) - 1), true); + } else { + TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", prePotionName); + } + } + } + // 元数据 + item.setItemMeta(meta); + // 数据 + NBTItem nbt = new NBTItem(item); + // 物品标签 + if (section.contains("nbt")) { + for (String name : section.getConfigurationSection("nbt").getKeys(false)) { + Object obj = section.get("nbt." + name); + if (obj instanceof String) { + nbt.setString(name, obj.toString()); + } else if (obj instanceof Double) { + nbt.setDouble(name, Double.valueOf(obj.toString())); + } else if (obj instanceof Integer) { + nbt.setInteger(name, Integer.valueOf(obj.toString())); + } else if (obj instanceof Long) { + nbt.setLong(name, Long.valueOf(obj.toString())); + } else { + nbt.setObject(name, obj); + } + } + } + // 物品属性 + if (section.contains("attributes")) { + NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); + for (String hand : section.getConfigurationSection("attributes").getKeys(false)) { + for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) { + if (asAttribute(name) != null) { + try { + NBTListCompound _attr = attr.addCompound(); + Object num = section.get("attributes." + hand + "." + name); + if (num.toString().contains("%")) { + _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); + _attr.setInteger("Operation", 1); + } else { + _attr.setDouble("Amount", Double.valueOf(num.toString())); + _attr.setInteger("Operation", 0); + } + _attr.setString("AttributeName", asAttribute(name)); + _attr.setInteger("UUIDMost", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE)); + _attr.setInteger("UUIDLeast", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE)); + _attr.setString("Name", asAttribute(name)); + if (!"all".equals(hand)) { + _attr.setString("Slot", hand); + } + } catch (Exception ignored) { + } + } else { + TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", name); + } + } + } + } + return nbt.getItem(); } - + public static NBTItem setAttribute(NBTItem nbt, String name, Object num, String hand) { - NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); - if (asAttribute(name) != null) { - try { - NBTListCompound _attr = null; - for (int i = 0 ; i < attr.size() ; i++) { - NBTListCompound nlc = attr.getCompound(i); - if (nlc.getString("AttributeName").equals(asAttribute(name))) { - _attr = nlc; - } - } - if (_attr == null) { - _attr = attr.addCompound(); - } - if (num.toString().contains("%")) { - _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); - _attr.setInteger("Operation", 1); - } - else { - _attr.setDouble("Amount", Double.valueOf(num.toString())); - _attr.setInteger("Operation", 0); - } - _attr.setString("AttributeName", asAttribute(name)); - _attr.setInteger("UUIDMost", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); - _attr.setInteger("UUIDLeast", NumberUtils.getRand().nextInt(Integer.MAX_VALUE)); - _attr.setString("Name", asAttribute(name)); - if (!hand.equals("all")) { - _attr.setString("Slot", hand); - } - } - catch (Exception e) { - MsgUtils.warn("&8" + name + " &c属性载入失败: &8" + e.getMessage()); - } - } - else { - MsgUtils.warn("&8" + name + " &c不是一个有效的属性名称"); - MsgUtils.warn("&c输入 &4/taboolib attributes&c 查看所有属性"); - } - return nbt; + NBTList attr = nbt.getList("AttributeModifiers", NBTType.NBTTagCompound); + if (asAttribute(name) != null) { + try { + NBTListCompound _attr = null; + for (int i = 0; i < attr.size(); i++) { + NBTListCompound nlc = attr.getCompound(i); + if (nlc.getString("AttributeName").equals(asAttribute(name))) { + _attr = nlc; + } + } + if (_attr == null) { + _attr = attr.addCompound(); + } + if (num.toString().contains("%")) { + _attr.setDouble("Amount", Double.valueOf(num.toString().replace("%", "")) / 100D); + _attr.setInteger("Operation", 1); + } else { + _attr.setDouble("Amount", Double.valueOf(num.toString())); + _attr.setInteger("Operation", 0); + } + _attr.setString("AttributeName", asAttribute(name)); + _attr.setInteger("UUIDMost", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE)); + _attr.setInteger("UUIDLeast", NumberUtils.getRandom().nextInt(Integer.MAX_VALUE)); + _attr.setString("Name", asAttribute(name)); + if (!"all".equals(hand)) { + _attr.setString("Slot", hand); + } + } catch (NumberFormatException ignored) { + } + } else { + TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", name); + } + return nbt; } - + @Deprecated public static void putO(ItemStack item, Inventory inv, int i) { - inv.setItem(i, item); - inv.setItem(i+1, item); - inv.setItem(i+2, item); - inv.setItem(i+9, item); - inv.setItem(i+10, null); - inv.setItem(i+11, item); - inv.setItem(i+18, item); - inv.setItem(i+19, item); - inv.setItem(i+20, item); - } + inv.setItem(i, item); + inv.setItem(i + 1, item); + inv.setItem(i + 2, item); + inv.setItem(i + 9, item); + inv.setItem(i + 10, null); + inv.setItem(i + 11, item); + inv.setItem(i + 18, item); + inv.setItem(i + 19, item); + inv.setItem(i + 20, item); + } } diff --git a/src/main/java/me/skymc/taboolib/string/language2/Language2Format.java b/src/main/java/me/skymc/taboolib/string/language2/Language2Format.java index ccb1dff..6fba600 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/Language2Format.java +++ b/src/main/java/me/skymc/taboolib/string/language2/Language2Format.java @@ -1,9 +1,6 @@ package me.skymc.taboolib.string.language2; -import lombok.Getter; import me.skymc.taboolib.string.language2.value.*; - -import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.util.ArrayList; @@ -15,97 +12,101 @@ import java.util.List; * @since 2018-03-08 22:45:56 */ public class Language2Format implements Language2Line { - - @Getter - private Language2Value language2Value = null; - - @Getter - private List language2Lines = new ArrayList<>(); - - public Language2Format(Player player, Language2Value value) { - language2Value = value; - // 语言类型 - Language2Type type = Language2Type.TEXT; - // 递交数据 - List values = new LinkedList<>(); - - // 遍历内容 - for (String line : value.getLanguageValue()) { - // 文本类型 - if (line.contains("[text]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.TEXT; - } - // 大标题 - else if (line.contains("[title]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.TITLE; - } - // 小标题 - else if (line.contains("[action]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.ACTION; - } - // JSON - else if (line.contains("[json]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.JSON; - } - // JSON2 - else if (line.contains("[json2]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.JSON2; - } - // 音效 - else if (line.contains("[sound]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.SOUND; - } - // 书本 - else if (line.contains("[book]")) { - // 递交数据 - parseValue(player, values, type); - // 更改类型 - type = Language2Type.BOOK; - } - else if (line.contains("[return]")) { - // 递交数据 - parseValue(player, values, type); - } - // 默认 - else { - // 追加内容 - values.add(line); - } - } - } - - /** - * 识别内容 - * - * @param player 玩家 - * @param list 数据 - * @param type 类型 - */ - private void parseValue(Player player, List list, Language2Type type) { - if (list.size() == 0) { - return; - } - // 变量转换 - List listPlaceholder = language2Value.setPlaceholder(list, player); - // 大标题 + + private Language2Value language2Value; + private List language2Lines = new ArrayList<>(); + + public Language2Format(Player player, Language2Value value) { + language2Value = value; + // 语言类型 + Language2Type type = Language2Type.TEXT; + // 递交数据 + List values = new LinkedList<>(); + + // 遍历内容 + for (String line : value.getLanguageValue()) { + // 文本类型 + if (line.contains("[text]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.TEXT; + } + // 大标题 + else if (line.contains("[title]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.TITLE; + } + // 小标题 + else if (line.contains("[action]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.ACTION; + } + // JSON + else if (line.contains("[json]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.JSON; + } + // JSON2 + else if (line.contains("[json2]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.JSON2; + } + // 音效 + else if (line.contains("[sound]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.SOUND; + } + // 书本 + else if (line.contains("[book]")) { + // 递交数据 + parseValue(player, values, type); + // 更改类型 + type = Language2Type.BOOK; + } else if (line.contains("[return]")) { + // 递交数据 + parseValue(player, values, type); + } + // 默认 + else { + // 追加内容 + values.add(line); + } + } + } + + public Language2Value getLanguage2Value() { + return language2Value; + } + + public List getLanguage2Lines() { + return language2Lines; + } + + /** + * 识别内容 + * + * @param player 玩家 + * @param list 数据 + * @param type 类型 + */ + private void parseValue(Player player, List list, Language2Type type) { + if (list.size() == 0) { + return; + } + // 变量转换 + List listPlaceholder = language2Value.setPlaceholder(list, player); + // 大标题 switch (type) { case TITLE: language2Lines.add(new Language2Title(this, listPlaceholder)); @@ -133,23 +134,19 @@ public class Language2Format implements Language2Line { default: language2Lines.add(new Language2Text(this, listPlaceholder)); break; - } - // 清理数据 - list.clear(); - listPlaceholder.clear(); - } + } + // 清理数据 + list.clear(); + listPlaceholder.clear(); + } - @Override - public void send(Player player) { - for (Language2Line line : language2Lines) { - line.send(player); - } - } + @Override + public void send(Player player) { + language2Lines.forEach(line -> line.send(player)); + } - @Override - public void console() { - for (Language2Line line : language2Lines) { - line.console(); - } - } + @Override + public void console() { + language2Lines.forEach(Language2Line::console); + } } From 8a20fb7edb65184599ea480dc399b3d156e8e2e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9D=8F=E9=BB=91?= Date: Wed, 23 May 2018 22:12:59 +0800 Subject: [PATCH 5/9] =?UTF-8?q?=E7=89=88=E6=9C=AC=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=87=B3=204.05=20=E4=BF=AE=E5=A4=8D=EF=BC=9A=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E6=A3=80=E6=B5=8B=E5=A4=B1=E6=95=88=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=EF=BC=9ATLocale=20=E8=BD=BD=E5=85=A5=E8=AF=AD?= =?UTF-8?q?=E8=A8=80=E6=96=87=E4=BB=B6=E7=9A=84=E8=AF=AD=E6=B3=95=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E5=AF=BC=E8=87=B4=E8=B5=84=E6=BA=90=E6=B5=AA=E8=B4=B9?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98=20=E6=96=B0=E5=A2=9E=EF=BC=9A?= =?UTF-8?q?=E6=8B=A5=E6=9C=89=20"taboolib.update.notify"=20=E6=9D=83?= =?UTF-8?q?=E9=99=90=E7=9A=84=E7=8E=A9=E5=AE=B6=E8=BF=9B=E6=9C=8D=E5=B0=86?= =?UTF-8?q?=E4=BC=9A=E6=94=B6=E5=88=B0=E6=9B=B4=E6=96=B0=E6=8F=90=E9=86=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- .../ilummc/tlib/resources/TLocaleLoader.java | 2 +- src/main/java/me/skymc/taboolib/Main.java | 3 +- .../skymc/taboolib/fileutils/FileUtils.java | 8 ++++- .../listener/ListenerPlayerJoinAndQuit.java | 26 ++++++++++++++++ .../taboolib/listener/ListenerPlayerQuit.java | 15 ---------- .../me/skymc/taboolib/update/UpdateTask.java | 30 +++++++++++++++---- src/main/resources/lang/zh_CN.yml | 3 +- 8 files changed, 62 insertions(+), 27 deletions(-) create mode 100644 src/main/java/me/skymc/taboolib/listener/ListenerPlayerJoinAndQuit.java delete mode 100644 src/main/java/me/skymc/taboolib/listener/ListenerPlayerQuit.java diff --git a/pom.xml b/pom.xml index 07bb135..4aaeaa4 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ me.skymc TabooLib - 4.03 + 4.05 UTF-8 diff --git a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java index c9f6bcb..2aef0c0 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java @@ -141,7 +141,7 @@ public class TLocaleLoader { } private static YamlConfiguration getLocaleAtStream(Plugin plugin, File localeFile) { - InputStream localeInputSteam = FileUtils.getResource("lang/" + localeFile.getName()); + InputStream localeInputSteam = FileUtils.getResource(plugin, "lang/" + localeFile.getName()); try { String yamlText = new String(IO.readFully(localeInputSteam), Charset.forName("utf-8")); YamlConfiguration yaml = new YamlConfiguration(); diff --git a/src/main/java/me/skymc/taboolib/Main.java b/src/main/java/me/skymc/taboolib/Main.java index a181285..731b886 100644 --- a/src/main/java/me/skymc/taboolib/Main.java +++ b/src/main/java/me/skymc/taboolib/Main.java @@ -7,7 +7,6 @@ import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.anvil.AnvilContainerAPI; import me.skymc.taboolib.bstats.Metrics; import me.skymc.taboolib.commands.TabooLibMainCommand; -import me.skymc.taboolib.commands.internal.BaseMainCommand; import me.skymc.taboolib.commands.internal.TBaseCommand; import me.skymc.taboolib.commands.language.Language2Command; import me.skymc.taboolib.commands.locale.TabooLibLocaleCommand; @@ -334,7 +333,7 @@ public class Main extends JavaPlugin implements Listener { getServer().getPluginManager().registerEvents(this, this); getServer().getPluginManager().registerEvents(new ListenerPlayerCommand(), this); getServer().getPluginManager().registerEvents(new ListenerPlayerJump(), this); - getServer().getPluginManager().registerEvents(new ListenerPlayerQuit(), this); + getServer().getPluginManager().registerEvents(new ListenerPlayerJoinAndQuit(), this); getServer().getPluginManager().registerEvents(new ChatCatcher(), this); getServer().getPluginManager().registerEvents(new DataUtils(), this); getServer().getPluginManager().registerEvents(new AnvilContainerAPI(), this); diff --git a/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java b/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java index a3040e4..a0afd4d 100644 --- a/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java +++ b/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java @@ -2,8 +2,10 @@ package me.skymc.taboolib.fileutils; import ch.njol.util.Closeable; import com.ilummc.tlib.util.IO; +import javafx.print.PageLayout; import me.skymc.taboolib.Main; import org.apache.commons.io.IOUtils; +import org.bukkit.plugin.Plugin; import java.io.*; import java.net.HttpURLConnection; @@ -48,8 +50,12 @@ public class FileUtils { } public static InputStream getResource(String filename) { + return getResource(Main.getInst(), filename); + } + + public static InputStream getResource(Plugin plugin, String filename) { try { - URL url = Main.class.getClassLoader().getResource(filename); + URL url = plugin.getClass().getClassLoader().getResource(filename); if (url == null) { return null; } else { diff --git a/src/main/java/me/skymc/taboolib/listener/ListenerPlayerJoinAndQuit.java b/src/main/java/me/skymc/taboolib/listener/ListenerPlayerJoinAndQuit.java new file mode 100644 index 0000000..3f262df --- /dev/null +++ b/src/main/java/me/skymc/taboolib/listener/ListenerPlayerJoinAndQuit.java @@ -0,0 +1,26 @@ +package me.skymc.taboolib.listener; + +import com.ilummc.tlib.resources.TLocale; +import me.skymc.taboolib.TabooLib; +import me.skymc.taboolib.playerdata.DataUtils; +import me.skymc.taboolib.update.UpdateTask; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +public class ListenerPlayerJoinAndQuit implements Listener { + + @EventHandler + public void onJoin(PlayerJoinEvent e) { + if (UpdateTask.isHaveUpdate() && e.getPlayer().hasPermission("taboolib.update.notify")) { + TLocale.Logger.sendTo(e.getPlayer(), "UPDATETASK.VERSION-OUTDATED", String.valueOf(TabooLib.getPluginVersion()), String.valueOf(UpdateTask.getNewVersion())); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onQuit(PlayerQuitEvent e) { + DataUtils.saveOnline(e.getPlayer().getName()); + } +} diff --git a/src/main/java/me/skymc/taboolib/listener/ListenerPlayerQuit.java b/src/main/java/me/skymc/taboolib/listener/ListenerPlayerQuit.java deleted file mode 100644 index 066e77c..0000000 --- a/src/main/java/me/skymc/taboolib/listener/ListenerPlayerQuit.java +++ /dev/null @@ -1,15 +0,0 @@ -package me.skymc.taboolib.listener; - -import me.skymc.taboolib.playerdata.DataUtils; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerQuitEvent; - -public class ListenerPlayerQuit implements Listener{ - - @EventHandler (priority = EventPriority.MONITOR) - public void quit(PlayerQuitEvent e) { - DataUtils.saveOnline(e.getPlayer().getName()); - } -} diff --git a/src/main/java/me/skymc/taboolib/update/UpdateTask.java b/src/main/java/me/skymc/taboolib/update/UpdateTask.java index 7deb383..ee4f992 100644 --- a/src/main/java/me/skymc/taboolib/update/UpdateTask.java +++ b/src/main/java/me/skymc/taboolib/update/UpdateTask.java @@ -1,5 +1,6 @@ package me.skymc.taboolib.update; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.ilummc.tlib.resources.TLocale; @@ -14,10 +15,19 @@ import org.bukkit.scheduler.BukkitRunnable; */ public class UpdateTask { - private static final String API = "https://internal.github.com/repos/Bkm016/TabooLib/releases/latest"; + private static boolean haveUpdate = false; + private static double newVersion = 0; + + public static boolean isHaveUpdate() { + return haveUpdate; + } + + public static double getNewVersion() { + return newVersion; + } /** - * 检测更新 + * 旧地址:https://internal.github.com/repos/Bkm016/TabooLib/releases/latest */ public UpdateTask() { new BukkitRunnable() { @@ -27,13 +37,21 @@ public class UpdateTask { if (!Main.getInst().getConfig().getBoolean("UPDATE-CHECK")) { return; } - String value = FileUtils.getStringFromURL(API, "{}"); - JsonObject json = new JsonParser().parse(value).getAsJsonObject(); - if (json.entrySet().size() > 0) { - double newVersion = Double.parseDouble(json.get("tag_name").getAsString()); + + String value = FileUtils.getStringFromURL("https://api.github.com/repos/Bkm016/TabooLib/tags", null); + if (value == null) { + TLocale.Logger.error("UPDATETASK.VERSION-FAIL"); + return; + } + + JsonElement json = new JsonParser().parse(value); + if (json.isJsonArray()) { + JsonObject latestObject = json.getAsJsonArray().get(0).getAsJsonObject(); + newVersion = latestObject.get("name").getAsDouble(); if (TabooLib.getPluginVersion() >= newVersion) { TLocale.Logger.info("UPDATETASK.VERSION-LATEST"); } else { + haveUpdate = true; TLocale.Logger.info("UPDATETASK.VERSION-OUTDATED", String.valueOf(TabooLib.getPluginVersion()), String.valueOf(newVersion)); } } diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 6555707..3e8ddbf 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -112,7 +112,8 @@ ANVIL-CONTAINER: - '&7随后点击右侧输出物品' UPDATETASK: - VERSION-LATEST: '插件已是最新版, 无需更新!' + VERSION-FAIL: '&4更新记录获取失败, 请检查网络连接!' + VERSION-LATEST: '&7插件已是最新版, 无需更新!' VERSION-OUTDATED: - '&8####################################################' - '&7 检测到有新的版本更新!' From 5843e0be042b14563ecf7e60cf74fb9cb3fffc3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9D=8F=E9=BB=91?= Date: Sun, 27 May 2018 21:15:29 +0800 Subject: [PATCH 6/9] =?UTF-8?q?=E7=89=88=E6=9C=AC=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=87=B3=204.06=20=E6=96=B0=E5=A2=9E=EF=BC=9ATLocale=20?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=20BOOK=20=E7=B1=BB=E5=9E=8B=EF=BC=8C?= =?UTF-8?q?=E7=94=A8=E4=BA=8E=E5=8F=91=E9=80=81=E4=B9=A6=E6=9C=AC=E7=95=8C?= =?UTF-8?q?=E9=9D=A2=EF=BC=88=E4=BB=A3=E6=9B=BF=20Language2=EF=BC=89=20?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=EF=BC=9ATLocale=20=E6=96=B0=E5=A2=9E=20BAR?= =?UTF-8?q?=20=E7=B1=BB=E5=9E=8B=EF=BC=8C=E7=94=A8=E4=BA=8E=E5=8F=91?= =?UTF-8?q?=E9=80=81=20Bossbar=EF=BC=88=E9=9C=80=E8=A6=81=20BossBarAPI?= =?UTF-8?q?=EF=BC=89=20=E6=96=B0=E5=A2=9E=EF=BC=9ATLocale#Tellraw=20?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E7=94=A8=E4=BA=8E=E5=8F=91=E9=80=81=E5=8E=9F?= =?UTF-8?q?=E5=A7=8B=20json=20=E4=BF=A1=E6=81=AF=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=EF=BC=9ATellrawJson=20=E5=B7=A5=E5=85=B7=E7=94=A8=E4=BA=8E?= =?UTF-8?q?=E5=88=9B=E5=BB=BA=E5=8E=9F=E5=A7=8B=20json=20=E4=BF=A1?= =?UTF-8?q?=E6=81=AF=20=E6=96=B0=E5=A2=9E=EF=BC=9AVariableFormatter=20?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E7=94=A8=E4=BA=8E=E5=8F=98=E9=87=8F=E8=AF=86?= =?UTF-8?q?=E5=88=AB=20=E6=96=B0=E5=A2=9E=EF=BC=9AArrayUtils=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E6=95=B0=E7=BB=84=E4=BF=AE=E6=94=B9=E6=96=B9=E6=B3=95?= =?UTF-8?q?=20=E4=BF=AE=E5=A4=8D=EF=BC=9ALanguage2Book=20=E5=B7=A5?= =?UTF-8?q?=E5=85=B7=E5=A4=B1=E6=95=88=E9=97=AE=E9=A2=98=20=E8=B0=83?= =?UTF-8?q?=E6=95=B4=EF=BC=9AJsonFormatter=20=E5=B7=A5=E5=85=B7=E5=B7=B2?= =?UTF-8?q?=E8=BF=87=E6=97=B6=EF=BC=8C=E4=B8=8D=E5=86=8D=E7=BB=B4=E6=8A=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 从该版本起不再对 1.7.10 版本进行支持与维护,任何在 1.7.10 版本内出现的问题不再修复。 1.7.10 稳定版:v3.832 --- pom.xml | 9 +- .../tlib/bungee/chat/ComponentSerializer.java | 1 + .../com/ilummc/tlib/resources/TLocale.java | 30 +- .../ilummc/tlib/resources/TLocaleLoader.java | 2 + .../tlib/resources/type/TLocaleBook.java | 91 ++++++ .../tlib/resources/type/TLocaleBossBar.java | 95 ++++++ .../tlib/resources/type/TLocaleJson.java | 88 ++++- .../java/com/ilummc/tlib/util/Strings.java | 22 +- .../bookformatter/BookReflection.java | 63 ++-- .../bookformatter/action/ClickAction.java | 6 +- .../bookformatter/action/HoverAction.java | 10 +- .../bookformatter/builder/BookBuilder.java | 17 +- .../bookformatter/builder/PageBuilder.java | 28 +- .../bookformatter/builder/TextBuilder.java | 5 +- .../taboolib/json/tellraw/TellrawJson.java | 133 ++++++++ .../taboolib/jsonformatter/JSONFormatter.java | 14 +- .../jsonformatter/hover/ShowItemEvent.java | 117 +++---- .../listener/ListenerPlayerCommand.java | 48 +-- .../java/me/skymc/taboolib/nms/NMSUtil18.java | 4 +- .../java/me/skymc/taboolib/nms/NMSUtil19.java | 304 +++++++++--------- .../java/me/skymc/taboolib/nms/NMSUtils.java | 3 + .../me/skymc/taboolib/player/PlayerUtils.java | 100 +++--- .../me/skymc/taboolib/string/ArrayUtils.java | 111 +++++-- .../taboolib/string/VariableFormatter.java | 113 +++++++ .../string/language2/value/Language2Book.java | 139 ++++---- src/main/resources/lang/zh_CN.yml | 4 + src/main/resources/plugin.yml | 2 +- 27 files changed, 1095 insertions(+), 464 deletions(-) create mode 100644 src/main/java/com/ilummc/tlib/resources/type/TLocaleBook.java create mode 100644 src/main/java/com/ilummc/tlib/resources/type/TLocaleBossBar.java create mode 100644 src/main/java/me/skymc/taboolib/json/tellraw/TellrawJson.java create mode 100644 src/main/java/me/skymc/taboolib/string/VariableFormatter.java diff --git a/pom.xml b/pom.xml index 4aaeaa4..e1ec024 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ me.skymc TabooLib - 4.05 + 4.06 UTF-8 @@ -176,6 +176,13 @@ system ${basedir}/libs/Vault.jar + + bossbar + bossbar + 1 + system + ${basedir}/libs/BossBarAPI.jar + \ No newline at end of file diff --git a/src/main/java/com/ilummc/tlib/bungee/chat/ComponentSerializer.java b/src/main/java/com/ilummc/tlib/bungee/chat/ComponentSerializer.java index b6165db..6d19961 100644 --- a/src/main/java/com/ilummc/tlib/bungee/chat/ComponentSerializer.java +++ b/src/main/java/com/ilummc/tlib/bungee/chat/ComponentSerializer.java @@ -6,6 +6,7 @@ import com.ilummc.tlib.bungee.api.chat.TextComponent; import com.ilummc.tlib.bungee.api.chat.TranslatableComponent; import java.lang.reflect.Type; +import java.util.Arrays; import java.util.HashSet; /** diff --git a/src/main/java/com/ilummc/tlib/resources/TLocale.java b/src/main/java/com/ilummc/tlib/resources/TLocale.java index b2dc858..9747a35 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocale.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocale.java @@ -2,20 +2,30 @@ package com.ilummc.tlib.resources; import com.ilummc.tlib.TLib; import com.ilummc.tlib.bungee.api.ChatColor; +import com.ilummc.tlib.bungee.api.chat.BaseComponent; +import com.ilummc.tlib.bungee.api.chat.TextComponent; +import com.ilummc.tlib.bungee.chat.ComponentSerializer; import com.ilummc.tlib.inject.TLoggerManager; import com.ilummc.tlib.util.Ref; import com.ilummc.tlib.util.Strings; import me.clip.placeholderapi.PlaceholderAPI; import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; +import me.skymc.taboolib.nms.NMSUtil19; +import me.skymc.taboolib.nms.NMSUtils; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; +/** + * @author IzzelAliz + */ public class TLocale { private TLocale() { @@ -128,4 +138,22 @@ public class TLocale { } } + public static class Tellraw extends TLocale { + + private static final Field playerConnection = NMSUtils.getFieldSilent(NMSUtil19.class_EntityPlayer, "playerConnection"); + private static final Method sendPacket = NMSUtils.getMethodSilent(NMSUtil19.class_PlayerConnection, "sendPacket", NMSUtil19.class_Packet); + private static final Constructor PacketPlayOutChat = NMSUtils.getConstructorSilent(NMSUtil19.class_PacketPlayOutChat, NMSUtil19.class_IChatBaseComponent); + + public static void send(CommandSender sender, String rawMessage) { + if (sender instanceof Player) { + try { + sendPacket.invoke(playerConnection.get(NMSUtils.getHandle(sender)), PacketPlayOutChat.newInstance(rawMessage)); + } catch (Exception e) { + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + sender.getName() + " " + rawMessage); + } + } else { + sender.sendMessage(TextComponent.toLegacyText(ComponentSerializer.parse(rawMessage))); + } + } + } } diff --git a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java index 2aef0c0..98f9a99 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocaleLoader.java @@ -30,8 +30,10 @@ public class TLocaleLoader { public static void init() { ConfigurationSerialization.registerClass(TLocaleText.class, "TEXT"); ConfigurationSerialization.registerClass(TLocaleJson.class, "JSON"); + ConfigurationSerialization.registerClass(TLocaleBook.class, "BOOK"); ConfigurationSerialization.registerClass(TLocaleSound.class, "SOUND"); ConfigurationSerialization.registerClass(TLocaleTitle.class, "TITLE"); + ConfigurationSerialization.registerClass(TLocaleBossBar.class, "BAR"); ConfigurationSerialization.registerClass(TLocaleActionBar.class, "ACTION"); } diff --git a/src/main/java/com/ilummc/tlib/resources/type/TLocaleBook.java b/src/main/java/com/ilummc/tlib/resources/type/TLocaleBook.java new file mode 100644 index 0000000..978eb27 --- /dev/null +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleBook.java @@ -0,0 +1,91 @@ +package com.ilummc.tlib.resources.type; + +import com.google.common.collect.Maps; +import com.ilummc.tlib.bungee.chat.ComponentSerializer; +import com.ilummc.tlib.resources.TLocale; +import com.ilummc.tlib.resources.TLocaleSerialize; +import com.ilummc.tlib.util.Strings; +import me.skymc.taboolib.Main; +import me.skymc.taboolib.bookformatter.BookFormatter; +import me.skymc.taboolib.bookformatter.builder.BookBuilder; +import me.skymc.taboolib.json.tellraw.TellrawJson; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.serialization.SerializableAs; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import javax.annotation.concurrent.ThreadSafe; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * @Author sky + * @Since 2018-05-27 0:05 + */ +@ThreadSafe +@SerializableAs("BOOK") +public class TLocaleBook extends TLocaleSerialize { + + /* + BookTest: + - ==: BOOK + pages: + 0: + - '第一页内容' + - '[ <变量1@page-1> ]' + 1: + - '第二页内容' + - '[ <变量2@page-2> ]' + args: + page-1: + hover: '展示内容1' + command: '/say %player_name% NB1' + page-2: + hover: '展示内容2' + suggest: '/say %player_name% NB2' + */ + + private final List pages; + private final Map map; + private final boolean papi; + + public TLocaleBook(List pages, Map map, boolean papi) { + this.pages = pages; + this.map = map; + this.papi = papi; + } + + @Override + public Map serialize() { + return Maps.newHashMap(map); + } + + @Override + public void sendTo(CommandSender sender, String... args) { + if (!(sender instanceof Player)) { + return; + } + new BukkitRunnable() { + @Override + public void run() { + BookBuilder bookBuilder = BookFormatter.writtenBook(); + pages.stream().map(jsonPage -> papi ? TLocale.Translate.setPlaceholders(sender, Strings.replaceWithOrder(jsonPage.toRawMessage(), args)) : TLocale.Translate.setColored(Strings.replaceWithOrder(jsonPage.toRawMessage(), args))).map(ComponentSerializer::parse).forEach(bookBuilder::addPages); + new BukkitRunnable() { + @Override + public void run() { + BookFormatter.forceOpen((Player) sender, bookBuilder.build()); + } + }.runTask(Main.getInst()); + } + }.runTaskAsynchronously(Main.getInst()); + } + + public static TLocaleBook valueOf(Map map) { + Map pages = map.containsKey("pages") ? (Map) map.get("pages") : new HashMap<>(); + Map section = map.containsKey("args") ? (Map) map.get("args") : new HashMap<>(); + List pageJsonList = pages.values().stream().map(page -> TLocaleJson.formatJson(section, page, TellrawJson.create())).collect(Collectors.toList()); + return new TLocaleBook(pageJsonList, map, isPlaceholderEnabled(map)); + } +} diff --git a/src/main/java/com/ilummc/tlib/resources/type/TLocaleBossBar.java b/src/main/java/com/ilummc/tlib/resources/type/TLocaleBossBar.java new file mode 100644 index 0000000..62261ca --- /dev/null +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleBossBar.java @@ -0,0 +1,95 @@ +package com.ilummc.tlib.resources.type; + +import com.ilummc.tlib.resources.TLocale; +import com.ilummc.tlib.resources.TLocaleSerialize; +import com.ilummc.tlib.util.Strings; +import me.skymc.taboolib.other.NumberUtils; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.serialization.SerializableAs; +import org.bukkit.entity.Player; +import org.inventivetalent.bossbar.BossBar; +import org.inventivetalent.bossbar.BossBarAPI; + +import javax.annotation.concurrent.ThreadSafe; +import java.util.Map; + +/** + * @Author sky + * @Since 2018-05-27 18:52 + */ +@ThreadSafe +@SerializableAs("BAR") +public class TLocaleBossBar extends TLocaleSerialize { + + /* + BossBar: + - ==: BAR + text: 'BossBar 血条公告' + color: BLUE + style: NOTCHED_20 + progress: 1.0 + timeout: 20 + timeout-interval: 2 + */ + + private final String text; + private final BossBarAPI.Color color; + private final BossBarAPI.Style style; + private final float progress; + private final int timeout; + private final int timeoutInterval; + private final boolean papi; + + public TLocaleBossBar(String text, BossBarAPI.Color color, BossBarAPI.Style style, float progress, int timeout, int timeoutInterval, boolean papi) { + this.text = text; + this.color = color; + this.style = style; + this.progress = progress; + this.timeout = timeout; + this.timeoutInterval = timeoutInterval; + this.papi = papi; + } + + @Override + public void sendTo(CommandSender sender, String... args) { + if (Bukkit.getPluginManager().getPlugin("BossBarAPI") == null) { + TLocale.Logger.error("LOCALE.BAR-PLUGIN-NOT-FOUND"); + return; + } + if (sender instanceof Player) { + TextComponent textComponent = new TextComponent(papi ? TLocale.Translate.setPlaceholders(sender, Strings.replaceWithOrder(text, args)) : TLocale.Translate.setColored(Strings.replaceWithOrder(text, args))); + BossBar bossBar = BossBarAPI.addBar((Player) sender, textComponent, color, style, progress, timeout, timeoutInterval); + } else { + sender.sendMessage(text); + } + } + + @Override + public Map serialize() { + return null; + } + + public static TLocaleBossBar valueOf(Map map) { + return new TLocaleBossBar(map.getOrDefault("text", "§4* Invalid Text*").toString(), getColor(String.valueOf(map.get("color"))), getStyle(String.valueOf(map.get("style"))), (float) NumberUtils.getDouble(String.valueOf(map.getOrDefault("progress", 1))), NumberUtils.getInteger(String.valueOf(map.getOrDefault("timeout", 20))), NumberUtils.getInteger(String.valueOf(map.getOrDefault("timeout-interval", 2))), isPlaceholderEnabled(map)); + } + + private static BossBarAPI.Color getColor(String color) { + try { + return BossBarAPI.Color.valueOf(color); + } catch (Exception e) { + TLocale.Logger.error("LOCALE.BAR-STYLE-IDENTIFICATION-FAILED", e.toString()); + return BossBarAPI.Color.WHITE; + } + } + + private static BossBarAPI.Style getStyle(String style) { + try { + return BossBarAPI.Style.valueOf(style); + } catch (Exception e) { + TLocale.Logger.error("LOCALE.BAR-COLOR-IDENTIFICATION-FAILED", e.toString()); + return BossBarAPI.Style.NOTCHED_20; + } + } +} diff --git a/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java b/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java index 4cc689b..2a14974 100644 --- a/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java +++ b/src/main/java/com/ilummc/tlib/resources/type/TLocaleJson.java @@ -10,10 +10,12 @@ import com.ilummc.tlib.compat.PlaceholderHook; import com.ilummc.tlib.resources.TLocale; import com.ilummc.tlib.resources.TLocaleSerialize; import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.jsonformatter.JSONFormatter; +import me.skymc.taboolib.inventory.ItemUtils; +import me.skymc.taboolib.json.tellraw.TellrawJson; +import me.skymc.taboolib.other.NumberUtils; +import me.skymc.taboolib.string.VariableFormatter; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.SerializableAs; -import org.bukkit.entity.Player; import javax.annotation.concurrent.ThreadSafe; import java.util.*; @@ -21,6 +23,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; + @ThreadSafe @SerializableAs("JSON") public class TLocaleJson extends TLocaleSerialize { @@ -72,11 +75,11 @@ public class TLocaleJson extends TLocaleSerialize { // 可能有很多个 BaseComponent,于是为每个 component 单独设置各种事件 BaseComponent[] component = TextComponent.fromLegacyText(text); arg.forEach((key, value) -> { - if ("suggest".equalsIgnoreCase(key)) { + if (key.equalsIgnoreCase("suggest")) { Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, String.valueOf(value)))); - } else if ("command".equalsIgnoreCase(key) || "commands".equalsIgnoreCase(key)) { + } else if (key.equalsIgnoreCase("command") || "commands".equalsIgnoreCase(key)) { Arrays.stream(component).forEach(baseComponent -> baseComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, String.valueOf(value)))); - } else if ("hover".equalsIgnoreCase(key)) { + } else if (key.equalsIgnoreCase("hover")) { Arrays.stream(component).forEach(baseComponent -> baseComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(TLocale.Translate.setColored(String.valueOf(value))).create()))); } }); @@ -101,7 +104,7 @@ public class TLocaleJson extends TLocaleSerialize { private static List getTextList(Object textObj) { if (textObj instanceof List) { - return ((List) textObj).stream().map(Object::toString).map(s -> TLocale.Translate.setColored(s)).collect(Collectors.toList()); + return ((List) textObj).stream().map(Object::toString).map(TLocale.Translate::setColored).collect(Collectors.toList()); } else if (textObj instanceof String) { return Lists.newArrayList(TLocale.Translate.setColored((String) textObj)); } else { @@ -125,11 +128,11 @@ public class TLocaleJson extends TLocaleSerialize { } private void sendRawMessage(CommandSender sender, BaseComponent[] components) { - if (sender instanceof Player) { - JSONFormatter.sendRawMessage((Player) sender, ComponentSerializer.toString(components)); - } else { - sender.sendMessage(TextComponent.toLegacyText(components)); - } + TLocale.Tellraw.send(sender, ComponentSerializer.toString(components)); + } + + private List replace(List component, CommandSender sender, String... args) { + return component.stream().map(c -> replace(c, sender, args)).collect(Collectors.toList()); } private BaseComponent[] replace(BaseComponent[] component, CommandSender sender, String... args) { @@ -140,10 +143,6 @@ public class TLocaleJson extends TLocaleSerialize { return components; } - private List replace(List component, CommandSender sender, String... args) { - return component.stream().map(c -> replace(c, sender, args)).collect(Collectors.toList()); - } - private BaseComponent replace(BaseComponent component, CommandSender sender, String... args) { if (component.getClickEvent() != null) { ClickEvent clickEvent = new ClickEvent(component.getClickEvent().getAction(), replace(sender, component.getClickEvent().getValue(), args)); @@ -166,4 +165,63 @@ public class TLocaleJson extends TLocaleSerialize { String s = Strings.replaceWithOrder(text, args); return papi ? PlaceholderHook.replace(sender, s) : s; } + + public static TellrawJson formatJson(Map section, Object textObject, TellrawJson pageJson) { + List textList = textObject instanceof List ? (List) textObject : Collections.singletonList(String.valueOf(textObject)); + // 遍历本页文本 + for (int i = 0; i < textList.size(); i++) { + // 捕捉变量 + for (VariableFormatter.Variable variable : new VariableFormatter(textList.get(i), pattern).find().getVariableList()) { + // 如果是变量 + if (variable.isVariable()) { + String[] split = variable.getText().split("@"); + // @ 前面的字符串 + String text = split.length > 1 ? split[0] : "§4* Invalid Text *"; + // @ 后面的节点名 + String node = split.length > 1 ? split[1] : null; + // 处理变量 + formatNode(section, pageJson, text, node); + } else { + pageJson.append(variable.getText()); + } + } + if (i + 1 < textList.size()) { + pageJson.newLine(); + } + } + return pageJson; + } + + private static void formatNode(Map section, TellrawJson pageJson, String text, String node) { + if (section.containsKey(node)) { + try { + Map args = (Map) section.get(node); + // 文本 + pageJson.append(args.getOrDefault("text", text).toString()); + // 功能 + if (args.containsKey("item")) { + pageJson.hoverItem(ItemUtils.getCacheItem(args.get("item").toString())); + } + if (args.containsKey("hover")) { + pageJson.hoverText(args.get("hover").toString()); + } + if (args.containsKey("suggest")) { + pageJson.clickSuggest(args.get("suggest").toString()); + } + if (args.containsKey("command")) { + pageJson.clickCommand(args.get("command").toString()); + } + if (args.containsKey("page")) { + pageJson.clickChangePage(NumberUtils.getInteger(args.get("page").toString())); + } + if (args.containsKey("url")) { + pageJson.clickOpenURL(args.get("url").toString()); + } + } catch (Exception e) { + TLocale.Logger.error("LOCALE.BOOK-ARGUMENTS-IDENTIFICATION-FAILED", e.toString()); + } + } else { + pageJson.append("§4* Invalid Argument *"); + } + } } diff --git a/src/main/java/com/ilummc/tlib/util/Strings.java b/src/main/java/com/ilummc/tlib/util/Strings.java index e454212..40207d0 100644 --- a/src/main/java/com/ilummc/tlib/util/Strings.java +++ b/src/main/java/com/ilummc/tlib/util/Strings.java @@ -2,6 +2,14 @@ package com.ilummc.tlib.util; public class Strings { + public static boolean isBlank(String var) { + return var == null || var.trim().isEmpty(); + } + + public static boolean isEmpty(CharSequence var) { + return var == null || var.length() == 0; + } + /** * 优化过的 String#replace,比默认快了大概 5 倍 * @@ -28,15 +36,13 @@ public class Strings { return stringBuilder.toString(); } + // ********************************* + // + // Deprecated + // + // ********************************* + public static String replaceWithOrder(String template, String... args) { return replaceWithOrder(template, (Object[]) args); } - - public static boolean isBlank(String var) { - return var == null || var.trim().isEmpty(); - } - - public static boolean isEmpty(CharSequence var) { - return var == null || var.length() == 0; - } } diff --git a/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java b/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java index 5cbf36c..b090544 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/BookReflection.java @@ -1,8 +1,10 @@ package me.skymc.taboolib.bookformatter; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; -import net.md_5.bungee.chat.ComponentSerializer; +import com.ilummc.tlib.bungee.api.chat.BaseComponent; +import com.ilummc.tlib.bungee.api.chat.TextComponent; +import com.ilummc.tlib.bungee.chat.ComponentSerializer; +import com.ilummc.tlib.logger.TLogger; +import com.ilummc.tlib.resources.TLocale; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -12,6 +14,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -31,11 +34,13 @@ public final class BookReflection { private static final Method craftPlayerGetHandle; - //This method takes an enum that represents the player's hand only in versions >= 1.9 - //In the other versions it only takes the nms item + /* + This method takes an enum that represents the player's hand only in versions >= 1.9 + In the other versions it only takes the nms item + */ private static final Method entityPlayerOpenBook; - //only version >= 1.9 + // only version >= 1.9 private static final Object[] hands; //Older versions @@ -115,18 +120,22 @@ public final class BookReflection { * @param meta the book meta to change * @param components the pages of the book */ - @SuppressWarnings("unchecked")//reflections = unchecked warnings - public static void setPages(BookMeta meta, BaseComponent[][] components) { + public static void setPages(BookMeta meta, BaseComponent[]... components) { + List pages = null; try { - List pages = (List) craftMetaBookField.get(meta); - pages.clear(); - for (BaseComponent[] c : components) { - final String json = ComponentSerializer.toString(c); - //System.out.println("page:" + json); //Debug - pages.add(chatSerializerA.invoke(null, json)); - } + pages = (List) craftMetaBookField.get(meta); } catch (Exception e) { - throw new UnsupportedVersionException(e); + TLogger.getGlobalLogger().error("Error while executing reflections, failed to get bookmeta (version: " + BookReflection.version + ")"); + return; + } + pages.clear(); + for (BaseComponent[] c : components) { + try { + pages.add(chatSerializerA.invoke(null, ComponentSerializer.toString(c))); + } catch (Exception e) { + TLogger.getGlobalLogger().error("Error while executing reflections, submit to developers the following log (version: " + BookReflection.version + ")"); + e.printStackTrace(); + } } } @@ -136,17 +145,21 @@ public final class BookReflection { * @param meta the book meta to change * @param components the pages of the book */ - @SuppressWarnings("unchecked")//reflections = unchecked warnings - public static void addPages(BookMeta meta, BaseComponent[][] components) { + public static void addPages(BookMeta meta, BaseComponent[]... components) { + List pages = null; try { - List pages = (List) craftMetaBookField.get(meta); - for (BaseComponent[] c : components) { - final String json = ComponentSerializer.toString(c); - //System.out.println("page:" + json); //Debug - pages.add(chatSerializerA.invoke(null, json)); - } + pages = (List) craftMetaBookField.get(meta); } catch (Exception e) { - throw new UnsupportedVersionException(e); + TLogger.getGlobalLogger().error("Error while executing reflections, failed to get bookmeta (version: " + BookReflection.version + ")"); + return; + } + for (BaseComponent[] c : components) { + try { + pages.add(chatSerializerA.invoke(null, ComponentSerializer.toString(c))); + } catch (Exception e) { + TLogger.getGlobalLogger().error("Error while executing reflections, submit to developers the following log (version: " + BookReflection.version + ")"); + e.printStackTrace(); + } } } diff --git a/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java b/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java index 70c7003..428c447 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/action/ClickAction.java @@ -1,6 +1,6 @@ package me.skymc.taboolib.bookformatter.action; -import net.md_5.bungee.api.chat.ClickEvent; +import com.ilummc.tlib.bungee.api.chat.ClickEvent; /** * @author sky @@ -86,12 +86,12 @@ public interface ClickAction { @Override public ClickEvent.Action action() { - return null; + return action; } @Override public String value() { - return null; + return value; } } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/bookformatter/action/HoverAction.java b/src/main/java/me/skymc/taboolib/bookformatter/action/HoverAction.java index b45d86d..48bad9f 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/action/HoverAction.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/action/HoverAction.java @@ -1,10 +1,10 @@ package me.skymc.taboolib.bookformatter.action; +import com.ilummc.tlib.bungee.api.chat.BaseComponent; +import com.ilummc.tlib.bungee.api.chat.HoverEvent; +import com.ilummc.tlib.bungee.api.chat.TextComponent; import me.skymc.taboolib.bookformatter.BookAchievement; import me.skymc.taboolib.bookformatter.BookReflection; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Achievement; import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; @@ -157,12 +157,12 @@ public interface HoverAction { @Override public HoverEvent.Action action() { - return null; + return action; } @Override public BaseComponent[] value() { - return new BaseComponent[0]; + return value; } } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/bookformatter/builder/BookBuilder.java b/src/main/java/me/skymc/taboolib/bookformatter/builder/BookBuilder.java index 3c639ed..d79d6f5 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/builder/BookBuilder.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/builder/BookBuilder.java @@ -1,7 +1,7 @@ package me.skymc.taboolib.bookformatter.builder; +import com.ilummc.tlib.bungee.api.chat.BaseComponent; import me.skymc.taboolib.bookformatter.BookReflection; -import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; @@ -125,4 +125,19 @@ public class BookBuilder { book.setItemMeta(meta); return book; } + + // ********************************* + // + // Getter and Setter + // + // ********************************* + + + public BookMeta getMeta() { + return meta; + } + + public ItemStack getBook() { + return book; + } } \ No newline at end of file diff --git a/src/main/java/me/skymc/taboolib/bookformatter/builder/PageBuilder.java b/src/main/java/me/skymc/taboolib/bookformatter/builder/PageBuilder.java index 73e7ced..f95e033 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/builder/PageBuilder.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/builder/PageBuilder.java @@ -1,7 +1,7 @@ package me.skymc.taboolib.bookformatter.builder; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; +import com.ilummc.tlib.bungee.api.chat.*; +import me.skymc.taboolib.string.ArrayUtils; import java.util.ArrayList; import java.util.Arrays; @@ -14,7 +14,7 @@ import java.util.List; */ public class PageBuilder { - private List text = new ArrayList<>(); + private BaseComponent[] text = TextComponent.fromLegacyText(""); /** * Adds a simple black-colored text to the page @@ -22,7 +22,7 @@ public class PageBuilder { * @return the PageBuilder's calling instance */ public PageBuilder add(String text) { - this.text.add(TextBuilder.of(text).build()); + Arrays.stream(TextComponent.fromLegacyText(text)).forEach(component -> this.text = ArrayUtils.arrayAppend(this.text, component)); return this; } @@ -32,7 +32,7 @@ public class PageBuilder { * @return the PageBuilder's calling instance */ public PageBuilder add(BaseComponent component) { - this.text.add(component); + this.text = ArrayUtils.arrayAppend(this.text, component); return this; } @@ -42,17 +42,7 @@ public class PageBuilder { * @return the PageBuilder's calling instance */ public PageBuilder add(BaseComponent... components) { - this.text.addAll(Arrays.asList(components)); - return this; - } - - /** - * Adds one or more components to the page - * @param components the components to add - * @return the PageBuilder's calling instance - */ - public PageBuilder add(Collection components) { - this.text.addAll(components); + Arrays.stream(components).forEach(component -> this.text = ArrayUtils.arrayAppend(this.text, component)); return this; } @@ -61,8 +51,7 @@ public class PageBuilder { * @return the PageBuilder's calling instance */ public PageBuilder newLine() { - this.text.add(new TextComponent("\n")); - return this; + return add("\n"); } /** @@ -78,10 +67,9 @@ public class PageBuilder { * @return an array of BaseComponents representing the page */ public BaseComponent[] build() { - return text.toArray(new BaseComponent[0]); + return text; } - /** * Creates a new PageBuilder instance wih the parameter as the initial text * @param text the initial text of the page diff --git a/src/main/java/me/skymc/taboolib/bookformatter/builder/TextBuilder.java b/src/main/java/me/skymc/taboolib/bookformatter/builder/TextBuilder.java index c670f24..34a271c 100644 --- a/src/main/java/me/skymc/taboolib/bookformatter/builder/TextBuilder.java +++ b/src/main/java/me/skymc/taboolib/bookformatter/builder/TextBuilder.java @@ -1,11 +1,8 @@ package me.skymc.taboolib.bookformatter.builder; +import com.ilummc.tlib.bungee.api.chat.*; import me.skymc.taboolib.bookformatter.action.ClickAction; import me.skymc.taboolib.bookformatter.action.HoverAction; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.ClickEvent; -import net.md_5.bungee.api.chat.HoverEvent; -import net.md_5.bungee.api.chat.TextComponent; /** * @author sky diff --git a/src/main/java/me/skymc/taboolib/json/tellraw/TellrawJson.java b/src/main/java/me/skymc/taboolib/json/tellraw/TellrawJson.java new file mode 100644 index 0000000..15d3caf --- /dev/null +++ b/src/main/java/me/skymc/taboolib/json/tellraw/TellrawJson.java @@ -0,0 +1,133 @@ +package me.skymc.taboolib.json.tellraw; + +import com.ilummc.tlib.bungee.api.chat.*; +import com.ilummc.tlib.bungee.chat.ComponentSerializer; +import com.ilummc.tlib.logger.TLogger; +import com.ilummc.tlib.resources.TLocale; +import me.skymc.taboolib.inventory.ItemUtils; +import me.skymc.taboolib.methods.ReflectionUtils; +import me.skymc.taboolib.nms.NMSUtils; +import me.skymc.taboolib.other.NumberUtils; +import me.skymc.taboolib.string.ArrayUtils; +import me.skymc.taboolib.string.VariableFormatter; +import org.bukkit.command.CommandSender; +import org.bukkit.inventory.ItemStack; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * @Author sky + * @Since 2018-05-26 14:42json + */ +public class TellrawJson { + + private BaseComponent[] components = TextComponent.fromLegacyText(""); + private final Class craftItemStackClazz = NMSUtils.getOBCClass("inventory.CraftItemStack"); + private final Class nmsItemStackClazz = NMSUtils.getNMSClass("ItemStack"); + private final Class nbtTagCompoundClazz = NMSUtils.getNMSClass("NBTTagCompound"); + private final String INVALID_ITEM = "{id:stone,tag:{display:{Name:§c* Invalid ItemStack *}}}"; + + TellrawJson() { + } + + public static TellrawJson create() { + return new TellrawJson(); + } + + public String toRawMessage() { + return ComponentSerializer.toString(components); + } + + public String toLegacyText() { + return TextComponent.toLegacyText(components); + } + + public TellrawJson newLine() { + return append("\n"); + } + + public TellrawJson append(String text) { + Arrays.stream(TextComponent.fromLegacyText(text)).forEach(component -> this.components = ArrayUtils.arrayAppend(this.components, component)); + return this; + } + + public TellrawJson hoverText(String text) { + getLatestComponent().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(text).create())); + return this; + } + + public TellrawJson hoverItem(ItemStack itemStack) { + getLatestComponent().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_ITEM, new ComponentBuilder(getItemComponent(itemStack)).create())); + return this; + } + + public TellrawJson clickCommand(String command) { + getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command)); + return this; + } + + public TellrawJson clickSuggest(String command) { + getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, command)); + return this; + } + + public TellrawJson clickOpenURL(String url) { + getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url)); + return this; + } + + public TellrawJson clickChangePage(int page) { + getLatestComponent().setClickEvent(new ClickEvent(ClickEvent.Action.CHANGE_PAGE, String.valueOf(page))); + return this; + } + + public void send(CommandSender sender) { + TLocale.Tellraw.send(sender, toRawMessage()); + } + + public String getItemComponent(ItemStack itemStack) { + try { + Method asNMSCopyMethod = ReflectionUtils.getMethod(craftItemStackClazz, "asNMSCopy", ItemStack.class); + Method saveNmsItemStackMethod = ReflectionUtils.getMethod(nmsItemStackClazz, "save", nbtTagCompoundClazz); + Object nmsNbtTagCompoundObj = nbtTagCompoundClazz.newInstance(); + Object nmsItemStackObj = asNMSCopyMethod.invoke(null, itemStack); + return saveNmsItemStackMethod.invoke(nmsItemStackObj, nmsNbtTagCompoundObj).toString(); + } catch (Throwable t) { + TLogger.getGlobalLogger().error("failed to serialize itemstack to nms item: " + t.toString()); + return INVALID_ITEM; + } + } + + // ********************************* + // + // Private Methods + // + // ********************************* + + private BaseComponent getLatestComponent() { + return components[components.length - 1]; + } + + private void setLatestComponent(BaseComponent component) { + components[components.length - 1] = component; + } + + // ********************************* + // + // Getter and Setter + // + // ********************************* + + public BaseComponent[] getComponents() { + return components; + } + + public void setComponents(BaseComponent[] components) { + this.components = components; + } + +} diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java b/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java index b6ddeac..6ac0c21 100644 --- a/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java +++ b/src/main/java/me/skymc/taboolib/jsonformatter/JSONFormatter.java @@ -1,5 +1,6 @@ package me.skymc.taboolib.jsonformatter; +import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.json.JSONArray; import me.skymc.taboolib.json.JSONObject; import me.skymc.taboolib.jsonformatter.click.ClickEvent; @@ -15,17 +16,14 @@ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; +/** + * @author Unknown + */ +@Deprecated public class JSONFormatter { public static void sendRawMessage(Player player, String message) { - try { - Object entityplayer = NMSUtils.getHandle(player); - Object ppco = ppc.get(entityplayer); - Object packet = ppocc.newInstance(message); - sp.invoke(ppco, packet); - } catch (Exception e) { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "tellraw " + player.getName() + " " + message); - } + TLocale.Tellraw.send(player, message); } private JSONArray ja = new JSONArray(); diff --git a/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowItemEvent.java b/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowItemEvent.java index 863294c..54e02a5 100644 --- a/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowItemEvent.java +++ b/src/main/java/me/skymc/taboolib/jsonformatter/hover/ShowItemEvent.java @@ -3,6 +3,7 @@ package me.skymc.taboolib.jsonformatter.hover; import me.skymc.taboolib.TabooLib; import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.json.JSONObject; +import me.skymc.taboolib.json.tellraw.TellrawJson; import me.skymc.taboolib.nms.item.DabItemUtils; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; @@ -13,64 +14,68 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -public class ShowItemEvent extends HoverEvent{ - - private JSONObject object = new JSONObject(); - - public Object getItemTag(ItemStack item) { - try { - return DabItemUtils.getInstance().getTag(DabItemUtils.getInstance().getNMSCopy(item)); - } catch (Exception e) { - return null; - } - } - - @SuppressWarnings("deprecation") - public ShowItemEvent(ItemStack is){ - try{ - object.put("action", "show_item"); - StringBuilder tag = new StringBuilder(); - Object itemTag = getItemTag(is); - if (itemTag != null) { +public class ShowItemEvent extends HoverEvent { + + private JSONObject object = new JSONObject(); + + public Object getItemTag(ItemStack item) { + try { + return DabItemUtils.getInstance().getTag(DabItemUtils.getInstance().getNMSCopy(item)); + } catch (Exception e) { + return null; + } + } + + @SuppressWarnings("deprecation") + public ShowItemEvent(ItemStack is) { + if (TabooLib.getVerint() > 10700) { + try { + object.put("action", "show_item"); + object.put("value", TellrawJson.create().getItemComponent(is)); + } catch (Exception ignored) { + } + } + try { + object.put("action", "show_item"); + StringBuilder tag = new StringBuilder(); + Object itemTag = getItemTag(is); + if (itemTag != null) { tag.append(",tag:").append(itemTag); - } - else { - ItemMeta im = is.getItemMeta(); - List lore = im.hasLore() ? im.getLore() : new ArrayList<>(); - Map enchants = is.getItemMeta().getEnchants(); + } else { + ItemMeta im = is.getItemMeta(); + List lore = im.hasLore() ? im.getLore() : new ArrayList<>(); + Map enchants = is.getItemMeta().getEnchants(); tag.append(",tag:{display:{Name:").append(enchants.size() > 0 ? "§b§o" : "§f").append(ItemUtils.getCustomName(is)); - if (lore.size() > 0) { - tag.append(",Lore:["); - for (String s : lore){ + if (lore.size() > 0) { + tag.append(",Lore:["); + for (String s : lore) { tag.append("\"").append(s).append("\","); - } - tag.delete(tag.length() - 1, tag.length()); - tag.append("]"); - } - tag.append("}"); - if (enchants.size() > 0) { - if(tag.length() > 6) { - tag.append(","); - } - tag.append("ench:["); - for (Entry e : enchants.entrySet()) { + } + tag.delete(tag.length() - 1, tag.length()); + tag.append("]"); + } + tag.append("}"); + if (enchants.size() > 0) { + if (tag.length() > 6) { + tag.append(","); + } + tag.append("ench:["); + for (Entry e : enchants.entrySet()) { tag.append("{id:").append(e.getKey().getId()).append(",lvl:").append(e.getValue()).append("},"); - } - tag.delete(tag.length() - 1, tag.length()); - tag.append("]"); - } - tag.append("}"); - } - - object.put("value", "{id:" + (TabooLib.getVerint() > 10700 ? DabItemUtils.getMinecraftName(is) : is.getTypeId()) + ",Count:" + is.getAmount() + tag.toString() + "}"); - } catch(Exception e) { - e.printStackTrace(); - } - } - - @Override - public JSONObject getEvent(){ - return object; - } - + } + tag.delete(tag.length() - 1, tag.length()); + tag.append("]"); + } + tag.append("}"); + } + object.put("value", "{id:" + (TabooLib.getVerint() > 10700 ? DabItemUtils.getMinecraftName(is) : is.getTypeId()) + ",Count:" + is.getAmount() + tag.toString() + "}"); + } catch (Exception ignored) { + } + } + + @Override + public JSONObject getEvent() { + return object; + } + } diff --git a/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java b/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java index 603f4ce..7b07bf3 100644 --- a/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java +++ b/src/main/java/me/skymc/taboolib/listener/ListenerPlayerCommand.java @@ -14,29 +14,29 @@ import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.server.ServerCommandEvent; public class ListenerPlayerCommand implements Listener { - - @EventHandler - public void cmd(ServerCommandEvent e) { - if ("savefile".equals(e.getCommand())) { - if (TabooLib.getVerint() > 10700) { - e.setCancelled(true); - } + + @EventHandler + public void cmd(ServerCommandEvent e) { + if ("savefile".equals(e.getCommand())) { + if (TabooLib.getVerint() > 10700) { + e.setCancelled(true); + } Bukkit.getScheduler().runTask(Main.getInst(), DataUtils::saveAllCaches); - Bukkit.getScheduler().runTask(Main.getInst(), () -> PlayerDataManager.saveAllCaches(true, false)); - } - } - - @SuppressWarnings("deprecation") - @EventHandler - public void cmd(PlayerCommandPreprocessEvent e) { - if ("/unbreakable".equals(e.getMessage()) && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.unbreakable")) { - e.setCancelled(true); - - NBTItem nbti = new NBTItem(e.getPlayer().getItemInHand()); - nbti.setInteger("Unbreakable", 1); - e.getPlayer().setItemInHand(nbti.getItem()); - - MsgUtils.send(e.getPlayer(), "Success!"); - } - } + Bukkit.getScheduler().runTask(Main.getInst(), () -> PlayerDataManager.saveAllCaches(true, false)); + } + } + + @SuppressWarnings("deprecation") + @EventHandler + public void cmd(PlayerCommandPreprocessEvent e) { + if ("/unbreakable".equals(e.getMessage()) && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.unbreakable")) { + e.setCancelled(true); + + NBTItem nbti = new NBTItem(e.getPlayer().getItemInHand()); + nbti.setInteger("Unbreakable", 1); + e.getPlayer().setItemInHand(nbti.getItem()); + + MsgUtils.send(e.getPlayer(), "Success!"); + } + } } diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java b/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java index 849d117..fcdf616 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtil18.java @@ -20,8 +20,10 @@ import java.util.List; import java.util.Map; import java.util.UUID; +/** + * @author Unknown + */ @SuppressWarnings({"rawtypes", "unchecked"}) -@Deprecated public class NMSUtil18 { protected static boolean failed = false; diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java b/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java index db241bc..7177ddd 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java @@ -22,17 +22,19 @@ import java.lang.reflect.Method; import java.util.*; import java.util.logging.Level; -@SuppressWarnings({ "rawtypes", "unchecked" }) -@Deprecated +/** + * @author Unknown + */ +@SuppressWarnings({"rawtypes", "unchecked"}) public class NMSUtil19 { - + protected static boolean failed = false; protected static boolean legacy = false; protected static String versionPrefix = ""; protected final static int NBT_TYPE_COMPOUND = 10; - protected final static int NBT_TYPE_INT_ARRAY= 11; + protected final static int NBT_TYPE_INT_ARRAY = 11; protected final static int NBT_TYPE_DOUBLE = 6; protected final static int NBT_TYPE_FLOAT = 5; protected final static int NBT_TYPE_STRING = 8; @@ -40,91 +42,91 @@ public class NMSUtil19 { protected static int WITHER_SKULL_TYPE = 66; protected static int FIREWORK_TYPE = 76; - protected static Class class_Block; - protected static Class class_ItemStack; - protected static Class class_NBTBase; - protected static Class class_NBTTagCompound; - protected static Class class_NBTTagList; - protected static Class class_NBTTagByte; - protected static Class class_NBTTagDouble; - protected static Class class_NBTTagFloat; - protected static Class class_NBTTagInt; - protected static Class class_NBTTagLong; - protected static Class class_NBTTagShort; - protected static Class class_NBTTagString; - protected static Class class_CraftTask; - protected static Class class_CraftInventoryCustom; - protected static Class class_CraftItemStack; - protected static Class class_CraftBlockState; - protected static Class class_CraftLivingEntity; - protected static Class class_CraftWorld; - protected static Class class_Consumer; - protected static Class class_Entity; - protected static Class class_EntityCreature; - protected static Class class_EntityLiving; - protected static Class class_EntityHuman; - protected static Class class_DataWatcher; - protected static Class class_DamageSource; - protected static Class class_EntityDamageSource; - protected static Class class_World; - protected static Class class_WorldServer; - protected static Class class_Packet; + public static Class class_Block; + public static Class class_ItemStack; + public static Class class_NBTBase; + public static Class class_NBTTagCompound; + public static Class class_NBTTagList; + public static Class class_NBTTagByte; + public static Class class_NBTTagDouble; + public static Class class_NBTTagFloat; + public static Class class_NBTTagInt; + public static Class class_NBTTagLong; + public static Class class_NBTTagShort; + public static Class class_NBTTagString; + public static Class class_CraftTask; + public static Class class_CraftInventoryCustom; + public static Class class_CraftItemStack; + public static Class class_CraftBlockState; + public static Class class_CraftLivingEntity; + public static Class class_CraftWorld; + public static Class class_Consumer; + public static Class class_Entity; + public static Class class_EntityCreature; + public static Class class_EntityLiving; + public static Class class_EntityHuman; + public static Class class_DataWatcher; + public static Class class_DamageSource; + public static Class class_EntityDamageSource; + public static Class class_World; + public static Class class_WorldServer; + public static Class class_Packet; protected static Class class_EnumSkyBlock; - protected static Class class_EntityPainting; - protected static Class class_EntityItemFrame; - protected static Class class_EntityMinecartRideable; - protected static Class class_EntityTNTPrimed; - protected static Class class_AxisAlignedBB; - protected static Class class_PathPoint; - protected static Class class_PathEntity; - protected static Class class_EntityFirework; - protected static Class class_CraftSkull; - protected static Class class_CraftBanner; - protected static Class class_CraftMetaSkull; - protected static Class class_CraftMetaBanner; - protected static Class class_GameProfile; - protected static Class class_GameProfileProperty; - protected static Class class_BlockPosition; - protected static Class class_NBTCompressedStreamTools; - protected static Class class_TileEntity; - protected static Class class_TileEntitySign; - protected static Class class_TileEntityContainer; - protected static Class class_ChestLock; + public static Class class_EntityPainting; + public static Class class_EntityItemFrame; + public static Class class_EntityMinecartRideable; + public static Class class_EntityTNTPrimed; + public static Class class_AxisAlignedBB; + public static Class class_PathPoint; + public static Class class_PathEntity; + public static Class class_EntityFirework; + public static Class class_CraftSkull; + public static Class class_CraftBanner; + public static Class class_CraftMetaSkull; + public static Class class_CraftMetaBanner; + public static Class class_GameProfile; + public static Class class_GameProfileProperty; + public static Class class_BlockPosition; + public static Class class_NBTCompressedStreamTools; + public static Class class_TileEntity; + public static Class class_TileEntitySign; + public static Class class_TileEntityContainer; + public static Class class_ChestLock; protected static Class class_EnumDirection; - protected static Class class_EntityHorse; - protected static Class class_EntityWitherSkull; - protected static Class class_PacketPlayOutAttachEntity; - protected static Class class_PacketPlayOutEntityDestroy; - protected static Class class_PacketPlayOutSpawnEntity; - protected static Class class_PacketPlayOutSpawnEntityLiving; - protected static Class class_PacketPlayOutEntityMetadata; - protected static Class class_PacketPlayOutEntityStatus; - protected static Class class_PacketPlayOutCustomSoundEffect; - protected static Class class_PacketPlayOutExperience; - protected static Class class_PacketPlayOutAnimation; - protected static Class class_PacketPlayOutBlockBreakAnimation; + public static Class class_EntityHorse; + public static Class class_EntityWitherSkull; + public static Class class_PacketPlayOutAttachEntity; + public static Class class_PacketPlayOutEntityDestroy; + public static Class class_PacketPlayOutSpawnEntity; + public static Class class_PacketPlayOutSpawnEntityLiving; + public static Class class_PacketPlayOutEntityMetadata; + public static Class class_PacketPlayOutEntityStatus; + public static Class class_PacketPlayOutCustomSoundEffect; + public static Class class_PacketPlayOutExperience; + public static Class class_PacketPlayOutAnimation; + public static Class class_PacketPlayOutBlockBreakAnimation; protected static Enum enum_SoundCategory_PLAYERS; protected static Class class_EnumSoundCategory; - protected static Class class_EntityFallingBlock; - protected static Class class_EntityArmorStand; - protected static Class class_EntityPlayer; - protected static Class class_PlayerConnection; - protected static Class class_Chunk; - protected static Class class_CraftPlayer; - protected static Class class_CraftChunk; - protected static Class class_CraftEntity; - protected static Class class_EntityProjectile; - protected static Class class_EntityFireball; - protected static Class class_EntityArrow; - protected static Class class_CraftArrow; - protected static Class class_MinecraftServer; - protected static Class class_CraftServer; - protected static Class class_DataWatcherObject; - protected static Class class_PacketPlayOutChat; + public static Class class_EntityFallingBlock; + public static Class class_EntityArmorStand; + public static Class class_EntityPlayer; + public static Class class_PlayerConnection; + public static Class class_Chunk; + public static Class class_CraftPlayer; + public static Class class_CraftChunk; + public static Class class_CraftEntity; + public static Class class_EntityProjectile; + public static Class class_EntityFireball; + public static Class class_EntityArrow; + public static Class class_CraftArrow; + public static Class class_MinecraftServer; + public static Class class_CraftServer; + public static Class class_DataWatcherObject; + public static Class class_PacketPlayOutChat; protected static Class class_ChatMessageType; protected static Enum enum_ChatMessageType_GAME_INFO; - protected static Class class_ChatComponentText; - protected static Class class_IChatBaseComponent; + public static Class class_ChatComponentText; + public static Class class_IChatBaseComponent; protected static Method class_NBTTagList_addMethod; protected static Method class_NBTTagList_getMethod; @@ -275,8 +277,7 @@ public class NMSUtil19 { protected static Field class_Entity_moveStrafingField; protected static Field class_Entity_moveForwardField; - static - { + static { // Find classes Bukkit hides from us. :-D // Much thanks to @DPOHVAR for sharing the PowerNBT code that powers the reflection approach. String className = Bukkit.getServer().getClass().getName(); @@ -312,8 +313,8 @@ public class NMSUtil19 { class_Packet = fixBukkitClass("net.minecraft.server.Packet"); class_World = fixBukkitClass("net.minecraft.server.World"); class_WorldServer = fixBukkitClass("net.minecraft.server.WorldServer"); - class_EnumSkyBlock = (Class)fixBukkitClass("net.minecraft.server.EnumSkyBlock"); - class_EnumSoundCategory = (Class)fixBukkitClass("net.minecraft.server.SoundCategory"); + class_EnumSkyBlock = (Class) fixBukkitClass("net.minecraft.server.EnumSkyBlock"); + class_EnumSoundCategory = (Class) fixBukkitClass("net.minecraft.server.SoundCategory"); enum_SoundCategory_PLAYERS = Enum.valueOf(class_EnumSoundCategory, "PLAYERS"); class_EntityPainting = fixBukkitClass("net.minecraft.server.EntityPainting"); class_EntityCreature = fixBukkitClass("net.minecraft.server.EntityCreature"); @@ -394,7 +395,7 @@ public class NMSUtil19 { class_EntityPlayer_setResourcePackMethod = class_EntityPlayer.getMethod("setResourcePack", String.class, String.class); class_CraftServer_getServerMethod = class_CraftServer.getMethod("getServer"); class_MinecraftServer_getResourcePackMethod = class_MinecraftServer.getMethod("getResourcePack"); - + class_CraftInventoryCustom_constructor = class_CraftInventoryCustom.getConstructor(InventoryHolder.class, Integer.TYPE, String.class); class_EntityFireworkConstructor = class_EntityFirework.getConstructor(class_World, Double.TYPE, Double.TYPE, Double.TYPE, class_ItemStack); class_PacketSpawnEntityConstructor = class_PacketPlayOutSpawnEntity.getConstructor(class_Entity, Integer.TYPE); @@ -478,10 +479,10 @@ public class NMSUtil19 { class_Chunk_doneField.setAccessible(true); class_CraftItemStack_getHandleField = class_CraftItemStack.getDeclaredField("handle"); class_CraftItemStack_getHandleField.setAccessible(true); - + class_MemorySection_mapField = MemorySection.class.getDeclaredField("map"); class_MemorySection_mapField.setAccessible(true); - + class_TileEntityContainer = fixBukkitClass("net.minecraft.server.TileEntityContainer"); class_ChestLock = fixBukkitClass("net.minecraft.server.ChestLock"); class_Entity_getBoundingBox = class_Entity.getMethod("getBoundingBox"); @@ -508,7 +509,7 @@ public class NMSUtil19 { class_CraftBanner_setPatternsMethod = class_CraftBanner.getMethod("setPatterns", List.class); class_CraftBanner_setBaseColorMethod = class_CraftBanner.getMethod("setBaseColor", DyeColor.class); - class_EnumDirection = (Class)fixBukkitClass("net.minecraft.server.EnumDirection"); + class_EnumDirection = (Class) fixBukkitClass("net.minecraft.server.EnumDirection"); class_BlockPosition_Constructor = class_BlockPosition.getConstructor(Double.TYPE, Double.TYPE, Double.TYPE); class_EntityPaintingConstructor = class_EntityPainting.getConstructor(class_World, class_BlockPosition, class_EnumDirection); class_EntityItemFrameConstructor = class_EntityItemFrame.getConstructor(class_World, class_BlockPosition, class_EnumDirection); @@ -603,7 +604,7 @@ public class NMSUtil19 { class_ChatComponentText_constructor = class_ChatComponentText.getConstructor(String.class); // 1.12 specific - class_ChatMessageType = (Class)fixBukkitClass("net.minecraft.server.ChatMessageType"); + class_ChatMessageType = (Class) fixBukkitClass("net.minecraft.server.ChatMessageType"); enum_ChatMessageType_GAME_INFO = Enum.valueOf(class_ChatMessageType, "GAME_INFO"); class_PacketPlayOutChat_constructor = class_PacketPlayOutChat.getConstructor(class_IChatBaseComponent, class_ChatMessageType); @@ -771,8 +772,7 @@ public class NMSUtil19 { Bukkit.getLogger().log(Level.WARNING, "An error occurred, setting arrow lifespan will not work", ex); class_EntityArrow_lifeField = null; } - if (class_EntityArrow_lifeField != null) - { + if (class_EntityArrow_lifeField != null) { class_EntityArrow_lifeField.setAccessible(true); } @@ -874,8 +874,7 @@ public class NMSUtil19 { // 1.10 and earlier legacy = true; } - } - catch (Throwable ex) { + } catch (Throwable ex) { failed = true; Bukkit.getLogger().log(Level.SEVERE, "An unexpected error occurred initializing Magic", ex); } @@ -884,7 +883,7 @@ public class NMSUtil19 { public static boolean getFailed() { return failed; } - + public static boolean isLegacy() { return legacy; } @@ -994,7 +993,7 @@ public class NMSUtil19 { Object chunkHandle = getHandle(chunk); boolean done = false; try { - done = (Boolean)class_Chunk_doneField.get(chunkHandle); + done = (Boolean) class_Chunk_doneField.get(chunkHandle); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1021,11 +1020,11 @@ public class NMSUtil19 { return handle; } - protected static void sendPacket(Server server, Location source, Collection players, Object packet) throws Exception { + protected static void sendPacket(Server server, Location source, Collection players, Object packet) throws Exception { players = ((players != null && players.size() > 0) ? players : server.getOnlinePlayers()); int viewDistance = Bukkit.getServer().getViewDistance() * 16; - int viewDistanceSquared = viewDistance * viewDistance; + int viewDistanceSquared = viewDistance * viewDistance; World sourceWorld = source.getWorld(); for (Player player : players) { Location location = player.getLocation(); @@ -1045,31 +1044,29 @@ public class NMSUtil19 { Method sendPacketMethod = connection.getClass().getMethod("sendPacket", class_Packet); sendPacketMethod.invoke(connection, packet); } - - public static int getFacing(BlockFace direction) - { + + public static int getFacing(BlockFace direction) { int dir; switch (direction) { - case SOUTH: - default: - dir = 0; - break; - case WEST: - dir = 1; - break; - case NORTH: - dir = 2; - break; - case EAST: - dir = 3; - break; + case SOUTH: + default: + dir = 0; + break; + case WEST: + dir = 1; + break; + case NORTH: + dir = 2; + break; + case EAST: + dir = 3; + break; } - + return dir; } - public static Entity getBukkitEntity(Object entity) - { + public static Entity getBukkitEntity(Object entity) { if (entity == null) { return null; } @@ -1079,7 +1076,7 @@ public class NMSUtil19 { if (!(bukkitEntity instanceof Entity)) { return null; } - return (Entity)bukkitEntity; + return (Entity) bukkitEntity; } catch (Throwable ex) { ex.printStackTrace(); } @@ -1197,7 +1194,7 @@ public class NMSUtil19 { } Boolean result = false; try { - result = (Boolean)class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag); + result = (Boolean) class_NBTTagCompound_hasKeyMethod.invoke(nbtBase, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1267,7 +1264,7 @@ public class NMSUtil19 { } String meta = null; try { - meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag); + meta = (String) class_NBTTagCompound_getStringMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1280,7 +1277,7 @@ public class NMSUtil19 { } String meta = null; try { - meta = (String)class_NBTTagCompound_getStringMethod.invoke(node, tag); + meta = (String) class_NBTTagCompound_getStringMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1293,7 +1290,7 @@ public class NMSUtil19 { } Byte meta = null; try { - meta = (Byte)class_NBTTagCompound_getByteMethod.invoke(node, tag); + meta = (Byte) class_NBTTagCompound_getByteMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1306,7 +1303,7 @@ public class NMSUtil19 { } Integer meta = null; try { - meta = (Integer)class_NBTTagCompound_getIntMethod.invoke(node, tag); + meta = (Integer) class_NBTTagCompound_getIntMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1319,7 +1316,7 @@ public class NMSUtil19 { } Boolean meta = null; try { - meta = (Boolean)class_NBTTagCompound_getBooleanMethod.invoke(node, tag); + meta = (Boolean) class_NBTTagCompound_getBooleanMethod.invoke(node, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1327,7 +1324,7 @@ public class NMSUtil19 { } public static void setMeta(Object node, String tag, String value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) { + if (node == null || !class_NBTTagCompound.isInstance(node)) { return; } try { @@ -1342,7 +1339,7 @@ public class NMSUtil19 { } public static void setMetaLong(Object node, String tag, long value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) { + if (node == null || !class_NBTTagCompound.isInstance(node)) { return; } try { @@ -1353,7 +1350,7 @@ public class NMSUtil19 { } public static void setMetaBoolean(Object node, String tag, boolean value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) { + if (node == null || !class_NBTTagCompound.isInstance(node)) { return; } try { @@ -1364,7 +1361,7 @@ public class NMSUtil19 { } public static void setMetaDouble(Object node, String tag, double value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) { + if (node == null || !class_NBTTagCompound.isInstance(node)) { return; } try { @@ -1375,7 +1372,7 @@ public class NMSUtil19 { } public static void setMetaInt(Object node, String tag, int value) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) { + if (node == null || !class_NBTTagCompound.isInstance(node)) { return; } try { @@ -1386,7 +1383,7 @@ public class NMSUtil19 { } public static void removeMeta(Object node, String tag) { - if (node == null|| !class_NBTTagCompound.isInstance(node)) { + if (node == null || !class_NBTTagCompound.isInstance(node)) { return; } try { @@ -1453,7 +1450,7 @@ public class NMSUtil19 { ex.printStackTrace(); return false; } - + return true; } @@ -1471,7 +1468,7 @@ public class NMSUtil19 { if (tagObject == null) { return null; } - meta = (String)class_NBTTagCompound_getStringMethod.invoke(tagObject, tag); + meta = (String) class_NBTTagCompound_getStringMethod.invoke(tagObject, tag); } catch (Throwable ex) { ex.printStackTrace(); } @@ -1578,7 +1575,7 @@ public class NMSUtil19 { } catch (Throwable ignored) { } - + return unbreakableFlag != null && unbreakableFlag; } @@ -1646,7 +1643,7 @@ public class NMSUtil19 { Object explosion = class_World_explodeMethod.invoke(worldHandle, entityHandle, x, y, z, power, setFire, breakBlocks); Field cancelledField = explosion.getClass().getDeclaredField("wasCanceled"); - result = (Boolean)cancelledField.get(explosion); + result = (Boolean) cancelledField.get(explosion); } catch (Throwable ex) { ex.printStackTrace(); result = false; @@ -1665,7 +1662,7 @@ public class NMSUtil19 { public static void makeUnplaceable(ItemStack itemStack) { setMeta(itemStack, "unplaceable", "true"); } - + public static void removeUnplaceable(ItemStack itemStack) { removeMeta(itemStack, "unplaceable"); } @@ -1743,7 +1740,7 @@ public class NMSUtil19 { } else { nmsStack = class_ItemStack_createStackMethod.invoke(null, itemTag); } - item = (ItemStack)class_CraftItemStack_mirrorMethod.invoke(null, nmsStack); + item = (ItemStack) class_CraftItemStack_mirrorMethod.invoke(null, nmsStack); } catch (Exception ex) { ex.printStackTrace(); } @@ -1753,7 +1750,7 @@ public class NMSUtil19 { public static ItemStack[] getItems(Object rootTag, String tagName) { try { Object itemList = class_NBTTagCompound_getListMethod.invoke(rootTag, tagName, NBT_TYPE_COMPOUND); - Integer size = (Integer)class_NBTTagList_sizeMethod.invoke(itemList); + Integer size = (Integer) class_NBTTagList_sizeMethod.invoke(itemList); ItemStack[] items = new ItemStack[size]; for (int i = 0; i < size; i++) { try { @@ -1823,10 +1820,10 @@ public class NMSUtil19 { class_TileEntity_saveMethod.invoke(tileEntity, entityData); Object itemList = class_NBTTagCompound_getListMethod.invoke(entityData, "Items", NBT_TYPE_COMPOUND); if (itemList != null) { - List items = (List)class_NBTTagList_list.get(itemList); + List items = (List) class_NBTTagList_list.get(itemList); items.clear(); } - class_NBTTagCompound_removeMethod.invoke(entityData,"Item"); + class_NBTTagCompound_removeMethod.invoke(entityData, "Item"); class_TileEntity_loadMethod.invoke(tileEntity, entityData); class_TileEntity_updateMethod.invoke(tileEntity); } @@ -1871,9 +1868,9 @@ public class NMSUtil19 { } try { Object posList = class_NBTTagCompound_getListMethod.invoke(entityData, tag, NBT_TYPE_DOUBLE); - Double x = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 0); - Double y = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 1); - Double z = (Double)class_NBTTagList_getDoubleMethod.invoke(posList, 2); + Double x = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 0); + Double y = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 1); + Double z = (Double) class_NBTTagList_getDoubleMethod.invoke(posList, 2); if (x != null && y != null && z != null) { return new Vector(x, y, z); } @@ -1886,7 +1883,7 @@ public class NMSUtil19 { public static Entity getEntity(World world, UUID uuid) { try { Object worldHandle = getHandle(world); - final Map entityMap = (Map)class_WorldServer_entitiesByUUIDField.get(worldHandle); + final Map entityMap = (Map) class_WorldServer_entitiesByUUIDField.get(worldHandle); if (entityMap != null) { Object nmsEntity = entityMap.get(uuid); if (nmsEntity != null) { @@ -1906,9 +1903,8 @@ public class NMSUtil19 { ex.printStackTrace(); } } - - public static void playCustomSound(Player player, Location location, String sound, float volume, float pitch) - { + + public static void playCustomSound(Player player, Location location, String sound, float volume, float pitch) { try { Object packet = class_PacketPlayOutCustomSoundEffect_Constructor.newInstance(sound, enum_SoundCategory_PLAYERS, location.getX(), location.getY(), location.getZ(), volume, pitch); sendPacket(player, packet); @@ -1917,17 +1913,15 @@ public class NMSUtil19 { } } - public static Map getMap(ConfigurationSection section) - { + public static Map getMap(ConfigurationSection section) { if (section == null) { return null; } - if (section instanceof MemorySection) - { + if (section instanceof MemorySection) { try { Object mapObject = class_MemorySection_mapField.get(section); if (mapObject instanceof Map) { - return (Map)mapObject; + return (Map) mapObject; } } catch (Exception ex) { ex.printStackTrace(); @@ -1940,7 +1934,7 @@ public class NMSUtil19 { for (String key : keys) { map.put(key, section.get(key)); } - + return map; } @@ -1956,7 +1950,7 @@ public class NMSUtil19 { if (handle == null) { return false; } - return (Boolean)class_ItemStack_isEmptyMethod.invoke(handle); + return (Boolean) class_ItemStack_isEmptyMethod.invoke(handle); } catch (Throwable ex) { ex.printStackTrace(); } diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtils.java b/src/main/java/me/skymc/taboolib/nms/NMSUtils.java index 7ec6521..88995c3 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtils.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtils.java @@ -7,6 +7,9 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +/** + * @author Unknown + */ public class NMSUtils { public static Class c = getOBCClass("block.CraftBlock"); diff --git a/src/main/java/me/skymc/taboolib/player/PlayerUtils.java b/src/main/java/me/skymc/taboolib/player/PlayerUtils.java index 76ce71e..bc2a665 100644 --- a/src/main/java/me/skymc/taboolib/player/PlayerUtils.java +++ b/src/main/java/me/skymc/taboolib/player/PlayerUtils.java @@ -8,54 +8,56 @@ import org.bukkit.inventory.ItemStack; import java.util.HashSet; -@SuppressWarnings("deprecation") +/** + * @author sky + */ public class PlayerUtils { - - /** - * 获取目标方块 - * - * @param player 玩家 - * @param max 最大视野 - * @return - */ - public static Block getTargetBlock(Player player, int max) { - HashSet Byte = new HashSet<>(); - Byte.add((byte) 0); - return player.getTargetBlock(Byte, max); - } - - /** - * 重写数据 - * - * @param player 玩家 - * @param scoreboard 是否清理计分板 - */ - public static void resetData(Player player, boolean scoreboard) { - if (player.isDead()) { - player.spigot().respawn(); - } - player.closeInventory(); - player.setGameMode(GameMode.SURVIVAL); - player.getInventory().setArmorContents(new ItemStack[4]); - player.getInventory().setContents(new ItemStack[0]); - player.setAllowFlight(false); - player.setFlying(false); - player.setExp(0.0F); - player.setLevel(0); - player.setSneaking(false); - player.setSprinting(false); - player.setFoodLevel(20); - player.setSaturation(10.0F); - player.setExhaustion(0.0F); - player.setMaxHealth(20.0D); - player.setHealth(20.0D); - player.setFireTicks(0); - player.setItemOnCursor(null); - player.getActivePotionEffects().clear(); - player.getEnderChest().clear(); - player.updateInventory(); - if (scoreboard) { - player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - } - } + + /** + * 获取目标方块 + * + * @param player 玩家 + * @param max 最大视野 + * @return + */ + public static Block getTargetBlock(Player player, int max) { + HashSet bytes = new HashSet<>(); + bytes.add((byte) 0); + return player.getTargetBlock(bytes, max); + } + + /** + * 重写数据 + * + * @param player 玩家 + * @param scoreboard 是否清理计分板 + */ + public static void resetData(Player player, boolean scoreboard) { + if (player.isDead()) { + player.spigot().respawn(); + } + player.closeInventory(); + player.setGameMode(GameMode.SURVIVAL); + player.getInventory().setArmorContents(new ItemStack[4]); + player.getInventory().setContents(new ItemStack[0]); + player.setAllowFlight(false); + player.setFlying(false); + player.setExp(0.0F); + player.setLevel(0); + player.setSneaking(false); + player.setSprinting(false); + player.setFoodLevel(20); + player.setSaturation(10.0F); + player.setExhaustion(0.0F); + player.setMaxHealth(20.0D); + player.setHealth(20.0D); + player.setFireTicks(0); + player.setItemOnCursor(null); + player.getActivePotionEffects().clear(); + player.getEnderChest().clear(); + player.updateInventory(); + if (scoreboard) { + player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + } + } } diff --git a/src/main/java/me/skymc/taboolib/string/ArrayUtils.java b/src/main/java/me/skymc/taboolib/string/ArrayUtils.java index 561c282..86bc5fe 100644 --- a/src/main/java/me/skymc/taboolib/string/ArrayUtils.java +++ b/src/main/java/me/skymc/taboolib/string/ArrayUtils.java @@ -1,5 +1,10 @@ package me.skymc.taboolib.string; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -11,34 +16,80 @@ import java.util.stream.IntStream; * @since 2018-04-16 */ public class ArrayUtils { - - public static List asList(T... args) { - List list = new ArrayList<>(); - Collections.addAll(list, args); - return list; - } - - public static String[] addFirst(String[] args, String... value) { - if (args.length < 1) { - return value; - } - List list = asList(args); - for (int i = value.length - 1 ; i >= 0 ; i--) { - list.add(0, value[i]); - } - return list.toArray(new String[0]); - } - - public static String[] removeFirst(String[] args) { - if (args.length <= 1) { - return new String[0]; - } - List list = asList(args); - list.remove(0); - return list.toArray(new String[0]); - } - - public static String arrayJoin(String[] args, int start) { - return IntStream.range(start, args.length).mapToObj(i -> args[i] + " ").collect(Collectors.joining()).trim(); - } + + public static String arrayJoin(String[] args, int start) { + return IntStream.range(start, args.length).mapToObj(i -> args[i] + " ").collect(Collectors.joining()).trim(); + } + + @SafeVarargs + public static List asList(T... args) { + List list = new ArrayList<>(); + Collections.addAll(list, args); + return list; + } + + public static T[] arrayAppend(T[] array, T obj) { + T[] arrayNew = arrayExpand(array, 1); + arrayNew[array.length] = obj; + return arrayNew; + } + + public static T[] arrayAddFirst(T[] array, T obj) { + T[] arrayNew = arrayExpandAtFirst(array, 1); + arrayNew[0] = obj; + return arrayNew; + } + + @SuppressWarnings("SuspiciousSystemArraycopy") + public static T arrayExpand(T oldArray, int expand) { + int length = Array.getLength(oldArray); + Object newArray = Array.newInstance(oldArray.getClass().getComponentType(), length + expand); + System.arraycopy(oldArray, 0, newArray, 0, length); + return (T) newArray; + } + + @SuppressWarnings("SuspiciousSystemArraycopy") + public static T arrayExpandAtFirst(T oldArray, int expand) { + int length = Array.getLength(oldArray); + Object newArray = Array.newInstance(oldArray.getClass().getComponentType(), length + expand); + System.arraycopy(oldArray, 0, newArray, expand, length); + return (T) newArray; + } + + public static T cloneAsByte(T obj) throws Exception { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); + objectOutputStream.writeObject(obj); + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); + ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); + return (T) objectInputStream.readObject(); + } + + // ********************************* + // + // Deprecated + // + // ********************************* + + @Deprecated + public static String[] addFirst(String[] args, String... value) { + if (args.length < 1) { + return value; + } + List list = asList(args); + for (int i = value.length - 1; i >= 0; i--) { + list.add(0, value[i]); + } + return list.toArray(new String[0]); + } + + @Deprecated + public static String[] removeFirst(String[] args) { + if (args.length <= 1) { + return new String[0]; + } + List list = asList(args); + list.remove(0); + return list.toArray(new String[0]); + } } diff --git a/src/main/java/me/skymc/taboolib/string/VariableFormatter.java b/src/main/java/me/skymc/taboolib/string/VariableFormatter.java new file mode 100644 index 0000000..84567e0 --- /dev/null +++ b/src/main/java/me/skymc/taboolib/string/VariableFormatter.java @@ -0,0 +1,113 @@ +package me.skymc.taboolib.string; + +import com.ilummc.tlib.util.Strings; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @Author sky + * @Since 2018-05-27 11:33 + */ +public class VariableFormatter { + + private Pattern pattern; + private String text; + private String textOrigin; + private List variableList = new ArrayList<>(); + + public VariableFormatter(String text) { + this(text, "<([^<>]+)>"); + } + + public VariableFormatter(String text, String regex) { + this(text, Pattern.compile(regex)); + } + + public VariableFormatter(String text, Pattern pattern) { + this.text = text; + this.textOrigin = text; + this.pattern = pattern; + } + + public VariableFormatter reset() { + text = textOrigin; + variableList.clear(); + return this; + } + + public VariableFormatter find() { + reset(); + Matcher matcher = pattern.matcher(text); + while (matcher.find()) { + String group = matcher.group(); + String[] textOther = text.split(group); + String textLeft = text.indexOf(group) > 0 ? textOther[0] : null; + String textRight = textOther.length >= 2 ? text.substring(text.indexOf(group) + group.length()) : null; + if (textLeft != null) { + variableList.add(new Variable(textLeft, false)); + } + variableList.add(new Variable(group.substring(1, group.length() - 1), true)); + if (textRight != null && !pattern.matcher(textRight).find()) { + variableList.add(new Variable(textRight, false)); + } else { + text = String.valueOf(textRight); + } + } + if (variableList.size() == 0) { + variableList.add(new Variable(text, false)); + } + return this; + } + + @Override + public String toString() { + return Strings.replaceWithOrder("VariableFormatter'{'pattern={0}, text=''{1}'', textOrigin=''{2}'', variableList={3}'}'", pattern, text, textOrigin, variableList); + } + + // ********************************* + // + // Getter and Setter + // + // ********************************* + + public String getText() { + return text; + } + + public List getVariableList() { + return variableList; + } + + // ********************************* + // + // Public classes + // + // ********************************* + + public static class Variable { + + private final String text; + private final boolean variable; + + public Variable(String text, boolean variable) { + this.text = text; + this.variable = variable; + } + + public String getText() { + return text; + } + + public boolean isVariable() { + return variable; + } + + @Override + public String toString() { + return Strings.replaceWithOrder("Variable'{'text=''{0}'', variable={1}'}'", text, variable); + } + } +} diff --git a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Book.java b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Book.java index 5eb7a67..f2118a3 100644 --- a/src/main/java/me/skymc/taboolib/string/language2/value/Language2Book.java +++ b/src/main/java/me/skymc/taboolib/string/language2/value/Language2Book.java @@ -1,5 +1,9 @@ package me.skymc.taboolib.string.language2.value; +import com.ilummc.tlib.bungee.api.chat.BaseComponent; +import com.ilummc.tlib.bungee.api.chat.ClickEvent; +import com.ilummc.tlib.bungee.api.chat.HoverEvent; +import com.ilummc.tlib.bungee.api.chat.TextComponent; import me.skymc.taboolib.bookformatter.BookFormatter; import me.skymc.taboolib.bookformatter.action.ClickAction; import me.skymc.taboolib.bookformatter.action.HoverAction; @@ -8,6 +12,7 @@ import me.skymc.taboolib.bookformatter.builder.PageBuilder; import me.skymc.taboolib.bookformatter.builder.TextBuilder; import me.skymc.taboolib.inventory.ItemUtils; import me.skymc.taboolib.other.NumberUtils; +import me.skymc.taboolib.string.VariableFormatter; import me.skymc.taboolib.string.language2.Language2Format; import me.skymc.taboolib.string.language2.Language2Line; import me.skymc.taboolib.string.language2.Language2Value; @@ -21,7 +26,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; -import java.util.regex.Matcher; import java.util.regex.Pattern; /** @@ -52,17 +56,15 @@ public class Language2Book implements Language2Line { // 变量 this.player = player; this.value = format.getLanguage2Value(); - - // 获取书本设置 + this.book = BookFormatter.writtenBook(); + // 设置 formatOptions(list); - // 书本 - book = BookFormatter.writtenBook(); // 内容 PageBuilder page = new PageBuilder(); // 遍历内容 for (String line : list) { // 翻页 - if ("[page]".equals(line)) { + if (line.equals("[page]")) { book.addPages(page.build()); page = new PageBuilder(); } @@ -70,57 +72,50 @@ public class Language2Book implements Language2Line { else if (line.startsWith("@option")) { break; } else { - Matcher matcher = pattern.matcher(line); - boolean find = false; - while (matcher.find()) { - find = true; - String optionName = matcher.group(1); - String optionFullName = "<@" + matcher.group(1) + ">"; - // 判断设置是否存在 - if (!options.containsKey(optionName)) { - page.add("§4[]"); - } else { - String[] line_split = line.split(optionFullName); - try { - // 单独一行 - if (line_split.length == 0) { - page.add(options.get(optionName).build()).endLine(); - } else { - // 前段 - page.add(line_split[0]); - // 变量 - page.add(options.get(optionName).build()); - // 后段 - if (line_split.length >= 2) { - // 获取文本 - StringBuilder sb = new StringBuilder(); - for (int i = 1; i < line_split.length; i++) { - sb.append(line_split[i]).append(optionFullName); - } - // 更改文本 - line = sb.substring(0, sb.length() - optionFullName.length()); - // 如果后段还有变量 - if (!pattern.matcher(line).find()) { - page.add(line_split[1]).endLine(); - } - } else { - page.endLine(); - } + for (VariableFormatter.Variable variable : new VariableFormatter(line, pattern).find().getVariableList()) { + if (variable.isVariable()) { + String node = variable.getText().substring(1); + if (!options.containsKey(node)) { + page.add("§4[]"); + } else { + TextBuilder builder = options.get(node); + BaseComponent component = new TextComponent(builder.getText()); + if (builder.getHover() != null) { + component.setHoverEvent(new HoverEvent(builder.getHover().action(), builder.getHover().value())); } - } catch (Exception e) { - page.add("§4[]"); + if (builder.getClick() != null) { + component.setClickEvent(new ClickEvent(builder.getClick().action(), builder.getClick().value())); + } + page.add(component); } + } else { + page.add(variable.getText()); } } - if (!find) { - page.add(line).endLine(); - } + page.newLine(); } } // 结尾 book.addPages(page.build()); } + + @Override + public void send(Player player) { + BookFormatter.forceOpen(player, book.build()); + } + + @Override + public void console() { + Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); + } + + // ********************************* + // + // Getter and Setter + // + // ********************************* + public static Pattern getPattern() { return pattern; } @@ -141,6 +136,46 @@ public class Language2Book implements Language2Line { return book; } + // ********************************* + // + // Private Methods + // + // ********************************* + + private List> getBookPages(List source) { + List> list = new ArrayList<>(); + for (String line : removeOption(source)) { + if (line.equalsIgnoreCase("[page]")) { + list.add(new ArrayList<>()); + } else { + getLatestList(list).add(line); + } + } + return list; + } + + public List getLatestList(List> list) { + if (list.size() == 0) { + List newList = new ArrayList<>(); + list.add(newList); + return newList; + } else { + return list.get(list.size() - 1); + } + } + + public List removeOption(List source) { + List list = new ArrayList<>(); + for (String line : source) { + if (!line.contains("@option")) { + list.add(line); + } else { + return list; + } + } + return list; + } + private void formatOptions(List list) { // 获取书本设置 HashMap> _options = getOptions(list); @@ -204,14 +239,4 @@ public class Language2Book implements Language2Line { options_source.put(optionName, option); return options_source; } - - @Override - public void send(Player player) { - BookFormatter.forceOpen(player, book.build()); - } - - @Override - public void console() { - Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[]"); - } } diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 3e8ddbf..2f4ae64 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -57,6 +57,10 @@ NOTIFY: LOCALE: TITLE-SEND-TO-NON-PLAYER: '该语言类型只能发送给玩家:{0}' PLUGIN-NOT-FOUND: '无效的语言文件发送形式: &4{0}' + BOOK-ARGUMENTS-IDENTIFICATION-FAILED: 'TlocaleBook 的变量识别失败: {0}' + BAR-COLOR-IDENTIFICATION-FAILED: 'TLocaleBossBar 的颜色识别失败: {0}' + BAR-STYLE-IDENTIFICATION-FAILED: 'TLocaleBossBar 的类型识别失败: {0}' + BAR-PLUGIN-NOT-FOUND: 'TLocaleBossBar 的依赖插件 BossBarAPI 不存在' MISC: FIELD-COPY-FAILED: '拷贝 {0} 对象失败' diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index f51358c..e683e5f 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -25,4 +25,4 @@ commands: aliases: [tlm] depend: [Vault] -softdepend: [PlaceholderAPI, Skript, TabooCode, MassiveLag] \ No newline at end of file +softdepend: [PlaceholderAPI, Skript, MassiveLag] \ No newline at end of file From efeb088a70d82ec8d4d4e7bbe82e8328b746e07c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9D=8F=E9=BB=91?= Date: Thu, 31 May 2018 22:16:50 +0800 Subject: [PATCH 7/9] =?UTF-8?q?=E7=89=88=E6=9C=AC=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=87=B3=204.07=20=E4=BF=AE=E5=A4=8D=EF=BC=9A=E7=8E=A9?= =?UTF-8?q?=E5=AE=B6=E5=88=97=E8=A1=A8=E6=8E=92=E5=BA=8F=E5=AF=BC=E8=87=B4?= =?UTF-8?q?=E5=85=B6=E4=BB=96=E5=B0=8F=E6=B8=B8=E6=88=8F=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=E6=8A=A5=E5=BA=9F=EF=BC=88=E8=87=AA=E5=B7=B1=E5=86=99=E4=B8=AA?= =?UTF-8?q?=E5=AE=B9=E5=99=A8=E4=BF=9D=E5=AD=98=E7=8E=A9=E5=AE=B6=E8=83=BD?= =?UTF-8?q?=E7=B4=AF=E6=AD=BB=EF=BC=9F=E9=9D=9E=E8=A6=81=E7=94=A8=E5=82=BB?= =?UTF-8?q?=E9=80=BC=E8=AE=A1=E5=88=86=E6=9D=BF=EF=BC=9F=EF=BC=89=20?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=EF=BC=9A1.8=20=E9=A6=96=E6=AC=A1=E5=8F=91?= =?UTF-8?q?=E9=80=81=20Json=20=E6=8A=A5=E9=94=99=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- src/main/java/com/ilummc/tlib/resources/TLocale.java | 1 + .../java/me/skymc/taboolib/itagapi/TagDataHandler.java | 3 ++- src/main/java/me/skymc/taboolib/itagapi/TagPacket.java | 1 + .../java/me/skymc/taboolib/itagapi/TagPlayerData.java | 10 +++++++--- src/main/java/me/skymc/taboolib/nms/NMSUtil19.java | 7 +++++-- src/main/resources/config.yml | 4 ++++ 7 files changed, 21 insertions(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index e1ec024..c7ea8c9 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ me.skymc TabooLib - 4.06 + 4.07 UTF-8 diff --git a/src/main/java/com/ilummc/tlib/resources/TLocale.java b/src/main/java/com/ilummc/tlib/resources/TLocale.java index 9747a35..c696a4d 100644 --- a/src/main/java/com/ilummc/tlib/resources/TLocale.java +++ b/src/main/java/com/ilummc/tlib/resources/TLocale.java @@ -155,5 +155,6 @@ public class TLocale { sender.sendMessage(TextComponent.toLegacyText(ComponentSerializer.parse(rawMessage))); } } + } } diff --git a/src/main/java/me/skymc/taboolib/itagapi/TagDataHandler.java b/src/main/java/me/skymc/taboolib/itagapi/TagDataHandler.java index 8d58ea8..4770dbf 100644 --- a/src/main/java/me/skymc/taboolib/itagapi/TagDataHandler.java +++ b/src/main/java/me/skymc/taboolib/itagapi/TagDataHandler.java @@ -6,6 +6,7 @@ import me.skymc.taboolib.packet.PacketUtils; import org.bukkit.Bukkit; 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.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerJoinEvent; @@ -156,7 +157,7 @@ public class TagDataHandler implements Listener { downloadPlayerVariable(e.getPlayer()); } - @EventHandler + @EventHandler (priority = EventPriority.MONITOR) public void onQuit(PlayerQuitEvent e) { cancelPlayerVariable(e.getPlayer(), unregisterPlayerData(e.getPlayer())); } diff --git a/src/main/java/me/skymc/taboolib/itagapi/TagPacket.java b/src/main/java/me/skymc/taboolib/itagapi/TagPacket.java index 595106c..d4d19f8 100644 --- a/src/main/java/me/skymc/taboolib/itagapi/TagPacket.java +++ b/src/main/java/me/skymc/taboolib/itagapi/TagPacket.java @@ -14,6 +14,7 @@ import me.skymc.taboolib.events.itag.PlayerReceiveNameTagEvent; import org.bukkit.Bukkit; 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.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; diff --git a/src/main/java/me/skymc/taboolib/itagapi/TagPlayerData.java b/src/main/java/me/skymc/taboolib/itagapi/TagPlayerData.java index 9718614..b7ceb67 100644 --- a/src/main/java/me/skymc/taboolib/itagapi/TagPlayerData.java +++ b/src/main/java/me/skymc/taboolib/itagapi/TagPlayerData.java @@ -1,9 +1,11 @@ package me.skymc.taboolib.itagapi; import com.ilummc.tlib.util.Strings; +import me.skymc.taboolib.Main; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import java.text.MessageFormat; import java.util.Objects; import java.util.UUID; @@ -14,19 +16,21 @@ import java.util.UUID; public class TagPlayerData { private final UUID uuid; + private final String nameOrigin; private String nameDisplay; private String prefix; private String suffix; public TagPlayerData(Player player) { this.uuid = player.getUniqueId(); + this.nameOrigin = player.getName(); this.nameDisplay = player.getName(); this.prefix = ""; this.suffix = ""; } public String getTeamHash() { - return String.valueOf(Objects.hash(prefix)); + return Main.getInst().getConfig().getBoolean("TABLIST-SORT") ? String.valueOf(Objects.hash(prefix)) : nameOrigin; } public TagPlayerData reset() { @@ -38,7 +42,7 @@ public class TagPlayerData { @Override public String toString() { - return Strings.replaceWithOrder("TagPlayerData'{'uuid={0}, nameDisplay=''{1}'', prefix=''{2}'', suffix=''{3}'''}'", uuid, nameDisplay, prefix, suffix); + return Strings.replaceWithOrder("TagPlayerData'{'uuid={0}, nameOrigin=''{1}'', nameDisplay=''{2}'', prefix=''{3}'', suffix=''{4}'''}'", uuid, nameOrigin, nameDisplay, prefix, suffix); } // ********************************* @@ -52,7 +56,7 @@ public class TagPlayerData { } public String getNameOrigin() { - return Bukkit.getPlayer(uuid).getName(); + return nameOrigin; } public String getNameDisplay() { diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java b/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java index 7177ddd..94ecc74 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java @@ -921,13 +921,16 @@ public class NMSUtil19 { return result; } - public static Class fixBukkitClass(String className) throws ClassNotFoundException { + public static Class fixBukkitClass(String className) { if (!versionPrefix.isEmpty()) { className = className.replace("org.bukkit.craftbukkit.", "org.bukkit.craftbukkit." + versionPrefix); className = className.replace("net.minecraft.server.", "net.minecraft.server." + versionPrefix); } - return NMSUtils.class.getClassLoader().loadClass(className); + try { + return NMSUtils.class.getClassLoader().loadClass(className); + } catch (ClassNotFoundException ignored) { + } } public static Object getHandle(Server server) { diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 91a40b6..9f49274 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -33,6 +33,10 @@ LOCALE: # 关闭可提升性能 # 如果需要开启仍然可以在语言文件中加入 papi: true USE_PAPI: false + +# 玩家列表(TAB)是否根据前缀排序 +# 启用后将会导致部分通过计分板获取玩家数据的插件出错(BedwarsRel、SkyWars) +TABLIST-SORT: false # 是否启用更新检测 UPDATE-CHECK: true From 2c61f793f710ec69046d1e8cafd6d6fb990ba002 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9D=8F=E9=BB=91?= Date: Sun, 3 Jun 2018 21:10:00 +0800 Subject: [PATCH 8/9] =?UTF-8?q?=E7=89=88=E6=9C=AC=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=87=B3=204.08=20=E8=B0=83=E6=95=B4=EF=BC=9A=E4=BC=98?= =?UTF-8?q?=E5=8C=96=20/tplugin=20=E5=90=84=E9=A1=B9=E5=91=BD=E4=BB=A4?= =?UTF-8?q?=EF=BC=8C=E6=9B=B4=E5=A4=9A=E6=8F=90=E7=A4=BA=E3=80=82=20?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=EF=BC=9A=E4=BF=AE=E5=A4=8D=20BaseSubCommand?= =?UTF-8?q?=20=E4=B8=AD=E4=BB=85=E5=85=81=E8=AE=B8=E6=8E=A7=E5=88=B6?= =?UTF-8?q?=E5=8F=B0=E7=B1=BB=E5=9E=8B=E6=97=A0=E6=95=88=E7=9A=84=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E3=80=82=20=E6=96=B0=E5=A2=9E=EF=BC=9A/tlib=20updateP?= =?UTF-8?q?lugin=20=E5=91=BD=E4=BB=A4=E7=94=A8=E4=BA=8E=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E3=80=82=20=E6=96=B0=E5=A2=9E=EF=BC=9A?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E4=B8=8B=E8=BD=BD=E6=9C=80=E6=96=B0=E7=89=88?= =?UTF-8?q?=EF=BC=88=E9=BB=98=E8=AE=A4=E5=85=B3=E9=97=AD=EF=BC=89=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- .../commands/TabooLibMainCommand.java | 65 +++++++++++++ .../commands/internal/BaseMainCommand.java | 6 +- .../plugin/TabooLibPluginMainCommand.java | 54 +++++++---- .../skymc/taboolib/fileutils/FileUtils.java | 6 +- .../java/me/skymc/taboolib/nms/NMSUtil19.java | 3 +- .../taboolib/plugin/PluginLoadState.java | 24 +++++ .../taboolib/plugin/PluginLoadStateType.java | 34 +++++++ .../taboolib/plugin/PluginUnloadState.java | 24 +++++ .../me/skymc/taboolib/plugin/PluginUtils.java | 95 +++++++++---------- .../me/skymc/taboolib/update/UpdateTask.java | 13 ++- src/main/resources/config.yml | 3 + src/main/resources/lang/zh_CN.yml | 17 +++- 13 files changed, 262 insertions(+), 84 deletions(-) create mode 100644 src/main/java/me/skymc/taboolib/plugin/PluginLoadState.java create mode 100644 src/main/java/me/skymc/taboolib/plugin/PluginLoadStateType.java create mode 100644 src/main/java/me/skymc/taboolib/plugin/PluginUnloadState.java diff --git a/pom.xml b/pom.xml index c7ea8c9..e89eeb8 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ me.skymc TabooLib - 4.07 + 4.08 UTF-8 diff --git a/src/main/java/me/skymc/taboolib/commands/TabooLibMainCommand.java b/src/main/java/me/skymc/taboolib/commands/TabooLibMainCommand.java index 2db286c..a97cfeb 100644 --- a/src/main/java/me/skymc/taboolib/commands/TabooLibMainCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/TabooLibMainCommand.java @@ -1,14 +1,24 @@ package me.skymc.taboolib.commands; import com.ilummc.tlib.resources.TLocale; +import com.ilummc.tlib.util.Strings; +import me.skymc.taboolib.Main; import me.skymc.taboolib.commands.internal.BaseMainCommand; import me.skymc.taboolib.commands.internal.BaseSubCommand; import me.skymc.taboolib.commands.internal.type.CommandArgument; import me.skymc.taboolib.commands.internal.type.CommandRegister; +import me.skymc.taboolib.commands.internal.type.CommandType; import me.skymc.taboolib.commands.taboolib.*; +import me.skymc.taboolib.fileutils.FileUtils; import me.skymc.taboolib.inventory.ItemUtils; +import me.skymc.taboolib.plugin.PluginUtils; +import me.skymc.taboolib.update.UpdateTask; +import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; +import org.bukkit.scheduler.BukkitRunnable; + +import java.io.File; /** * @Author sky @@ -723,4 +733,59 @@ public class TabooLibMainCommand extends BaseMainCommand { new ImportCommand(sender, args); } }; + + @CommandRegister(priority = 26) + BaseSubCommand updatePlugin = new BaseSubCommand() { + + @Override + public String getLabel() { + return "updatePlugin"; + } + + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TABOOLIB.UPDATEPLUGIN.DESCRIPTION"); + } + + @Override + public CommandArgument[] getArguments() { + return new CommandArgument[0]; + } + + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + if (!UpdateTask.isHaveUpdate()) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.UPDATEPLUGIN.UPDATE-NOT-FOUND"); + return; + } + + File file = new File("plugins/update"); + if (!file.exists()) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.UPDATEPLUGIN.UPDATE-NOT-SUPPORT"); + return; + } + + File pluginFile = PluginUtils.getPluginFile(Main.getInst()); + if (pluginFile == null) { + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.UPDATEPLUGIN.FILE-NOT-FOUND"); + return; + } + + new BukkitRunnable() { + + @Override + public void run() { + String url = Strings.replaceWithOrder("https://github.com/Bkm016/TabooLib/releases/download/{0}/TabooLib-{0}.jar", UpdateTask.getNewVersion()); + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.UPDATEPLUGIN.UPDATE-START", url); + FileUtils.download(url, new File(file, pluginFile.getName())); + TLocale.sendTo(sender, "COMMANDS.TABOOLIB.UPDATEPLUGIN.UPDATE-SUCCESS"); + } + }.runTaskAsynchronously(Main.getInst()); + } + + @Override + public CommandType getType() { + return CommandType.CONSOLE; + } + }; } diff --git a/src/main/java/me/skymc/taboolib/commands/internal/BaseMainCommand.java b/src/main/java/me/skymc/taboolib/commands/internal/BaseMainCommand.java index c2669d9..36ac981 100644 --- a/src/main/java/me/skymc/taboolib/commands/internal/BaseMainCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/internal/BaseMainCommand.java @@ -109,7 +109,7 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor, continue; } if (!isConfirmType(sender, subCommand.getType())) { - TLocale.sendTo(sender, "COMMANDS.INTERNAL.ONLY-PLAYER", args[0], TLocale.asString("COMMANDS.INTERNAL.TYPE-" + subCommand.getType())); + TLocale.sendTo(sender, "COMMANDS.INTERNAL.TYPE-ERROR", args[0], TLocale.asString("COMMANDS.INTERNAL.TYPE-" + subCommand.getType())); return true; } String[] subCommandArgs = ArrayUtils.removeFirst(args); @@ -166,7 +166,9 @@ public abstract class BaseMainCommand implements IMainCommand, CommandExecutor, } private boolean isConfirmType(CommandSender sender, CommandType commandType) { - return commandType == CommandType.ALL || (sender instanceof Player && commandType == CommandType.PLAYER); + return commandType == CommandType.ALL + || (sender instanceof Player && commandType == CommandType.PLAYER) + || (sender instanceof ConsoleCommandSender && commandType == CommandType.CONSOLE); } private void helpCommand(CommandSender sender, String label) { diff --git a/src/main/java/me/skymc/taboolib/commands/plugin/TabooLibPluginMainCommand.java b/src/main/java/me/skymc/taboolib/commands/plugin/TabooLibPluginMainCommand.java index 4f80d08..42a0a86 100644 --- a/src/main/java/me/skymc/taboolib/commands/plugin/TabooLibPluginMainCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/plugin/TabooLibPluginMainCommand.java @@ -7,6 +7,9 @@ import me.skymc.taboolib.commands.internal.BaseSubCommand; import me.skymc.taboolib.commands.internal.ISubCommand; import me.skymc.taboolib.commands.internal.type.CommandArgument; import me.skymc.taboolib.commands.internal.type.CommandRegister; +import me.skymc.taboolib.plugin.PluginLoadState; +import me.skymc.taboolib.plugin.PluginLoadStateType; +import me.skymc.taboolib.plugin.PluginUnloadState; import me.skymc.taboolib.plugin.PluginUtils; import me.skymc.taboolib.string.ArrayUtils; import org.bukkit.Bukkit; @@ -62,16 +65,29 @@ public class TabooLibPluginMainCommand extends BaseMainCommand { public void onCommand(CommandSender sender, Command command, String label, String[] args) { String name = ArrayUtils.arrayJoin(args, 0); if (PluginUtils.getPluginByName(name) != null) { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-PLUGIN", name); + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-PLUGIN", name, name + " already loaded!"); } else { - switch (PluginUtils.load(name)) { - case "loaded": { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-SUCCESS", name); + PluginLoadState loadState; + try { + loadState = PluginUtils.load(name); + } catch (Exception e) { + loadState = new PluginLoadState(PluginLoadStateType.INVALID_PLUGIN, e.toString()); + } + switch (loadState.getStateType()) { + case INVALID_DESCRIPTION: { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-DESCRIPTION"); break; } - default: { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-FAIL", name); + case INVALID_PLUGIN: { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-PLUGIN", name, loadState.getMessage()); + break; } + case FILE_NOT_FOUND: { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.FILE-NOT-FOUND", name); + break; + } + default: + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.LOAD-SUCCESS", name); } } } @@ -104,14 +120,16 @@ public class TabooLibPluginMainCommand extends BaseMainCommand { } else if (PluginUtils.isIgnored(plugin)) { TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN-IGNORED", name); } else { - switch (PluginUtils.unload(plugin)) { - case "unloaded": { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-SUCCESS", name); - break; - } - default: { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-FAIL", name); - } + PluginUnloadState unloadState; + try { + unloadState = PluginUtils.unload(plugin); + } catch (Exception e) { + unloadState = new PluginUnloadState(true, e.toString()); + } + if (unloadState.isFailed()) { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-FAIL", name, unloadState.getMessage()); + } else { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.UNLOAD-SUCCESS", name); } } } @@ -185,9 +203,9 @@ public class TabooLibPluginMainCommand extends BaseMainCommand { String.valueOf(plugin.getDescription().getMain()), String.valueOf(plugin.getDescription().getVersion()), String.valueOf(plugin.getDescription().getWebsite()), - String.valueOf(plugin.getDescription().getCommands().keySet())); - } catch (Exception ignored) { - TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-PLUGIN", name); + String.valueOf(plugin.getDescription().getCommands() == null ? "" : plugin.getDescription().getCommands().keySet())); + } catch (Exception e) { + TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-DESCRIPTION", name, e.getMessage()); } } } @@ -213,7 +231,7 @@ public class TabooLibPluginMainCommand extends BaseMainCommand { @Override public void onCommand(CommandSender sender, Command command, String label, String[] args) { - List pluginList = Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(Plugin::getName).sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.toList()); + List pluginList = Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(PluginUtils::getFormattedName).sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.toList()); TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LIST.LIST-PLUGIN", String.valueOf(Bukkit.getPluginManager().getPlugins().length), Joiner.on(", ").join(pluginList)); } }; diff --git a/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java b/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java index a0afd4d..676e092 100644 --- a/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java +++ b/src/main/java/me/skymc/taboolib/fileutils/FileUtils.java @@ -119,7 +119,7 @@ public class FileUtils { * * @param file 文件夹 */ - public void deleteAllFile(File file) { + public static void deleteAllFile(File file) { if (!file.exists()) { return; } @@ -139,7 +139,7 @@ public class FileUtils { * @param file1 文件1 * @param file2 文件2 */ - public void copyAllFile(String file1, String file2) { + public static void copyAllFile(String file1, String file2) { File _file1 = new File(file1); File _file2 = new File(file2); if (!_file2.exists()) { @@ -168,7 +168,7 @@ public class FileUtils { * @param file1 文件1 * @param file2 文件2 */ - public void fileChannelCopy(File file1, File file2) { + public static void fileChannelCopy(File file1, File file2) { FileInputStream fileIn = null; FileOutputStream fileOut = null; FileChannel channelIn = null; diff --git a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java b/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java index 94ecc74..7c24b14 100644 --- a/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java +++ b/src/main/java/me/skymc/taboolib/nms/NMSUtil19.java @@ -911,7 +911,7 @@ public class NMSUtil19 { } public static Class getBukkitClass(String className) { - Class result = null; + Class result; try { result = fixBukkitClass(className); } catch (Exception ex) { @@ -930,6 +930,7 @@ public class NMSUtil19 { try { return NMSUtils.class.getClassLoader().loadClass(className); } catch (ClassNotFoundException ignored) { + return null; } } diff --git a/src/main/java/me/skymc/taboolib/plugin/PluginLoadState.java b/src/main/java/me/skymc/taboolib/plugin/PluginLoadState.java new file mode 100644 index 0000000..59b7250 --- /dev/null +++ b/src/main/java/me/skymc/taboolib/plugin/PluginLoadState.java @@ -0,0 +1,24 @@ +package me.skymc.taboolib.plugin; + +/** + * @Author sky + * @Since 2018-06-01 21:34 + */ +public class PluginLoadState { + + private final PluginLoadStateType stateType; + private final String message; + + public PluginLoadState(PluginLoadStateType stateType, String message) { + this.stateType = stateType; + this.message = message; + } + + public PluginLoadStateType getStateType() { + return stateType; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/me/skymc/taboolib/plugin/PluginLoadStateType.java b/src/main/java/me/skymc/taboolib/plugin/PluginLoadStateType.java new file mode 100644 index 0000000..15c98b3 --- /dev/null +++ b/src/main/java/me/skymc/taboolib/plugin/PluginLoadStateType.java @@ -0,0 +1,34 @@ +package me.skymc.taboolib.plugin; + +/** + * @Author sky + * @Since 2018-06-01 21:32 + */ +public enum PluginLoadStateType { + + /** + * 目录不存在 + */ + DIRECTORY_NOT_FOUND, + + /** + * 插件不存在 + */ + FILE_NOT_FOUND, + + /** + * 无效的描述 + */ + INVALID_DESCRIPTION, + + /** + * 无效的插件 + */ + INVALID_PLUGIN, + + /** + * 载入成功 + */ + LOADED + +} diff --git a/src/main/java/me/skymc/taboolib/plugin/PluginUnloadState.java b/src/main/java/me/skymc/taboolib/plugin/PluginUnloadState.java new file mode 100644 index 0000000..5e94809 --- /dev/null +++ b/src/main/java/me/skymc/taboolib/plugin/PluginUnloadState.java @@ -0,0 +1,24 @@ +package me.skymc.taboolib.plugin; + +/** + * @Author sky + * @Since 2018-06-01 21:39 + */ +public class PluginUnloadState { + + private final boolean failed; + private final String message; + + public PluginUnloadState(boolean failed, String message) { + this.failed = failed; + this.message = message; + } + + public boolean isFailed() { + return failed; + } + + public String getMessage() { + return message; + } +} diff --git a/src/main/java/me/skymc/taboolib/plugin/PluginUtils.java b/src/main/java/me/skymc/taboolib/plugin/PluginUtils.java index a592f4c..30d3a53 100644 --- a/src/main/java/me/skymc/taboolib/plugin/PluginUtils.java +++ b/src/main/java/me/skymc/taboolib/plugin/PluginUtils.java @@ -1,8 +1,3 @@ -// -// Source code recreated from a .class file by IntelliJ IDEA -// (powered by Fernflower decompiler) -// - package me.skymc.taboolib.plugin; import com.google.common.base.Joiner; @@ -26,16 +21,33 @@ import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.IntStream; +/** + * @author PluginMan + */ public class PluginUtils { - private PluginUtils() { + PluginUtils() { + } + + public static File getPluginFile(Plugin plugin) { + for (File pluginFile : Objects.requireNonNull(new File("plugins").listFiles())) { + if (pluginFile.getName().endsWith(".jar")) { + try { + PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(pluginFile); + if (desc.getName().equalsIgnoreCase(plugin.getName())) { + return pluginFile; + } + } catch (InvalidDescriptionException ignored) { + } + } + } + return null; } public static void enable(Plugin plugin) { if (plugin != null && !plugin.isEnabled()) { Bukkit.getPluginManager().enablePlugin(plugin); } - } public static void disable(Plugin plugin) { @@ -45,11 +57,11 @@ public class PluginUtils { } public static void enableAll() { - Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> isIgnored(plugin)).forEach(PluginUtils::enable); + Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(PluginUtils::isIgnored).forEach(PluginUtils::enable); } public static void disableAll() { - Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> isIgnored(plugin)).forEach(PluginUtils::disable); + Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(PluginUtils::isIgnored).forEach(PluginUtils::disable); } public static String getFormattedName(Plugin plugin) { @@ -58,7 +70,7 @@ public class PluginUtils { public static String getFormattedName(Plugin plugin, boolean includeVersions) { ChatColor color = plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED; - String pluginName = color + plugin.getName(); + String pluginName = color + plugin.getName() + ChatColor.RESET; if (includeVersions) { pluginName = pluginName + " (" + plugin.getDescription().getVersion() + ")"; } @@ -89,9 +101,8 @@ public class PluginUtils { Map commands = plugin.getDescription().getCommands(); if (commands != null) { for (Object o : commands.entrySet()) { - Entry thisEntry = (Entry) o; - if (thisEntry != null) { - parsedCommands.add((String) thisEntry.getKey()); + if (o != null) { + parsedCommands.add((String) ((Entry) o).getKey()); } } } @@ -158,37 +169,28 @@ public class PluginUtils { return plugin.equals(Main.getInst()); } - private static String load(Plugin plugin) { + private static PluginLoadState load(Plugin plugin) { return load(plugin.getName()); } - /** - * 返回内容: - * - * plugin-directory —— 插件目录不存在 - * cannot-find —— 插件不存在 - * invalid-description —— 无效的描述 - * invalid-plugin —— 无效的插件 - * loaded —— 载入成功 - */ - public static String load(String name) { + public static PluginLoadState load(String name) { Plugin target; File pluginDir = new File("plugins"); if (!pluginDir.isDirectory()) { - return "plugin-directory"; + return new PluginLoadState(PluginLoadStateType.DIRECTORY_NOT_FOUND, "null"); } else { File pluginFile = new File(pluginDir, name + ".jar"); - if (!pluginFile.isFile()) { - for (File f : Objects.requireNonNull(pluginDir.listFiles())) { - if (f.getName().endsWith(".jar")) { + if (!pluginFile.exists()) { + for (File plugin : Objects.requireNonNull(pluginDir.listFiles())) { + if (plugin.getName().endsWith(".jar")) { try { - PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(f); + PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(plugin); if (desc.getName().equalsIgnoreCase(name)) { - pluginFile = f; + pluginFile = plugin; break; } - } catch (InvalidDescriptionException var11) { - return "cannot-find"; + } catch (InvalidDescriptionException ignored) { + return new PluginLoadState(PluginLoadStateType.FILE_NOT_FOUND, "null"); } } } @@ -196,15 +198,15 @@ public class PluginUtils { try { target = Bukkit.getPluginManager().loadPlugin(pluginFile); - } catch (InvalidDescriptionException var9) { - return "invalid-description"; - } catch (InvalidPluginException var10) { - return "invalid-plugin"; + } catch (InvalidDescriptionException e) { + return new PluginLoadState(PluginLoadStateType.INVALID_DESCRIPTION, e.toString()); + } catch (InvalidPluginException e) { + return new PluginLoadState(PluginLoadStateType.INVALID_PLUGIN, e.toString()); } target.onLoad(); Bukkit.getPluginManager().enablePlugin(target); - return "loaded"; + return new PluginLoadState(PluginLoadStateType.LOADED, "null"); } } @@ -213,20 +215,13 @@ public class PluginUtils { unload(plugin); load(plugin); } - } public static void reloadAll() { Arrays.stream(Bukkit.getPluginManager().getPlugins(), 0, Bukkit.getPluginManager().getPlugins().length).filter(PluginUtils::isIgnored).forEach(PluginUtils::reload); } - /** - * 返回内容: - * - * failed —— 卸载失败 - * unloaded —— 卸载成功 - */ - public static String unload(Plugin plugin) { + public static PluginUnloadState unload(Plugin plugin) { String name = plugin.getName(); PluginManager pluginManager = Bukkit.getPluginManager(); SimpleCommandMap commandMap = null; @@ -236,7 +231,6 @@ public class PluginUtils { Map> listeners = null; if (pluginManager != null) { pluginManager.disablePlugin(plugin); - try { Field pluginsField = Bukkit.getPluginManager().getClass().getDeclaredField("plugins"); pluginsField.setAccessible(true); @@ -259,8 +253,8 @@ public class PluginUtils { Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands"); knownCommandsField.setAccessible(true); commands = (Map) knownCommandsField.get(commandMap); - } catch (NoSuchFieldException | IllegalAccessException var15) { - return "failed"; + } catch (NoSuchFieldException | IllegalAccessException e) { + return new PluginUnloadState(true, e.toString()); } } @@ -276,10 +270,8 @@ public class PluginUtils { Iterator it; if (listeners != null) { it = listeners.values().iterator(); - while (it.hasNext()) { SortedSet set = (SortedSet) it.next(); - while (it.hasNext()) { RegisteredListener value = (RegisteredListener) it.next(); if (value.getPlugin() == plugin) { @@ -291,7 +283,6 @@ public class PluginUtils { if (commandMap != null) { it = commands.entrySet().iterator(); - while (it.hasNext()) { Entry entry = (Entry) it.next(); if (entry.getValue() instanceof PluginCommand) { @@ -312,7 +303,7 @@ public class PluginUtils { Logger.getLogger(PluginUtils.class.getName()).log(Level.SEVERE, null, var13); } } - return "unloaded"; + return new PluginUnloadState(false, "null"); } private static String consolidateStrings(String[] args, int start) { diff --git a/src/main/java/me/skymc/taboolib/update/UpdateTask.java b/src/main/java/me/skymc/taboolib/update/UpdateTask.java index ee4f992..6d469ca 100644 --- a/src/main/java/me/skymc/taboolib/update/UpdateTask.java +++ b/src/main/java/me/skymc/taboolib/update/UpdateTask.java @@ -7,6 +7,7 @@ import com.ilummc.tlib.resources.TLocale; import me.skymc.taboolib.Main; import me.skymc.taboolib.TabooLib; import me.skymc.taboolib.fileutils.FileUtils; +import org.bukkit.Bukkit; import org.bukkit.scheduler.BukkitRunnable; /** @@ -26,9 +27,6 @@ public class UpdateTask { return newVersion; } - /** - * 旧地址:https://internal.github.com/repos/Bkm016/TabooLib/releases/latest - */ public UpdateTask() { new BukkitRunnable() { @@ -53,6 +51,15 @@ public class UpdateTask { } else { haveUpdate = true; TLocale.Logger.info("UPDATETASK.VERSION-OUTDATED", String.valueOf(TabooLib.getPluginVersion()), String.valueOf(newVersion)); + + new BukkitRunnable() { + @Override + public void run() { + if (Main.getInst().getConfig().getBoolean("UPDATE-DOWNLOAD", false)) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "taboolib updatePlugin"); + } + } + }.runTask(Main.getInst()); } } } diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 9f49274..72b53ab 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -41,6 +41,9 @@ TABLIST-SORT: false # 是否启用更新检测 UPDATE-CHECK: true +# 是否启用自动更新 +UPDATE-DOWNLOAD: false + # 是否在关闭服务器时清理玩家数据 # 该配置将在启用数据库储存时失效 DELETE-DATA: false diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 2f4ae64..4ca772c 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -157,7 +157,7 @@ COMMANDS: ONLY-PLAYER: '&8[&3&lTabooLib&8] &4控制台无法这么做' ONLY-STORAGE-SQL: '&8[&3&lTabooLib&8] &4只有启用数据库储存时才能这么做' INTERNAL: - ONLY-PLAYER: '&8[&3&lTabooLib&8] &7指令 &f{0} &7只能由 &f{1} &7执行' + TYPE-ERROR: '&8[&3&lTabooLib&8] &7指令 &f{0} &7只能由 &f{1} &7执行' TYPE-PLAYER: 玩家 TYPE-CONSOLE: 控制台 ERROR-USAGE: @@ -230,6 +230,13 @@ COMMANDS: IMPORTING-START: '&8[&3&lTabooLib&8] &7开始导入 &f{0} &7项玩家数据' IMPORTING-PROGRESS: '&8[&3&lTabooLib&8] &7导入玩家数据: &f{0} &7进度: &f{1}/{2}' SUCCESS: '&8[&3&lTabooLib&8] &7导入完成' + UPDATEPLUGIN: + DESCRIPTION: '&4更新插件 &8(谨防非正规途径的插件获取方式)' + UPDATE-NOT-FOUND: '&8[&3&lTabooLib&8] &7插件已是最新版, 无需更新!' + UPDATE-NOT-SUPPORT: '&8[&3&lTabooLib&8] &4您的服务器不支持在线更新!' + FILE-NOT-FOUND: '&8[&3&lTabooLib&8] &4尚未寻找到插件文件' + UPDATE-START: '&8[&3&lTabooLib&8] &7开始下载:&f {0}' + UPDATE-SUCCESS: '&8[&3&lTabooLib&8] &7最新版下载完成, 重启服务器自动更新!' JAVASHELL: DESCRIPTION: LOAD: '载入脚本' @@ -470,6 +477,7 @@ COMMANDS: ARGUMENTS: 0: '名称' INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4不存在' + INVALID-DESCRIPTION: '&8[&3&lTabooLib&8] &4获取插件 &c{0} &4信息失败: &c{1}' INFO-PLUGIN: - '&8[&3&lTabooLib&8] &7插件名称: &f{0}' - '&8[&3&lTabooLib&8] &7描述: &f{1}' @@ -484,9 +492,10 @@ COMMANDS: DESCRIPTION: '载入插件' ARGUMENTS: 0: '名称' - INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4已经载入' + INVALID-DESCRIPTION: '&8[&3&lTabooLib&8] &4插件目录不存在' + INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4载入失败: &c{1}' + FILE-NOT-FOUND: '&8[&3&lTabooLib&8] &4插件 &c{0} &4文件不存在' LOAD-SUCCESS: '&8[&3&lTabooLib&8] &7插件已载入' - LOAD-FAIL: '&8[&3&lTabooLib&8] &7插件载入失败' UNLOAD: DESCRIPTION: '卸载插件' ARGUMENTS: @@ -494,7 +503,7 @@ COMMANDS: INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4不存在' INVALID-PLUGIN-IGNORED: '&8[&3&lTabooLib&8] &4插件 &c{0} &4无法操作' UNLOAD-SUCCESS: '&8[&3&lTabooLib&8] &7插件已卸载' - UNLOAD-FAIL: '&8[&3&lTabooLib&8] &7插件卸载失败' + UNLOAD-FAIL: '&8[&3&lTabooLib&8] &4插件 &c{0} &e卸载失败: &c{1}' RELOAD: DESCRIPTION: '重载插件' ARGUMENTS: From 8e5279d720dc8042c5abbe9161d64918efe7cb89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9D=8F=E9=BB=91?= Date: Fri, 8 Jun 2018 23:00:28 +0800 Subject: [PATCH 9/9] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- src/main/java/me/skymc/taboolib/TabooLib.java | 20 ++++++++++++------- .../commands/taboolib/CycleInfoCommand.java | 2 +- .../commands/taboolib/CycleResetCommand.java | 2 +- .../commands/taboolib/CycleUpdateCommand.java | 2 +- .../commands/taboolib/ShellLoadCommand.java | 2 +- .../commands/taboolib/ShellUnloadCommand.java | 2 +- 7 files changed, 19 insertions(+), 13 deletions(-) diff --git a/pom.xml b/pom.xml index e89eeb8..59b125b 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ me.skymc TabooLib - 4.08 + 4.09 UTF-8 diff --git a/src/main/java/me/skymc/taboolib/TabooLib.java b/src/main/java/me/skymc/taboolib/TabooLib.java index 1e3c84c..9ae1e60 100644 --- a/src/main/java/me/skymc/taboolib/TabooLib.java +++ b/src/main/java/me/skymc/taboolib/TabooLib.java @@ -45,6 +45,10 @@ public class TabooLib { return Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; } + public static int getVersionNumber() { + return getVerint(); + } + public static String getServerUID() { if (!DataUtils.getPluginData("TabooLibrary", null).contains("serverUID")) { DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString()); @@ -56,20 +60,22 @@ public class TabooLib { DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString()); } + @Deprecated public static int getVerint() { - if (getVersion().startsWith("v1_7")) { + String version = getVersion(); + if (version.startsWith("v1_7")) { return 10700; - } else if (getVersion().startsWith("v1_8")) { + } else if (version.startsWith("v1_8")) { return 10800; - } else if (getVersion().startsWith("v1_9")) { + } else if (version.startsWith("v1_9")) { return 10900; - } else if (getVersion().startsWith("v1_10")) { + } else if (version.startsWith("v1_10")) { return 11000; - } else if (getVersion().startsWith("v1_11")) { + } else if (version.startsWith("v1_11")) { return 11100; - } else if (getVersion().startsWith("v1_12")) { + } else if (version.startsWith("v1_12")) { return 11200; - } else if (getVersion().startsWith("v1_13")) { + } else if (version.startsWith("v1_13")) { return 11300; } return 0; diff --git a/src/main/java/me/skymc/taboolib/commands/taboolib/CycleInfoCommand.java b/src/main/java/me/skymc/taboolib/commands/taboolib/CycleInfoCommand.java index 6ddacae..6307c0c 100644 --- a/src/main/java/me/skymc/taboolib/commands/taboolib/CycleInfoCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/taboolib/CycleInfoCommand.java @@ -13,7 +13,7 @@ public class CycleInfoCommand extends SubCommand { public CycleInfoCommand(CommandSender sender, String[] args) { super(sender, args); - if (args.length < 3) { + if (args.length < 2) { TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN"); return; } diff --git a/src/main/java/me/skymc/taboolib/commands/taboolib/CycleResetCommand.java b/src/main/java/me/skymc/taboolib/commands/taboolib/CycleResetCommand.java index 9816e72..5af4875 100644 --- a/src/main/java/me/skymc/taboolib/commands/taboolib/CycleResetCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/taboolib/CycleResetCommand.java @@ -16,7 +16,7 @@ public class CycleResetCommand extends SubCommand { public CycleResetCommand(CommandSender sender, String[] args) { super(sender, args); - if (args.length < 3) { + if (args.length < 2) { TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN"); return; } diff --git a/src/main/java/me/skymc/taboolib/commands/taboolib/CycleUpdateCommand.java b/src/main/java/me/skymc/taboolib/commands/taboolib/CycleUpdateCommand.java index ad646da..ad2ff66 100644 --- a/src/main/java/me/skymc/taboolib/commands/taboolib/CycleUpdateCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/taboolib/CycleUpdateCommand.java @@ -15,7 +15,7 @@ public class CycleUpdateCommand extends SubCommand { public CycleUpdateCommand(CommandSender sender, String[] args) { super(sender, args); - if (args.length < 3) { + if (args.length < 2) { TLocale.sendTo(sender, "COMMANDS.PARAMETER.UNKNOWN"); return; } diff --git a/src/main/java/me/skymc/taboolib/commands/taboolib/ShellLoadCommand.java b/src/main/java/me/skymc/taboolib/commands/taboolib/ShellLoadCommand.java index 3b82d16..d8e87eb 100644 --- a/src/main/java/me/skymc/taboolib/commands/taboolib/ShellLoadCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/taboolib/ShellLoadCommand.java @@ -11,7 +11,7 @@ public class ShellLoadCommand extends SubCommand { public ShellLoadCommand(CommandSender sender, String[] args) { super(sender, args); - if (args.length < 3) { + if (args.length < 2) { TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-NAME"); return; } diff --git a/src/main/java/me/skymc/taboolib/commands/taboolib/ShellUnloadCommand.java b/src/main/java/me/skymc/taboolib/commands/taboolib/ShellUnloadCommand.java index 17c7628..995ae2b 100644 --- a/src/main/java/me/skymc/taboolib/commands/taboolib/ShellUnloadCommand.java +++ b/src/main/java/me/skymc/taboolib/commands/taboolib/ShellUnloadCommand.java @@ -11,7 +11,7 @@ public class ShellUnloadCommand extends SubCommand { public ShellUnloadCommand(CommandSender sender, String[] args) { super(sender, args); - if (args.length < 3) { + if (args.length < 2) { TLocale.sendTo(sender, "COMMANDS.TABOOLIB.JAVASHELL.INVALID-NAME"); return; }