diff --git a/README.md b/README.md index 1017ab5..521dd1c 100644 --- a/README.md +++ b/README.md @@ -38,9 +38,9 @@ --- | 命令 | 作用 | 权限 | | --- | --- | --- | -| /tabooliblocale | 语言文件 | taboolib.admin | -| /taboolibplugin | 插件管理 | taboolib.admin | -| /taboolibexecute | 命令执行 | taboolib.admin | +| /tLocale | 语言文件 | taboolib.admin | +| /tPlugin | 插件管理 | taboolib.admin | +| /tExecute | 命令执行 | taboolib.admin |
diff --git a/build.gradle b/build.gradle index 270adef..cc8f684 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ plugins { id 'com.github.johnrengelman.shadow' version '4.0.4' } group = 'me.skymc' -version = '4.9' +version = '5.0' sourceCompatibility = 1.8 targetCompatibility = 1.8 @@ -28,14 +28,11 @@ dependencies { exclude(module: 'log4j') } compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.8' - shadow group: 'com.zaxxer', name: 'HikariCP', version: '3.1.0' - shadow group: 'org.javalite', name: 'activejdbc', version: '2.0' compile group: 'org.ow2.asm', name: 'asm', version: '7.0-beta' compile group: 'com.google.code.gson', name: 'gson', version: '2.7' - shadow group: 'com.h2database', name: 'h2', version: '1.4.197' - shadow group: 'me.clip', name: 'placeholderapi', version: '2.8.4' - shadow group: 'net.objecthunter', name: 'exp4j', version: '0.4.8' + shadow group: 'com.zaxxer', name: 'HikariCP', version: '3.1.0' shadow group: 'org.scala-lang', name: 'scala-library', version: '2.12.8' + shadow group: 'me.clip', name: 'placeholderapi', version: '2.8.4' shadow fileTree(dir: 'libs', includes: ['*.jar']) } @@ -48,11 +45,11 @@ processResources { inputs.property "version", project.version from(sourceSets.main.resources.srcDirs) { - include 'plugin.yml' + include 'version' expand 'version': project.version } from(sourceSets.main.resources.srcDirs) { - exclude 'plugin.yml' + exclude 'version' } } \ No newline at end of file diff --git a/cloud.json b/cloud.json deleted file mode 100644 index 9e71283..0000000 --- a/cloud.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "plugins": { - "TabooMenu": { - "author": [ - "Bkm016", - "filoghost" - ], - "description": "一款高自由,高效率,功能丰富的菜单插件。", - "detail": [ - "独创忽略大小写式节点判断", - "保留 ChestCommands 载入格式,更换插件直接复制文件", - "保留 ChestCommands 的大部分节点", - "保留 ChestCommands 的 51 项物品别名", - "保留 ChestCommands 的 cc 指令,直接更换也不会影响其他插件", - "更简单的物品坐标写法", - "更强大的指令功能,多达 7 种触发方式,17 种执行方式", - "更强大的物品扣除功能,多达 6 种检测方式", - "更直观的物品条件写法", - "更智能的菜单刷新方式", - "物品 ID 容错,智能匹配", - "关闭菜单时自动打开其他菜单", - "点击/查看物品时执行自定义脚本", - "PlaceholderAPI 支持。", - "独立权限控制", - "在线模板编辑", - "冷却时间", - "..." - ], - "version": "1.73", - "last_update": "2018-7-4", - "last_update_note": "修复优先级问题", - "link": "https://gitee.com/bkm016/TabooLibCloud/raw/master/plugins/TabooMenu.jar" - }, - "TabooScript": { - "author": [ - "lzzelAliz", - "Bkm016" - ], - "description": "告别 Java 开启奔放脚本时代。", - "detail": [ - "快速上手,写法自由,功能强大", - "超强 Bukkit 脚本拓展" - ], - "version": "1.3", - "last_update": "2018-10-1", - "last_update_note": "-", - "link": "https://gitee.com/bkm016/TabooLibCloud/raw/master/plugins/TabooScript.jar" - }, - "TabooLibBungeeSuite": { - "author": [ - "Bkm016" - ], - "description": "用于 BungeeCord 与 Bukkit 之间的快速交流工具。", - "detail": [ - "本插件为前置依赖无详细介绍" - ], - "version": "1.3", - "last_update": "2018-6-21", - "last_update_note": "-", - "link": "https://gitee.com/bkm016/TabooLibCloud/raw/master/plugins/TabooLibBungeeSuite.jar" - }, - "TabooSK": { - "author": [ - "Bkm016" - ], - "description": "Skript 扩展插件。", - "detail": [ - "计分板、配置文件、时间戳等高性能语法。" - ], - "version": "2.2", - "last_update": "2018-8-14", - "last_update_note": "更新了MythicMobs的物品获取语法", - "link": "https://gitee.com/bkm016/TabooLibCloud/raw/master/plugins/TabooSK.jar" - } - } -} \ No newline at end of file diff --git a/src/main/resources/Addons/TabooLibDeprecated b/src/main/resources/Addons/TabooLibDeprecated deleted file mode 100644 index e7a08a3..0000000 Binary files a/src/main/resources/Addons/TabooLibDeprecated and /dev/null differ diff --git a/src/main/resources/Language2/Language2.yml b/src/main/resources/Language2/Language2.yml deleted file mode 100644 index 06221ec..0000000 --- a/src/main/resources/Language2/Language2.yml +++ /dev/null @@ -1,125 +0,0 @@ -# UTF-8 - -# 错误代码: -# 0:语言文件不存在 -# 1:语言文本不存在 -# 10: 大标题语言类型识别异常 -# 11: 动作栏语言类型识别异常 -# 12: 动作栏重复次数异常 -# 20: JSON 空文本异常 -# 21: JSON 语言类型识别异常 -# 30: 大标题不兼容当前版本服务器 -# 31: 动作栏不兼容当前版本服务器 -# 40: 语言文件类型异常 -# 50: BOOK 语言类型指定 option 不存在 -# 51: BOOK 语言类型识别异常 -# 52: BOOK 语言类型 url 地址错误(http:// or https://) -# 60: JSON2 语言类型指定 option 不存在 -# 61: JSON2 语言类型识别异常 - -# 正常提示 -TEXT: '&f正常的提示' - -# 多行正常提示 -# 类型 [text] 可以省略不写 -TEXT-MULTI: -- '[text]' -- '&f正常的提示 - 1' -- '&f正常的提示 - 2' - -# JSON提示 + 占位符 -# 占位符注释需要追加到第一行类型末尾 -PAPI-TEXT: -- '[json][papi]' -- '&f变量提示, 玩家名称: %player_name%' - -# JSON提示 -JSON-NORMAL-TEXT: -- '[json]' -- '提示信息 - 1' -- ' text: 这是一个一般提示' - -# JSON提示 -JSON-COMMAND-TEXT: -- '[json]' -- '提示信息 - 2' -- ' text: 点击执行指令' -- ' command: /say %player% 牛逼' - -# JSON提示 -JSON-SUGGEST-TEXT: -- '[json]' -- '提示信息 - 3' -- ' text: 点击打印指令' -- ' suggest: /say %player% 牛逼' - -# JSON提示 -# [breka] 注释为 JSON 提示类型中的换行符 -JSON-MULTILINE-TEXT: -- '[json]' -- '提示信息 - 4' -- ' text: 这是一段换行提示1' -- '&a (单行追加内容)' -- '[break]' -- '提示信息 - 6' -- ' text: 这是一段换行提示3' -- '&a (单行追加内容)' - -# 大标题提示 -TITLE-TEXT: -- '[title]' -- ' title: 大标题' -- ' subtitle: 小标题' -- ' stay: 10|40|10' - -# 动作栏提示 -ACTION-TEXT: -- '[action]' -- ' text: 动作栏提示' -- ' repeat: 10' - -# 多类型混合 -TITLE-ACTION-TEXT: -- '[title]' -- ' title: 大标题' -- ' subtitle: 小标题' -- ' stay: 10|40|10' -- '[action]' -- ' text: 动作栏提示' -- ' repeat: 10' - -# 音效 + 文本提示 -SOUND-TEXT: -- '[text]' -- '单行文本 - 1' -- '单行文本 - 2' -- '[sound]' -- 'BLOCK_ANVIL_USE-1-1' - -# 书本界面 -BOOK-TEXT: -- '[book]' -- '书本单行文本' -- '&4书本单行文本' -- '&4&l书本单行文本' -- '[page]' -- '<@1>' -- '<@1> | <@1> 单行重复变量' -- '<@1> | <@2> 单行不同变量' -- '@option:1' -- ' text: 文本' -- ' command: 执行命令' -- ' showtext: 显示文本' -- '@option:2' -- ' text: 测试' -- ' command: 执行命令' -- ' showtext: 显示文本' - -# JSON2 -JSON-NEW: -- '[json2]' -- '新 <@1> 内容 - 1' -- '新 <@1> 内容 - 2' -- '@option:1' -- ' text: JSON' -- ' showtext: 展示文本' diff --git a/src/main/resources/Language2/zh_CN.yml b/src/main/resources/Language2/zh_CN.yml deleted file mode 100644 index 09527b0..0000000 --- a/src/main/resources/Language2/zh_CN.yml +++ /dev/null @@ -1,66 +0,0 @@ -COMMAND-ERROR: '&8[&3&lTLM&8] &4指令错误' -COMMAND-HELP: -- '' -- '&b&l----- &3&lTaooLibraryModule Commands &b&l-----' -- '' -- '&f /tlm kit list &6- &e列出所有礼包' -- '&f /tlm kit reward &8[&7名称] &8<&7名称&8> &6- &e领取礼包' -- '&f /tlm kit reset &8[&7名称] &8<&7玩家&8> &6- &e刷新礼包' -- '' -- '&f /tlm inv list &6- &e列出所有保存的背包' -- '&f /tlm inv info &8[&7名称] &6- &e查看保存背包' -- '&f /tlm inv save &8[&7名称] &6- &e保存当前背包' -- '&f /tlm inv paste &8[&7名称] &8<&7玩家&8> &8<&7-b|a&8> &6- &e覆盖背包' -- '&f /tlm inv delete &8[&7名称] &6- &e删除保存背包' -- '' -- '&f /tlm list &6- &e列出所有模块' -- '' -- '&f /tlm reload &8[&7模块名|TLM|ALL&8] &6- &e列出所有模块' -- '' - -# 3.58 增加 -NOPERMISSION-HELP: '&8[&3&lTLM&8] &4你没有权限列出帮助命令' -NOPERMISSION-LIST: '&8[&3&lTLM&8] &4你没有权限这么做' -NOPERMISSION-RELOAD: '&8[&3&lTLM&8] &4你没有权限这么做' -NOPERMISSION-KIT-REWARD: '&8[&3&lTLM&8] &4你没有权限这么做' -NOPERMISSION-KIT-RESET: '&8[&3&lTLM&8] &4你没有权限这么做' - -# 3.60 新增 -NOPERMISSION-KIT-LIST: '&8[&3&lTLM&8] &4你没有权限这么做' -NOPERMISSION-INV: '&8[&3&lTLM&8] &4你没有权限这么做' - -# 3.59 增加 -KIT-EMPTY: '&8[&3&lTLM&8] &4参数错误' -KIT-NAME: '&8[&3&lTLM&8] &4请输入正确的礼包名称' -KIT-DISABLE: '&8[&3&lTLM&8] &4该模块尚未在配置文件中启用' -KIT-NOTFOUND: '&8[&3&lTLM&8] &4礼包 &c$kit &4不存在' -KIT-OFFLINE: '&8[&3&lTLM&8] &4玩家 &c$name &4不在线' -KIT-CONSOLE: '&8[&3&lTLM&8] &4后台不允许输入这个指令' -KIT-COOLDOWN: '&8[&3&lTLM&8] &4礼包 &c$kit &4正在冷却中' -KIT-DISPOSABLE: '&8[&3&lTLM&8] &4礼包 &c$kit &4只能领取一次' -KIT-RESET-ALL: '&8[&3&lTLM&8] &7礼包 &f$kit &7已刷新' -KIT-RESET-PLAYER: '&8[&3&lTLM&8] &7玩家 &f$player &7的礼包 &f$kit &7已刷新' -KIT-SUCCESS: '&8[&3&lTLM&8] &7礼包 &f$kit &7已领取' -KIT-PLACEHOLDER: - 0: '&4模块未启用' - 1: '&4礼包不存在' - 2: '&8已领取' - 3: '&a可领取' - 4: '&4冷却中' - 5: '&4无权限' - -# 3.60 新增 -KIT-LIST: '&8[&3&lTLM&8] &7当前礼包: &f$kits' - -# 3.60 增加 -INV-EMPTY: '&8[&3&lTLM&8] &4参数错误' -INV-DISABLE: '&8[&3&lTLM&8] &4该模块尚未在配置文件中启用' -INV-CONSOLE: '&8[&3&lTLM&8] &4该命令不允许控制台执行' -INV-NAME: '&8[&3&lTLM&8] &4请输入正确的背包名称' -INV-LIST: '&8[&3&lTLM&8] &7当前已保存背包: &f$name' -INV-NOTFOUND: '&8[&3&lTLM&8] &4背包 &c$name &4不存在' -INV-INFO-TITLE: '背包信息: $name' -INV-SAVE: '&8[&3&lTLM&8] &7背包 &f$name &7已保存!' -INV-OFFLINE: '&8[&3&lTLM&8] &4玩家 &c$name &4不在线' -INV-PASTE: '&8[&3&lTLM&8] &7背包 &f$name &7已覆盖到玩家 &f$player&7!' -INV-DELETE: '&8[&3&lTLM&8] &4背包 &c$name &4已删除' \ No newline at end of file diff --git a/src/main/resources/TLM/CommandChanger.yml b/src/main/resources/TLM/CommandChanger.yml deleted file mode 100644 index 353fbeb..0000000 --- a/src/main/resources/TLM/CommandChanger.yml +++ /dev/null @@ -1,14 +0,0 @@ -# 指令配置 -Commands: - # 配置序号(不可重复) - test: - # 输入命令 - Input: '/kit' - # 替换命令 - Replace: '/tlm kit' - # 替换模式(省略默认全部) - # ---------- # - # CONSOLE = 后台 - # PLAYER = 玩家 - # ---------- # - ReplaceMode: 'PLAYER' \ No newline at end of file diff --git a/src/main/resources/TLM/Kits.yml b/src/main/resources/TLM/Kits.yml deleted file mode 100644 index 00d7e81..0000000 --- a/src/main/resources/TLM/Kits.yml +++ /dev/null @@ -1,34 +0,0 @@ -# 礼包配置 -Kits: - # 礼包名 - kit_name: - # 礼包刷新时间 - # ---------- # - # 1d = 1天 - # 1h = 1小时 - # 1m = 1分钟 - # 1s = 1秒钟 - # 时间之间用 ";" 分隔, 例如 1小时30分钟 = "1h;30m" - # ---------- # - Cooldown: '1d' - - # 背包空间不足时物品是否掉落 - FullDrop: true - - # 是否只能领取一次 - Disposable: false - - # 礼包领取权限 - Permission: 'taboolib.kit.kit_name' - - # 礼包领取权限提示 - Permission-message: '&4你没有权限领取这个礼包' - - # 礼包内容 - # 空格左侧为物品名,右侧为物品数量 - Items: - - 'UnlimitSword 1' - - # 礼包命令 - Commands: - - 'say $player 领取了礼包 kit_name!' \ No newline at end of file diff --git a/src/main/resources/TLM/TimeCycle.yml b/src/main/resources/TLM/TimeCycle.yml deleted file mode 100644 index 6a4e5a8..0000000 --- a/src/main/resources/TLM/TimeCycle.yml +++ /dev/null @@ -1,35 +0,0 @@ -# 时间检查器 -TimeCycle: - # 检查器名称 - cycle_name: - # 检查器周期 - # ---------- # - # 1d = 1天 - # 1h = 1小时 - # 1m = 1分钟 - # 1s = 1秒钟 - # 时间之间用 ";" 分隔, 例如 1小时30分钟 = "1h;30m" - # ---------- # - Cycle: '1d' - - # 更新配置 - UpdateCommand: - - 'say 检查器 cycle_name 更新!' - - # 初始化配置 - Initialise: - # 初始化时间 - # 特殊时间 - # - DAY_OF_WEEK = 本周第几天 (最小:1) - # - DAY_OF_MONTH = 本月第几天 (最小:1) - InitialiseDate: - # 初始化时将小时设置为 0 - - 'HOUR_OF_DAY=0' - # 初始化时将分钟设置为 0 - - 'MINUTE=0' - # 初始化时将秒钟设置为 0 - - 'SECOND=0' - - # 初始化命令 - InitialiseCommand: - - 'say 检查器 cycle_name 初始化完成!' \ No newline at end of file diff --git a/src/main/resources/bungee.yml b/src/main/resources/bungee.yml deleted file mode 100644 index 1ac27bb..0000000 --- a/src/main/resources/bungee.yml +++ /dev/null @@ -1,5 +0,0 @@ -name: TabooLib -main: me.skymc.taboolib.bungee.TabooLibBungee -version: ${project.version} - -author: [lzzelAliz, 坏黑] \ No newline at end of file diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml deleted file mode 100644 index 24aa81e..0000000 --- a/src/main/resources/config.yml +++ /dev/null @@ -1,98 +0,0 @@ -# 权限不足时提示 -NO-PERMISSION-MESSAGE: '&f&l(&4&l?&f&l) &c你没有权利这么做' -# 不满足条件时提示 -NO-CLAIM-MESSAGE: '&f&l(&4&l?&f&l) &c你现在还不能这么做 &7(%s%&7)' - -# 数据储存地址 -# 该配置将在启用数据库储存时失效 -DATAURL: - # 玩家数据 - PLAYER-DATA: 'plugins/TabooLib/playerdata/' - # 插件数据 - SERVER-DATA: 'plugins/TabooLib/serverdata/' - # 物品数据(来自 ItemSave 插件) - ITEMDIR: 'plugins/Skript/scripts/config/item.yml' - -# 语言文件相关设置 -LOCALE: - # 加载语言文件的顺序 - PRIORITY: - - zh_CN - - en_US - # 默认是否启用语言文件中 PlaceholderAPI 的替换功能 - # 关闭可提升性能 - # 如果需要开启仍然可以在语言文件中加入 papi: true - USE_PAPI: false - -# 是否注入 PluginManager,关闭后可能会导致部分功能出错。 -PLUGIN-INJECTOR: - ENABLE: true - # 检测下面的插件并自动关闭注入 - DISABLE-ON-PLUGIN-EXISTS: - - LuckPerms - -# 是否在当前服务器启用交流网终端 -# 启用后将会收到大量调试信息, 不建议使用 -SERVER: false - -# 网络连接测试地址 -TEST-URL: 'aliyun.com' - -# 玩家列表(TAB-API)是否根据前缀排序 -TABLIST-SORT: true - -# 玩家列表(TAB-API)是否自动清理没有成员的队伍 -TABLIST-AUTO-CLEAN-TEAM: true - -# 是否启用发包(禁用后会影响 tagDisplay() 方法的使用) -TABLIST-PACKET: true - -# 是否启用更新检测 -UPDATE-CHECK: true - -# 是否启用自动更新 -UPDATE-DOWNLOAD: false - -# 是否启用附属插件异常拦截 -EXCEPTION-MIRROR: true - -# 是否在关闭服务器时清理玩家数据 -# 该配置将在启用数据库储存时失效 -DELETE-DATA: false - -# 是否在服务器关闭时清理无效变量 -# 该配置仅在启用数据库储存时有效 -# 该方法可能会导致数据丢失? -# 不建议开启 -DELETE-VARIABLE: false - -# 是否以 UUID 的形式创建玩家数据 -# 不建议开启!除非用 TabooLib 储存的插件支持新版储存方式! -ENABLE-UUID: false - -# 是否隐藏保存数据的提示 -HIDE-NOTIFY: true - -# 数据库信息 -# 该功能在当前版本下无法使用,请勿启用 -MYSQL: - # 是否启用数据库 - ENABLE: false - # 数据库地址 - HOST: 'localhost' - # 数据库端口 - PORT: 3306 - # 数据库用户 - USER: root - # 数据库密码 - PASSWORD: '' - # 数据库名称 - DATABASE: 'test' - # 数据表前缀 - PREFIX: 'taboolib' - -# 全局变量信息 -PluginData: - # 检查更新间隔(单位:秒) - # 检查变量是否被其他服务器更新 - CHECK-DELAY: 5 \ No newline at end of file diff --git a/src/main/resources/hikarisettings.yml b/src/main/resources/datasource.yml similarity index 100% rename from src/main/resources/hikarisettings.yml rename to src/main/resources/datasource.yml diff --git a/src/main/resources/items.yml b/src/main/resources/items.yml deleted file mode 100644 index 665d8f2..0000000 --- a/src/main/resources/items.yml +++ /dev/null @@ -1,51 +0,0 @@ -UnlimitSword: - material: DIAMOND_SWORD - name: '&b&nUnlimitSword' - lore: - - '' - - '&8&oAn sword of infinitely durable' - - '&8&oAnd hide attributes lore' - - '' - flags: - - HIDE_ATTRIBUTES - nbt: - Unbreakable: 1 - -ColorLeather: - material: LEATHER_CHESTPLATE - name: '&aLe&2at&3he&4r C&5he&6st&7pl&8at&9e' - lore: - - '' - - '&8&oA chestplate of colored' - - '&8&oAnd enchanted with &7DURABILITY I' - - '' - enchants: - DURABILITY: 1 - color: 255-0-0 - -SpeedPotion: - material: POTION - name: '&1&nSpeed Potion' - lore: - - '' - - '&8&oA potion of &7SPEED I' - - '&8&oAnd not have Particles' - - '' - potions: - SPEED: 200-5 - -KingsAxe: - material: GOLD_AXE - name: '&e&nKingsAxe' - lore: - - '' - - '&6&o100 damage !!!' - - '&6&o30% speed !!!' - - '' - - '&e&oA knife a pupil !!!' - - '' - attributes: - mainhand: - damage: 100 - speed: 30% - \ No newline at end of file diff --git a/src/main/resources/lang/internal.yml b/src/main/resources/lang/internal.yml index fb41bc9..3a1f124 100644 --- a/src/main/resources/lang/internal.yml +++ b/src/main/resources/lang/internal.yml @@ -1,8 +1,7 @@ -TRY-LOADING-LANG: '插件 {0} 尝试加载 {1} 作为语言文件' -SUCCESS-LOADING-LANG-NORMAL: '成功加载 {0} 插件的 {1} 语言文件, 共 {2} 项' -SUCCESS-LOADING-LANG-UPDATE: '成功加载 {0} 插件的 {1} 语言文件, 共 {2} 项, 及 {3} 项新条目' +TRY-LOADING-LANG: '尝试为 {0} 加载 {1} 语言文件' +SUCCESS-LOADING-LANG-NORMAL: '成功为 {0} 加载 {1} 语言文件, 共 {2} 项' +SUCCESS-LOADING-LANG-UPDATE: '成功为 {0} 加载 {1} 语言文件, 共 {2} 项, 及 {3} 项新条目' ERROR-LOADING-LANG: '加载 {0} 插件的语言文件时发生异常:{1}' -RELOADING-LANG: '正在重新载入 {0} 插件的语言文件' FETCH-LOCALE-ERROR: '语言文件获取失败:{0}' SEND-LOCALE-ERROR: '语言文件发送失败:{0}' LOCALE-ERROR-REASON: '原因:{0}' diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 0be6abc..55f73af 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -1,21 +1,3 @@ -TLIB: - INJECTION-SUCCESS: '注入成功' - INJECTION-FAILED: - - '注入失败' - - '&c提前加载依赖于 TabooLib 的所有插件的相关功能' - INJECTION-DISABLED: - - '关闭注入' - - '&c提前加载依赖于 TabooLib 的所有插件的相关功能' - LOAD-FAIL-OFFLINE: - - '**********************************************' - - '** TabooLib-{0} 无法在您的服务器上使用' - - '**' - - '** 您的服务器尚未连接互联网导致本插件无法正常载入' - - '** 请使用离线版本或是手动下载依赖库文件' - - '**' - - '** 详情查阅: https://github.com/Bkm016/TabooLib' - - '**********************************************' - DEPENDENCY: DOWNLOAD-OFFLINE: '已启用离线模式, 将不会下载第三方依赖库' DOWNLOAD-CONNECTED: ' 正在下载 {0} 大小 {1}' @@ -27,38 +9,7 @@ DEPENDENCY: PLUGIN-AUTOLOAD-FAIL: '{0} 所依赖的插件 {1} 尝试自动加载失败,请尝试手动下载' PLUGIN-LOAD-SUCCESS: ' {0} 请求的插件 {1} 加载成功' PLUGIN-LOAD-FAIL: ' {0} 请求的插件 {1} 加载失败' - LOADING-START: '正在加载 {0} 插件所需的依赖' -# LIBRARY-LOAD-SUCCESS: ' {0} 请求的库文件 {1} 加载成功' LIBRARY-LOAD-FAIL: ' {0} 请求的库文件 {1} 加载失败' - LOAD-COMPLETE: '依赖加载完成' -# LOAD-CLASSES: '&7缓存 &f{0} &7插件的 &f{1} &7个类耗时&f {2} &7毫秒.' - -CONFIG: - LOAD-FAIL-NO-ANNOTATION: '插件 {0} 的配置类 {1} 加载失败:没有 @Config 注解' - LOAD-FAIL: '插件 {0} 的配置类 {1} 加载失败:没有 @Config 注解' - LOAD-FAIL-NO-FILE: '插件 {0} 的配置类 {1} 加载失败:没有 @Config 注解或文件不存在' - LOAD-SUCCESS: '插件 {0} 的 {1} 配置文件成功加载' - SAVE-FAIL-NO-ANNOTATION: '插件 {0} 的配置类 {1} 序列化失败:没有 @Config 注解' - SAVE-FAIL: '插件 {0} 的配置类 {1} 加载失败:没有 @Config 注解' - SAVE-SUCCESS: '插件 {0} 的配置 {1} 已保存' - RELOAD-SUCCESS: '插件 {0} 的配置 {1} 成功重载' - RELOAD-FAIL: '插件 {0} 的配置 {1} 成功重载' - LISTEN-START: '开始监听 {0} 插件的 {1} 配置文件' - -NOTIFY: - ERROR-SERVER-KEY: '&4检测到本服序列号与其他服务器相同, 已重新生成!' - ERROR-CONNECTION-FAIL: '&4数据库连接失败, 请检查配置是否正确!' - SUCCESS-LOADED: - - '§7插件载入完成!' - - '§7插件作者: §f{0}' - - '§7插件版本: §f{1}' - - '§7游戏版本: §f{2}' - SUCCESS-DISABLE: - - '&c插件已卸载, 感谢您使用&4禁忌书库' - - '&c插件作者: &4坏黑' - FAIL-DISABLE: - - '&c插件尚未启动完成, 已跳过卸载代码' - - '&c插件作者: &4坏黑' LOCALE: TITLE-SEND-TO-NON-PLAYER: '该语言类型只能发送给玩家:{0}' @@ -74,27 +25,10 @@ MISC: FIELD-COPY-FAILED: '拷贝 {0} 对象失败' FIELD-COPY-ERROR: '拷贝 {0} 对象出错:{1}' -#COOLDOWNPACK: -# PACK-REGISTER: '注册冷却包: {0}, 时间: {1} 秒 ({2})' -# PACK-REGISTER-ANONYMOUS: '注册冷却包: {0}, 时间: {1} 秒 (匿名注册)' -# PACK-UNREGISTER: '注销冷却包: {0} (主动注销)' -# PACK-UNREGISTER-AUTO: '注销冷却包: {0} (自动注销)' - -GLOBAL-DATAMANAGER: - ERROR-CHECK-VARIABLE: '&4变量 &c{0} &4载入异常: &c{1}' - SUCCESS-LOADED-VARIABLE: '&7从数据库中获取 &f{0} &7个变量, 耗时: &f{1} &7(ms)' - PLAYER-DATAMANAGER: - ERROR-STORAGE-SQL: '不允许在储存模式为数据库的情况下获取离线玩家数据' ERROR-PLAYER-DATA: '&4玩家 &c{0} &4的数据载入出现异常: &c{1}' SUCCESS-SAVE-DATA: '&7保存 &f{0} &7条玩家数据, 耗时: &f{1} &7(ms)' -ENTITY-UTILS: - NOTFOUND-PROTOCOLLIB: '缺少前置插件 ProtocolLib' - -FILE-UTILS: - FAIL-LOAD-CONFIGURATION: '&4配置文件载入失败!, 插件: &c{0}&4, 文件: &c{1}' - DATA-UTILS: SUCCESS-SAVE-DATA: '&7保存 &f{0} &7条插件数据, 耗时: &f{1} &7(ms)' FAIL-SAVE-FILE: '&4文件 &c{0}&4 保存失败, 原因: &c{1}' @@ -106,53 +40,14 @@ ITEM-UTILS: FAIL-LOAD-POTION: '&c{0} &4不是一个有效的药水名称, 输入 &c/tlib potions&4 查看所有药水' FAIL-LOAD-FLAG: '&c{0} &4不是一个有效的标签名称, 输入 &c/tlib flags&4 查看所有标签' FAIL-SAVE-EXISTS: '无法载入载入物品 &4{0}&c, 因为它已经存在了' -# SUCCESS-LOAD-CACHES: '&7载入 &f{0} &7项缓存物品' -# SUCCESS-LOAD-NAMES: '&7载入 &f{0} &7项物品名称' EMPTY-ITEM: '空' -LANGUAGE2: - FAIL-NOTFOUND-FILE: '语言文件 {0} 不存在' - -TIMECYCLE: - FAIL-CYCLE-EXISTS: '注册周期管理器 &8{0}&c 失败, 原因: &4名称重复' - -UPDATETASK: - VERSION-FAIL: '&4更新记录获取失败, 请检查网络连接!' - VERSION-LATEST: '&7插件已是最新版, 无需更新!' - VERSION-OUTDATED: - - '&8####################################################' - - '&7 检测到有新的版本更新!' - - '&7 当前版本: &f{0}' - - '&7 最新版本: &f{1}' - - '&7 下载地址: &fhttp://www.mcbbs.net/thread-773065-1-1.html' - - '&7 开源地址: &fhttps://github.com/Bkm016/TabooLib/' - - '&8####################################################' - -MYSQL-CONNECTION: - FAIL-CONNECT: '&4数据库 &c{0} &4连接失败, 原因: &c{0}' - FAIL-NOTFOUND-DRIVE: '&7驱动器获取失败, 无法连接到数据库' - FAIL-NOTFOUND-CONNECTION: '&7警告! 数据库尚未连接, 请检查配置文件后重启服务器! ({0})' - FAIL-COMMAND-NORMAL: '&4数据库命令执行出错, 错误原因: &c{0}' - FAIL-COMMAND-DETAIL: '&4数据库命令执行出错, 错误代码: &c{0}&4, 错误原因: &c{1}' - FAIL-EXECUTE-TASK: '异步任务失败, 执行方式改为同步执行' - SUCCESS-REGISTERED: '&7插件 &f{0}&7 注册新的数据库连接' - SUCCESS-REGISTERED-EXISTS: '&7插件 &f{0}&7 引用插件 &f{1}&7 注册的数据库连接' - SUCCESS-REGISTERED-LISTENER: '&7启动数据库连接监控' - SUCCESS-CONNECTION-CANCEL: '已停止插件 &f{0}&7 的 &f{1}&7 条数据库连接' - NOTIFY-CONNECTING: '&7正在连接数据库, 地址: &f{0}' - NOTIFY-CONNECTED: '&7数据库连接成功 ({0}ms)' - MYSQL-HIKARI: CREATE-SUCCESS: '&7插件 &f{0}&7 注册新的数据库连接: &f{1}' CREATE-EXISTS: '&7插件 &f{0}&7 引用插件 &f{1}&7 注册的数据库连接' CLOSE-SUCCESS: '&7插件 &f{0} &7注册的数据库连接 &f{1} &7已被注销!' CLOSE-FAIL: '&7插件 &f{0} &7注册的数据库连接正在被 &f{1} &7个插件使用, 无法注销!' -TABOOLIB-MODULE: - SUCCESS-LOADED: '&7载入 &f{0} &7个 &fTLM &7模块' - FAIL-LOADED: '&4模块载入异常: &c{0}&4, 模块: &c{1}&4, 位于: &c{2}' - FAIL-RUNTIME: '&4模块运行异常: &c{0}&4, 模块: &c{1}&4, 位于: &c{2}' - COMMANDS: GLOBAL: ONLY-PLAYER: '&8[&3&lTabooLib&8] &4控制台无法这么做' @@ -169,9 +64,7 @@ COMMANDS: - '&8[&3&lTabooLib&8] &7指令 &f{0} &7不存在' - '&8[&3&lTabooLib&8] &7你可能想要:' - '&8[&3&lTabooLib&8] &7{1}' - COMMAND-CREATE-FAILED: '&7插件 &f{0} &7的 &f{1} &7命令注册失败: &c{2}' -# COMMAND-CREATE: '&7自动为插件 &f{0} &7的 &f{1} &7命令注册到服务器' -# COMMAND-REGISTER: '&7自动为插件 &f{0} &7的 &f{1} &7命令注册 &f{2} &7条子命令' + COMMAND-CREATE-FAILED: '&c插件 &7{0} &c的 &7{1} &c命令注册失败: &7{2}' COMMAND-HELP: ' §f/{0} {1} {2}§6- §e{3}' COMMAND-HELP-EMPTY: ' §f/{0} {1} {2}' COMMAND-ARGUMENT: '§7<§8{0}§7>' @@ -179,285 +72,6 @@ COMMANDS: PARAMETER: UNKNOWN: '&8[&3&lTabooLib&8] &4指令错误' INSUFFICIENT: '&8[&3&lTabooLib&8] &4参数不足' - RELOAD: - LOADING: '&8[&3&lTabooLib&8] &7重载中...' - SUCCESS-NORMAL: '&8[&3&lTabooLib&8] &7重载成功' - SUCCESS-ELAPSED-TIME: '&8[&3&lTabooLib&8] &7重载成功, 耗时: &f{0} ms' - TABOOLIB: - COMMAND-TITLE: '&e&l----- &6&lTabooLib Commands &e&l-----' - SAVE: - DESCRIPTION: '载入插件' - ARGUMENTS: - 0: '名称' - INVALID-NAME: '&8[&3&lTabooLib&8] &4请输入正确的名称' - INVALID-ITEM: '&8[&3&lTabooLib&8] &4请手持正确的物品' - INVALID-ITEM-FINAL-EXISTS: '&8[&3&lTabooLib&8] &4该名称所对应的物品保存于固定物品库中, 无法覆盖' - GUIDE-EXISTS: '&8[&3&lTabooLib&8] &4你有一个正在进行的聊天引导, 请完成后在这么做' - GUIDE-BEFORE: '&8[&3&lTabooLib&8] &7物品 &f{0}&7 已存在, 如果你想要覆盖它, 请在聊天框中输入 "&fYES&7"' - GUIDE-QUIT: '&8[&3&lTabooLib&8] &7退出引导' - SUCCESS: '&8[&3&lTabooLib&8] &7物品 &f{0} &7已替换' - ITEM: - DESCRIPTION: '给予玩家物品' - ARGUMENTS: - 0: '名称' - 1: '玩家' - 2: '数量' - INVALID-NAME: '&8[&3&lTabooLib&8] &4请输入正确的名称' - INVALID-ITEM: '&8[&3&lTabooLib&8] &4物品 &c{0} &4不存在' - INVALID-PLAYER: '&8[&3&lTabooLib&8] &4玩家 &c{0} &4不在线' - INVALID-NUMBER: '&8[&3&lTabooLib&8] &4数量必须大于0' - SUCCESS: '&8[&3&lTabooLib&8] &7物品已发送至玩家 &f{0} &7的背包中' - ITEMRELOAD: - DESCRIPTION: '重载物品缓存' - SUCCESS-RELOAD: '&8[&3&lTabooLib&8] &7重载成功' - VARIABLE: - DESCRIPTION: - GET: '查看变量' - SET: '设置变量' - ARGUMENTS: - GET: - 0: '-s|-a' - 1: '键' - SET: - 0: '-s|-a' - 1: '键' - 2: '值' - WRITE-ERROR-TYPE: '&8[&3&lTabooLib&8] &4请输入正确的写入方式: &c-s&4、&c-a' - WRITE-SUCCESS: '&8[&3&lTabooLib&8] &7写入完成, 耗时: &f{0} &7(ms)' - READ-ERROR-TYPE: '&8[&3&lTabooLib&8] &4请输入正确的写入方式: &c-s&4、&c-a' - READ-RESULT: '&8[&3&lTabooLib&8] &7变量 &f{0} &7的值为: &f{1}' - READ-SUCCESS: '&8[&3&lTabooLib&8] &7写入完成, 耗时: &f{0} &7(ms)' - IMPORTDATA: - DESCRIPTION: '&4向数据库导入本地数据 &8(该操作将会清空数据库)' - CLEARING: '&8[&3&lTabooLib&8] &7正在清空数据库...' - EMPTYDATA: '&8[&3&lTabooLib&8] &4没有玩家数据可以导入' - 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-FOUND-SIZE: '&8[&3&lTabooLib&8] &4文件长度获取失败.' - UPDATE-NOT-SUPPORT: '&8[&3&lTabooLib&8] &4您的服务器不支持在线更新!' - UPDATE-SUCCESS: '&8[&3&lTabooLib&8] &7最新版下载完成, 服务器即将重启!' - UPDATE-FAILED: '&8[&3&lTabooLib&8] &4最新版下载失败.' - FILE-NOT-FOUND: '&8[&3&lTabooLib&8] &4尚未寻找到插件文件.' - PLAYER-ONLINE: '&8[&3&lTabooLib&8] &4服务器有玩家在线无法更新插件.' - ARGUMENTS: - 0: '-f' - PLAYERTAG: - DESCRIPTION: - DISPLAY: '设置玩家展示名称' - PREFIX: '设置玩家头顶前缀' - SUFFIX: '设置玩家头顶后缀' - DELETE: '删除玩家称号数据' - ARGUMENTS: - DISPLAY: - 0: '玩家' - 1: '文本' - PREFIX: - 0: '玩家' - 1: '文本' - SUFFIX: - 0: '玩家' - 1: '文本' - DELETE: - 0: '玩家' - INVALID-PLAYER: '&8[&3&lTabooLib&8] &4玩家 &c{0} &4不在线' - SUCCESS-DISPLAY-SET: '&8[&3&lTabooLib&8] &7设置玩家 &f{0} &7的名称为 &f{1}' - SUCCESS-PREFIX-SET: '&8[&3&lTabooLib&8] &7设置玩家 &f{0} &7的前缀为 &f{1}' - SUCCESS-SUFFIX-SET: '&8[&3&lTabooLib&8] &7设置玩家 &f{0} &7的后缀为 &f{1}' - SUCCESS-DELETE: '&8[&3&lTabooLib&8] &7删除玩家 &f{0} &7的称号数据' - LAGSERVER: - DESCRIPTION: '休眠主线程' - ARGUMENTS: - 0: '毫秒' - INVALID-TIME: '&8[&3&lTabooLib&8] &4休眠时间不可超过 &c30000 &4毫秒' - START: '&8[&3&lTabooLib&8] &7线程休眠开始.' - STOP: '&8[&3&lTabooLib&8] &7线程休眠结束.' - INFO: - DESCRIPTION: '查看物品信息' - INVALID-ITEM: '&8[&3&lTabooLib&8] &4请手持正确的物品' - ITEM-INFO: - - ==: JSON - text: - - '' - - '&b&l----- &3&lItemStack Info &b&l-----' - - '' - - '&7 - 物品材质: &f<{0}@type>' - - '&7 - 物品名称: &f<{1}@name>' - - '&7 - 物品序号: &f<{2}@id>' - - '&7 - 物品数据: &f' - - '' - args: - type: - hover: '&f点击复制' - suggest: '{0}' - name: - hover: '&f点击复制' - suggest: '{1}' - id: - hover: '&f点击复制' - suggest: '{2}' - nbt: - hover: '{3}' - ITEMLIST: - DESCRIPTION: '查看所有物品' - MENU: - TITLE: '物品库 {0}' - NEXT: '&f上一页' - BACK: '&f下一页' - LORE: - - '' - - '&f&m ' - - '&f序列号: &8{0}' - SOUNDS: - DESCRIPTION: '查看所有音效' - MENU: - TITLE: '音效库 {0}' - NEXT: '&f上一页' - BACK: '&f下一页' - LORE: - - '' - - '&fQ键: &70 音调' - - '&f左键: &71 音调' - - '&f右键: &72 音调' - - '&f中键: &7复制名称' - RESULT: - SEARCH: - - '&7查询名称: &f{0}' - - '&7查询结果: &f{1}' - COPY: - - ==: JSON - text: '&7点击复制: <&f&n{0}@sound>' - args: - sound: - hover: 点击复制音效 - suggest: '{0}' - TIMECYCLE: - DESCRIPTION: - LIST: '列出所有时间检查器' - INFO: '查询检查器信息' - RESET: '初始化时间检查器' - UPDATE: '更新时间检查器' - ARGUMENTS: - INFO: - 0: '名称' - RESET: - 0: '名称' - UPDATE: - 0: '名称' - INVALID-CYCLE: '&8[&3&lTabooLib&8] &4检查器 &c{0} &4不存在' - CYCLE-UPDATE: '&8[&3&lTabooLib&8] &7检查器 &f{0} &7已更新' - CYCLE-RESET: '&8[&3&lTabooLib&8] &7检查器 &f{0} &7初始化完成' - CYCLE-INFO: - - '' - - '&b&l----- &3&lTimeCycle Info &b&l-----' - - '' - - ' &f- &7注册周期: &f{0}' - - ' &f- &7注册插件: &f{1}' - - ' &f- &7上次刷新时间: &f{2}' - - ' &f- &7下次刷新时间: &f{3}' - - '' - LIST: - HEAD: - - '' - - '&b&l----- &3&lTimeCycle List &b&l-----' - - '' - BODY: - - ==: JSON - text: ' &7- &f{0} <&8(点击复制)@copy>' - args: - copy: - hover: '&f点击复制' - suggest: '{0}' - FOOT: - - '' - ATTRIBUTES: - DESCRIPTION: '查看所有属性' - HEAD: - - '' - - '&b&l----- &3&lItemStack Attributes &b&l-----' - - '' - BODY: - - ==: JSON - text: ' &7- &f{0} <&8(点击复制)@copy>' - args: - copy: - hover: '&f点击复制' - suggest: '{0}' - FOOT: - - '' - ENCHANTS: - DESCRIPTION: '查看所有附魔' - HEAD: - - '' - - '&b&l----- &3&lItemStack Enchantments &b&l-----' - - '' - BODY: - - ==: JSON - text: ' &7- &f{0}. {1} <&8(点击复制)@copy>' - args: - copy: - hover: '&f点击复制' - suggest: '{1}' - FOOT: - - '' - POTIONS: - DESCRIPTION: '查看所有药水' - HEAD: - - '' - - '&b&l----- &3&lItemStack PotionEffects &b&l-----' - - '' - BODY: - - ==: JSON - text: ' &7- &f{0}. {1} <&8(点击复制)@copy>' - args: - copy: - hover: '&f点击复制' - suggest: '{1}' - FOOT: - - '' - FLAGS: - DESCRIPTION: '查看所有标签' - HEAD: - - '' - - '&b&l----- &3&lItemStack Flags &b&l-----' - - '' - BODY: - - ==: JSON - text: ' &7- &f{0} <&8(点击复制)@copy>' - args: - copy: - hover: '&f点击复制' - suggest: '{0}' - FOOT: - - '' - SLOTS: - DESCRIPTION: '查看所有部位' - HEAD: - - '' - - '&b&l----- &3&lItemStack Slots &b&l-----' - - '' - BODY: - - ==: JSON - text: ' &7- &f{0} <&8(点击复制)@copy>' - args: - copy: - hover: '&f点击复制' - suggest: '{0}' - FOOT: - - '' - LANGUAGE2: - INVALID-PLAYER: '&8[&3&lTabooLib&8] &4玩家 &c{0} &4不在线' - SUCCESS-SEND: '&8[&3&lTabooLib&8] &7信息已发送, 耗时&f: {0}' - HELP: - - '' - - '&e&l----- &6&lLanguage2 Commands &e&l-----' - - '' - - '&f /{0} send &8[&7玩家/ALL&8] &8[&7语言&8] &8<&7变量&8> &6- &e发送语言提示' - - '&f /{0} reload &6- &e重载语言库' - - '' TLOCALE: COMMAND-TITLE: '&e&l----- &6&lTabooLibLoacle Commands &e&l-----' SEND: @@ -517,15 +131,6 @@ COMMANDS: INVALID-PLUGIN: '&8[&3&lTabooLib&8] &4插件 &c{0} &4不存在' INVALID-PLUGIN-IGNORED: '&8[&3&lTabooLib&8] &4插件 &c{0} &4无法操作' TRY-RELOAD: '&8[&3&lTabooLib&8] &7尝试重载插件...' - TRANSLATE-UUID: - COMMAND-TITLE: '&e&l----- &6&lTranslateUUID Commands &e&l-----' - IMPORTLOCAL: - DESCRIPTION: '导入本地数据到数据库' - DISABLED: '&8[&3&lTabooLib&8] &4该功能尚未启用' - SUCCESS: '&8[&3&lTabooLib&8] &7请求已发送, 详细信息请查看控制台' - RELOAD: - DESCRIPTION: '重载配置及数据库' - SUCCESS: '&8[&3&lTabooLib&8] &7请求已发送, 详细信息请查看控制台' TEXECUTE: COMMAND-TITLE: '&e&l----- &6&lTabooLibExecute Commands &e&l-----' CHAT: @@ -566,81 +171,6 @@ COMMANDS: 0: '目录' 1: '内容' SUCCESS: '&8[&3&lTabooLib&8] &7写入完成.' - TCLOUD: - COMMAND-TITLE: '&e&l----- &6&lTabooLibCloud Commands &e&l-----' - REFRESH: - DESCRIPTION: '刷新扩展列表' - SUCCESS: '&8[&3&lTabooLib&8] &7请求已发送. &8(详细信息请在控制台查看)' - STATUS: - DESCRIPTION: '查看扩展统计' - STATUS: - - '&8[&3&lTabooLib&8] &7当前总共 &f{0} &7项扩展被 &fTCLOUD &7录入, 其中包含:' - - '&8[&3&lTabooLib&8] &7内置扩展 &f{1} &7项' - - '&8[&3&lTabooLib&8] &7插件扩展 &f{2} &7项' - CONNECT-FAILED: '&8[&3&lTabooLib&8] &c尚未获取扩展列表.' - INFO: - DESCRIPTION: '查看扩展信息' - ARGUMENTS: - 0: '名称' - EXPANSION-NOT-FOUND: '&8[&3&lTabooLib&8] &c扩展 &4{0} &c不存在.' - EXPANSION-INFO: - - '&8[&3&lTabooLib&8] &7扩展 &f{0} &7信息:' - - '&8[&3&lTabooLib&8] &7作者 &f{1}' - - '&8[&3&lTabooLib&8] &7版本 &f{2}' - - '&8[&3&lTabooLib&8] &7描述 &f{3}' - - '&8[&3&lTabooLib&8] &7最后更新时间 &f{4}' - - '&8[&3&lTabooLib&8] &7最后更新内容 &f{5}' - EXPANSION-INFO-DETAIL: - 0: '&8[&3&lTabooLib&8] &7详细描述' - 1: '&8[&3&lTabooLib&8] &7- &f{0}' - DOWNLOAD: - DESCRIPTION: '下载扩展' - ARGUMENTS: - 0: '名称' - EXPANSION-NOT-FOUND: '&8[&3&lTabooLib&8] &c扩展 &4{0} &c不存在.' - EXPANSION-EXISTS: '&8[&3&lTabooLib&8] &c扩展 &4{0} &c已存在.' - EXPANSION-VERSION: '&8[&3&lTabooLib&8] &c扩展 &4{0} &c需要 &4TabooLib v{1}&c 版本才可以使用!' - DOWNLOAD-START: - - '&8[&3&lTabooLib&8] &7扩展 &f{0} &7开始下载:' - - '&8[&3&lTabooLib&8] &7地址 &f{1}' - DOWNLOAD-SUCCESS: '&8[&3&lTabooLib&8] &7扩展 &f{0} &7下载完成, 请重启服务器.' - UPDATE: - DESCRIPTION: '更新扩展' - ARGUMENTS: - 0: '名称' - EXPANSION-NOT-FOUND: '&8[&3&lTabooLib&8] &c扩展 &4{0} &c不存在.' - EXPANSION-NOT-EXISTS: '&8[&3&lTabooLib&8] &c扩展 &4{0} &c尚未下载.' - EXPANSION-NO-UPDATE: '&8[&3&lTabooLib&8] &7扩展 &f{0} &7已是最新版本.' - EXPANSION-VERSION: '&8[&3&lTabooLib&8] &c扩展 &4{0} &c需要 &4TabooLib v{1}&c 版本才可以使用!' - UPDATE-START: - - '&8[&3&lTabooLib&8] &7扩展 &f{0} &7开始更新:' - - '&8[&3&lTabooLib&8] &7版本 &f{1}' - - '&8[&3&lTabooLib&8] &7地址 &f{2}' - UPDATE-SUCCESS: '&8[&3&lTabooLib&8] &7扩展 &f{0} &7更新完成, 请重启服务器.' - LIST: - DESCRIPTION: '查看扩展列表' - ARGUMENTS: - 0: 'PLUGINS/INTERNAL' - 1: '页数' - INVALID-TYPE: - 0: '&8[&3&lTabooLib&8] &c错误的扩展类型. &4(PLUGINS、INTERNAL)' - 1: '&8[&3&lTabooLib&8] &c错误的页数.' - LIST-HEAD: - - '' - - '&e&l----- &6&lTabooLibCloud Expansions : &f{0} &6&l: &f{1}/{2} &e&l-----' - - '' - LIST-EXPANSION: - 0: ' &f{0}. &8{1} &7{2}' - 1: ' &f{0}. &c{1} &7{2}' - 2: ' &f{0}. &a{1} &7{2}' - LIST-BOTTOM: - - '' - - ' &f> &8[未安装] &a[已安装] &c[可更新]' - - '' - -DATABASE: - CONNECTION-ESTABLISHED: '成功连接到 {0} 数据库,连接池大小 {1}' - CONNECTION-ERROR: '连接到数据库错误:{0}' COMMUNICATION: FAILED-LOAD-SETTINGS: '§8[§3§lTabooLibClient§8] &4配置载入失败: {0}' @@ -657,43 +187,4 @@ UTIL: DOWNLOAD-CONNECTED: '开始下载文件 {0} 大小 {1}' DOWNLOAD-PROGRESS: ' 下载速度 {0} 进度 {1}' DOWNLOAD-SUCCESS: '下载 {0} 完成!' - DOWNLOAD-FAILED: '下载 {0} 失败!' - -TCLOUD: - LIST-LOAD-SUCCESS: '载入 &fTCLOUD &7扩展列表完成! 耗时 &f{0} &7毫秒' - LIST-LOAD-FAILED: '载入 &4{0} &c扩展数据失败: &4{1}' - LIST-PARSE-FAILED: '读取 &4TCLOUD &c扩展列表失败: &4{0}' - LIST-CONNECT-FAILED: '获取 &4TCLOUD &c扩展列表失败!' - -TFILTER: - EXCEPTION-MIRROR: - EVENT: - HEAD: - - '&c插件 &4{0} &c执行事件时出现异常! &7(处理耗时: {1}ms)' - - '&c异常事件: &4{2}' - - '&c异常类型: &4{3}' - - '&c异常内容: &4{4}' - - '&c异常位置:' - STACK-TRACE: '&7 {0}. &4{1}' - COMMAND: - HEAD: - - '&c插件 &4{0} &c执行命令时出现异常! &7(处理耗时: {1}ms)' - - '&c异常命令: &4{2}' - - '&c异常类型: &4{3}' - - '&c异常内容: &4{4}' - - '&c异常位置:' - STACK-TRACE: '&7 {0}. &4{1}' - SCHEDULE: - HEAD: - - '&c插件 &4{0} &c执行任务时出现异常! &7(处理耗时: {1}ms)' - - '&c异常类型: &4{2}' - - '&c异常内容: &4{3}' - - '&c异常位置:' - STACK-TRACE: '&7 {0}. &4{1}' - OTHER: - HEAD: - - '&c插件 &4{0} &c运行时出现异常! &7(处理耗时: {1}ms)' - - '&c异常类型: &4{2}' - - '&c异常内容: &4{3}' - - '&c异常位置:' - STACK-TRACE: '&7 {0}. &4{1}' \ No newline at end of file + DOWNLOAD-FAILED: '下载 {0} 失败!' \ No newline at end of file diff --git a/src/main/resources/module.yml b/src/main/resources/module.yml deleted file mode 100644 index ccd6800..0000000 --- a/src/main/resources/module.yml +++ /dev/null @@ -1,10 +0,0 @@ -# 语言文件 -Language: 'zh_CN' - -# 启用模块 -# 该配置需要重启服务器才会生效 -EnableModule: -#- 'Kits' -#- 'TimeCycle' -#- 'CommandChanger' -#- 'InventorySave' \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml deleted file mode 100644 index 5432566..0000000 --- a/src/main/resources/plugin.yml +++ /dev/null @@ -1,14 +0,0 @@ -name: TabooLib -main: me.skymc.taboolib.Main -version: ${version} -api-version: 1.13 - -authors: -- 坏黑 -- lzzelAliz - -softdepend: -- Vault -- PlaceholderAPI -- Skript -- MassiveLag \ No newline at end of file diff --git a/src/main/resources/settings.yml b/src/main/resources/settings.yml new file mode 100644 index 0000000..1ca603f --- /dev/null +++ b/src/main/resources/settings.yml @@ -0,0 +1,29 @@ +# 语言文件相关设置 +LOCALE: + # 加载语言文件的顺序 + PRIORITY: + - zh_CN + - en_US + # 默认是否启用语言文件中 PlaceholderAPI 的替换功能 + # 关闭可提升性能 + # 如果需要开启仍然可以在语言文件中加入 papi: true + USE_PAPI: false + +# 玩家数据储存位置 +# 如果服务器存在 TabooLib 的插件版本 +# 请设置相同路径 +LOCAL-PLAYER: 'plugins/TabooLib/playerdata/' + +# 是否以 UUID 的形式创建玩家数据 +# 如果服务器存在 TabooLib 的插件版本则不建议开启 +LOCAL-PLAYER-UUID: false + +# 是否在当前服务器启用交流网终端 +# 启用后将会收到大量调试信息, 不建议使用 +SERVER: false + +# 玩家列表(TAB-API)是否根据前缀排序 +TABLIST-SORT: true + +# 玩家列表(TAB-API)是否自动清理没有成员的队伍 +TABLIST-AUTO-CLEAN-TEAM: true \ No newline at end of file diff --git a/src/main/resources/translateuuid.yml b/src/main/resources/translateuuid.yml deleted file mode 100644 index 3e15dbb..0000000 --- a/src/main/resources/translateuuid.yml +++ /dev/null @@ -1,11 +0,0 @@ -# 是否启用 -Enable: false - -# 数据库地址 -Database: - host: 'localhost' - port: '3306' - user: 'root' - password: '' - database: 'test' - table: 'taboolib_translate_uuid_database' \ No newline at end of file diff --git a/src/main/resources/version b/src/main/resources/version new file mode 100644 index 0000000..e78e522 --- /dev/null +++ b/src/main/resources/version @@ -0,0 +1 @@ +${version} \ No newline at end of file diff --git a/src/main/scala/com/ilummc/eagletdl/AlreadyStartException.java b/src/main/scala/com/ilummc/eagletdl/AlreadyStartException.java deleted file mode 100644 index 2e1e0bc..0000000 --- a/src/main/scala/com/ilummc/eagletdl/AlreadyStartException.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.ilummc.eagletdl; - -public class AlreadyStartException extends RuntimeException { - -} diff --git a/src/main/scala/com/ilummc/eagletdl/CompleteEvent.java b/src/main/scala/com/ilummc/eagletdl/CompleteEvent.java deleted file mode 100644 index 839625b..0000000 --- a/src/main/scala/com/ilummc/eagletdl/CompleteEvent.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.ilummc.eagletdl; - -public class CompleteEvent { - private EagletTask task; - private boolean success; - - CompleteEvent(EagletTask task, boolean success) { - this.task = task; - this.success = success; - } - - public boolean isSuccess() { - return success; - } - - public EagletTask getTask() { - return task; - } -} diff --git a/src/main/scala/com/ilummc/eagletdl/ConnectedEvent.java b/src/main/scala/com/ilummc/eagletdl/ConnectedEvent.java deleted file mode 100644 index 5299f27..0000000 --- a/src/main/scala/com/ilummc/eagletdl/ConnectedEvent.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.ilummc.eagletdl; - -public class ConnectedEvent { - - private long contentLength; - private EagletTask task; - - public ConnectedEvent(long length, EagletTask task) { - this.contentLength = length; - this.task = task; - } - - /** - * Get the length of the download task. - *

- * If the length is -1, this task cannot be downloaded in multiple threads. - * - * @return length - */ - public long getContentLength() { - return contentLength; - } - - public EagletTask getTask() { - return task; - } -} diff --git a/src/main/scala/com/ilummc/eagletdl/DoNotSupportMultipleThreadException.java b/src/main/scala/com/ilummc/eagletdl/DoNotSupportMultipleThreadException.java deleted file mode 100644 index 0c59692..0000000 --- a/src/main/scala/com/ilummc/eagletdl/DoNotSupportMultipleThreadException.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.ilummc.eagletdl; - -public class DoNotSupportMultipleThreadException extends RuntimeException { -} diff --git a/src/main/scala/com/ilummc/eagletdl/EagletHandler.java b/src/main/scala/com/ilummc/eagletdl/EagletHandler.java deleted file mode 100644 index ef63e4a..0000000 --- a/src/main/scala/com/ilummc/eagletdl/EagletHandler.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.ilummc.eagletdl; - -@FunctionalInterface -public interface EagletHandler { - - void handle(T event) ; - -} diff --git a/src/main/scala/com/ilummc/eagletdl/EagletTask.java b/src/main/scala/com/ilummc/eagletdl/EagletTask.java deleted file mode 100644 index c69e551..0000000 --- a/src/main/scala/com/ilummc/eagletdl/EagletTask.java +++ /dev/null @@ -1,477 +0,0 @@ -package com.ilummc.eagletdl; - -import java.io.File; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.Proxy; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantLock; - -public class EagletTask { - - private ReentrantLock lock = new ReentrantLock(); - - Map httpHeader = new ConcurrentHashMap<>(); - - private URL url; - - EagletHandler onError = event -> event.getException().printStackTrace(); - - private EagletHandler onStart; - - private EagletHandler onComplete; - - private EagletHandler onConnected; - - private EagletHandler onProgress; - - private Proxy proxy; - - private String md5, sha1, sha256; - - String requestMethod = "GET"; - - private int threadAmount = 1; - - int connectionTimeout = 7000; - int readTimeout = 7000; - int maxRetry = 5; - - private File dest; - - private transient boolean running = false; - private transient long contentLength, maxBlockingTime = 7000; - private transient ExecutorService executorService; - private transient Thread monitor; - - public EagletTask() { - } - - /** - * Stop this task forcefully, and the target file will not be removed. - */ - public void stop() { - executorService.shutdownNow(); - monitor.interrupt(); - } - - /** - * Start the download file - *

- * 开始下载文件 - */ - public EagletTask start() { - // create thread pool for download - executorService = Executors.newFixedThreadPool(threadAmount); - // check if is already running - if (running) { - throw new AlreadyStartException(); - } - // start the monitor thread - monitor = new Thread(() -> { - lock.lock(); - // fire a new start event - if (onStart != null) { - onStart.handle(new StartEvent(this)); - } - try { - // create the target file - if (!dest.exists()) { - dest.createNewFile(); - } - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - // set the connection properties - httpHeader.forEach(connection::addRequestProperty); - connection.setRequestMethod(requestMethod); - connection.setConnectTimeout(30000); - connection.setReadTimeout(30000); - connection.connect(); - contentLength = connection.getContentLengthLong(); - // fire a new connected event - // contains connection properties - if (onConnected != null) { - onConnected.handle(new ConnectedEvent(contentLength, this)); - } - // if this is an unknown length task - if (contentLength == -1 || threadAmount == 1) { - // pass the connection instance to this new thread - SingleThreadDownload download = new SingleThreadDownload(connection, dest, this); - executorService.execute(download); - long last = 0; - do { - Thread.sleep(500); - // check the progress - long progress = download.getCurrentProgress(); - // fire a new progress event - if (onProgress != null) { - onProgress.handle(new ProgressEvent(progress - last < 0 ? 0 : progress - last, this, ((double) progress) / Math.max((double) contentLength, 0D))); - } - last = progress; - // check complete - } while (last != contentLength && !download.isComplete()); - // close the thread pool, DoNotSupportMultipleThreadExceptionrelease resources - executorService.shutdown(); - // change the running flag to false - running = false; - } else { - List splitDownloads = new ArrayList<>(); - // Assign download task length - long blockSize = contentLength / threadAmount; - for (int threadId = 0; threadId < threadAmount; threadId++) { - long startIndex = threadId * blockSize; - long endIndex = (threadId + 1) * blockSize - 1; - if (threadId == (threadAmount - 1)) { - endIndex = contentLength - 1; - } - SplitDownload download = new SplitDownload(url, startIndex, endIndex, dest, this); - // Start downloading - executorService.execute(download); - splitDownloads.add(download); - } - long last = 0; - do { - Thread.sleep(500); - long progress = 0; - // Collect download progress - for (SplitDownload splitDownload : splitDownloads) { - progress += splitDownload.getCurrentIndex() - splitDownload.startIndex; - // blocked then restart from current index - if (!splitDownload.isComplete() && System.currentTimeMillis() - splitDownload.getLastUpdateTime() > maxBlockingTime) { - splitDownload.setStartIndex(splitDownload.getCurrentIndex()); - if (splitDownload.getRetry() <= maxRetry) { - executorService.execute(splitDownload); - } else { - throw new RetryFailedException(this); - } - } - } - // Fire a progress event - if (onProgress != null) { - onProgress.handle(new ProgressEvent(progress - last, this, - ((double) progress) / ((double) contentLength))); - } - last = progress; - // check complete - } while (last < contentLength); - // close the thread pool, release resources - executorService.shutdown(); - // change the running flag to false - running = false; - } - // check hash - if (md5 != null && !md5.equalsIgnoreCase(HashUtil.md5(dest))) { - throw new HashNotMatchException(); - } - if (sha1 != null && !sha1.equalsIgnoreCase(HashUtil.sha1(dest))) { - throw new HashNotMatchException(); - } - if (sha256 != null && !sha256.equalsIgnoreCase(HashUtil.sha256(dest))) { - throw new HashNotMatchException(); - } - if (onComplete != null) { - onComplete.handle(new CompleteEvent(this, true)); - } - } catch (Exception e) { - onError.handle(new ErrorEvent(e, this)); - executorService.shutdown(); - if (onComplete != null) { - onComplete.handle(new CompleteEvent(this, false)); - } - } finally { - lock.unlock(); - } - }, "EagletTaskMonitor"); - monitor.start(); - return this; - } - - public EagletTask waitUntil() { - while (lock.tryLock()) { - lock.unlock(); - } - lock.lock(); - lock.unlock(); - return this; - } - - public EagletTask waitFor(long timeout, TimeUnit unit) { - while (lock.tryLock()) { - lock.unlock(); - } - try { - lock.tryLock(timeout, unit); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return this; - } - - public EagletTask maxRetry(int maxRetry) { - this.maxRetry = maxRetry; - return this; - } - - /** - * Set the sha256 hash of the download file. Case is not sensitive. - *

- * If the hash check failed, an error event will be fired. - * - * @param sha256 file sha1 - * @return task instance - */ - public EagletTask sha256(String sha256) { - this.sha256 = sha256; - return this; - } - - /** - * Set the sha1 hash of the download file. Case is not sensitive. - *

- * If the hash check failed, an error event will be fired. - * - * @param sha1 file sha1 - * @return task instance - */ - public EagletTask sha1(String sha1) { - this.sha1 = sha1; - return this; - } - - /** - * Set the md5 hash of the download file. Case is not sensitive. - *

- * If the hash check failed, an error event will be fired. - * - * @param md5 file md5 - * @return task instance - */ - public EagletTask md5(String md5) { - this.md5 = md5; - return this; - } - - /** - * Set the max blocked time per download thread. - *

- * If the thread blocks exceeded the provided time, this thread will re-start the task. - * - * @param maxBlockingTime time - * @return task instance - */ - private EagletTask maxBlocking(long maxBlockingTime) { - this.maxBlockingTime = maxBlockingTime; - return this; - } - - /** - * Set the progress handler - *

- * This handler will be called every 1000 milli seconds. - *

- * 设置处理进度的时间监听器。该监听器的 handle 方法每秒调用一次。 - * - * @param onProgress handler - * @return task instance - */ - public EagletTask setOnProgress(EagletHandler onProgress) { - this.onProgress = onProgress; - return this; - } - - /** - * Set the download file - * - * @param file the file's absolute path - * @return task instance - */ - public EagletTask file(String file) { - this.dest = new File(file); - return this; - } - - /** - * Set the download file - * - * @param file the file - * @return task instance - */ - public EagletTask file(File file) { - this.dest = file; - return this; - } - - /** - * Set the connected handler - *

- * This will be called when the connection is established - *

- * Async call - * - * @param onConnected onConnected event handler - * @return task instance - */ - public EagletTask setOnConnected(EagletHandler onConnected) { - this.onConnected = onConnected; - return this; - } - - /** - * Set the read timeout, default is 7000 - * - * @param timeout timeout - * @return task instance - */ - public EagletTask readTimeout(int timeout) { - this.readTimeout = timeout; - return this; - } - - /** - * Set the connection timeout, default is 7000 - * - * @param timeout timeout - * @return task instance - */ - public EagletTask connectionTimeout(int timeout) { - this.connectionTimeout = timeout; - return this; - } - - /** - * Set the request method, default is GET - * - * @param requestMethod the request method - * @return task instance - */ - public EagletTask requestMethod(String requestMethod) { - this.requestMethod = requestMethod; - return this; - } - - /** - * Set the complete event handler - *

- * This handler will be called when everything is complete, and the downloaded file is available - *

- * Async call - * - * @param onComplete the handler - * @return task instance - */ - public EagletTask setOnComplete(EagletHandler onComplete) { - this.onComplete = onComplete; - return this; - } - - /** - * Set the start handler - *

- * This handler will be called when the start method is called - *

- * Async call - * - * @param onStart the handler - * @return task instance - */ - public EagletTask setOnStart(EagletHandler onStart) { - this.onStart = onStart; - return this; - } - - /** - * Set the network proxy - * - * @param proxy the proxy - * @return task instance - */ - public EagletTask proxy(Proxy proxy) { - this.proxy = proxy; - return this; - } - - /** - * Set the error handler, default is to print the stack trace - *

- * This handler will be called when an exception is thrown - *

- * Async call - * - * @param onError the handler - * @return task instance - */ - public EagletTask setOnError(EagletHandler onError) { - this.onError = onError; - return this; - } - - - /** - * Set how much thread should be used to download, default is 1 - * - * @param i thread amount - * @return task instance - */ - public EagletTask setThreads(int i) { - if (i < 1) { - throw new RuntimeException("Thread amount cannot be zero or negative!"); - } - threadAmount = i; - return this; - } - - /** - * Set the download source - * - * @param url the url - * @return task instance - */ - public EagletTask url(URL url) { - this.url = url; - return this; - } - - /** - * Set the download source - * - * @param url the url - * @return task instance - */ - public EagletTask url(String url) { - try { - this.url = new URL(url); - } catch (MalformedURLException e) { - onError.handle(new ErrorEvent(e, this)); - } - return this; - } - - /** - * Clear the http header field - * - * @return task instance - */ - public EagletTask clearHeaders() { - httpHeader.clear(); - return this; - } - - /** - * Set the header field of the http request - * - * @param key header key - * @param value header value - * @return builder instance - */ - public EagletTask header(String key, String value) { - httpHeader.put(key, value); - return this; - } - -} diff --git a/src/main/scala/com/ilummc/eagletdl/ErrorEvent.java b/src/main/scala/com/ilummc/eagletdl/ErrorEvent.java deleted file mode 100644 index 801ac9d..0000000 --- a/src/main/scala/com/ilummc/eagletdl/ErrorEvent.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ilummc.eagletdl; - -public class ErrorEvent { - - private Throwable e; - private EagletTask task; - - public ErrorEvent(Throwable e, EagletTask task) { - this.e = e; - this.task = task; - } - - public EagletTask getTask() { - return task; - } - - public Throwable getException() { - return e; - } -} diff --git a/src/main/scala/com/ilummc/eagletdl/HashNotMatchException.java b/src/main/scala/com/ilummc/eagletdl/HashNotMatchException.java deleted file mode 100644 index bdb3bcd..0000000 --- a/src/main/scala/com/ilummc/eagletdl/HashNotMatchException.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.ilummc.eagletdl; - -public class HashNotMatchException extends RuntimeException { -} diff --git a/src/main/scala/com/ilummc/eagletdl/HashUtil.java b/src/main/scala/com/ilummc/eagletdl/HashUtil.java deleted file mode 100644 index 10bf013..0000000 --- a/src/main/scala/com/ilummc/eagletdl/HashUtil.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.ilummc.eagletdl; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -public class HashUtil { - - public static String sha256(File file) { - try { - FileInputStream fis = new FileInputStream(file); - MessageDigest md = MessageDigest.getInstance("SHA256"); - byte[] buffer = new byte[1024]; - int length = -1; - while ((length = fis.read(buffer, 0, 1024)) != -1) { - md.update(buffer, 0, length); - } - BigInteger bigInt = new BigInteger(1, md.digest()); - return bigInt.toString(16); - } catch (NoSuchAlgorithmException | IOException e) { - e.printStackTrace(); - } - return null; - } - - public static String sha1(File file) { - try { - FileInputStream fis = new FileInputStream(file); - MessageDigest md = MessageDigest.getInstance("SHA1"); - byte[] buffer = new byte[1024]; - int length = -1; - while ((length = fis.read(buffer, 0, 1024)) != -1) { - md.update(buffer, 0, length); - } - BigInteger bigInt = new BigInteger(1, md.digest()); - return bigInt.toString(16); - } catch (NoSuchAlgorithmException | IOException e) { - e.printStackTrace(); - } - return null; - } - - public static String md5(File file) { - try { - FileInputStream fis = new FileInputStream(file); - MessageDigest md = MessageDigest.getInstance("MD5"); - byte[] buffer = new byte[1024]; - int length = -1; - while ((length = fis.read(buffer, 0, 1024)) != -1) { - md.update(buffer, 0, length); - } - BigInteger bigInt = new BigInteger(1, md.digest()); - return bigInt.toString(16); - } catch (NoSuchAlgorithmException | IOException e) { - e.printStackTrace(); - } - return null; - } - -} diff --git a/src/main/scala/com/ilummc/eagletdl/ProgressEvent.java b/src/main/scala/com/ilummc/eagletdl/ProgressEvent.java deleted file mode 100644 index f6cf1b7..0000000 --- a/src/main/scala/com/ilummc/eagletdl/ProgressEvent.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.ilummc.eagletdl; - -import java.text.DecimalFormat; - -public class ProgressEvent { - - private long speed; - private EagletTask task; - private double percentage; - - ProgressEvent(long speed, EagletTask task, double percentage) { - this.speed = speed; - this.task = task; - this.percentage = percentage; - } - - public EagletTask getTask() { - return task; - } - - public long getSpeed() { - return speed; - } - - public double getPercentage() { - return percentage; - } - - public String getPercentageFormatted() { - return formatDouble(percentage * 100D) + " %"; - } - - /** - * Get the speed with format like X.00 MiB, Y.50 GiB, etc. - * - * @return formatted speed string - */ - public String getSpeedFormatted() { - return format(getSpeed()); - } - - private static String formatDouble(double d) { - return new DecimalFormat("0.00").format(d); - } - - public static String format(long l) { - if (l < 1024) return l + " B"; - if (l < 1024 * 1024) return formatDouble((double) l / 1024D) + " KiB"; - if (l < 1024 * 1024 * 1024) return formatDouble((double) l / (1024D * 1024D)) + " MiB"; - if (l < 1024 * 1024 * 1024 * 1024L) return formatDouble((double) l / (1024D * 1024D * 1024)) + " GiB"; - return ""; - } -} diff --git a/src/main/scala/com/ilummc/eagletdl/RetryFailedException.java b/src/main/scala/com/ilummc/eagletdl/RetryFailedException.java deleted file mode 100644 index e8a022d..0000000 --- a/src/main/scala/com/ilummc/eagletdl/RetryFailedException.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ilummc.eagletdl; - -public class RetryFailedException extends RuntimeException { - - private EagletTask task; - - RetryFailedException(EagletTask task) { - this.task = task; - } - - public EagletTask getTask() { - return task; - } -} diff --git a/src/main/scala/com/ilummc/eagletdl/SingleThreadDownload.java b/src/main/scala/com/ilummc/eagletdl/SingleThreadDownload.java deleted file mode 100644 index d03967e..0000000 --- a/src/main/scala/com/ilummc/eagletdl/SingleThreadDownload.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.ilummc.eagletdl; - -import java.io.*; -import java.net.HttpURLConnection; - -class SingleThreadDownload implements Runnable { - - private HttpURLConnection connection; - private File target; - private EagletTask task; - - private transient long currentProgress = 0, lastUpdateTime = System.currentTimeMillis(); - - private transient boolean complete = false; - - SingleThreadDownload(HttpURLConnection connection, File target, EagletTask task) { - this.connection = connection; - this.target = target; - this.task = task; - } - - long getLastUpdateTime() { - return lastUpdateTime; - } - - long getCurrentProgress() { - return currentProgress; - } - - public boolean isComplete() { - return complete; - } - - @Override - public void run() { - byte[] buf = new byte[1024]; - int len = 0; - try (BufferedInputStream stream = new BufferedInputStream(connection.getInputStream()); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(target))) { - while ((len = stream.read(buf)) > 0) { - outputStream.write(buf, 0, len); - currentProgress += len; - lastUpdateTime = System.currentTimeMillis(); - } - } catch (IOException e) { - task.onError.handle(new ErrorEvent(e, task)); - } - complete = true; - } -} diff --git a/src/main/scala/com/ilummc/eagletdl/SplitDownload.java b/src/main/scala/com/ilummc/eagletdl/SplitDownload.java deleted file mode 100644 index dd17663..0000000 --- a/src/main/scala/com/ilummc/eagletdl/SplitDownload.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.ilummc.eagletdl; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.RandomAccessFile; -import java.net.HttpURLConnection; -import java.net.URL; - -class SplitDownload implements Runnable { - - private URL url; - long startIndex, endIndex; - private File target; - private EagletTask task; - - private transient long currentIndex, lastUpdateTime = System.currentTimeMillis(), tmpStart; - private transient int retry = 0; - private transient boolean complete; - - SplitDownload(URL url, long startIndex, long endIndex, File dest, EagletTask task) { - this.url = url; - tmpStart = this.startIndex = this.currentIndex = startIndex; - this.endIndex = endIndex; - target = dest; - this.task = task; - } - - void setStartIndex(long index) { - this.tmpStart = index; - } - - long getLastUpdateTime() { - return lastUpdateTime; - } - - long getCurrentIndex() { - return currentIndex; - } - - int getRetry() { - return retry; - } - - boolean isComplete() { - return complete || currentIndex == endIndex + 1; - } - - @Override - public void run() { - try { - complete = false; - currentIndex = tmpStart; - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - // set the connection properties - task.httpHeader.forEach(connection::addRequestProperty); - connection.setRequestMethod(task.requestMethod); - connection.setConnectTimeout(task.connectionTimeout); - connection.setReadTimeout(task.readTimeout); - // set the download range - connection.setRequestProperty("Range", "bytes=" + tmpStart + "-" + endIndex); - connection.connect(); - // if response code not equals 206, it means that the server do not support multi thread downloading - if (connection.getResponseCode() == 206) { - RandomAccessFile file = new RandomAccessFile(target, "rwd"); - file.seek(tmpStart); - byte[] buf = new byte[1024]; - int len; - try (BufferedInputStream stream = new BufferedInputStream(connection.getInputStream())) { - while ((len = stream.read(buf)) > 0) { - file.write(buf, 0, len); - lastUpdateTime = System.currentTimeMillis(); - currentIndex += len; - // some mysterious error occurred while downloading - if (currentIndex >= endIndex + 2) { - currentIndex = tmpStart; - lastUpdateTime = 0; - retry++; - return; - } - } - complete = true; - } - file.close(); - } else { - throw new DoNotSupportMultipleThreadException(); - } - } catch (Exception e) { - task.onError.handle(new ErrorEvent(e, task)); - retry++; - } - } -} diff --git a/src/main/scala/com/ilummc/eagletdl/StartEvent.java b/src/main/scala/com/ilummc/eagletdl/StartEvent.java deleted file mode 100644 index b0c7f61..0000000 --- a/src/main/scala/com/ilummc/eagletdl/StartEvent.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ilummc.eagletdl; - -public class StartEvent { - - private EagletTask task; - - StartEvent(EagletTask task) { - this.task = task; - } - - public EagletTask getTask() { - return task; - } -} diff --git a/src/main/scala/com/ilummc/tlib/ExampleMain.java b/src/main/scala/com/ilummc/tlib/ExampleMain.java deleted file mode 100644 index b6426a6..0000000 --- a/src/main/scala/com/ilummc/tlib/ExampleMain.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.ilummc.tlib; - -import com.ilummc.tlib.annotations.TConfig; -import com.ilummc.tlib.bean.Property; -import org.bukkit.Bukkit; -import org.bukkit.plugin.java.JavaPlugin; - -import java.lang.management.GarbageCollectorMXBean; -import java.lang.management.ManagementFactory; -import java.lang.management.MemoryMXBean; -import java.util.concurrent.TimeUnit; - -@TConfig(name = "cfg.yml", charset = "GBK") -public class ExampleMain extends JavaPlugin { - - private Property update = Property.of(false); - - public static void main(String[] args) { - MemoryMXBean bean = ManagementFactory.getMemoryMXBean(); - System.out.println(bean.getHeapMemoryUsage().toString()); - System.out.println(bean.getNonHeapMemoryUsage().toString()); - for (int i = 0; i < 10; i++) { - for (GarbageCollectorMXBean mxBean : ManagementFactory.getGarbageCollectorMXBeans()) { - System.out.println(mxBean.getName()); - System.out.println(mxBean.getCollectionCount()); - System.out.println(mxBean.getCollectionTime()); - for (String s : mxBean.getMemoryPoolNames()) { - System.out.println(s); - } - System.out.println(mxBean.getObjectName().toString()); - } - System.gc(); - } - for (String s : ManagementFactory.getRuntimeMXBean().getInputArguments()) { - System.out.println(s); - } - } - - @Override - public void onEnable() { - update.addListener(((oldVal, newVal) -> { - Bukkit.getLogger().info("配置项 enableUpdate 的值由 " + oldVal + " 变为了 " + newVal); - if (newVal) { - Updater.start(); - } else { - Updater.stop(); - } - })); - } - - private static class Updater { - public static void start() { - - } - - public static void stop() { - - } - } - - private static class CD { - - final long start, period; - final TimeUnit unit; - final Runnable onStart, onFinish, onTimer; - - CD(long start, long period, TimeUnit unit, Runnable onStart, Runnable onFinish, Runnable onTimer) { - this.start = start; - this.period = period; - this.unit = unit; - this.onStart = onStart; - this.onFinish = onFinish; - this.onTimer = onTimer; - } - - public static void main(String[] args) { - CD.builder().setOnStart(() -> { - }).setOnFinish(() -> { - }).setOnTimer(1000, TimeUnit.MILLISECONDS, () -> { - }).build(); - } - - public static CdBuilder builder() { - return new CdBuilder(); - } - - private static class CdBuilder { - private long start, period; - private TimeUnit unit; - private Runnable onStart, onFinish, onTimer; - - public CdBuilder setOnStart(Runnable runnable) { - this.onStart = runnable; - return this; - } - - public CdBuilder setOnFinish(Runnable runnable) { - this.onFinish = runnable; - return this; - } - - public CdBuilder setOnTimer(long period, TimeUnit timeUnit, Runnable runnable) { - this.period = period; - this.unit = timeUnit; - this.onTimer = runnable; - return this; - } - - public CD build() { - return new CD(start, period, unit, onStart, onFinish, onTimer); - } - } - } -} diff --git a/src/main/scala/com/ilummc/tlib/TLib.java b/src/main/scala/com/ilummc/tlib/TLib.java deleted file mode 100644 index ad11ca0..0000000 --- a/src/main/scala/com/ilummc/tlib/TLib.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.ilummc.tlib; - -import com.ilummc.tlib.annotations.Dependency; -import com.ilummc.tlib.compat.PlaceholderHook; -import com.ilummc.tlib.config.TLibConfig; -import com.ilummc.tlib.db.Pool; -import com.ilummc.tlib.inject.TConfigWatcher; -import com.ilummc.tlib.inject.TDependencyInjector; -import com.ilummc.tlib.inject.TPluginManager; -import com.ilummc.tlib.logger.TLogger; -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.TabooLib; -import me.skymc.taboolib.fileutils.FileUtils; -import me.skymc.taboolib.plugin.PluginUtils; -import org.bukkit.Bukkit; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Field; -import java.nio.charset.Charset; -import java.util.Arrays; - -@Dependency(type = Dependency.Type.LIBRARY, maven = "com.zaxxer:HikariCP:3.1.0") -@Dependency(type = Dependency.Type.LIBRARY, maven = "org.slf4j:slf4j-api:1.7.25") -@Dependency(type = Dependency.Type.LIBRARY, maven = "org.javalite:activejdbc:2.0") -@Dependency(type = Dependency.Type.LIBRARY, maven = "org.javalite:javalite-common:2.0") -@Dependency(type = Dependency.Type.LIBRARY, maven = "org.javalite:app-config:2.0") -@Dependency(type = Dependency.Type.LIBRARY, maven = "org.codehaus.jackson:jackson-mapper-asl:1.9.13") -@Dependency(type = Dependency.Type.LIBRARY, maven = "org.codehaus.jackson:jackson-core-asl:1.9.13") -@Dependency(type = Dependency.Type.LIBRARY, maven = "jaxen:jaxen:1.1.6") -@Dependency(type = Dependency.Type.LIBRARY, maven = "dom4j:dom4j:1.6.1") -@Dependency(type = Dependency.Type.LIBRARY, maven = "xml-apis:xml-apis:1.0.b2") -@Dependency(type = Dependency.Type.LIBRARY, maven = "org.ehcache:ehcache:3.5.2") -@Dependency(type = Dependency.Type.LIBRARY, maven = "com.h2database:h2:1.4.197") -public class TLib { - - private static TLib tLib; - private static YamlConfiguration internalLanguage; - private TLogger logger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE); - private TLibConfig config; - private TConfigWatcher configWatcher = new TConfigWatcher(); - private File libsFolder; - - private TLib() { - libsFolder = new File(Main.getInst().getDataFolder(), "/libs"); - if (!libsFolder.exists()) { - libsFolder.mkdirs(); - } - try { - 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) { - } - } - - public static void init() { - tLib = new TLib(); - - TLocaleLoader.init(); - PlaceholderHook.init(); - TLocaleLoader.load(Main.getInst(), false); - } - - public static void initPost() { - TDependencyInjector.inject(Main.getInst(), TLib.getTLib()); - try { - Pool.init(); - } catch (Throwable ignored) { - } - } - - public static void unload() { - try { - Pool.unload(); - } catch (Throwable ignored) { - } - tLib.getConfigWatcher().unregisterAll(); - TDependencyInjector.eject(Main.getInst(), tLib); - - } - - public static void injectPluginManager() { - if (!tLib.isInjectEnabled() || tLib.isBlackListPluginExists()) { - TLocale.Logger.warn("TLIB.INJECTION-DISABLED"); - Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> plugin != Main.getInst()).forEach(plugin -> TDependencyInjector.inject(plugin, plugin)); - return; - } - try { - Field field = Bukkit.getServer().getClass().getDeclaredField("pluginManager"); - field.setAccessible(true); - field.set(Bukkit.getServer(), new TPluginManager()); - TLocale.Logger.info("TLIB.INJECTION-SUCCESS"); - } catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException ignored) { - TLocale.Logger.error("TLIB.INJECTION-FAILED"); - Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> !TabooLib.isTabooLib(plugin)).forEach(plugin -> TDependencyInjector.inject(plugin, plugin)); - } - } - - public static TLib getTLib() { - return tLib; - } - - public static YamlConfiguration getInternalLanguage() { - return internalLanguage; - } - - public TLogger getLogger() { - return logger; - } - - public TLibConfig getConfig() { - return config; - } - - public TConfigWatcher getConfigWatcher() { - return configWatcher; - } - - public File getLibsFolder() { - return libsFolder; - } - - public boolean isInjectEnabled() { - return Main.getInst().getConfig().getBoolean("PLUGIN-INJECTOR.ENABLE", true); - } - - public boolean isBlackListPluginExists() { - return Main.getInst().getConfig().getStringList("PLUGIN-INJECTOR.DISABLE-ON-PLUGIN-EXISTS").stream().anyMatch(PluginUtils::isPluginExists); - } - -} diff --git a/src/main/scala/com/ilummc/tlib/annotations/Logger.java b/src/main/scala/com/ilummc/tlib/annotations/Logger.java deleted file mode 100644 index da9456a..0000000 --- a/src/main/scala/com/ilummc/tlib/annotations/Logger.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.ilummc.tlib.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -public @interface Logger { - - String value() default "[{0}|{1}§f] {2}"; - - int level() default com.ilummc.tlib.logger.TLogger.INFO; - -} diff --git a/src/main/scala/com/ilummc/tlib/annotations/TConfig.java b/src/main/scala/com/ilummc/tlib/annotations/TConfig.java deleted file mode 100644 index 3a28756..0000000 --- a/src/main/scala/com/ilummc/tlib/annotations/TConfig.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ilummc.tlib.annotations; - -import com.ilummc.tlib.util.Ref; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.Modifier; - -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -public @interface TConfig { - - String name() default "config.yml"; - - boolean fromJar() default false; - - boolean saveOnExit() default false; - - boolean readOnly() default true; - - String charset() default "UTF-8"; - - boolean listenChanges() default false; - - int excludeModifiers() default Modifier.STATIC | Modifier.TRANSIENT | Ref.ACC_SYNTHETIC | Ref.ACC_BRIDGE; - -} diff --git a/src/main/scala/com/ilummc/tlib/annotations/TLocalePlugin.java b/src/main/scala/com/ilummc/tlib/annotations/TLocalePlugin.java deleted file mode 100644 index 40f6ce6..0000000 --- a/src/main/scala/com/ilummc/tlib/annotations/TLocalePlugin.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ilummc.tlib.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -public @interface TLocalePlugin { -} diff --git a/src/main/scala/com/ilummc/tlib/annotations/clr/CommandHandler.java b/src/main/scala/com/ilummc/tlib/annotations/clr/CommandHandler.java deleted file mode 100644 index c38a610..0000000 --- a/src/main/scala/com/ilummc/tlib/annotations/clr/CommandHandler.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ilummc.tlib.annotations.clr; - -import java.lang.annotation.*; - -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -@Repeatable(CommandHandlers.class) -public @interface CommandHandler { - - /** - * Name of the command - * - * @return Name of the command - */ - String value(); - -} diff --git a/src/main/scala/com/ilummc/tlib/annotations/clr/CommandHandlers.java b/src/main/scala/com/ilummc/tlib/annotations/clr/CommandHandlers.java deleted file mode 100644 index 34cfb32..0000000 --- a/src/main/scala/com/ilummc/tlib/annotations/clr/CommandHandlers.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ilummc.tlib.annotations.clr; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface CommandHandlers { - - CommandHandler[] value(); - -} diff --git a/src/main/scala/com/ilummc/tlib/annotations/clr/Sub.java b/src/main/scala/com/ilummc/tlib/annotations/clr/Sub.java deleted file mode 100644 index 2ee6e27..0000000 --- a/src/main/scala/com/ilummc/tlib/annotations/clr/Sub.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ilummc.tlib.annotations.clr; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -public @interface Sub { - - String value(); - -} diff --git a/src/main/scala/com/ilummc/tlib/annotations/db/Database.java b/src/main/scala/com/ilummc/tlib/annotations/db/Database.java deleted file mode 100644 index cdf2b49..0000000 --- a/src/main/scala/com/ilummc/tlib/annotations/db/Database.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.ilummc.tlib.annotations.db; - -public @interface Database { - - boolean sharedPool() default true; - - int poolSize() default 8; - - Class configClass(); - -} diff --git a/src/main/scala/com/ilummc/tlib/annotations/db/DatabasePassword.java b/src/main/scala/com/ilummc/tlib/annotations/db/DatabasePassword.java deleted file mode 100644 index 6f42c90..0000000 --- a/src/main/scala/com/ilummc/tlib/annotations/db/DatabasePassword.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.ilummc.tlib.annotations.db; - -public @interface DatabasePassword { -} diff --git a/src/main/scala/com/ilummc/tlib/annotations/db/DatabaseType.java b/src/main/scala/com/ilummc/tlib/annotations/db/DatabaseType.java deleted file mode 100644 index 48070ca..0000000 --- a/src/main/scala/com/ilummc/tlib/annotations/db/DatabaseType.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.ilummc.tlib.annotations.db; - -public @interface DatabaseType { -} diff --git a/src/main/scala/com/ilummc/tlib/annotations/db/DatabaseUrl.java b/src/main/scala/com/ilummc/tlib/annotations/db/DatabaseUrl.java deleted file mode 100644 index 056dd25..0000000 --- a/src/main/scala/com/ilummc/tlib/annotations/db/DatabaseUrl.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.ilummc.tlib.annotations.db; - -public @interface DatabaseUrl { -} diff --git a/src/main/scala/com/ilummc/tlib/annotations/db/DatabaseUser.java b/src/main/scala/com/ilummc/tlib/annotations/db/DatabaseUser.java deleted file mode 100644 index b8ab435..0000000 --- a/src/main/scala/com/ilummc/tlib/annotations/db/DatabaseUser.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.ilummc.tlib.annotations.db; - -public @interface DatabaseUser { -} diff --git a/src/main/scala/com/ilummc/tlib/annotations/db/SQLTable.java b/src/main/scala/com/ilummc/tlib/annotations/db/SQLTable.java deleted file mode 100644 index 543d3f2..0000000 --- a/src/main/scala/com/ilummc/tlib/annotations/db/SQLTable.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ilummc.tlib.annotations.db; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -public @interface SQLTable { - - String value(); - -} diff --git a/src/main/scala/com/ilummc/tlib/bean/Property.java b/src/main/scala/com/ilummc/tlib/bean/Property.java deleted file mode 100644 index 66f3950..0000000 --- a/src/main/scala/com/ilummc/tlib/bean/Property.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.ilummc.tlib.bean; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.BiConsumer; - -public class Property { - - private Property(T value) { - this.value = value; - } - - private List> consumers; - - private T value; - - public void set(T value) { - if (value != this.value) { - if (consumers != null) { - for (BiConsumer consumer : consumers) { - consumer.accept(this.value, value); - } - } - this.value = value; - } - } - - public T get() { - return value; - } - - public void addListener(BiConsumer consumer) { - if (consumers == null) { - consumers = new ArrayList<>(); - } - consumers.add(consumer); - } - - public static Property of(T value) { - return new Property<>(value); - } - -} diff --git a/src/main/scala/com/ilummc/tlib/bean/PropertyTypeAdaptor.java b/src/main/scala/com/ilummc/tlib/bean/PropertyTypeAdaptor.java deleted file mode 100644 index f802433..0000000 --- a/src/main/scala/com/ilummc/tlib/bean/PropertyTypeAdaptor.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.ilummc.tlib.bean; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonParseException; - -import java.lang.reflect.Type; - -public class PropertyTypeAdaptor implements JsonDeserializer { - - @Override - public Property deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { - return null; - } -} diff --git a/src/main/scala/com/ilummc/tlib/clr/CommandLineResolver.java b/src/main/scala/com/ilummc/tlib/clr/CommandLineResolver.java deleted file mode 100644 index 5341f28..0000000 --- a/src/main/scala/com/ilummc/tlib/clr/CommandLineResolver.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.ilummc.tlib.clr; - -public class CommandLineResolver { - - - -} diff --git a/src/main/scala/com/ilummc/tlib/config/TLibConfig.java b/src/main/scala/com/ilummc/tlib/config/TLibConfig.java deleted file mode 100644 index 9ecb9de..0000000 --- a/src/main/scala/com/ilummc/tlib/config/TLibConfig.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.ilummc.tlib.config; - -import com.ilummc.tlib.annotations.TConfig; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author sky - * @since 2018-04-22 14:31:11 - */ -@TConfig(name = "tlib.yml") -public class TLibConfig { - - private String dataSourceClassName; - - private String jdbcUrl = "jdbc:h2:file:~/plugins/TabooLib/h2"; - - private String driverClassName; - - private String username = ""; - - private String password = ""; - - private int maximumPoolSize = 4; - - private Map settings = new HashMap() {{ - put("cachePrepStmts", true); - put("useServerPrepStmts", true); - }}; - - public String getDataSourceClassName() { - return dataSourceClassName; - } - - public String getJdbcUrl() { - return jdbcUrl; - } - - public String getDriverClassName() { - return driverClassName; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - public int getMaximumPoolSize() { - return maximumPoolSize; - } - - public Map getSettings() { - return settings; - } -} diff --git a/src/main/scala/com/ilummc/tlib/db/Pool.java b/src/main/scala/com/ilummc/tlib/db/Pool.java deleted file mode 100644 index 82ccbfc..0000000 --- a/src/main/scala/com/ilummc/tlib/db/Pool.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.ilummc.tlib.db; - -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.resources.TLocale; -import org.javalite.activejdbc.Base; - -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -public final class Pool extends ThreadPoolExecutor { - - private static final AtomicInteger number = new AtomicInteger(1); - - private static final Pool singleton = new Pool(); - - private final TLibDataSource dataSource; - - private Pool() { - super(TLib.getTLib().getConfig().getMaximumPoolSize(), - TLib.getTLib().getConfig().getMaximumPoolSize(), - 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); - try { - dataSource = new TLibDataSource(); - this.setThreadFactory(r -> new Thread(() -> { - Base.open(dataSource.getDataSource()); - r.run(); - }, "TabooLib-DbPool-" + number.getAndIncrement())); - prestartAllCoreThreads(); - TLocale.sendToConsole("DATABASE.CONNECTION-ESTABLISHED", dataSource.getDataSource().getConnection().getMetaData().getDatabaseProductName(), - String.valueOf(TLib.getTLib().getConfig().getMaximumPoolSize())); - } catch (Exception e) { - TLocale.sendToConsole("DATABASE.CONNECTION-ERROR", e.toString()); - throw new RuntimeException(); - } - } - - public static void run(Runnable runnable) { - instance().execute(runnable); - } - - public static void init() { - - } - - public static void unload() { - instance().dataSource.disconnect(); - instance().shutdown(); - } - - public static Pool instance() { - return singleton; - } - - @Override - protected void afterExecute(Runnable r, Throwable t) { - if (t != null) { - Base.close(); - } - } - -} diff --git a/src/main/scala/com/ilummc/tlib/db/TLibDataSource.java b/src/main/scala/com/ilummc/tlib/db/TLibDataSource.java deleted file mode 100644 index 734b0be..0000000 --- a/src/main/scala/com/ilummc/tlib/db/TLibDataSource.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.ilummc.tlib.db; - -import com.ilummc.tlib.TLib; -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import org.javalite.activejdbc.Base; - -import javax.sql.DataSource; -import java.util.Properties; - -public class TLibDataSource { - - private final HikariDataSource dataSource; - - TLibDataSource() { - Properties properties = new Properties(); - properties.put("jdbcUrl", TLib.getTLib().getConfig().getJdbcUrl()); - properties.put("username", TLib.getTLib().getConfig().getUsername()); - properties.put("password", TLib.getTLib().getConfig().getPassword()); - properties.put("dataSourceClassName", TLib.getTLib().getConfig().getDataSourceClassName()); - properties.put("driverClassName", TLib.getTLib().getConfig().getDriverClassName()); - TLib.getTLib().getConfig().getSettings().forEach((k, v) -> properties.put("dataSource." + k, v)); - dataSource = new HikariDataSource(new HikariConfig(properties)); - Base.open(dataSource); - } - - public DataSource getDataSource() { - return dataSource; - } - - public void disconnect() { - Base.close(); - } - -} diff --git a/src/main/scala/com/ilummc/tlib/dependency/TDependency.java b/src/main/scala/com/ilummc/tlib/dependency/TDependency.java deleted file mode 100644 index 1ed290e..0000000 --- a/src/main/scala/com/ilummc/tlib/dependency/TDependency.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.ilummc.tlib.dependency; - -import com.ilummc.eagletdl.EagletTask; -import com.ilummc.eagletdl.ProgressEvent; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.Main; - -import java.io.File; -import java.util.concurrent.atomic.AtomicBoolean; - -public class TDependency { - - // 阿里 http://maven.aliyun.com/nexus/content/groups/public - // Maven Central - public static final String MAVEN_REPO = "http://repo1.maven.org/maven2"; - - /** - * 请求一个插件作为依赖,这个插件将会在所有已经添加的 Jenkins 仓库、Maven 仓库寻找 - *

- * 阻塞线程进行下载/加载 - * - * @param args 插件名称,下载地址(可选) - * @return 是否成功加载了依赖 - */ - public static boolean requestPlugin(String... args) { - return false; - } - - /** - * 请求一个库作为依赖,这个库将会在 Maven Central、oss.sonatype 以及自定义的 Maven 仓库寻找 - *

- * 阻塞线程进行下载/加载 - * - * @param type 依赖名,格式为 groupId:artifactId:version - * @return 是否成功加载库,如果加载成功,插件将可以任意调用使用的类 - */ - public static boolean requestLib(String type, String repo, String url) { - if (type.matches(".*:.*:.*")) { - String[] arr = type.split(":"); - File file = new File(Main.getInst().getDataFolder(), "/libs/" + String.join("-", arr) + ".jar"); - if (file.exists()) { - TDependencyLoader.addToPath(Main.getInst(), file); - return true; - } else { - if (downloadMaven(repo, arr[0], arr[1], arr[2], file, url)) { - TDependencyLoader.addToPath(Main.getInst(), file); - return true; - } else { - return false; - } - } - } - return false; - } - - private static boolean downloadMaven(String url, String groupId, String artifactId, String version, File target, String dl) { - if (Main.isOfflineVersion()) { - TLocale.Logger.warn("DEPENDENCY.DOWNLOAD-OFFLINE"); - return false; - } - AtomicBoolean failed = new AtomicBoolean(false); - String link = dl.length() == 0 ? url + "/" + groupId.replace('.', '/') + "/" + artifactId + "/" + version + "/" + artifactId + "-" + version + ".jar" : dl; - new EagletTask() - .url(link) - .file(target) - .setThreads(1) - .setOnError(event -> event.getException().printStackTrace()) - .setOnConnected(event -> TLocale.Logger.info("DEPENDENCY.DOWNLOAD-CONNECTED", String.join(":", new String[] {groupId, artifactId, version}), ProgressEvent.format(event.getContentLength()))) - .setOnProgress(event -> TLocale.Logger.info("DEPENDENCY.DOWNLOAD-PROGRESS", event.getSpeedFormatted(), event.getPercentageFormatted())) - .setOnComplete(event -> { - if (event.isSuccess()) { - TLocale.Logger.info("DEPENDENCY.DOWNLOAD-SUCCESS", String.join(":", new String[] {groupId, artifactId, version})); - } else { - failed.set(true); - TLocale.Logger.error("DEPENDENCY.DOWNLOAD-FAILED", String.join(":", new String[] {groupId, artifactId, version}), link, target.getName()); - } - }).start().waitUntil(); - return !failed.get(); - } -} diff --git a/src/main/scala/com/ilummc/tlib/filter/TLoggerFilter.java b/src/main/scala/com/ilummc/tlib/filter/TLoggerFilter.java deleted file mode 100644 index e83cfd3..0000000 --- a/src/main/scala/com/ilummc/tlib/filter/TLoggerFilter.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.ilummc.tlib.filter; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.ilummc.tlib.filter.impl.FilterConfiguration; -import com.ilummc.tlib.filter.impl.FilterInvalidPluginLoader; -import me.skymc.taboolib.TabooLib; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.logging.Filter; -import java.util.logging.LogRecord; -import java.util.logging.Logger; - -/** - * @author Bkm016 - * @since 2018-04-22 - */ -public class TLoggerFilter implements Filter { - - private Filter filter; - private Logger logger; - private static List handlers = Lists.newLinkedList(); - private static Map pluginFilter = Maps.newHashMap(); - private static TLoggerFilter globalFilter; - private static String playerConnectionName; - - static { - handlers.add(new FilterConfiguration()); - handlers.add(new FilterInvalidPluginLoader()); - // handlers.add(new FilterExceptionMirror()); - } - - public static void preInit() { - inject(new TLoggerFilter(), Bukkit.getLogger()); - inject(new TLoggerFilter(), TabooLib.instance().getLogger()); - try { - playerConnectionName = Class.forName("net.minecraft.server." + TabooLib.getVersion() + ".PlayerConnection").getName(); - } catch (Exception ignored) { - } - } - - public static void postInit() { - Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(TabooLib::isDependTabooLib).forEach(plugin -> inject(new TLoggerFilter(), plugin.getLogger())); - } - - public static void inject0() { - inject(new TLoggerFilter(), Logger.getLogger(playerConnectionName)); - } - - public static void inject(TLoggerFilter filter, Logger logger) { - if (!(logger.getFilter() instanceof TLoggerFilter)) { - try { - filter.filter = logger.getFilter(); - filter.logger = logger; - logger.setFilter(filter); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public static void eject(Plugin plugin) { - try { - if (plugin.getLogger().getFilter() instanceof TLoggerFilter) { - ((TLoggerFilter) plugin.getLogger().getFilter()).filter = null; - ((TLoggerFilter) plugin.getLogger().getFilter()).logger = null; - plugin.getLogger().setFilter(null); - } - } catch (Throwable t) { - t.printStackTrace(); - } - } - - public static TLoggerFilter getGlobalFilter() { - return globalFilter; - } - - public static Map getPluginFilter() { - return pluginFilter; - } - - public static List getHandlers() { - return handlers; - } - - public Filter getFilter() { - return filter; - } - - public Logger getLogger() { - return logger; - } - - @Override - public boolean isLoggable(LogRecord e) { - return handlers.stream().allMatch(filter -> filter.isLoggable(e)) && (filter == null || filter.isLoggable(e)); - } -} diff --git a/src/main/scala/com/ilummc/tlib/filter/TLoggerFilterHandler.java b/src/main/scala/com/ilummc/tlib/filter/TLoggerFilterHandler.java deleted file mode 100644 index 9e4ef1b..0000000 --- a/src/main/scala/com/ilummc/tlib/filter/TLoggerFilterHandler.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.ilummc.tlib.filter; - -import java.util.logging.LogRecord; - -/** - * @Author 坏黑 - * @Since 2018-11-29 11:42 - */ -public abstract class TLoggerFilterHandler { - - abstract public boolean isLoggable(LogRecord e); - -} diff --git a/src/main/scala/com/ilummc/tlib/filter/impl/FilterConfiguration.java b/src/main/scala/com/ilummc/tlib/filter/impl/FilterConfiguration.java deleted file mode 100644 index b476822..0000000 --- a/src/main/scala/com/ilummc/tlib/filter/impl/FilterConfiguration.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ilummc.tlib.filter.impl; - -import com.ilummc.tlib.filter.TLoggerFilterHandler; - -import java.util.Arrays; -import java.util.logging.LogRecord; - -/** - * @Author 坏黑 - * @Since 2018-11-29 11:47 - */ -public class FilterConfiguration extends TLoggerFilterHandler { - - @Override - public boolean isLoggable(LogRecord e) { - if (String.valueOf(e.getMessage()).contains("Cannot load configuration from stream")) { - StackTraceElement[] elements = Thread.currentThread().getStackTrace(); - for (StackTraceElement element : elements) { - if (element.getClassName().contains("ConfigUtils")) { - // Bukkit 拦截异常?我再扔一个 - System.out.println(Arrays.asList(e.getParameters())); - } - } - return false; - } - return true; - } -} diff --git a/src/main/scala/com/ilummc/tlib/filter/impl/FilterExceptionMirror.java b/src/main/scala/com/ilummc/tlib/filter/impl/FilterExceptionMirror.java deleted file mode 100644 index db01569..0000000 --- a/src/main/scala/com/ilummc/tlib/filter/impl/FilterExceptionMirror.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.ilummc.tlib.filter.impl; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.ilummc.tlib.filter.TLoggerFilterHandler; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; -import org.bukkit.command.CommandException; -import org.bukkit.event.EventException; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; - -import java.util.List; -import java.util.Set; -import java.util.concurrent.atomic.AtomicReference; -import java.util.logging.LogRecord; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * @Author 坏黑 - * @Since 2018-11-29 11:42 - */ -public class FilterExceptionMirror extends TLoggerFilterHandler { - - interface ArgumentsCallback { - - String[] run(); - } - - private static Pattern patternEvent = Pattern.compile("Could not pass event (.+?) to (.+?)"); - private static Pattern patternCommand = Pattern.compile("Unhandled exception executing command '(.+?)' in plugin (.+?)"); - - /** - * 判断是否为调度器异常 - */ - public boolean isScheduleException(LogRecord log) { - return String.valueOf(log.getMessage()).contains("generated an exception"); - } - - /** - * 是否为可捕捉异常 - */ - public boolean isValidException(Throwable throwable) { - return throwable.getCause() != null && throwable.getCause().getStackTrace() != null && throwable.getCause().getStackTrace().length > 0; - } - - /** - * 向控制台打印捕捉到的异常 - * - * @param stackTraceElements 堆栈 - * @param message 信息类型 - * @param args 信息参数 - * @return 是否成功捕捉并打印 - */ - public boolean printException(AtomicReference plugin, StackTraceElement[] stackTraceElements, String message, ArgumentsCallback args) { - Set plugins = Sets.newHashSet(); - List stackTraces = Lists.newLinkedList(); - for (StackTraceElement stack : stackTraceElements) { - try { - plugins.add(JavaPlugin.getProvidingPlugin(Class.forName(stack.getClassName()))); - stackTraces.add(stack); - } catch (Exception ignored) { - } - } - if (!plugins.isEmpty() && plugins.stream().allMatch(p -> TabooLib.isTabooLib(p) || TabooLib.isDependTabooLib(p))) { - plugin.set(plugins.iterator().next()); - TLocale.Logger.error("TFILTER.EXCEPTION-MIRROR." + message + ".HEAD", args.run()); - for (int i = 0; i < stackTraces.size(); i++) { - StackTraceElement stack = stackTraces.get(i); - TLocale.Logger.error("TFILTER.EXCEPTION-MIRROR." + message + ".STACK-TRACE", String.valueOf(i), stack.toString()); - } - return true; - } - return false; - } - - @Override - public boolean isLoggable(LogRecord e) { - if (!Main.getInst().getConfig().getBoolean("EXCEPTION-MIRROR", true) || e.getThrown() == null) { - return true; - } - // 是否为调度器异常 - if (isScheduleException(e)) { - long time = System.currentTimeMillis(); - AtomicReference plugin = new AtomicReference<>(); - return !printException(plugin, e.getThrown().getStackTrace(), "SCHEDULE", () -> new String[] {plugin.get().getName(), String.valueOf(System.currentTimeMillis() - time), e.getThrown().getClass().getSimpleName(), String.valueOf(e.getThrown().getMessage())}); - } - // 是否为其他可捕捉异常 - else if (isValidException(e.getThrown())) { - // 事件异常 - if (e.getThrown() instanceof EventException) { - Matcher matcher = patternEvent.matcher(e.getMessage()); - if (matcher.find()) { - long time = System.currentTimeMillis(); - AtomicReference plugin = new AtomicReference<>(); - return !printException(plugin, e.getThrown().getCause().getStackTrace(), "EVENT", () -> new String[] {plugin.get().getName(), String.valueOf(System.currentTimeMillis() - time), matcher.group(1), e.getThrown().getCause().getClass().getSimpleName(), String.valueOf(e.getThrown().getCause().getMessage())}); - } - } - // 命令异常 - else if (e.getThrown() instanceof CommandException) { - Matcher matcher = patternCommand.matcher(e.getThrown().getMessage()); - if (matcher.find()) { - long time = System.currentTimeMillis(); - AtomicReference plugin = new AtomicReference<>(); - return !printException(plugin, e.getThrown().getCause().getStackTrace(), "COMMAND", () -> new String[] {plugin.get().getName(), String.valueOf(System.currentTimeMillis() - time), matcher.group(1), e.getThrown().getCause().getClass().getSimpleName(), String.valueOf(e.getThrown().getCause().getMessage())}); - } - } - // 其他异常 - else { - long time = System.currentTimeMillis(); - AtomicReference plugin = new AtomicReference<>(); - return !printException(plugin, e.getThrown().getCause().getStackTrace(), "OTHER", () -> new String[] {plugin.get().getName(), String.valueOf(System.currentTimeMillis() - time), e.getThrown().getCause().getClass().getSimpleName(), String.valueOf(e.getThrown().getCause().getMessage())}); - } - } - return true; - } -} diff --git a/src/main/scala/com/ilummc/tlib/filter/impl/FilterInvalidPluginLoader.java b/src/main/scala/com/ilummc/tlib/filter/impl/FilterInvalidPluginLoader.java deleted file mode 100644 index e93cdf8..0000000 --- a/src/main/scala/com/ilummc/tlib/filter/impl/FilterInvalidPluginLoader.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.ilummc.tlib.filter.impl; - -import com.ilummc.tlib.filter.TLoggerFilterHandler; - -import java.util.logging.LogRecord; - -/** - * @Author 坏黑 - * @Since 2018-11-29 11:47 - */ -public class FilterInvalidPluginLoader extends TLoggerFilterHandler { - - @Override - public boolean isLoggable(LogRecord e) { - // 屏蔽插件加载器注入导致的警告信息 - return !String.valueOf(e.getMessage()).contains("Enabled plugin with unregistered PluginClassLoader"); - } -} diff --git a/src/main/scala/com/ilummc/tlib/inject/TConfigInjector.java b/src/main/scala/com/ilummc/tlib/inject/TConfigInjector.java deleted file mode 100644 index d7f788d..0000000 --- a/src/main/scala/com/ilummc/tlib/inject/TConfigInjector.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.ilummc.tlib.inject; - -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 org.apache.commons.lang3.Validate; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import org.yaml.snakeyaml.DumperOptions; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Field; -import java.nio.charset.Charset; -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 { - 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()); - } - } - Object obj = unserialize(plugin, clazz); - if (config.readOnly()) { - saveConfig(plugin, obj); - } - return obj; - } catch (NullPointerException e) { - TLocale.Logger.warn("CONFIG.LOAD-FAIL-NO-ANNOTATION", plugin.toString(), clazz.getSimpleName()); - } catch (Exception e) { - 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 { - TConfig config = clazz.getAnnotation(TConfig.class); - Validate.notNull(config); - return ConfigUtils.confToObj( - ConfigUtils.mapToConf( - ConfigUtils.yamlToMap( - 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()); - return null; - } catch (Exception e) { - try { - return clazz.newInstance(); - } catch (InstantiationException | IllegalAccessException e1) { - TLocale.Logger.warn("CONFIG.LOAD-FAIL", plugin.toString(), clazz.getSimpleName()); - return null; - } - } - } - - public static Map serialize(Plugin plugin, Object object) { - try { - TConfig config = object.getClass().getAnnotation(TConfig.class); - Validate.notNull(config); - return ConfigUtils.objToMap(ConfigUtils.objToConf(object).getValues(false), config.excludeModifiers()); - } catch (NullPointerException e) { - TLocale.Logger.warn("CONFIG.SAVE-FAIL-NO-ANNOTATION", plugin.toString(), object.getClass().getSimpleName()); - } catch (Exception e) { - TLocale.Logger.warn("CONFIG.SAVE-FAIL", plugin.toString(), object.getClass().getSimpleName()); - } - return null; - } - - public static void saveConfig(Plugin plugin, Object object) throws IOException, NullPointerException { - TConfig config = object.getClass().getAnnotation(TConfig.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); - File target = new File(plugin.getDataFolder(), config.name()); - if (!target.exists()) { - target.createNewFile(); - } - byte[] arr = configuration.saveToString().getBytes(config.charset()); - Files.write(arr, target); - } - -} diff --git a/src/main/scala/com/ilummc/tlib/inject/TDependencyInjector.java b/src/main/scala/com/ilummc/tlib/inject/TDependencyInjector.java deleted file mode 100644 index 448fa29..0000000 --- a/src/main/scala/com/ilummc/tlib/inject/TDependencyInjector.java +++ /dev/null @@ -1,188 +0,0 @@ -package com.ilummc.tlib.inject; - -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.annotations.*; -import com.ilummc.tlib.dependency.TDependency; -import com.ilummc.tlib.resources.TLocale; -import com.ilummc.tlib.resources.TLocaleLoader; -import com.ilummc.tlib.util.Ref; -import me.skymc.taboolib.TabooLib; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; - -import java.io.File; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Izzel_Aliz - */ -public class TDependencyInjector { - - private static List injected = new ArrayList<>(); - - static void injectOnEnable(Plugin plugin) { - inject(plugin, plugin); - } - - static void ejectOnDisable(Plugin plugin) { - eject(plugin, plugin); - } - - public static boolean injected(Plugin plugin) { - return injected.contains(plugin.getName()); - } - - public static void inject(Plugin plugin, Object o) { - if (!injected.contains(plugin.getName())) { - injected.add(plugin.getName()); - TLocaleLoader.load(plugin, true); - injectDependencies(plugin, o); - injectLogger(plugin, o); - injectConfig(plugin, o); - injectPluginInstance(plugin, o); - } - } - - public static void eject(Plugin plugin, Object o) { - try { - injected.remove(plugin.getName()); - ejectConfig(plugin, o); - } catch (Throwable ignored) { - } - } - - 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; - } - - private static void ejectConfig(Plugin plugin, Object o) { - for (Field field : Ref.getDeclaredFields(o.getClass())) { - TConfig config; - if ((config = field.getType().getAnnotation(TConfig.class)) != null && config.saveOnExit()) { - try { - field.setAccessible(true); - TConfigInjector.saveConfig(plugin, field.get(o)); - TLocale.Logger.info("CONFIG.SAVE-SUCCESS", plugin.toString(), config.name()); - } catch (Exception e) { - TLocale.Logger.warn("CONFIG.SAVE-FAIL", plugin.toString(), config.name()); - e.printStackTrace(); - } - } - } - } - - private static void injectConfig(Plugin plugin, Object o) { - for (Field field : Ref.getDeclaredFields(o.getClass())) { - try { - TConfig config; - if ((config = field.getType().getAnnotation(TConfig.class)) != null) { - field.setAccessible(true); - Object obj = TConfigInjector.loadConfig(plugin, field.getType()); - if (obj != null) { - TLocale.Logger.info("CONFIG.LOAD-SUCCESS", plugin.toString(), config.name()); - field.set(o, obj); - if (config.listenChanges()) { - TLocale.Logger.info("CONFIG.LISTEN-START", plugin.toString(), config.name()); - TLib.getTLib().getConfigWatcher().addOnListen( - new File(plugin.getDataFolder(), config.name()), - obj, - object -> { - try { - TConfigInjector.reloadConfig(plugin, object); - TLocale.Logger.info("CONFIG.RELOAD-SUCCESS", plugin.toString(), config.name()); - } catch (Exception ignored) { - TLocale.Logger.warn("CONFIG.RELOAD-FAIL", plugin.toString(), config.name()); - } - } - ); - } - } - } - } catch (Exception ignored) { - } - } - } - - private static void injectLogger(Plugin plugin, Object o) { - for (Field field : Ref.getDeclaredFields(o.getClass())) { - try { - Logger logger; - if ((logger = field.getAnnotation(Logger.class)) != null) { - field.getType().asSubclass(com.ilummc.tlib.logger.TLogger.class); - com.ilummc.tlib.logger.TLogger tLogger = new com.ilummc.tlib.logger.TLogger(logger.value(), plugin, logger.level()); - if (!field.isAccessible()) { - field.setAccessible(true); - } - field.set(o, tLogger); - TLoggerManager.setDefaultLogger(plugin, tLogger); - } - } catch (Exception ignored2) { - } - } - } - - private static void injectPluginInstance(Plugin plugin, Object o) { - for (Field field : Ref.getDeclaredFields(o.getClass())) { - try { - PluginInstance instance; - if ((instance = field.getAnnotation(PluginInstance.class)) != null) { - if (!field.isAccessible()) { - field.setAccessible(true); - } - field.getType().asSubclass(JavaPlugin.class); - Plugin pl; - if ((pl = Bukkit.getPluginManager().getPlugin(instance.value())) == null) { - if (!TDependency.requestPlugin(instance.value())) { - TLocale.Logger.warn("PLUGIN-AUTOLOAD-FAIL", plugin.getName(), instance.value()); - return; - } else { - pl = Bukkit.getPluginManager().getPlugin(instance.value()); - } - } - if (pl != null) { - field.set(o, pl); - } - } - } catch (Exception ignored) { - } - } - } - - private static void injectDependencies(Plugin plugin, Object o) { - Dependency[] dependencies = getDependencies(o); - if (dependencies.length != 0) { - TLocale.Logger.info("DEPENDENCY.LOADING-START", plugin.getName()); - for (Dependency dependency : dependencies) { - if (dependency.type() == Dependency.Type.PLUGIN) { - if (TDependency.requestPlugin(dependency.plugin())) { - TabooLib.debug(" Loaded " + dependency.plugin() + " (" + plugin.getName() + ")"); -// TLocale.Logger.info("DEPENDENCY.PLUGIN-LOAD-SUCCESS", plugin.getName(), dependency.plugin()); - } else { - TLocale.Logger.warn("DEPENDENCY.PLUGIN-LOAD-FAIL", plugin.getName(), dependency.plugin()); - } - } - if (dependency.type() == Dependency.Type.LIBRARY) { - if (TDependency.requestLib(dependency.maven(), dependency.mavenRepo(), dependency.url())) { - TabooLib.debug(" Loaded " + String.join(":", dependency.maven()) + " (" + plugin.getName() + ")"); -// TLocale.Logger.info("DEPENDENCY.LIBRARY-LOAD-SUCCESS", plugin.getName(), String.join(":", dependency.maven())); - } else { - TLocale.Logger.warn("DEPENDENCY.LIBRARY-LOAD-FAIL", plugin.getName(), String.join(":", dependency.maven())); - } - } - } - TLocale.Logger.info("DEPENDENCY.LOAD-COMPLETE"); - } - } -} diff --git a/src/main/scala/com/ilummc/tlib/inject/TPluginManager.java b/src/main/scala/com/ilummc/tlib/inject/TPluginManager.java deleted file mode 100644 index 31a5849..0000000 --- a/src/main/scala/com/ilummc/tlib/inject/TPluginManager.java +++ /dev/null @@ -1,231 +0,0 @@ -package com.ilummc.tlib.inject; - -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.Main; -import org.bukkit.Bukkit; -import org.bukkit.Server; -import org.bukkit.command.SimpleCommandMap; -import org.bukkit.event.Event; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.permissions.Permissible; -import org.bukkit.permissions.Permission; -import org.bukkit.plugin.*; - -import java.io.File; -import java.lang.reflect.Field; -import java.util.*; -import java.util.regex.Pattern; - -@SuppressWarnings("unused") -public class TPluginManager implements PluginManager { - - private static TPluginManager singleton; - private final PluginManager instance; - private final Main main = (Main) Main.getInst(); - private static File updateDirectory = null; - private Server server; - private Map fileAssociations = new HashMap<>(); - private List plugins = new ArrayList<>(); - private Map lookupNames = new HashMap<>(); - private SimpleCommandMap commandMap; - private Map permissions = new HashMap<>(); - private Map> defaultPerms = new LinkedHashMap<>(); - private Map> permSubs = new HashMap<>(); - private Map> defSubs = new HashMap<>(); - private boolean useTimings = false; - private List delayedDisable = new ArrayList<>(); - - public static void delayDisable(Plugin plugin) { - if (!singleton.delayedDisable.contains(plugin)) { - singleton.delayedDisable.add(plugin); - } - } - - public TPluginManager() { - instance = Bukkit.getPluginManager(); - // clone all Field in SimplePluginManager - cloneField("updateDirectory"); - cloneField("server"); - cloneField("fileAssociations"); - cloneField("plugins"); - cloneField("lookupNames"); - cloneField("commandMap"); - cloneField("permissions"); - cloneField("defaultPerms"); - cloneField("permSubs"); - cloneField("defSubs"); - cloneField("useTimings"); - singleton = this; - } - - private void cloneField(String bukkitName) { - try { - Field bukkitField = instance.getClass().getDeclaredField(bukkitName); - Field thisFiled = this.getClass().getDeclaredField(bukkitName); - if (bukkitField == null || thisFiled == null) { - TLocale.Logger.warn("MISC.FIELD-COPY-FAILED", bukkitName); - return; - } - bukkitField.setAccessible(true); - thisFiled.setAccessible(true); - thisFiled.set(this, bukkitField.get(instance)); - } catch (Exception e) { - TLocale.Logger.error("MISC.FIELD-COPY-ERROR", bukkitName, e.toString()); - } - } - - @Override - public void registerInterface(Class aClass) throws IllegalArgumentException { - instance.registerInterface(aClass); - } - - @Override - public Plugin getPlugin(String s) { - return instance.getPlugin(s); - } - - @Override - public Plugin[] getPlugins() { - return instance.getPlugins(); - } - - @Override - public boolean isPluginEnabled(String s) { - return instance.isPluginEnabled(s); - } - - @Override - public boolean isPluginEnabled(Plugin plugin) { - return instance.isPluginEnabled(plugin); - } - - @Override - public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException { - return instance.loadPlugin(file); - } - - @Override - public Plugin[] loadPlugins(File file) { - return instance.loadPlugins(file); - } - - @Override - public void disablePlugins() { - for (Plugin plugin : getPlugins()) { - if (plugin != main && !delayedDisable.contains(plugin)) { - disablePlugin(plugin); - } - } - Collections.reverse(delayedDisable); - delayedDisable.forEach(singleton::disablePlugin); - disablePlugin(main); - } - - @Override - public void clearPlugins() { - instance.clearPlugins(); - } - - @Override - public void callEvent(Event event) throws IllegalStateException { - instance.callEvent(event); - } - - @Override - public void registerEvents(Listener listener, Plugin plugin) { - instance.registerEvents(listener, plugin); - } - - @Override - public void registerEvent(Class aClass, Listener listener, EventPriority eventPriority, EventExecutor eventExecutor, Plugin plugin) { - instance.registerEvent(aClass, listener, eventPriority, eventExecutor, plugin); - } - - @Override - public void registerEvent(Class aClass, Listener listener, EventPriority eventPriority, EventExecutor eventExecutor, Plugin plugin, boolean b) { - instance.registerEvent(aClass, listener, eventPriority, eventExecutor, plugin, b); - } - - @Override - public void enablePlugin(Plugin plugin) { - TDependencyInjector.injectOnEnable(plugin); - instance.enablePlugin(plugin); - } - - @Override - public void disablePlugin(Plugin plugin) { - TDependencyInjector.ejectOnDisable(plugin); - instance.disablePlugin(plugin); - } - - @Override - public Permission getPermission(String s) { - return instance.getPermission(s); - } - - @Override - public void addPermission(Permission permission) { - instance.addPermission(permission); - } - - @Override - public void removePermission(Permission permission) { - instance.removePermission(permission); - } - - @Override - public void removePermission(String s) { - instance.removePermission(s); - } - - @Override - public Set getDefaultPermissions(boolean b) { - return instance.getDefaultPermissions(b); - } - - @Override - public void recalculatePermissionDefaults(Permission permission) { - instance.recalculatePermissionDefaults(permission); - } - - @Override - public void subscribeToPermission(String s, Permissible permissible) { - instance.subscribeToPermission(s, permissible); - } - - @Override - public void unsubscribeFromPermission(String s, Permissible permissible) { - instance.unsubscribeFromPermission(s, permissible); - } - - @Override - public Set getPermissionSubscriptions(String s) { - return instance.getPermissionSubscriptions(s); - } - - @Override - public void subscribeToDefaultPerms(boolean b, Permissible permissible) { - instance.subscribeToDefaultPerms(b, permissible); - } - - @Override - public void unsubscribeFromDefaultPerms(boolean b, Permissible permissible) { - instance.unsubscribeFromDefaultPerms(b, permissible); - } - - @Override - public Set getDefaultPermSubscriptions(boolean b) { - return instance.getDefaultPermSubscriptions(b); - } - - @Override - public Set getPermissions() { - return instance.getPermissions(); - } - - @Override - public boolean useTimings() { - return instance.useTimings(); - } -} diff --git a/src/main/scala/com/ilummc/tlib/nms/ActionBar.java b/src/main/scala/com/ilummc/tlib/nms/ActionBar.java deleted file mode 100644 index 46e3edc..0000000 --- a/src/main/scala/com/ilummc/tlib/nms/ActionBar.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.ilummc.tlib.nms; - -import com.ilummc.tlib.util.asm.AsmClassTransformer; -import me.skymc.taboolib.TabooLib; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -public abstract class ActionBar { - - private static ActionBar instance; - - static { - if (TabooLib.getVerint() > 11100) { - instance = (ActionBar) AsmClassTransformer.builder().from(Impl_1_12.class).fromVersion("v1_12_R1") - .toVersion(Bukkit.getServer().getClass().getName().split("\\.")[3]).build().transform(); - } else { - instance = (ActionBar) AsmClassTransformer.builder().from(Impl_1_8.class).fromVersion("v1_8_R3") - .toVersion(Bukkit.getServer().getClass().getName().split("\\.")[3]).build().transform(); - } - } - - public static void sendActionBar(Player player, String text) { - instance.send(player, text); - } - - public abstract void send(Player player, String text); - - public static class Impl_1_8 extends ActionBar { - - @Override - public void send(Player player, String text) { - net.minecraft.server.v1_8_R3.ChatComponentText component = new net.minecraft.server.v1_8_R3.ChatComponentText(text); - net.minecraft.server.v1_8_R3.PacketPlayOutChat packet = new net.minecraft.server.v1_8_R3.PacketPlayOutChat(component, (byte) 2); - ((org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); - } - } - - public static class Impl_1_12 extends ActionBar { - - @Override - public void send(Player player, String text) { - net.minecraft.server.v1_12_R1.ChatComponentText component = new net.minecraft.server.v1_12_R1.ChatComponentText(text); - net.minecraft.server.v1_12_R1.PacketPlayOutChat packet = new net.minecraft.server.v1_12_R1.PacketPlayOutChat(component, net.minecraft.server.v1_12_R1.ChatMessageType.a((byte) 2)); - ((org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); - } - } -} diff --git a/src/main/scala/com/ilummc/tlib/resources/TLocaleSender.java b/src/main/scala/com/ilummc/tlib/resources/TLocaleSender.java deleted file mode 100644 index 6d75fd4..0000000 --- a/src/main/scala/com/ilummc/tlib/resources/TLocaleSender.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.ilummc.tlib.resources; - -import org.bukkit.command.CommandSender; - -import java.util.List; - -/** - * @Author sky - * @Since 2018-05-12 13:58 - */ -public interface TLocaleSender { - - /** - * 发送信息 - * - * @param sender 发送目标 - * @param args 参数 - */ - void sendTo(CommandSender sender, String... args); - - /** - * 获取文本 - * - * @param args 参数 - * @return 文本 - */ - String asString(String... args); - - /** - * 获取文本集合 - * - * @param args 参数 - * @return 文本集合 - */ - List asStringList(String... args); - -} diff --git a/src/main/scala/com/ilummc/tlib/util/IO.java b/src/main/scala/com/ilummc/tlib/util/IO.java deleted file mode 100644 index 92d4d16..0000000 --- a/src/main/scala/com/ilummc/tlib/util/IO.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.ilummc.tlib.util; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -public class IO { - - public static byte[] readFully(InputStream inputStream) throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - byte[] buf = new byte[1024]; - int len = 0; - while ((len = inputStream.read(buf)) > 0) { - stream.write(buf, 0, len); - } - return stream.toByteArray(); - } -} diff --git a/src/main/scala/com/ilummc/tlib/util/Strings.java b/src/main/scala/com/ilummc/tlib/util/Strings.java deleted file mode 100644 index 40207d0..0000000 --- a/src/main/scala/com/ilummc/tlib/util/Strings.java +++ /dev/null @@ -1,48 +0,0 @@ -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 倍 - * - * @param template 模板替换文件 - * @param args 替换的参数 - * @return 替换好的字符串 - */ - public static String replaceWithOrder(String template, Object... args) { - if (args.length == 0 || template.length() == 0) { - return template; - } - char[] arr = template.toCharArray(); - StringBuilder stringBuilder = new StringBuilder(template.length()); - for (int i = 0; i < arr.length; i++) { - if (arr[i] == '{' && Character.isDigit(arr[Math.min(i + 1, arr.length - 1)]) - && arr[Math.min(i + 1, arr.length - 1)] - '0' < args.length - && arr[Math.min(i + 2, arr.length - 1)] == '}') { - stringBuilder.append(args[arr[i + 1] - '0']); - i += 2; - } else { - stringBuilder.append(arr[i]); - } - } - return stringBuilder.toString(); - } - - // ********************************* - // - // Deprecated - // - // ********************************* - - public static String replaceWithOrder(String template, String... args) { - return replaceWithOrder(template, (Object[]) args); - } -} diff --git a/src/main/scala/com/ilummc/tlibscala/runtime/RichOfflinePlayer.scala b/src/main/scala/com/ilummc/tlibscala/runtime/RichOfflinePlayer.scala deleted file mode 100644 index fa3d7f1..0000000 --- a/src/main/scala/com/ilummc/tlibscala/runtime/RichOfflinePlayer.scala +++ /dev/null @@ -1,30 +0,0 @@ -package com.ilummc.tlibscala.runtime - -import me.skymc.taboolib.Main -import me.skymc.taboolib.economy.EcoUtils -import me.skymc.taboolib.inventory.builder.ItemBuilder -import org.bukkit.OfflinePlayer -import org.bukkit.inventory.ItemStack - -class RichOfflinePlayer(private val offlinePlayer: OfflinePlayer) { - - def getSkullItem: ItemStack = new ItemBuilder(offlinePlayer).build() - - def getMoney: Double = EcoUtils.get(offlinePlayer) - - def withdraw(x: Double): Boolean = Main.getEconomy.withdrawPlayer(offlinePlayer, x).transactionSuccess - - def deposit(x: Double): Boolean = Main.getEconomy.depositPlayer(offlinePlayer, x).transactionSuccess - - def hasMoney(x: Double): Boolean = Main.getEconomy.has(offlinePlayer, x) - -} - - -object RichOfflinePlayer { - - implicit def player2rich(player: OfflinePlayer): RichOfflinePlayer = new RichOfflinePlayer(player) - - implicit def rich2player(player: RichOfflinePlayer): OfflinePlayer = player.offlinePlayer - -} \ No newline at end of file diff --git a/src/main/scala/com/ilummc/tlibscala/runtime/RichPlayer.scala b/src/main/scala/com/ilummc/tlibscala/runtime/RichPlayer.scala deleted file mode 100644 index 448a8b7..0000000 --- a/src/main/scala/com/ilummc/tlibscala/runtime/RichPlayer.scala +++ /dev/null @@ -1,68 +0,0 @@ -package com.ilummc.tlibscala.runtime - -import com.ilummc.tlib.resources.TLocale -import me.skymc.taboolib.anvil.AnvilContainerAPI -import me.skymc.taboolib.display.{ActionUtils, TitleUtils} -import me.skymc.taboolib.permission.PermissionUtils -import me.skymc.taboolib.player.PlayerUtils -import me.skymc.taboolib.scoreboard.ScoreboardUtil -import me.skymc.taboolib.sign.SignUtils -import org.bukkit.block.Block -import org.bukkit.entity.Player - -import scala.collection.JavaConverters._ - -class RichPlayer(private val player: Player) extends RichOfflinePlayer(player) { - - def sendActionBar(x: String): Unit = ActionUtils.send(player, x) - - def getFishTicks: Int = PlayerUtils.getFishingTicks(PlayerUtils.getPlayerHookedFish(player)) - - def setFishTicks(x: Int): Unit = PlayerUtils.setFishingTicks(PlayerUtils.getPlayerHookedFish(player), x) - - def resetData(): Unit = PlayerUtils.resetData(player, false) - - def resetData(scoreboard: Boolean): Unit = PlayerUtils.resetData(player, scoreboard) - - def displaySidebar(title: String, elements: Map[String, Integer]): Unit = ScoreboardUtil.rankedSidebarDisplay(player, title, mapAsJavaMap(elements)) - - def displaySidebarUnranked(title: String, elements: Array[String]): Unit = ScoreboardUtil.unrankedSidebarDisplay(player, elements: _*) - - def displaySidebarUnranked(title: String, elements: List[String]): Unit = ScoreboardUtil.unrankedSidebarDisplay(player, elements: _*) - - def displaySidebarUnranked(title: String, elements: String*): Unit = ScoreboardUtil.unrankedSidebarDisplay(player, elements: _*) - - def openSign(block: Block): Unit = SignUtils.openSign(player, block) - - def openSign(lines: Array[String], id: String): Unit = SignUtils.openSign(player, lines, id) - - //todo TagDataHandler - - def addPermission(perm: String): Unit = PermissionUtils.addPermission(player, perm) - - def removePermission(perm: String): Unit = PermissionUtils.removePermission(player, perm) - - def sendTitle(title: String, subtitle: String, fadein: Int, stay: Int, fadeout: Int): Unit = TitleUtils.sendTitle(player, title, subtitle, fadein, stay, fadeout) - - def sendTitle(p: Player, title: String, fadeint: Int, stayt: Int, fadeoutt: Int, subtitle: String, fadeinst: Int, stayst: Int, fadeoutst: Int): Unit = TitleUtils.sendTitle(p, title, fadeint, stayt, fadeoutt, subtitle, fadeinst, stayst, fadeoutst) - - def openAnvil(): Unit = AnvilContainerAPI.openAnvil(player) - - def sendLocalizedMessage(node: String, params: String*): Unit = TLocale.sendTo(player, node, params: _*) - - def locale(node: String, params: String*): Unit = sendLocalizedMessage(node, params: _*) - - def <<(text: String): RichPlayer = { - player.sendMessage(text) - this - } - -} - -object RichPlayer { - - implicit def player2rich(player: Player): RichPlayer = new RichPlayer(player) - - implicit def rich2player(player: RichPlayer): Player = player.player - -} diff --git a/src/main/scala/me/skymc/taboolib/bstats/Metrics.java b/src/main/scala/io/izzel/taboolib/Metrics.java similarity index 97% rename from src/main/scala/me/skymc/taboolib/bstats/Metrics.java rename to src/main/scala/io/izzel/taboolib/Metrics.java index 89db7bf..89d46af 100644 --- a/src/main/scala/me/skymc/taboolib/bstats/Metrics.java +++ b/src/main/scala/io/izzel/taboolib/Metrics.java @@ -1,11 +1,11 @@ -package me.skymc.taboolib.bstats; +package io.izzel.taboolib; import org.bukkit.Bukkit; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.ServicePriority; -import org.bukkit.plugin.java.JavaPlugin; import org.json.simple.JSONArray; import org.json.simple.JSONObject; @@ -55,7 +55,7 @@ public class Metrics { } // The plugin - private final JavaPlugin plugin; + private final Plugin plugin; // A list with all custom charts private final List charts = new ArrayList<>(); @@ -65,7 +65,7 @@ public class Metrics { * * @param plugin The plugin which stats should be submitted. */ - public Metrics(JavaPlugin plugin) { + public Metrics(Plugin plugin) { if (plugin == null) { throw new IllegalArgumentException("Plugin cannot be null!"); } @@ -78,27 +78,17 @@ public class Metrics { // Check if the config file exists if (!config.isSet("serverUuid")) { - // Add default values config.addDefault("enabled", true); // Every server gets it's unique random id. config.addDefault("serverUuid", UUID.randomUUID().toString()); // Should failed request be logged? config.addDefault("logFailedRequests", false); - - // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly no effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" - ).copyDefaults(true); try { config.save(configFile); } catch (IOException ignored) { } } - // Load the data serverUUID = config.getString("serverUuid"); logFailedRequests = config.getBoolean("logFailedRequests", false); diff --git a/src/main/scala/io/izzel/taboolib/PluginLoader.java b/src/main/scala/io/izzel/taboolib/PluginLoader.java new file mode 100644 index 0000000..51d7854 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/PluginLoader.java @@ -0,0 +1,117 @@ +package io.izzel.taboolib; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import io.izzel.taboolib.module.command.TCommandHandler; +import io.izzel.taboolib.module.config.TConfig; +import io.izzel.taboolib.module.config.TConfigWatcher; +import io.izzel.taboolib.module.db.IHost; +import io.izzel.taboolib.module.db.local.Local; +import io.izzel.taboolib.module.db.source.DBSource; +import io.izzel.taboolib.module.dependency.TDependencyInjector; +import io.izzel.taboolib.module.inject.TListenerHandler; +import io.izzel.taboolib.module.inject.TScheduleLoader; +import io.izzel.taboolib.module.locale.TLocaleLoader; +import org.bukkit.plugin.Plugin; + +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** + * @Author 坏黑 + * @Since 2019-07-05 15:14 + */ +public abstract class PluginLoader { + + private static List registerLoader = Lists.newArrayList(); + private static Set plugins = Sets.newHashSet(); + + static { + registerLoader.add(new PluginLoader() { + + @Override + public void onLoading(Plugin plugin) { + // 加载语言文件 + TLocaleLoader.load(plugin, false); + // 注入依赖 + TDependencyInjector.inject(plugin, plugin.getClass()); + // 读取插件类 + TabooLibLoader.setupClasses(plugin); + // 加载插件类 + TabooLibLoader.getPluginClassSafely(plugin).forEach(c -> TabooLibLoader.preLoadClass(plugin, c)); + } + + @Override + public void onStarting(Plugin plugin) { + // 加载监听器 + TListenerHandler.setupListener(plugin); + // 加载插件类 + TabooLibLoader.getPluginClassSafely(plugin).forEach(c -> TabooLibLoader.postLoadClass(plugin, c)); + // 注册插件命令 + TCommandHandler.registerCommand(plugin); + } + + @Override + public void onActivated(Plugin plugin) { + // 注册监听器 + TListenerHandler.registerListener(plugin); + // 注册调度器 + TScheduleLoader.run(plugin); + } + + @Override + public void onStopping(Plugin plugin) { + // 卸载语言文件 + TLocaleLoader.unload(plugin); + // 保存数据 + Local.saveFiles(plugin.getName()); + Local.clearFiles(plugin.getName()); + // 注销监听器 + TListenerHandler.cancelListener(plugin); + // 注销插件类 + TabooLibLoader.getPluginClassSafely(plugin).forEach(c -> TabooLibLoader.unloadClass(plugin, c)); + // 注销数据库连接 + Sets.newHashSet(DBSource.getDataSource().keySet()).stream().filter(IHost::isAutoClose).forEach(DBSource::closeDataSource); + // 释放文检动态读取 + Optional.ofNullable(TConfig.getFiles().remove(plugin.getName())).ifPresent(files -> files.forEach(file -> TConfigWatcher.getInst().removeListener(file))); + } + }); + } + + public void onLoading(Plugin plugin) { + } + + public void onStarting(Plugin plugin) { + } + + public void onActivated(Plugin plugin) { + } + + public void onStopping(Plugin plugin) { + } + + public static void addPlugin(Plugin plugin) { + plugins.add(plugin.getName()); + } + + public static void load(Plugin plugin) { + registerLoader.forEach(loader -> loader.onLoading(plugin)); + } + + public static void start(Plugin plugin) { + registerLoader.forEach(loader -> loader.onStarting(plugin)); + } + + public static void active(Plugin plugin) { + registerLoader.forEach(loader -> loader.onActivated(plugin)); + } + + public static void stop(Plugin plugin) { + registerLoader.forEach(loader -> loader.onStopping(plugin)); + } + + public static boolean isPlugin(Plugin plugin) { + return plugins.contains(plugin.getName()); + } +} diff --git a/src/main/scala/io/izzel/taboolib/TabooLib.java b/src/main/scala/io/izzel/taboolib/TabooLib.java new file mode 100644 index 0000000..90891db --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/TabooLib.java @@ -0,0 +1,109 @@ +package io.izzel.taboolib; + +import io.izzel.taboolib.common.plugin.InternalPlugin; +import io.izzel.taboolib.module.config.TConfig; +import io.izzel.taboolib.module.config.TConfigWatcher; +import io.izzel.taboolib.module.db.local.Local; +import io.izzel.taboolib.module.db.local.LocalPlayer; +import io.izzel.taboolib.module.db.source.DBSource; +import io.izzel.taboolib.module.dependency.Dependency; +import io.izzel.taboolib.module.locale.TLocaleLoader; +import io.izzel.taboolib.module.locale.logger.TLogger; +import io.izzel.taboolib.module.nms.NMS; +import io.izzel.taboolib.util.Files; +import io.izzel.taboolib.util.IO; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.util.NumberConversions; + +import java.nio.charset.Charset; +import java.util.concurrent.Executors; + +/** + * @Author 坏黑 + * @Since 2019-07-05 10:39 + *

+ * 注意与 TabooLib4.x 版本的兼容 + * 可能存在同时运行的情况 + */ +@Dependency(type = Dependency.Type.LIBRARY, maven = "org.slf4j:slf4j-api:1.7.25", url = "https://skymc.oss-cn-shanghai.aliyuncs.com/libs/org.slf4j-slf4j-api-1.7.25.jar") +@Dependency(type = Dependency.Type.LIBRARY, maven = "com.zaxxer:HikariCP:3.1.0", url = "https://skymc.oss-cn-shanghai.aliyuncs.com/libs/com.zaxxer-HikariCP-3.1.0.jar") +@Dependency(type = Dependency.Type.LIBRARY, maven = "org.scala-lang:scala-library:2.12.8", url = "https://skymc.oss-cn-shanghai.aliyuncs.com/libs/scala-library-2.12.8.jar") +public class TabooLib { + + private static TabooLib inst = new TabooLib(); + private static TLogger logger; + private static TConfig config; + + // 当前运行版本 + private static double version; + + // 内部语言文件 + private YamlConfiguration internal = new YamlConfiguration(); + + public TabooLib() { + inst = this; + logger = TLogger.getUnformatted("TabooLib"); + // 配置文件从 config.yml 修改为 settings.yml 防止与老版本插件冲突 + config = TConfig.create(getPlugin(), "settings.yml"); + // 加载版本号 + try { + version = NumberConversions.toDouble(IO.readFully(Files.getResource("version"), Charset.forName("utf-8"))); + } catch (Throwable t) { + t.printStackTrace(); + } + // 加载内部语言文件 + try { + internal.loadFromString(IO.readFully(Files.getResource("lang/internal.yml"), Charset.forName("utf-8"))); + } catch (Throwable t) { + t.printStackTrace(); + } + // 加载 TabooLib 语言文件 + TLocaleLoader.load(getPlugin(), false); + // 加载 TabooLib + TabooLibLoader.init(); + // 创建线程检测服务器是否关闭 + Executors.newSingleThreadExecutor().submit(() -> { + while (NMS.handle().isRunning()) { + } + // 保存数据 + Local.saveFiles(); + LocalPlayer.saveFiles(); + // 关闭文件监听 + TConfigWatcher.getInst().unregisterAll(); + // 关闭连接池 + DBSource.closeDataSourceForce(); + // 关闭插件 + PluginLoader.stop(getPlugin()); + }); + } + + public static InternalPlugin getPlugin() { + return InternalPlugin.getPlugin(); + } + + // ********************************* + // + // Getter and Setter + // + // ********************************* + + public static TabooLib getInst() { + return inst; + } + + public static TLogger getLogger() { + return logger; + } + + public static TConfig getConfig() { + return config; + } + + public static double getVersion() { + return version; + } + + public YamlConfiguration getInternal() { + return internal; + } +} diff --git a/src/main/scala/io/izzel/taboolib/TabooLibAPI.java b/src/main/scala/io/izzel/taboolib/TabooLibAPI.java new file mode 100644 index 0000000..fb0bffa --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/TabooLibAPI.java @@ -0,0 +1,91 @@ +package io.izzel.taboolib; + +import io.izzel.taboolib.module.db.local.Local; +import io.izzel.taboolib.module.nms.NMS; +import io.izzel.taboolib.util.Strings; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.server.ServerCommandEvent; +import org.bukkit.plugin.Plugin; + +/** + * @Author 坏黑 + * @Since 2019-07-05 14:31 + */ +public class TabooLibAPI { + + private static boolean bukkit; + private static boolean originLoaded; + + static { + try { + // 判断是否基于 Bukkit 运行 + bukkit = Class.forName("org.bukkit.Bukkit") != null; + // 获取 TabooLib4.x 版本是否载入 + originLoaded = Bukkit.getPluginManager().getPlugin("TabooLib") != null; + } catch (Exception ignored) { + } + } + + public static boolean isBukkit() { + return bukkit; + } + + public static boolean isOriginLoaded() { + return originLoaded; + } + + public static boolean isDependTabooLib(Plugin plugin) { + return PluginLoader.isPlugin(plugin); + } + + public static double[] getTPS() { + return NMS.handle().getTPS(); + } + + public static boolean isDebug() { + return Local.get().get("data").getBoolean("debug"); + } + + public static void setDebug(boolean debug) { + Local.get().get("data").set("debug", debug); + } + + public static void debug(String... args) { + debug(TabooLib.getPlugin(), args); + } + + public static void debug(Plugin plugin, String... args) { + if (!isDebug()) { + return; + } + for (String line : args) { + Bukkit.getConsoleSender().sendMessage("§4[" + plugin.getName() + "][DEBUG] §c" + line); + } + } + + public static boolean dispatchCommand(CommandSender sender, String command) { + try { + if ((sender instanceof Player)) { + PlayerCommandPreprocessEvent e = new PlayerCommandPreprocessEvent((Player) sender, "/" + command); + Bukkit.getPluginManager().callEvent(e); + if (e.isCancelled() || Strings.isBlank(e.getMessage()) || !e.getMessage().startsWith("/")) { + return false; + } + return Bukkit.dispatchCommand(e.getPlayer(), e.getMessage().substring(1)); + } else { + ServerCommandEvent e = new ServerCommandEvent(sender, command); + Bukkit.getPluginManager().callEvent(e); + if (e.isCancelled() || Strings.isBlank(e.getCommand())) { + return false; + } + return Bukkit.dispatchCommand(e.getSender(), e.getCommand()); + } + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } +} diff --git a/src/main/scala/io/izzel/taboolib/TabooLibLoader.java b/src/main/scala/io/izzel/taboolib/TabooLibLoader.java new file mode 100644 index 0000000..55c6bdd --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/TabooLibLoader.java @@ -0,0 +1,151 @@ +package io.izzel.taboolib; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import io.izzel.taboolib.client.TabooLibClient; +import io.izzel.taboolib.client.TabooLibServer; +import io.izzel.taboolib.module.dependency.TDependencyInjector; +import io.izzel.taboolib.module.inject.TSchedule; +import io.izzel.taboolib.util.Files; +import io.izzel.taboolib.util.Reflection; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.util.*; +import java.util.stream.Collectors; + +/** + * @Author 坏黑 + * @Since 2019-07-05 15:30 + */ +public class TabooLibLoader { + + static Map> pluginClasses = Maps.newHashMap(); + static List loaders = Lists.newArrayList(); + + @TSchedule + static void start() { + PluginLoader.active(TabooLib.getPlugin()); + // 通讯网络服务器 + if (TabooLib.getConfig().getBoolean("SERVER")) { + TabooLibServer.main(new String[0]); + } + // 通讯网络客户端 + TabooLibClient.init(); + } + + static void init() { + // 加载依赖 + TDependencyInjector.inject("TabooLib", TabooLib.class); + // 插件统计 + Metrics metrics = new Metrics(TabooLib.getPlugin()); + metrics.addCustomChart(new Metrics.SingleLineChart("plugins_using_taboolib", () -> Math.toIntExact(Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(TabooLibAPI::isDependTabooLib).count()))); + // 读取插件类 + setupClasses(TabooLib.getPlugin()); + // 读取加载器 + pluginClasses.get("TabooLib").stream().filter(TabooLibLoader::isLoader).forEach(pluginClass -> { + try { + loaders.add((Loader) Reflection.instantiateObject(pluginClass)); + } catch (Exception e) { + e.printStackTrace(); + } + loaders.sort(Comparator.comparingInt(Loader::priority)); + }); + // 加载插件 + PluginLoader.load(TabooLib.getPlugin()); + PluginLoader.start(TabooLib.getPlugin()); + } + + public static Optional> getPluginClasses(Plugin plugin) { + return Optional.ofNullable(pluginClasses.get(plugin.getName())); + } + + public static List getPluginClassSafely(Plugin plugin) { + List classes = pluginClasses.get(plugin.getName()); + return classes == null ? new ArrayList<>() : new ArrayList<>(classes); + } + + static boolean isLoader(Class pluginClass) { + return !Loader.class.equals(pluginClass) && Loader.class.isAssignableFrom(pluginClass); + } + + static void setupClasses(Plugin plugin) { + try { + long time = System.currentTimeMillis(); + List classes; + IgnoreClasses annotation = plugin.getClass().getAnnotation(IgnoreClasses.class); + if (annotation != null) { + classes = Files.getClasses(plugin, annotation.value()); + } else { + classes = Files.getClasses(plugin); + } + if (plugin.getName().equals("TabooLib")) { + classes = classes.stream().filter(c -> c.getName().startsWith("io.izzel")).collect(Collectors.toList()); + } + TabooLibAPI.debug("Saved " + classes.size() + " classes (" + plugin.getName() + ") (" + (System.currentTimeMillis() - time) + "ms)"); + pluginClasses.put(plugin.getName(), classes); + } catch (Exception ignored) { + } + } + + static void preLoadClass(Plugin plugin, Class loadClass) { + loaders.forEach(loader -> { + try { + loader.preLoad(plugin, loadClass); + } catch (NoClassDefFoundError ignore) { + } catch (Throwable e) { + e.printStackTrace(); + } + }); + } + + static void postLoadClass(Plugin plugin, Class loadClass) { + loaders.forEach(loader -> { + try { + loader.postLoad(plugin, loadClass); + } catch (NoClassDefFoundError ignore) { + } catch (Throwable e) { + e.printStackTrace(); + } + }); + } + + static void unloadClass(Plugin plugin, Class loadClass) { + loaders.forEach(loader -> { + try { + loader.unload(plugin, loadClass); + } catch (NoClassDefFoundError ignore) { + } catch (Throwable e) { + e.printStackTrace(); + } + }); + } + + public interface Loader { + + default void preLoad(org.bukkit.plugin.Plugin plugin, Class loadClass) { + } + + default void postLoad(org.bukkit.plugin.Plugin plugin, Class loadClass) { + } + + default void unload(Plugin plugin, Class cancelClass) { + } + + default int priority() { + return 0; + } + } + + @Target(ElementType.TYPE) + @Retention(RetentionPolicy.RUNTIME) + public @interface IgnoreClasses { + + String[] value(); + + } +} diff --git a/src/main/scala/io/izzel/taboolib/Version.java b/src/main/scala/io/izzel/taboolib/Version.java new file mode 100644 index 0000000..38d0fee --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/Version.java @@ -0,0 +1,57 @@ +package io.izzel.taboolib; + +import org.bukkit.Bukkit; + +/** + * @Author 坏黑 + * @Since 2019-07-05 14:42 + */ +public enum Version { + + v1_7(10700), v1_8(10800), v1_9(10900), v1_10(11000), v1_11(11100), v1_12(11200), v1_13(11300), v1_14(11400), vNull(0); + + private int versionInt; + + Version(int versionInt) { + this.versionInt = versionInt; + } + + public int getVersionInt() { + return versionInt; + } + + public static boolean isAfter(Version in) { + return getCurrentVersion().getVersionInt() >= in.getVersionInt(); + } + + public static boolean isBefore(Version in) { + return getCurrentVersion().getVersionInt() < in.getVersionInt(); + } + + public static String getBukkitVersion() { + return Bukkit.getServer().getClass().getName().split("\\.")[3]; + } + + public static Version getCurrentVersion() { + String nmsVersion = getBukkitVersion(); + if (nmsVersion.startsWith("v1_7")) { + return v1_7; + } else if (nmsVersion.startsWith("v1_8")) { + return v1_8; + } else if (nmsVersion.startsWith("v1_9")) { + return v1_9; + } else if (nmsVersion.startsWith("v1_10")) { + return v1_10; + } else if (nmsVersion.startsWith("v1_11")) { + return v1_11; + } else if (nmsVersion.startsWith("v1_12")) { + return v1_12; + } else if (nmsVersion.startsWith("v1_13")) { + return v1_13; + } else if (nmsVersion.startsWith("v1_14")) { + return v1_14; + } else { + return vNull; + } + } +} \ No newline at end of file diff --git a/src/main/scala/me/skymc/taboolib/socket/TabooLibClient.java b/src/main/scala/io/izzel/taboolib/client/TabooLibClient.java similarity index 78% rename from src/main/scala/me/skymc/taboolib/socket/TabooLibClient.java rename to src/main/scala/io/izzel/taboolib/client/TabooLibClient.java index 8eb0a24..8e657fc 100644 --- a/src/main/scala/me/skymc/taboolib/socket/TabooLibClient.java +++ b/src/main/scala/io/izzel/taboolib/client/TabooLibClient.java @@ -1,15 +1,15 @@ -package me.skymc.taboolib.socket; +package io.izzel.taboolib.client; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.commands.builder.SimpleCommandBuilder; -import me.skymc.taboolib.other.NumberUtils; -import me.skymc.taboolib.socket.packet.Packet; -import me.skymc.taboolib.socket.packet.PacketSerializer; -import me.skymc.taboolib.socket.packet.impl.PacketCommand; -import me.skymc.taboolib.socket.packet.impl.PacketMessage; -import me.skymc.taboolib.string.ArrayUtils; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.client.packet.Packet; +import io.izzel.taboolib.client.packet.impl.PacketCommand; +import io.izzel.taboolib.client.packet.impl.PacketMessage; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.command.lite.CommandBuilder; +import io.izzel.taboolib.client.packet.PacketSerializer; +import io.izzel.taboolib.util.ArrayUtil; import org.bukkit.Bukkit; +import org.bukkit.util.NumberConversions; import java.io.*; import java.net.Socket; @@ -34,7 +34,7 @@ public class TabooLibClient { public static void init() { if (TabooLibSettings.load()) { connect(); - Bukkit.getScheduler().runTaskTimerAsynchronously(TabooLib.instance(), TabooLibClient::reconnect, 0, 100); + Bukkit.getScheduler().runTaskTimerAsynchronously(TabooLib.getPlugin(), TabooLibClient::reconnect, 0, 100); } else { TLocale.sendToConsole("COMMUNICATION.FAILED-LOAD-SETTINGS", TabooLibSettings.getThrowable().toString()); } @@ -45,7 +45,7 @@ public class TabooLibClient { } public static void reconnect() { - if (System.currentTimeMillis() - latestResponse > NumberUtils.getInteger(TabooLibSettings.getSettings().getProperty("channel.timeout"))) { + if (System.currentTimeMillis() - latestResponse > NumberConversions.toInt(TabooLibSettings.getSettings().getProperty("channel.timeout"))) { connect(); } } @@ -59,7 +59,7 @@ public class TabooLibClient { } try { - socket = new Socket("localhost", NumberUtils.getInteger(TabooLibSettings.getSettings().getProperty("channel.port"))); + socket = new Socket("localhost", NumberConversions.toInt(TabooLibSettings.getSettings().getProperty("channel.port"))); reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), TabooLibSettings.getCharset())); writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), TabooLibSettings.getCharset()), true); notify = false; @@ -81,7 +81,7 @@ public class TabooLibClient { } }); - SimpleCommandBuilder.create("TabooLibClient", TabooLib.instance()) + CommandBuilder.create("TabooLibClient", TabooLib.getPlugin()) .aliases("tclient") .permission("*") .execute((sender, args) -> { @@ -89,13 +89,12 @@ public class TabooLibClient { sender.sendMessage("§c[TabooLibClient] §f/tclient message §7[TEXT] §8- §7发送测试信息"); sender.sendMessage("§c[TabooLibClient] §f/tclient command §7[TEXT] §8- §7发送测试命令"); } else if (args[0].equalsIgnoreCase("message") && args.length > 1) { - sendPacket(new PacketMessage(ArrayUtils.arrayJoin(args, 1))); + sendPacket(new PacketMessage(ArrayUtil.arrayJoin(args, 1))); } else if (args[0].equalsIgnoreCase("command") && args.length > 1) { - sendPacket(new PacketCommand(ArrayUtils.arrayJoin(args, 1))); + sendPacket(new PacketCommand(ArrayUtil.arrayJoin(args, 1))); } else { sender.sendMessage("§c[TabooLibClient] §7指令错误."); } - return true; }).build(); } diff --git a/src/main/scala/me/skymc/taboolib/socket/TabooLibServer.java b/src/main/scala/io/izzel/taboolib/client/TabooLibServer.java similarity index 86% rename from src/main/scala/me/skymc/taboolib/socket/TabooLibServer.java rename to src/main/scala/io/izzel/taboolib/client/TabooLibServer.java index ed2e92a..816d96f 100644 --- a/src/main/scala/me/skymc/taboolib/socket/TabooLibServer.java +++ b/src/main/scala/io/izzel/taboolib/client/TabooLibServer.java @@ -1,12 +1,12 @@ -package me.skymc.taboolib.socket; +package io.izzel.taboolib.client; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.other.NumberUtils; -import me.skymc.taboolib.socket.packet.Packet; -import me.skymc.taboolib.socket.packet.PacketSerializer; -import me.skymc.taboolib.socket.packet.impl.PacketHeartbeat; -import me.skymc.taboolib.socket.packet.impl.PacketQuit; -import me.skymc.taboolib.socket.server.ClientConnection; +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.client.packet.Packet; +import io.izzel.taboolib.client.packet.PacketSerializer; +import io.izzel.taboolib.client.packet.impl.PacketHeartbeat; +import io.izzel.taboolib.client.server.ClientConnection; +import io.izzel.taboolib.client.packet.impl.PacketQuit; +import org.bukkit.util.NumberConversions; import java.io.IOException; import java.net.ServerSocket; @@ -41,7 +41,7 @@ public class TabooLibServer { } try { - server = new ServerSocket(NumberUtils.getInteger(TabooLibSettings.getSettings().getProperty("channel.port"))); + server = new ServerSocket(NumberConversions.toInt(TabooLibSettings.getSettings().getProperty("channel.port"))); println("Starting TabooLib server on " + server.getInetAddress().getHostName() + ":" + server.getLocalPort()); } catch (IOException e) { println("Server starting failed: " + e.toString()); @@ -95,7 +95,7 @@ public class TabooLibServer { } public static void println(Object obj) { - System.out.println(TabooLib.isSpigot() ? obj : "[" + infoFormat.format(System.currentTimeMillis()) + " INFO]: " + obj); + System.out.println(TabooLibAPI.isBukkit() ? obj : "[" + infoFormat.format(System.currentTimeMillis()) + " INFO]: " + obj); } public static Optional> getConnection(int port) { diff --git a/src/main/scala/me/skymc/taboolib/socket/TabooLibSettings.java b/src/main/scala/io/izzel/taboolib/client/TabooLibSettings.java similarity index 97% rename from src/main/scala/me/skymc/taboolib/socket/TabooLibSettings.java rename to src/main/scala/io/izzel/taboolib/client/TabooLibSettings.java index fe39e1b..b14194c 100644 --- a/src/main/scala/me/skymc/taboolib/socket/TabooLibSettings.java +++ b/src/main/scala/io/izzel/taboolib/client/TabooLibSettings.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.socket; +package io.izzel.taboolib.client; import java.io.IOException; import java.io.InputStream; diff --git a/src/main/scala/me/skymc/taboolib/socket/packet/Packet.java b/src/main/scala/io/izzel/taboolib/client/packet/Packet.java similarity index 93% rename from src/main/scala/me/skymc/taboolib/socket/packet/Packet.java rename to src/main/scala/io/izzel/taboolib/client/packet/Packet.java index dcdfcf4..c74c03e 100644 --- a/src/main/scala/me/skymc/taboolib/socket/packet/Packet.java +++ b/src/main/scala/io/izzel/taboolib/client/packet/Packet.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.socket.packet; +package io.izzel.taboolib.client.packet; import com.google.gson.JsonObject; diff --git a/src/main/scala/me/skymc/taboolib/socket/packet/PacketParser.java b/src/main/scala/io/izzel/taboolib/client/packet/PacketParser.java similarity index 92% rename from src/main/scala/me/skymc/taboolib/socket/packet/PacketParser.java rename to src/main/scala/io/izzel/taboolib/client/packet/PacketParser.java index c77cd31..9e95c62 100644 --- a/src/main/scala/me/skymc/taboolib/socket/packet/PacketParser.java +++ b/src/main/scala/io/izzel/taboolib/client/packet/PacketParser.java @@ -1,7 +1,8 @@ -package me.skymc.taboolib.socket.packet; +package io.izzel.taboolib.client.packet; import com.google.gson.JsonObject; -import me.skymc.taboolib.fileutils.FileUtils; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.util.Files; import java.util.ArrayList; import java.util.Arrays; @@ -17,7 +18,7 @@ public class PacketParser { private List> packets = new ArrayList<>(); public PacketParser() { - FileUtils.getClasses(PacketParser.class).stream().filter(clazz -> clazz.isAnnotationPresent(PacketType.class)).forEach(clazz -> packets.add(clazz)); + Files.getClasses(TabooLib.getPlugin()).stream().filter(clazz -> clazz.isAnnotationPresent(PacketType.class)).forEach(clazz -> packets.add(clazz)); } public Packet parser(JsonObject json) { diff --git a/src/main/scala/me/skymc/taboolib/socket/packet/PacketSerializer.java b/src/main/scala/io/izzel/taboolib/client/packet/PacketSerializer.java similarity index 89% rename from src/main/scala/me/skymc/taboolib/socket/packet/PacketSerializer.java rename to src/main/scala/io/izzel/taboolib/client/packet/PacketSerializer.java index ddd5aeb..d44bc6e 100644 --- a/src/main/scala/me/skymc/taboolib/socket/packet/PacketSerializer.java +++ b/src/main/scala/io/izzel/taboolib/client/packet/PacketSerializer.java @@ -1,12 +1,12 @@ -package me.skymc.taboolib.socket.packet; +package io.izzel.taboolib.client.packet; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.TabooLibLoader; -import me.skymc.taboolib.listener.TListener; -import me.skymc.taboolib.socket.packet.impl.PacketEmpty; +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.TabooLibLoader; +import io.izzel.taboolib.client.packet.impl.PacketEmpty; +import io.izzel.taboolib.module.inject.TListener; import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -14,7 +14,6 @@ import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.plugin.Plugin; -import java.lang.reflect.Field; import java.util.Arrays; /** @@ -45,7 +44,7 @@ public class PacketSerializer implements Listener { } public static void loadPacket(Plugin plugin) { - if (TabooLib.isTabooLib(plugin) || TabooLib.isDependTabooLib(plugin)) { + if (plugin.getName().equals("TabooLib") || TabooLibAPI.isDependTabooLib(plugin)) { TabooLibLoader.getPluginClasses(plugin).ifPresent(classes -> classes.stream().filter(pluginClass -> pluginClass.isAnnotationPresent(PacketType.class)).forEach(pluginClass -> parser.getPackets().add(pluginClass))); } } @@ -55,7 +54,7 @@ public class PacketSerializer implements Listener { } public static void unloadPacket(Plugin plugin) { - if (TabooLib.isTabooLib(plugin) || TabooLib.isDependTabooLib(plugin)) { + if (plugin.getName().equals("TabooLib") || TabooLibAPI.isDependTabooLib(plugin)) { TabooLibLoader.getPluginClasses(plugin).ifPresent(classes -> classes.stream().filter(pluginClass -> pluginClass.isAnnotationPresent(PacketType.class)).forEach(pluginClass -> parser.getPackets().remove(pluginClass))); } } diff --git a/src/main/scala/me/skymc/taboolib/socket/packet/PacketType.java b/src/main/scala/io/izzel/taboolib/client/packet/PacketType.java similarity index 88% rename from src/main/scala/me/skymc/taboolib/socket/packet/PacketType.java rename to src/main/scala/io/izzel/taboolib/client/packet/PacketType.java index 10ead35..545c976 100644 --- a/src/main/scala/me/skymc/taboolib/socket/packet/PacketType.java +++ b/src/main/scala/io/izzel/taboolib/client/packet/PacketType.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.socket.packet; +package io.izzel.taboolib.client.packet; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/scala/me/skymc/taboolib/socket/packet/PacketValue.java b/src/main/scala/io/izzel/taboolib/client/packet/PacketValue.java similarity index 91% rename from src/main/scala/me/skymc/taboolib/socket/packet/PacketValue.java rename to src/main/scala/io/izzel/taboolib/client/packet/PacketValue.java index c3166ea..d4f9108 100644 --- a/src/main/scala/me/skymc/taboolib/socket/packet/PacketValue.java +++ b/src/main/scala/io/izzel/taboolib/client/packet/PacketValue.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.socket.packet; +package io.izzel.taboolib.client.packet; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketAlive.java b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketAlive.java similarity index 69% rename from src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketAlive.java rename to src/main/scala/io/izzel/taboolib/client/packet/impl/PacketAlive.java index ebd7c3a..d6356e0 100644 --- a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketAlive.java +++ b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketAlive.java @@ -1,8 +1,8 @@ -package me.skymc.taboolib.socket.packet.impl; +package io.izzel.taboolib.client.packet.impl; -import me.skymc.taboolib.socket.TabooLibServer; -import me.skymc.taboolib.socket.packet.Packet; -import me.skymc.taboolib.socket.packet.PacketType; +import io.izzel.taboolib.client.TabooLibServer; +import io.izzel.taboolib.client.packet.Packet; +import io.izzel.taboolib.client.packet.PacketType; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketCommand.java b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketCommand.java similarity index 75% rename from src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketCommand.java rename to src/main/scala/io/izzel/taboolib/client/packet/impl/PacketCommand.java index ac1bcb4..879ed8d 100644 --- a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketCommand.java +++ b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketCommand.java @@ -1,9 +1,9 @@ -package me.skymc.taboolib.socket.packet.impl; +package io.izzel.taboolib.client.packet.impl; -import me.skymc.taboolib.socket.TabooLibServer; -import me.skymc.taboolib.socket.packet.Packet; -import me.skymc.taboolib.socket.packet.PacketType; -import me.skymc.taboolib.socket.packet.PacketValue; +import io.izzel.taboolib.client.TabooLibServer; +import io.izzel.taboolib.client.packet.Packet; +import io.izzel.taboolib.client.packet.PacketType; +import io.izzel.taboolib.client.packet.PacketValue; import org.bukkit.Bukkit; /** diff --git a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketEmpty.java b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketEmpty.java similarity index 67% rename from src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketEmpty.java rename to src/main/scala/io/izzel/taboolib/client/packet/impl/PacketEmpty.java index dfdce56..ab0f950 100644 --- a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketEmpty.java +++ b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketEmpty.java @@ -1,7 +1,7 @@ -package me.skymc.taboolib.socket.packet.impl; +package io.izzel.taboolib.client.packet.impl; -import me.skymc.taboolib.socket.packet.Packet; -import me.skymc.taboolib.socket.packet.PacketType; +import io.izzel.taboolib.client.packet.Packet; +import io.izzel.taboolib.client.packet.PacketType; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketHeartbeat.java b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketHeartbeat.java similarity index 70% rename from src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketHeartbeat.java rename to src/main/scala/io/izzel/taboolib/client/packet/impl/PacketHeartbeat.java index e28d06c..523f4b5 100644 --- a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketHeartbeat.java +++ b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketHeartbeat.java @@ -1,9 +1,8 @@ -package me.skymc.taboolib.socket.packet.impl; +package io.izzel.taboolib.client.packet.impl; -import me.skymc.taboolib.socket.TabooLibClient; -import me.skymc.taboolib.socket.packet.Packet; -import me.skymc.taboolib.socket.packet.PacketType; -import org.bukkit.Bukkit; +import io.izzel.taboolib.client.TabooLibClient; +import io.izzel.taboolib.client.packet.Packet; +import io.izzel.taboolib.client.packet.PacketType; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketJoin.java b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketJoin.java similarity index 66% rename from src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketJoin.java rename to src/main/scala/io/izzel/taboolib/client/packet/impl/PacketJoin.java index d20ef1a..f7a0f93 100644 --- a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketJoin.java +++ b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketJoin.java @@ -1,9 +1,9 @@ -package me.skymc.taboolib.socket.packet.impl; +package io.izzel.taboolib.client.packet.impl; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.socket.TabooLibServer; -import me.skymc.taboolib.socket.packet.Packet; -import me.skymc.taboolib.socket.packet.PacketType; +import io.izzel.taboolib.client.TabooLibServer; +import io.izzel.taboolib.client.packet.Packet; +import io.izzel.taboolib.client.packet.PacketType; +import io.izzel.taboolib.module.locale.TLocale; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketMessage.java b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketMessage.java similarity index 70% rename from src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketMessage.java rename to src/main/scala/io/izzel/taboolib/client/packet/impl/PacketMessage.java index 9cc9698..2ab419a 100644 --- a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketMessage.java +++ b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketMessage.java @@ -1,11 +1,10 @@ -package me.skymc.taboolib.socket.packet.impl; +package io.izzel.taboolib.client.packet.impl; -import com.google.gson.JsonObject; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.socket.TabooLibServer; -import me.skymc.taboolib.socket.packet.Packet; -import me.skymc.taboolib.socket.packet.PacketType; -import me.skymc.taboolib.socket.packet.PacketValue; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.client.TabooLibServer; +import io.izzel.taboolib.client.packet.Packet; +import io.izzel.taboolib.client.packet.PacketType; +import io.izzel.taboolib.client.packet.PacketValue; import org.bukkit.Bukkit; /** diff --git a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketQuit.java b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketQuit.java similarity index 77% rename from src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketQuit.java rename to src/main/scala/io/izzel/taboolib/client/packet/impl/PacketQuit.java index fcb46fd..0c4ed43 100644 --- a/src/main/scala/me/skymc/taboolib/socket/packet/impl/PacketQuit.java +++ b/src/main/scala/io/izzel/taboolib/client/packet/impl/PacketQuit.java @@ -1,10 +1,10 @@ -package me.skymc.taboolib.socket.packet.impl; +package io.izzel.taboolib.client.packet.impl; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.socket.TabooLibServer; -import me.skymc.taboolib.socket.packet.Packet; -import me.skymc.taboolib.socket.packet.PacketType; -import me.skymc.taboolib.socket.packet.PacketValue; +import io.izzel.taboolib.client.TabooLibServer; +import io.izzel.taboolib.client.packet.Packet; +import io.izzel.taboolib.client.packet.PacketType; +import io.izzel.taboolib.client.packet.PacketValue; +import io.izzel.taboolib.module.locale.TLocale; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/socket/server/ClientConnection.java b/src/main/scala/io/izzel/taboolib/client/server/ClientConnection.java similarity index 85% rename from src/main/scala/me/skymc/taboolib/socket/server/ClientConnection.java rename to src/main/scala/io/izzel/taboolib/client/server/ClientConnection.java index 6c8a4a6..3097685 100644 --- a/src/main/scala/me/skymc/taboolib/socket/server/ClientConnection.java +++ b/src/main/scala/io/izzel/taboolib/client/server/ClientConnection.java @@ -1,10 +1,10 @@ -package me.skymc.taboolib.socket.server; +package io.izzel.taboolib.client.server; -import me.skymc.taboolib.other.NumberUtils; -import me.skymc.taboolib.socket.TabooLibServer; -import me.skymc.taboolib.socket.TabooLibSettings; -import me.skymc.taboolib.socket.packet.impl.PacketJoin; -import me.skymc.taboolib.socket.packet.impl.PacketQuit; +import io.izzel.taboolib.client.TabooLibServer; +import io.izzel.taboolib.client.TabooLibSettings; +import io.izzel.taboolib.client.packet.impl.PacketJoin; +import io.izzel.taboolib.client.packet.impl.PacketQuit; +import org.bukkit.util.NumberConversions; import java.io.BufferedReader; import java.io.InputStreamReader; @@ -53,7 +53,7 @@ public class ClientConnection implements Runnable { } public boolean isAlive() { - return System.currentTimeMillis() - latestResponse < NumberUtils.getInteger(TabooLibSettings.getSettings().getProperty("channel.timeout")); + return System.currentTimeMillis() - latestResponse < NumberConversions.toInt(TabooLibSettings.getSettings().getProperty("channel.timeout")); } // ********************************* diff --git a/src/main/scala/io/izzel/taboolib/common/command/TabooLibExecuteCommand.java b/src/main/scala/io/izzel/taboolib/common/command/TabooLibExecuteCommand.java new file mode 100644 index 0000000..950dc10 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/common/command/TabooLibExecuteCommand.java @@ -0,0 +1,149 @@ +package io.izzel.taboolib.common.command; + +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.command.base.BaseMainCommand; +import io.izzel.taboolib.module.command.base.BaseSubCommand; +import io.izzel.taboolib.module.command.base.BaseCommand; +import io.izzel.taboolib.module.command.base.Argument; +import io.izzel.taboolib.module.command.base.SubCommand; +import io.izzel.taboolib.util.ArrayUtil; +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +/** + * @Author sky + * @Since 2018-07-04 21:32 + */ +@BaseCommand( + name = "tExecute", + permission = "taboolib.admin" +) +public class TabooLibExecuteCommand extends BaseMainCommand { + + @Override + public String getCommandTitle() { + return TLocale.asString("COMMANDS.TEXECUTE.COMMAND-TITLE"); + } + + @SubCommand(priority = 1) + BaseSubCommand chat = new BaseSubCommand() { + + @Override + public String getLabel() { + return "chat"; + } + + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TEXECUTE.CHAT.DESCRIPTION"); + } + + @Override + public Argument[] getArguments() { + return new Argument[] { + new Argument(TLocale.asString("COMMANDS.TEXECUTE.CHAT.ARGUMENTS.0")), + new Argument(TLocale.asString("COMMANDS.TEXECUTE.CHAT.ARGUMENTS.1")) + }; + } + + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + Player player = Bukkit.getPlayerExact(args[0]); + if (player == null) { + TLocale.sendTo(sender, "INVALID-PLAYER-OFFLINE", args[0]); + return; + } + player.chat(ArrayUtil.arrayJoin(args, 1)); + } + }; + + @SubCommand(priority = 1) + BaseSubCommand command = new BaseSubCommand() { + @Override + public String getLabel() { + return "command"; + } + + @Override + public String[] getAliases() { + return new String[] {"cmd"}; + } + + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TEXECUTE.COMMAND.DESCRIPTION"); + } + + @Override + public Argument[] getArguments() { + return new Argument[] { + new Argument(TLocale.asString("COMMANDS.TEXECUTE.COMMAND.ARGUMENTS.0")), + new Argument(TLocale.asString("COMMANDS.TEXECUTE.COMMAND.ARGUMENTS.1")) + }; + } + + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + if (args[0].equalsIgnoreCase("console")) { + TabooLibAPI.dispatchCommand(Bukkit.getConsoleSender(), ArrayUtil.arrayJoin(args, 1)); + return; + } + Player player = Bukkit.getPlayerExact(args[0]); + if (player == null) { + TLocale.sendTo(sender, "INVALID-TARGET-NOT-FOUND", args[0]); + return; + } + TabooLibAPI.dispatchCommand(player, ArrayUtil.arrayJoin(args, 1)); + } + }; + + @SubCommand(priority = 2) + BaseSubCommand commandAsOp = new BaseSubCommand() { + + @Override + public String getLabel() { + return "commandAsOp"; + } + + @Override + public String[] getAliases() { + return new String[] {"op"}; + } + + @Override + public String getDescription() { + return TLocale.asString("COMMANDS.TEXECUTE.COMMAND-AS-OP.DESCRIPTION"); + } + + @Override + public Argument[] getArguments() { + return new Argument[] { + new Argument(TLocale.asString("COMMANDS.TEXECUTE.COMMAND-AS-OP.ARGUMENTS.0")), + new Argument(TLocale.asString("COMMANDS.TEXECUTE.COMMAND-AS-OP.ARGUMENTS.1")) + }; + } + + @Override + public void onCommand(CommandSender sender, Command command, String label, String[] args) { + if (args[0].equalsIgnoreCase("console")) { + TabooLibAPI.dispatchCommand(Bukkit.getConsoleSender(), ArrayUtil.arrayJoin(args, 1)); + return; + } + Player player = Bukkit.getPlayerExact(args[0]); + if (player == null) { + TLocale.sendTo(sender, "INVALID-TARGET-NOT-FOUND", args[0]); + return; + } + boolean isOp = player.isOp(); + player.setOp(true); + try { + TabooLibAPI.dispatchCommand(player, ArrayUtil.arrayJoin(args, 1)); + } catch (Exception ignored) { + } + player.setOp(isOp); + } + }; +} \ No newline at end of file diff --git a/src/main/scala/me/skymc/taboolib/commands/locale/TabooLibLocaleCommand.java b/src/main/scala/io/izzel/taboolib/common/command/TabooLibLocaleCommand.java similarity index 77% rename from src/main/scala/me/skymc/taboolib/commands/locale/TabooLibLocaleCommand.java rename to src/main/scala/io/izzel/taboolib/common/command/TabooLibLocaleCommand.java index 855743e..6372296 100644 --- a/src/main/scala/me/skymc/taboolib/commands/locale/TabooLibLocaleCommand.java +++ b/src/main/scala/io/izzel/taboolib/common/command/TabooLibLocaleCommand.java @@ -1,12 +1,12 @@ -package me.skymc.taboolib.commands.locale; +package io.izzel.taboolib.common.command; -import com.ilummc.tlib.resources.TLocale; -import com.ilummc.tlib.resources.TLocaleLoader; -import me.skymc.taboolib.commands.internal.BaseMainCommand; -import me.skymc.taboolib.commands.internal.BaseSubCommand; -import me.skymc.taboolib.commands.internal.TCommand; -import me.skymc.taboolib.commands.internal.type.CommandArgument; -import me.skymc.taboolib.commands.internal.type.CommandRegister; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.locale.TLocaleLoader; +import io.izzel.taboolib.module.command.base.BaseMainCommand; +import io.izzel.taboolib.module.command.base.BaseSubCommand; +import io.izzel.taboolib.module.command.base.BaseCommand; +import io.izzel.taboolib.module.command.base.Argument; +import io.izzel.taboolib.module.command.base.SubCommand; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -21,9 +21,8 @@ import java.util.stream.IntStream; * @author sky * @since 2018-04-22 14:36:28 */ -@TCommand( - name = "tabooliblocale", - aliases = {"taboolocale", "tlocale"}, +@BaseCommand( + name = "tLocale", permission = "taboolib.admin" ) public class TabooLibLocaleCommand extends BaseMainCommand { @@ -33,7 +32,7 @@ public class TabooLibLocaleCommand extends BaseMainCommand { return TLocale.asString("COMMANDS.TLOCALE.COMMAND-TITLE"); } - @CommandRegister + @SubCommand BaseSubCommand send = new BaseSubCommand() { @Override @@ -47,11 +46,11 @@ public class TabooLibLocaleCommand extends BaseMainCommand { } @Override - public CommandArgument[] getArguments() { - return new CommandArgument[] { - new CommandArgument(TLocale.asString("COMMANDS.TLOCALE.SEND.ARGUMENTS.0")), - new CommandArgument(TLocale.asString("COMMANDS.TLOCALE.SEND.ARGUMENTS.1")), - new CommandArgument(TLocale.asString("COMMANDS.TLOCALE.SEND.ARGUMENTS.2"), false) + public Argument[] getArguments() { + return new Argument[] { + new Argument(TLocale.asString("COMMANDS.TLOCALE.SEND.ARGUMENTS.0")), + new Argument(TLocale.asString("COMMANDS.TLOCALE.SEND.ARGUMENTS.1")), + new Argument(TLocale.asString("COMMANDS.TLOCALE.SEND.ARGUMENTS.2"), false) }; } diff --git a/src/main/scala/me/skymc/taboolib/commands/plugin/TabooLibPluginCommand.java b/src/main/scala/io/izzel/taboolib/common/command/TabooLibPluginCommand.java similarity index 72% rename from src/main/scala/me/skymc/taboolib/commands/plugin/TabooLibPluginCommand.java rename to src/main/scala/io/izzel/taboolib/common/command/TabooLibPluginCommand.java index 79c7a67..bce9e16 100644 --- a/src/main/scala/me/skymc/taboolib/commands/plugin/TabooLibPluginCommand.java +++ b/src/main/scala/io/izzel/taboolib/common/command/TabooLibPluginCommand.java @@ -1,17 +1,18 @@ -package me.skymc.taboolib.commands.plugin; +package io.izzel.taboolib.common.command; import com.google.common.base.Joiner; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.commands.internal.BaseMainCommand; -import me.skymc.taboolib.commands.internal.BaseSubCommand; -import me.skymc.taboolib.commands.internal.TCommand; -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 io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.command.base.BaseCommand; +import io.izzel.taboolib.module.command.base.BaseMainCommand; +import io.izzel.taboolib.module.command.base.BaseSubCommand; +import io.izzel.taboolib.module.command.base.Argument; +import io.izzel.taboolib.module.command.base.SubCommand; +import io.izzel.taboolib.util.plugin.PluginLoadState; +import io.izzel.taboolib.util.plugin.PluginLoadStateType; +import io.izzel.taboolib.util.plugin.PluginUnloadState; +import io.izzel.taboolib.util.plugin.PluginUtils; +import io.izzel.taboolib.util.ArrayUtil; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -25,9 +26,8 @@ import java.util.stream.Collectors; * @Author sky * @Since 2018-05-07 20:14 */ -@TCommand( - name = "taboolibplugin", - aliases = {"tabooplugin", "tplugin"}, +@BaseCommand( + name = "tPlugin", permission = "taboolib.admin" ) public class TabooLibPluginCommand extends BaseMainCommand { @@ -37,18 +37,7 @@ public class TabooLibPluginCommand extends BaseMainCommand { return TLocale.asString("COMMANDS.TPLUGIN.COMMAND-TITLE"); } -// @Override -// public List onTabComplete(CommandSender commandSender, Command command, String s, String[] args) { -// if (args.length == 1) { -// return getSubCommands().stream().filter(internalCommandExecutor -> internalCommandExecutor != null && (args[0].isEmpty() || internalCommandExecutor.getLabel().toLowerCase().startsWith(args[0].toLowerCase()))).map(BaseSubCommand::getLabel).collect(Collectors.toList()); -// } else if (args.length > 1 && isPluginCommand(args[0])) { -// return Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(x -> !PluginUtils.isIgnored(x)).collect(Collectors.toList()).stream().filter(plugin -> args[1].isEmpty() || plugin.getName().toLowerCase().startsWith(args[1].toLowerCase())).map(Plugin::getName).collect(Collectors.toList()); -// } else { -// return null; -// } -// } - - @CommandRegister(priority = 1) + @SubCommand(priority = 1) BaseSubCommand load = new BaseSubCommand() { @Override @@ -62,13 +51,13 @@ public class TabooLibPluginCommand extends BaseMainCommand { } @Override - public CommandArgument[] getArguments() { - return new CommandArgument[] {new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.LOAD.ARGUMENTS.0"), true)}; + public Argument[] getArguments() { + return new Argument[] {new Argument(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); + String name = ArrayUtil.arrayJoin(args, 0); if (PluginUtils.getPluginByName(name) != null) { TLocale.sendTo(sender, "COMMANDS.TPLUGIN.LOAD.INVALID-PLUGIN", name, name + " already loaded!"); } else { @@ -98,7 +87,7 @@ public class TabooLibPluginCommand extends BaseMainCommand { } }; - @CommandRegister(priority = 2) + @SubCommand(priority = 2) BaseSubCommand unload = new BaseSubCommand() { @Override @@ -112,15 +101,15 @@ public class TabooLibPluginCommand extends BaseMainCommand { } @Override - public CommandArgument[] getArguments() { - return new CommandArgument[] {new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.UNLOAD.ARGUMENTS.0"), true, () -> { - return Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(Plugin::getName).collect(Collectors.toList()); + public Argument[] getArguments() { + return new Argument[] {new Argument(TLocale.asString("COMMANDS.TPLUGIN.UNLOAD.ARGUMENTS.0"), true, () -> { + return java.util.Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(Plugin::getName).collect(Collectors.toList()); })}; } @Override public void onCommand(CommandSender sender, Command command, String label, String[] args) { - String name = ArrayUtils.arrayJoin(args, 0); + String name = ArrayUtil.arrayJoin(args, 0); Plugin plugin = PluginUtils.getPluginByName(name); if (plugin == null) { TLocale.sendTo(sender, "COMMANDS.TPLUGIN.UNLOAD.INVALID-PLUGIN", name); @@ -142,7 +131,7 @@ public class TabooLibPluginCommand extends BaseMainCommand { } }; - @CommandRegister(priority = 3) + @SubCommand(priority = 3) BaseSubCommand reload = new BaseSubCommand() { @Override @@ -156,28 +145,28 @@ public class TabooLibPluginCommand extends BaseMainCommand { } @Override - public CommandArgument[] getArguments() { - return new CommandArgument[] {new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.RELOAD.ARGUMENTS.0"), true, () -> { + public Argument[] getArguments() { + return new Argument[] {new Argument(TLocale.asString("COMMANDS.TPLUGIN.RELOAD.ARGUMENTS.0"), true, () -> { return Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(Plugin::getName).collect(Collectors.toList()); })}; } @Override public void onCommand(CommandSender sender, Command command, String label, String[] args) { - String name = ArrayUtils.arrayJoin(args, 0); + String name = ArrayUtil.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); + TabooLibAPI.dispatchCommand(sender, "taboolibplugin unload " + plugin.getName()); + TabooLibAPI.dispatchCommand(sender, "taboolibplugin load " + plugin.getName()); } } }; - @CommandRegister(priority = 4) + @SubCommand(priority = 4) BaseSubCommand info = new BaseSubCommand() { @Override @@ -191,13 +180,15 @@ public class TabooLibPluginCommand extends BaseMainCommand { } @Override - public CommandArgument[] getArguments() { - return new CommandArgument[] {new CommandArgument(TLocale.asString("COMMANDS.TPLUGIN.INFO.ARGUMENTS.0"), true)}; + public Argument[] getArguments() { + return new Argument[] {new Argument(TLocale.asString("COMMANDS.TPLUGIN.INFO.ARGUMENTS.0"), true, () -> { + return Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(Plugin::getName).collect(Collectors.toList()); + })}; } @Override public void onCommand(CommandSender sender, Command command, String label, String[] args) { - String name = ArrayUtils.arrayJoin(args, 0); + String name = ArrayUtil.arrayJoin(args, 0); Plugin plugin = PluginUtils.getPluginByName(name); if (plugin == null) { TLocale.sendTo(sender, "COMMANDS.TPLUGIN.INFO.INVALID-PLUGIN", name); @@ -220,7 +211,7 @@ public class TabooLibPluginCommand extends BaseMainCommand { } }; - @CommandRegister(priority = 5) + @SubCommand(priority = 5) BaseSubCommand list = new BaseSubCommand() { @Override @@ -234,8 +225,8 @@ public class TabooLibPluginCommand extends BaseMainCommand { } @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; + public Argument[] getArguments() { + return new Argument[0]; } @Override diff --git a/src/main/scala/me/skymc/taboolib/events/PlayerJumpEvent.java b/src/main/scala/io/izzel/taboolib/common/event/PlayerJumpEvent.java similarity index 95% rename from src/main/scala/me/skymc/taboolib/events/PlayerJumpEvent.java rename to src/main/scala/io/izzel/taboolib/common/event/PlayerJumpEvent.java index ba602e1..27700ef 100644 --- a/src/main/scala/me/skymc/taboolib/events/PlayerJumpEvent.java +++ b/src/main/scala/io/izzel/taboolib/common/event/PlayerJumpEvent.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.events; +package io.izzel.taboolib.common.event; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; diff --git a/src/main/scala/me/skymc/taboolib/events/PlayerLoadedEvent.java b/src/main/scala/io/izzel/taboolib/common/event/PlayerLoadedEvent.java similarity index 93% rename from src/main/scala/me/skymc/taboolib/events/PlayerLoadedEvent.java rename to src/main/scala/io/izzel/taboolib/common/event/PlayerLoadedEvent.java index 9559be8..2d9bc5c 100644 --- a/src/main/scala/me/skymc/taboolib/events/PlayerLoadedEvent.java +++ b/src/main/scala/io/izzel/taboolib/common/event/PlayerLoadedEvent.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.events; +package io.izzel.taboolib.common.event; import org.bukkit.entity.Player; import org.bukkit.event.Event; diff --git a/src/main/scala/me/skymc/taboolib/listener/ListenerNetWork.java b/src/main/scala/io/izzel/taboolib/common/listener/ListenerNetWork.java similarity index 59% rename from src/main/scala/me/skymc/taboolib/listener/ListenerNetWork.java rename to src/main/scala/io/izzel/taboolib/common/listener/ListenerNetWork.java index f3a1a28..b5a53b3 100644 --- a/src/main/scala/me/skymc/taboolib/listener/ListenerNetWork.java +++ b/src/main/scala/io/izzel/taboolib/common/listener/ListenerNetWork.java @@ -1,7 +1,6 @@ -package me.skymc.taboolib.listener; +package io.izzel.taboolib.common.listener; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.message.MsgUtils; +import io.izzel.taboolib.module.inject.TListener; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -14,11 +13,9 @@ import pw.yumc.Yum.events.PluginNetworkEvent; @TListener(depend = "YUM") public class ListenerNetWork implements Listener { - public static final String GG = "本监听只是为了防止本插件的更新检测被 YUM 插件阻止,别无它用。"; - @EventHandler(priority = EventPriority.HIGHEST) public void onNetWork(PluginNetworkEvent e) { - if (e.getPlugin() != null && e.getPlugin().equals(Main.getInst())) { + if (e.getPlugin() != null && e.getPlugin().getName().equals("TabooLib")) { e.setCancelled(false); } } diff --git a/src/main/scala/io/izzel/taboolib/common/listener/ListenerPlayerCommand.java b/src/main/scala/io/izzel/taboolib/common/listener/ListenerPlayerCommand.java new file mode 100644 index 0000000..957eaf9 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/common/listener/ListenerPlayerCommand.java @@ -0,0 +1,56 @@ +package io.izzel.taboolib.common.listener; + +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.Version; +import io.izzel.taboolib.module.db.local.Local; +import io.izzel.taboolib.module.db.local.LocalPlayer; +import io.izzel.taboolib.module.inject.TListener; +import io.izzel.taboolib.module.locale.logger.TLogger; +import io.izzel.taboolib.module.tellraw.TellrawJson; +import io.izzel.taboolib.util.item.Items; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.server.ServerCommandEvent; + +/** + * @author sky + */ +@TListener +public class ListenerPlayerCommand implements Listener { + + @EventHandler + public void cmd(ServerCommandEvent e) { + if (e.getCommand().equalsIgnoreCase("saveFiles")) { + if (Version.isAfter(Version.v1_8)) { + e.setCancelled(true); + } + Local.saveFiles(); + LocalPlayer.saveFiles(); + TLogger.getGlobalLogger().info("Successfully."); + } else if (e.getCommand().equalsIgnoreCase("tDebug")) { + if (Version.isAfter(Version.v1_8)) { + e.setCancelled(true); + } + if (TabooLibAPI.isDebug()) { + TabooLibAPI.setDebug(false); + TLogger.getGlobalLogger().info("&cDisabled."); + } else { + TabooLibAPI.setDebug(true); + TLogger.getGlobalLogger().info("&aEnabled."); + } + } + } + + @EventHandler + public void cmd(PlayerCommandPreprocessEvent e) { + if (e.getMessage().equals("/tellrawTest") && e.getPlayer().hasPermission("taboolib.tellraw")) { + e.setCancelled(true); + TellrawJson.create() + .append("§8[§3§lTabooLib§8] §7TellrawJson Test: §f[") + .append(Items.getName(e.getPlayer().getItemInHand())).hoverItem(e.getPlayer().getItemInHand()) + .append("§f]") + .send(e.getPlayer()); + } + } +} diff --git a/src/main/scala/me/skymc/taboolib/listener/ListenerPlayerJump.java b/src/main/scala/io/izzel/taboolib/common/listener/ListenerPlayerJump.java similarity index 88% rename from src/main/scala/me/skymc/taboolib/listener/ListenerPlayerJump.java rename to src/main/scala/io/izzel/taboolib/common/listener/ListenerPlayerJump.java index ad2217c..34b9521 100644 --- a/src/main/scala/me/skymc/taboolib/listener/ListenerPlayerJump.java +++ b/src/main/scala/io/izzel/taboolib/common/listener/ListenerPlayerJump.java @@ -1,6 +1,7 @@ -package me.skymc.taboolib.listener; +package io.izzel.taboolib.common.listener; -import me.skymc.taboolib.events.PlayerJumpEvent; +import io.izzel.taboolib.module.inject.TListener; +import io.izzel.taboolib.common.event.PlayerJumpEvent; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; @@ -30,15 +31,14 @@ public class ListenerPlayerJump implements Listener { PlayerJumpEvent evt = new PlayerJumpEvent(event.isCancelled(), event.getPlayer()); Bukkit.getPluginManager().callEvent(evt); if (evt.isCancelled()) { - event.setCancelled(true); + event.setTo(event.getFrom()); } } else if (this.cooldown.get(event.getPlayer()) <= System.currentTimeMillis()) { this.cooldown.put(event.getPlayer(), System.currentTimeMillis() + 350L); PlayerJumpEvent evt = new PlayerJumpEvent(event.isCancelled(), event.getPlayer()); - Bukkit.getPluginManager().callEvent(evt); if (evt.isCancelled()) { - event.setCancelled(true); + event.setTo(event.getFrom()); } } } diff --git a/src/main/scala/io/izzel/taboolib/common/plugin/InternalJavaPlugin.java b/src/main/scala/io/izzel/taboolib/common/plugin/InternalJavaPlugin.java new file mode 100644 index 0000000..eec45ee --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/common/plugin/InternalJavaPlugin.java @@ -0,0 +1,10 @@ +package io.izzel.taboolib.common.plugin; + +import org.bukkit.plugin.java.JavaPlugin; + +/** + * @Author 坏黑 + * @Since 2019-07-05 14:13 + */ +public class InternalJavaPlugin extends JavaPlugin { +} diff --git a/src/main/scala/io/izzel/taboolib/common/plugin/InternalPlugin.java b/src/main/scala/io/izzel/taboolib/common/plugin/InternalPlugin.java new file mode 100644 index 0000000..1d95132 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/common/plugin/InternalPlugin.java @@ -0,0 +1,139 @@ +package io.izzel.taboolib.common.plugin; + +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.util.Files; +import org.bukkit.Bukkit; +import org.bukkit.Server; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.PluginLoader; + +import java.io.File; +import java.io.InputStream; +import java.util.List; +import java.util.logging.Logger; + +/** + * @Author 坏黑 + * @Since 2019-07-05 14:02 + */ +public class InternalPlugin implements Plugin { + + private static InternalPlugin plugin; + + public static InternalPlugin getPlugin() { + return plugin; + } + + static { + plugin = new InternalPlugin(); + } + + @Override + public File getDataFolder() { + return new File("plugins/TabooLib"); + } + + @Override + public PluginDescriptionFile getDescription() { + return new PluginDescriptionFile("TabooLib", String.valueOf(TabooLib.getVersion()), "io.izzel.taboolib.common.plugin.InternalJavaPlugin"); + } + + @Override + public FileConfiguration getConfig() { + return null; + } + + @Override + public InputStream getResource(String s) { + return Files.getResourceTabooLib(s); + } + + @Override + public void saveConfig() { + } + + @Override + public void saveDefaultConfig() { + } + + @Override + public void saveResource(String s, boolean b) { + File file = new File(getDataFolder(), s); + if (!file.exists() || b) { + Files.toFile(getResource(s), Files.file(file)); + } + } + + @Override + public void reloadConfig() { + } + + @Override + public PluginLoader getPluginLoader() { + return InternalPluginLoader.getLoader(); + } + + @Override + public Server getServer() { + return Bukkit.getServer(); + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public void onDisable() { + + } + + @Override + public void onLoad() { + + } + + @Override + public void onEnable() { + + } + + @Override + public boolean isNaggable() { + return false; + } + + @Override + public void setNaggable(boolean b) { + } + + @Override + public ChunkGenerator getDefaultWorldGenerator(String s, String s1) { + return null; + } + + @Override + public Logger getLogger() { + return null; + } + + @Override + public String getName() { + return "TabooLib"; + } + + @Override + public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { + return false; + } + + @Override + public List onTabComplete(CommandSender commandSender, Command command, String s, String[] strings) { + return null; + } +} diff --git a/src/main/scala/io/izzel/taboolib/common/plugin/InternalPluginLoader.java b/src/main/scala/io/izzel/taboolib/common/plugin/InternalPluginLoader.java new file mode 100644 index 0000000..a5fcde3 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/common/plugin/InternalPluginLoader.java @@ -0,0 +1,59 @@ +package io.izzel.taboolib.common.plugin; + +import org.bukkit.Bukkit; +import org.bukkit.event.Event; +import org.bukkit.event.Listener; +import org.bukkit.plugin.*; +import org.bukkit.plugin.java.JavaPluginLoader; + +import java.io.File; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * @Author 坏黑 + * @Since 2019-07-05 14:09 + */ +public class InternalPluginLoader implements PluginLoader { + + private static JavaPluginLoader loader; + + public static PluginLoader getLoader() { + return loader; + } + + static { + loader = new JavaPluginLoader(Bukkit.getServer()); + } + + @Override + public Plugin loadPlugin(File file) throws UnknownDependencyException, InvalidPluginException { + return loader.loadPlugin(file); + } + + @Override + public PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException { + return loader.getPluginDescription(file); + } + + @Override + public Pattern[] getPluginFileFilters() { + return loader.getPluginFileFilters(); + } + + @Override + public Map, Set> createRegisteredListeners(Listener listener, Plugin plugin) { + return loader.createRegisteredListeners(listener, plugin); + } + + @Override + public void enablePlugin(Plugin plugin) { + loader.enablePlugin(plugin); + } + + @Override + public void disablePlugin(Plugin plugin) { + loader.disablePlugin(plugin); + } +} diff --git a/src/main/scala/me/skymc/taboolib/cronus/CronusParser.java b/src/main/scala/io/izzel/taboolib/cronus/CronusParser.java similarity index 96% rename from src/main/scala/me/skymc/taboolib/cronus/CronusParser.java rename to src/main/scala/io/izzel/taboolib/cronus/CronusParser.java index 82eb624..3a6bae4 100644 --- a/src/main/scala/me/skymc/taboolib/cronus/CronusParser.java +++ b/src/main/scala/io/izzel/taboolib/cronus/CronusParser.java @@ -1,7 +1,7 @@ -package me.skymc.taboolib.cronus; +package io.izzel.taboolib.cronus; -import me.skymc.taboolib.cronus.bukkit.ItemStack; -import me.skymc.taboolib.cronus.bukkit.Location; +import io.izzel.taboolib.cronus.bukkit.ItemStack; +import io.izzel.taboolib.cronus.bukkit.Location; import org.bukkit.Bukkit; import org.bukkit.util.NumberConversions; diff --git a/src/main/scala/me/skymc/taboolib/cronus/CronusUtils.java b/src/main/scala/io/izzel/taboolib/cronus/CronusUtils.java similarity index 98% rename from src/main/scala/me/skymc/taboolib/cronus/CronusUtils.java rename to src/main/scala/io/izzel/taboolib/cronus/CronusUtils.java index dbf866e..901c2c9 100644 --- a/src/main/scala/me/skymc/taboolib/cronus/CronusUtils.java +++ b/src/main/scala/io/izzel/taboolib/cronus/CronusUtils.java @@ -1,6 +1,6 @@ -package me.skymc.taboolib.cronus; +package io.izzel.taboolib.cronus; -import com.ilummc.tlib.util.Strings; +import io.izzel.taboolib.util.Strings; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; diff --git a/src/main/scala/me/skymc/taboolib/cronus/bukkit/ItemStack.java b/src/main/scala/io/izzel/taboolib/cronus/bukkit/ItemStack.java similarity index 93% rename from src/main/scala/me/skymc/taboolib/cronus/bukkit/ItemStack.java rename to src/main/scala/io/izzel/taboolib/cronus/bukkit/ItemStack.java index 1cebbde..e2c594a 100644 --- a/src/main/scala/me/skymc/taboolib/cronus/bukkit/ItemStack.java +++ b/src/main/scala/io/izzel/taboolib/cronus/bukkit/ItemStack.java @@ -1,6 +1,6 @@ -package me.skymc.taboolib.cronus.bukkit; +package io.izzel.taboolib.cronus.bukkit; -import me.skymc.taboolib.inventory.ItemUtils; +import io.izzel.taboolib.util.item.Items; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -29,11 +29,11 @@ public class ItemStack { } public boolean isName(org.bukkit.inventory.ItemStack itemStack) { - return name == null || ItemUtils.getCustomName(itemStack).contains(name); + return name == null || Items.getName(itemStack).contains(name); } public boolean isLore(org.bukkit.inventory.ItemStack itemStack) { - return lore == null || ItemUtils.hasLore(itemStack, lore); + return lore == null || Items.hasLore(itemStack, lore); } public boolean isDamage(org.bukkit.inventory.ItemStack itemStack) { diff --git a/src/main/scala/me/skymc/taboolib/cronus/bukkit/Location.java b/src/main/scala/io/izzel/taboolib/cronus/bukkit/Location.java similarity index 98% rename from src/main/scala/me/skymc/taboolib/cronus/bukkit/Location.java rename to src/main/scala/io/izzel/taboolib/cronus/bukkit/Location.java index 58f6d75..50bd130 100644 --- a/src/main/scala/me/skymc/taboolib/cronus/bukkit/Location.java +++ b/src/main/scala/io/izzel/taboolib/cronus/bukkit/Location.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.cronus.bukkit; +package io.izzel.taboolib.cronus.bukkit; import org.bukkit.Bukkit; diff --git a/src/main/scala/me/skymc/taboolib/cronus/util/StringExpression.java b/src/main/scala/io/izzel/taboolib/cronus/util/StringExpression.java similarity index 93% rename from src/main/scala/me/skymc/taboolib/cronus/util/StringExpression.java rename to src/main/scala/io/izzel/taboolib/cronus/util/StringExpression.java index afbfab8..9d508da 100644 --- a/src/main/scala/me/skymc/taboolib/cronus/util/StringExpression.java +++ b/src/main/scala/io/izzel/taboolib/cronus/util/StringExpression.java @@ -1,8 +1,8 @@ -package me.skymc.taboolib.cronus.util; +package io.izzel.taboolib.cronus.util; -import com.ilummc.tlib.logger.TLogger; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.common.inject.TInject; +import io.izzel.taboolib.module.locale.logger.TLogger; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.inject.TInject; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/src/main/scala/me/skymc/taboolib/cronus/util/StringNumber.java b/src/main/scala/io/izzel/taboolib/cronus/util/StringNumber.java similarity index 99% rename from src/main/scala/me/skymc/taboolib/cronus/util/StringNumber.java rename to src/main/scala/io/izzel/taboolib/cronus/util/StringNumber.java index a903e68..e0a4c09 100644 --- a/src/main/scala/me/skymc/taboolib/cronus/util/StringNumber.java +++ b/src/main/scala/io/izzel/taboolib/cronus/util/StringNumber.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.cronus.util; +package io.izzel.taboolib.cronus.util; /** * @Author 坏黑 diff --git a/src/main/scala/me/skymc/taboolib/common/pathfinder/PathfinderCreator.java b/src/main/scala/io/izzel/taboolib/module/ai/PathfinderCreator.java similarity index 75% rename from src/main/scala/me/skymc/taboolib/common/pathfinder/PathfinderCreator.java rename to src/main/scala/io/izzel/taboolib/module/ai/PathfinderCreator.java index e84fddb..60cb498 100644 --- a/src/main/scala/me/skymc/taboolib/common/pathfinder/PathfinderCreator.java +++ b/src/main/scala/io/izzel/taboolib/module/ai/PathfinderCreator.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.pathfinder; +package io.izzel.taboolib.module.ai; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/common/pathfinder/PathfinderExecutor.java b/src/main/scala/io/izzel/taboolib/module/ai/PathfinderExecutor.java similarity index 97% rename from src/main/scala/me/skymc/taboolib/common/pathfinder/PathfinderExecutor.java rename to src/main/scala/io/izzel/taboolib/module/ai/PathfinderExecutor.java index 9fb04f2..a7013fc 100644 --- a/src/main/scala/me/skymc/taboolib/common/pathfinder/PathfinderExecutor.java +++ b/src/main/scala/io/izzel/taboolib/module/ai/PathfinderExecutor.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.pathfinder; +package io.izzel.taboolib.module.ai; import org.bukkit.Location; import org.bukkit.entity.Entity; diff --git a/src/main/scala/me/skymc/taboolib/common/pathfinder/SimpleAi.java b/src/main/scala/io/izzel/taboolib/module/ai/SimpleAi.java similarity index 87% rename from src/main/scala/me/skymc/taboolib/common/pathfinder/SimpleAi.java rename to src/main/scala/io/izzel/taboolib/module/ai/SimpleAi.java index e1ac15b..3515f20 100644 --- a/src/main/scala/me/skymc/taboolib/common/pathfinder/SimpleAi.java +++ b/src/main/scala/io/izzel/taboolib/module/ai/SimpleAi.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.pathfinder; +package io.izzel.taboolib.module.ai; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/common/pathfinder/SimpleAiSelector.java b/src/main/scala/io/izzel/taboolib/module/ai/SimpleAiSelector.java similarity index 61% rename from src/main/scala/me/skymc/taboolib/common/pathfinder/SimpleAiSelector.java rename to src/main/scala/io/izzel/taboolib/module/ai/SimpleAiSelector.java index 6a45ce2..832ae83 100644 --- a/src/main/scala/me/skymc/taboolib/common/pathfinder/SimpleAiSelector.java +++ b/src/main/scala/io/izzel/taboolib/module/ai/SimpleAiSelector.java @@ -1,22 +1,22 @@ -package me.skymc.taboolib.common.pathfinder; +package io.izzel.taboolib.module.ai; -import me.skymc.taboolib.common.loader.Instantiable; -import me.skymc.taboolib.common.versioncontrol.SimpleVersionControl; +import io.izzel.taboolib.module.inject.TFunction; +import io.izzel.taboolib.module.lite.SimpleVersionControl; /** * @Author sky * @Since 2018-09-19 20:31 */ -@Instantiable("SimpleAiSelector") +@TFunction(enable = "init") public class SimpleAiSelector { private static PathfinderCreator internalPathfinderCreator; private static PathfinderExecutor internalPathfinderExecutor; - public SimpleAiSelector() { + static void init() { try { - internalPathfinderCreator = (PathfinderCreator) SimpleVersionControl.createNMS("me.skymc.taboolib.common.pathfinder.internal.InternalPathfinderCreator").translate().newInstance(); - internalPathfinderExecutor = (PathfinderExecutor) SimpleVersionControl.createNMS("me.skymc.taboolib.common.pathfinder.internal.InternalPathfinderExecutor").translate().newInstance(); + internalPathfinderCreator = (PathfinderCreator) SimpleVersionControl.createNMS("io.izzel.taboolib.module.ai.internal.InternalPathfinderCreator").translate().newInstance(); + internalPathfinderExecutor = (PathfinderExecutor) SimpleVersionControl.createNMS("io.izzel.taboolib.module.ai.internal.InternalPathfinderExecutor").translate().newInstance(); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/scala/me/skymc/taboolib/common/pathfinder/internal/InternalPathfinderCreator.java b/src/main/scala/io/izzel/taboolib/module/ai/internal/InternalPathfinderCreator.java similarity index 84% rename from src/main/scala/me/skymc/taboolib/common/pathfinder/internal/InternalPathfinderCreator.java rename to src/main/scala/io/izzel/taboolib/module/ai/internal/InternalPathfinderCreator.java index 027ec95..abc1d0c 100644 --- a/src/main/scala/me/skymc/taboolib/common/pathfinder/internal/InternalPathfinderCreator.java +++ b/src/main/scala/io/izzel/taboolib/module/ai/internal/InternalPathfinderCreator.java @@ -1,7 +1,7 @@ -package me.skymc.taboolib.common.pathfinder.internal; +package io.izzel.taboolib.module.ai.internal; -import me.skymc.taboolib.common.pathfinder.PathfinderCreator; -import me.skymc.taboolib.common.pathfinder.SimpleAi; +import io.izzel.taboolib.module.ai.PathfinderCreator; +import io.izzel.taboolib.module.ai.SimpleAi; /** * 该类仅用作生成 ASM 代码,无任何意义 diff --git a/src/main/scala/me/skymc/taboolib/common/pathfinder/internal/InternalPathfinderExecutor.java b/src/main/scala/io/izzel/taboolib/module/ai/internal/InternalPathfinderExecutor.java similarity index 88% rename from src/main/scala/me/skymc/taboolib/common/pathfinder/internal/InternalPathfinderExecutor.java rename to src/main/scala/io/izzel/taboolib/module/ai/internal/InternalPathfinderExecutor.java index ebfbb90..d72c69b 100644 --- a/src/main/scala/me/skymc/taboolib/common/pathfinder/internal/InternalPathfinderExecutor.java +++ b/src/main/scala/io/izzel/taboolib/module/ai/internal/InternalPathfinderExecutor.java @@ -1,9 +1,9 @@ -package me.skymc.taboolib.common.pathfinder.internal; +package io.izzel.taboolib.module.ai.internal; -import me.skymc.taboolib.common.pathfinder.PathfinderExecutor; -import me.skymc.taboolib.common.pathfinder.SimpleAi; -import me.skymc.taboolib.common.pathfinder.SimpleAiSelector; -import me.skymc.taboolib.nms.NMSUtils; +import io.izzel.taboolib.module.ai.PathfinderExecutor; +import io.izzel.taboolib.module.ai.SimpleAi; +import io.izzel.taboolib.module.ai.SimpleAiSelector; +import io.izzel.taboolib.module.lite.SimpleReflection; import net.minecraft.server.v1_8_R3.*; import org.bukkit.Location; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity; @@ -27,18 +27,17 @@ public class InternalPathfinderExecutor extends PathfinderExecutor { public InternalPathfinderExecutor() { try { - pathfinderGoalSelectorSet = NMSUtils.getNMSClass("PathfinderGoalSelector").getDeclaredField("b"); - pathfinderGoalSelectorSet.setAccessible(true); - controllerJumpCurrent = NMSUtils.getNMSClass("ControllerJump").getDeclaredField("a"); - controllerJumpCurrent.setAccessible(true); + SimpleReflection.saveField(PathfinderGoalSelector.class); + SimpleReflection.saveField(ControllerJump.class); + pathfinderGoalSelectorSet =SimpleReflection.getField(PathfinderGoalSelector.class, "b"); + controllerJumpCurrent = SimpleReflection.getField(ControllerJump.class, "a"); } catch (Exception e) { e.printStackTrace(); } try { - Class pathEntityClass = NMSUtils.getNMSClass("PathEntity"); - for (Field field : NMSUtils.getNMSClass("NavigationAbstract").getDeclaredFields()) { - if (field.getType().equals(pathEntityClass)) { - field.setAccessible(true); + SimpleReflection.saveField(NavigationAbstract.class); + for (Field field : SimpleReflection.getFields(NavigationAbstract.class).values()) { + if (field.getType().equals(PathEntity.class)) { pathEntity = field; return; } diff --git a/src/main/scala/me/skymc/taboolib/commands/internal/TCommandHandler.java b/src/main/scala/io/izzel/taboolib/module/command/TCommandHandler.java similarity index 55% rename from src/main/scala/me/skymc/taboolib/commands/internal/TCommandHandler.java rename to src/main/scala/io/izzel/taboolib/module/command/TCommandHandler.java index b9699ae..7ea8446 100644 --- a/src/main/scala/me/skymc/taboolib/commands/internal/TCommandHandler.java +++ b/src/main/scala/io/izzel/taboolib/module/command/TCommandHandler.java @@ -1,18 +1,16 @@ -package me.skymc.taboolib.commands.internal; +package io.izzel.taboolib.module.command; -import com.ilummc.tlib.inject.TPluginManager; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.common.util.SimpleReflection; -import me.skymc.taboolib.fileutils.FileUtils; -import me.skymc.taboolib.listener.TListener; -import me.skymc.taboolib.methods.ReflectionUtils; -import me.skymc.taboolib.string.ArrayUtils; +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.module.command.base.BaseCommand; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.command.base.BaseMainCommand; +import io.izzel.taboolib.module.inject.TFunction; +import io.izzel.taboolib.module.lite.SimpleReflection; +import io.izzel.taboolib.util.ArrayUtil; +import io.izzel.taboolib.util.Files; +import io.izzel.taboolib.util.Reflection; import org.bukkit.Bukkit; import org.bukkit.command.*; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.SimplePluginManager; @@ -26,30 +24,17 @@ import java.util.stream.Collectors; * @Author sky * @Since 2018-05-23 2:43 */ -@TListener -public class TCommandHandler implements Listener { +@TFunction(enable = "init") +public class TCommandHandler { private static SimpleCommandMap commandMap; private static Map knownCommands; - public TCommandHandler() { - SimpleReflection.saveField(Bukkit.getPluginManager() instanceof TPluginManager ? TPluginManager.class : SimplePluginManager.class, "commandMap"); + static void init() { + SimpleReflection.saveField(SimplePluginManager.class, "commandMap"); SimpleReflection.saveField(SimpleCommandMap.class, "knownCommands"); - commandMap = (SimpleCommandMap) SimpleReflection.getFieldValue(Bukkit.getPluginManager() instanceof TPluginManager ? TPluginManager.class : SimplePluginManager.class, Bukkit.getPluginManager(), "commandMap"); + commandMap = (SimpleCommandMap) SimpleReflection.getFieldValue(SimplePluginManager.class, Bukkit.getPluginManager(), "commandMap"); knownCommands = (Map) SimpleReflection.getFieldValue(SimpleCommandMap.class, commandMap, "knownCommands"); - try { - registerCommands(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @EventHandler - public void onEnable(PluginEnableEvent e) { - try { - registerCommand(e.getPlugin()); - } catch (Exception ignored) { - } } public static boolean registerPluginCommand(Plugin plugin, String command, CommandExecutor commandExecutor) { @@ -72,8 +57,11 @@ public class TCommandHandler implements Listener { return registerPluginCommand(plugin, command, description, usage, aliases, null, null, commandExecutor, tabCompleter); } - public static boolean registerPluginCommand(Plugin plugin, String command, String description, String usage, List aliases, String permission, String permissionMessage, CommandExecutor commandExecutor, TabCompleter tabCompleter) { - return registerPluginCommand(plugin, command, description, usage, aliases, permission, permissionMessage, commandExecutor, tabCompleter, false); + /** + * 获取插件注册的命令 + */ + public static Command getPluginCommand(String command) { + return commandMap.getCommand(command); } /** @@ -88,27 +76,23 @@ public class TCommandHandler implements Listener { * @param permissionMessage 权限提示 * @param commandExecutor 命令执行器 * @param tabCompleter 补全执行器 - * @param silence 是否屏蔽提示 * @return 注册结果(boolean) */ - public static boolean registerPluginCommand(Plugin plugin, String command, String description, String usage, List aliases, String permission, String permissionMessage, CommandExecutor commandExecutor, TabCompleter tabCompleter, boolean silence) { + public static boolean registerPluginCommand(Plugin plugin, String command, String description, String usage, List aliases, String permission, String permissionMessage, CommandExecutor commandExecutor, TabCompleter tabCompleter) { try { Constructor constructor = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class); constructor.setAccessible(true); PluginCommand pluginCommand = constructor.newInstance(command, plugin); pluginCommand.setExecutor(commandExecutor); pluginCommand.setTabCompleter(tabCompleter); - ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "description", description); - ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "usageMessage", usage); - ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "aliases", aliases.stream().map(String::toLowerCase).collect(Collectors.toList())); - ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "activeAliases", aliases.stream().map(String::toLowerCase).collect(Collectors.toList())); - ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "permission", permission); - ReflectionUtils.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "permissionMessage", permissionMessage); + Reflection.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "description", description); + Reflection.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "usageMessage", usage); + Reflection.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "aliases", aliases.stream().map(String::toLowerCase).collect(Collectors.toList())); + Reflection.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "activeAliases", aliases.stream().map(String::toLowerCase).collect(Collectors.toList())); + Reflection.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "permission", permission); + Reflection.setValue(pluginCommand, pluginCommand.getClass().getSuperclass(), true, "permissionMessage", permissionMessage); commandMap.register(plugin.getName(), pluginCommand); - TabooLib.debug("Command " + command + " created. (" + plugin.getName() + ")"); -// if (!TabooLib.isTabooLib(plugin) && !silence) { -// TLocale.Logger.info("COMMANDS.INTERNAL.COMMAND-CREATE", plugin.getName(), command); -// } + TabooLibAPI.debug("Command " + command + " created. (" + plugin.getName() + ")"); return true; } catch (Exception e) { TLocale.Logger.error("COMMANDS.INTERNAL.COMMAND-CREATE-FAILED", plugin.getName(), command, e.toString()); @@ -124,47 +108,30 @@ public class TCommandHandler implements Listener { * @param baseMainCommand 命令对象 * @return {@link BaseMainCommand} */ - public static BaseMainCommand registerCommand(TCommand tCommand, String command, BaseMainCommand baseMainCommand, Plugin plugin) { + public static BaseMainCommand registerCommand(BaseCommand tCommand, String command, BaseMainCommand baseMainCommand, Plugin plugin) { if (Bukkit.getPluginCommand(command) == null) { registerPluginCommand( plugin, command, - ArrayUtils.skipEmpty(tCommand.description(), "Registered by TabooLib."), - ArrayUtils.skipEmpty(tCommand.usage(), "/" + command), - ArrayUtils.skipEmpty(ArrayUtils.asList(tCommand.aliases()), new ArrayList<>()), - ArrayUtils.skipEmpty(tCommand.permission()), - ArrayUtils.skipEmpty(tCommand.permissionMessage()), + ArrayUtil.skipEmpty(tCommand.description(), "Registered by TabooLib."), + ArrayUtil.skipEmpty(tCommand.usage(), "/" + command), + ArrayUtil.skipEmpty(ArrayUtil.asList(tCommand.aliases()), new ArrayList<>()), + ArrayUtil.skipEmpty(tCommand.permission()), + ArrayUtil.skipEmpty(tCommand.permissionMessage()), baseMainCommand, baseMainCommand); } return BaseMainCommand.createCommandExecutor(command, baseMainCommand); } - /** - * 注册所有插件的所有 TCommand 命令 - */ - public static void registerCommands() { - for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - try { - registerCommand(plugin); - } catch (Exception e) { - e.printStackTrace(); - } - } - } /** * 注册插件的所有 TCommand 命令 - * - * @param plugin 插件 */ public static void registerCommand(Plugin plugin) { - if (!(plugin.equals(TabooLib.instance()) || TabooLib.isDependTabooLib(plugin))) { - return; - } - for (Class pluginClass : FileUtils.getClasses(plugin)) { - if (BaseMainCommand.class.isAssignableFrom(pluginClass) && pluginClass.isAnnotationPresent(TCommand.class)) { - TCommand tCommand = (TCommand) pluginClass.getAnnotation(TCommand.class); + for (Class pluginClass : Files.getClasses(plugin)) { + if (BaseMainCommand.class.isAssignableFrom(pluginClass) && pluginClass.isAnnotationPresent(BaseCommand.class)) { + BaseCommand tCommand = (BaseCommand) pluginClass.getAnnotation(BaseCommand.class); try { registerCommand(tCommand, tCommand.name(), (BaseMainCommand) pluginClass.newInstance(), plugin); } catch (Exception e) { @@ -174,16 +141,6 @@ public class TCommandHandler implements Listener { } } - /** - * 获取插件注册的命令 - * - * @param command 命令名称 - * @return {@link Command} - */ - public static Command getPluginCommand(String command) { - return commandMap.getCommand(command); - } - // ********************************* // // Getter and Setter diff --git a/src/main/scala/me/skymc/taboolib/commands/internal/type/CommandArgument.java b/src/main/scala/io/izzel/taboolib/module/command/base/Argument.java similarity index 71% rename from src/main/scala/me/skymc/taboolib/commands/internal/type/CommandArgument.java rename to src/main/scala/io/izzel/taboolib/module/command/base/Argument.java index 20b66a3..dae6c7e 100644 --- a/src/main/scala/me/skymc/taboolib/commands/internal/type/CommandArgument.java +++ b/src/main/scala/io/izzel/taboolib/module/command/base/Argument.java @@ -1,6 +1,6 @@ -package me.skymc.taboolib.commands.internal.type; +package io.izzel.taboolib.module.command.base; -import com.ilummc.tlib.resources.TLocale; +import io.izzel.taboolib.module.locale.TLocale; import java.util.Objects; @@ -8,10 +8,13 @@ import java.util.Objects; * @author Bkm016 * @since 2018-04-17 */ -public class CommandArgument { +public class Argument { + // 参数名称 private String name; + // 是否必须 private boolean required; + // 参数补全 private CommandTab tab; public String getName() { @@ -26,19 +29,19 @@ public class CommandArgument { return tab; } - public CommandArgument(String name) { + public Argument(String name) { this(name, true); } - public CommandArgument(String name, CommandTab tab) { + public Argument(String name, CommandTab tab) { this(name, true, tab); } - public CommandArgument(String name, boolean required) { + public Argument(String name, boolean required) { this(name, required, null); } - public CommandArgument(String name, boolean required, CommandTab tab) { + public Argument(String name, boolean required, CommandTab tab) { this.name = name; this.required = required; this.tab = tab; @@ -54,10 +57,10 @@ public class CommandArgument { if (this == o) { return true; } - if (!(o instanceof CommandArgument)) { + if (!(o instanceof Argument)) { return false; } - CommandArgument that = (CommandArgument) o; + Argument that = (Argument) o; return isRequired() == that.isRequired() && Objects.equals(getName(), that.getName()) && Objects.equals(tab, that.tab); diff --git a/src/main/scala/me/skymc/taboolib/commands/internal/TCommand.java b/src/main/scala/io/izzel/taboolib/module/command/base/BaseCommand.java similarity index 77% rename from src/main/scala/me/skymc/taboolib/commands/internal/TCommand.java rename to src/main/scala/io/izzel/taboolib/module/command/base/BaseCommand.java index b3a69c7..9bac631 100644 --- a/src/main/scala/me/skymc/taboolib/commands/internal/TCommand.java +++ b/src/main/scala/io/izzel/taboolib/module/command/base/BaseCommand.java @@ -1,10 +1,9 @@ -package me.skymc.taboolib.commands.internal; +package io.izzel.taboolib.module.command.base; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import java.util.List; /** * @Author sky @@ -12,7 +11,7 @@ import java.util.List; */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface TCommand { +public @interface BaseCommand { String name(); @@ -24,5 +23,5 @@ public @interface TCommand { String usage() default ""; - String[] aliases() default ""; + String[] aliases() default {}; } \ No newline at end of file diff --git a/src/main/scala/me/skymc/taboolib/commands/internal/BaseMainCommand.java b/src/main/scala/io/izzel/taboolib/module/command/base/BaseMainCommand.java similarity index 73% rename from src/main/scala/me/skymc/taboolib/commands/internal/BaseMainCommand.java rename to src/main/scala/io/izzel/taboolib/module/command/base/BaseMainCommand.java index a44d7da..788c171 100644 --- a/src/main/scala/me/skymc/taboolib/commands/internal/BaseMainCommand.java +++ b/src/main/scala/io/izzel/taboolib/module/command/base/BaseMainCommand.java @@ -1,13 +1,13 @@ -package me.skymc.taboolib.commands.internal; +package io.izzel.taboolib.module.command.base; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.commands.internal.type.*; -import me.skymc.taboolib.string.ArrayUtils; -import me.skymc.taboolib.string.StringUtils; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.Version; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.util.ArrayUtil; +import io.izzel.taboolib.util.Strings; import org.bukkit.Bukkit; import org.bukkit.command.*; import org.bukkit.entity.Player; @@ -16,7 +16,10 @@ import org.bukkit.scheduler.BukkitRunnable; import java.lang.reflect.Field; import java.lang.reflect.Method; -import java.util.*; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; @@ -28,7 +31,7 @@ public abstract class BaseMainCommand implements CommandExecutor, TabExecutor { private PluginCommand registerCommand; private List> linkClasses = new CopyOnWriteArrayList<>(); - private List subCommands = new CopyOnWriteArrayList<>(); + private List subCommands = new CopyOnWriteArrayList<>(); public static BaseMainCommand createCommandExecutor(String command, BaseMainCommand baseMainCommand) { Preconditions.checkArgument(Bukkit.getPluginCommand(command) != null, "PluginCommand \"" + command + "\" not found"); @@ -46,9 +49,9 @@ public abstract class BaseMainCommand implements CommandExecutor, TabExecutor { 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)); + baseMainCommand.getLinkClasses().forEach(clazz -> java.util.Arrays.stream(clazz.getDeclaredMethods()).filter(method -> method.getAnnotation(SubCommand.class) != null).forEach(methods::add)); if (methods.size() > 0) { - methods.sort(Comparator.comparingDouble(a -> a.getAnnotation(CommandRegister.class).priority())); + methods.sort(Comparator.comparingDouble(a -> a.getAnnotation(SubCommand.class).priority())); methods.forEach(x -> { try { x.setAccessible(true); @@ -57,13 +60,13 @@ public abstract class BaseMainCommand implements CommandExecutor, TabExecutor { } }); } - 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)))); + baseMainCommand.getLinkClasses().forEach(clazz -> java.util.Arrays.stream(clazz.getDeclaredFields()).filter(field -> field.getAnnotation(SubCommand.class) != null && field.getType().equals(io.izzel.taboolib.module.command.base.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.sort(Comparator.comparingDouble(commandField -> commandField.getField().getAnnotation(SubCommand.class).priority())); fields.forEach(commandField -> { try { commandField.getField().setAccessible(true); - BaseSubCommand subCommand = (BaseSubCommand) commandField.getField().get(commandField.getParent().newInstance()); + io.izzel.taboolib.module.command.base.BaseSubCommand subCommand = (io.izzel.taboolib.module.command.base.BaseSubCommand) commandField.getField().get(commandField.getParent().newInstance()); subCommand.setLabel(commandField.getField().getName()); baseMainCommand.registerSubCommand(subCommand); } catch (Exception ignored) { @@ -71,8 +74,7 @@ public abstract class BaseMainCommand implements CommandExecutor, TabExecutor { }); } if (methods.size() + fields.size() > 0) { - TabooLib.debug("Registered " + (methods.size() + fields.size()) + " sub-command with " + baseMainCommand.getRegisterCommand().getName() + " (" + baseMainCommand.getRegisterCommand().getPlugin().getName() + ")"); -// TLocale.Logger.info("COMMANDS.INTERNAL.COMMAND-REGISTER", baseMainCommand.getRegisterCommand().getPlugin().getName(), baseMainCommand.getRegisterCommand().getName(), String.valueOf(methods.size() + fields.size())); + TabooLibAPI.debug("Registered " + (methods.size() + fields.size()) + " sub-command with " + baseMainCommand.getRegisterCommand().getName() + " (" + baseMainCommand.getRegisterCommand().getPlugin().getName() + ")"); } } @@ -88,11 +90,11 @@ public abstract class BaseMainCommand implements CommandExecutor, TabExecutor { return linkClasses; } - public List getSubCommands() { + public List getSubCommands() { return subCommands; } - public void registerSubCommand(BaseSubCommand subCommand) { + public void registerSubCommand(io.izzel.taboolib.module.command.base.BaseSubCommand subCommand) { if (subCommand != null) { Preconditions.checkArgument(subCommand.getLabel() != null, "Command label can not be null"); Preconditions.checkArgument(subCommand.getArguments() != null, "Command arguments can not be null"); @@ -120,8 +122,8 @@ public abstract class BaseMainCommand implements CommandExecutor, TabExecutor { }); return label.stream().filter(l -> args[0].isEmpty() || l.toLowerCase().startsWith(args[0].toLowerCase())).collect(Collectors.toList()); } - for (BaseSubCommand subCommand : subCommands) { - CommandArgument[] arguments = subCommand.getArguments(); + for (io.izzel.taboolib.module.command.base.BaseSubCommand subCommand : subCommands) { + Argument[] arguments = subCommand.getArguments(); if (args[0].equalsIgnoreCase(subCommand.getLabel()) && args.length - 1 <= arguments.length) { CommandTab commandTab = arguments[args.length - 2].getTab(); if (commandTab != null) { @@ -137,15 +139,15 @@ public abstract class BaseMainCommand implements CommandExecutor, TabExecutor { if (args.length == 0) { onCommandHelp(sender, command, label, args); } else { - for (BaseSubCommand subCommand : subCommands) { - if (subCommand == null || !(args[0].equalsIgnoreCase(subCommand.getLabel()) || Arrays.stream(subCommand.getAliases()).anyMatch(args[0]::equalsIgnoreCase)) || !hasPermission(sender, subCommand)) { + for (io.izzel.taboolib.module.command.base.BaseSubCommand subCommand : subCommands) { + if (subCommand == null || !(args[0].equalsIgnoreCase(subCommand.getLabel()) || java.util.Arrays.stream(subCommand.getAliases()).anyMatch(args[0]::equalsIgnoreCase)) || !hasPermission(sender, subCommand)) { continue; } if (!isConfirmType(sender, 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); + String[] subCommandArgs = ArrayUtil.removeFirst(args); if (subCommand.isParameterConform(subCommandArgs)) { subCommand.onCommand(sender, command, label, subCommand.ignoredLabel() ? subCommandArgs : args); } else { @@ -157,12 +159,12 @@ public abstract class BaseMainCommand implements CommandExecutor, TabExecutor { @Override public void run() { - 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()); + List commandCompute = subCommands.stream().filter(x -> x != null && hasPermission(sender, x)).sorted((b, a) -> Double.compare(Strings.similarDegree(args[0], a.getLabel()), Strings.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()); } } - }.runTaskAsynchronously(Main.getInst()); + }.runTaskAsynchronously(TabooLib.getPlugin()); } return true; } @@ -196,7 +198,7 @@ public abstract class BaseMainCommand implements CommandExecutor, TabExecutor { // ********************************* private String getEmptyLine() { - return TabooLib.getVerint() < 10800 ? "~" : ""; + return Version.isAfter(Version.v1_8) ? "" : "~"; } private boolean isConfirmType(CommandSender sender, CommandType commandType) { @@ -206,7 +208,10 @@ public abstract class BaseMainCommand implements CommandExecutor, TabExecutor { } private void disguisedPlugin() { - linkClasses.forEach(clazz -> disguisedPlugin(clazz, registerCommand.getPlugin())); + try { + linkClasses.forEach(clazz -> disguisedPlugin(clazz, registerCommand.getPlugin())); + } catch (Throwable ignored) { + } } private void disguisedPlugin(Class targetClass, Plugin plugin) { @@ -218,7 +223,7 @@ public abstract class BaseMainCommand implements CommandExecutor, TabExecutor { } } - private boolean hideInHelp(BaseSubCommand baseSubCommand) { + private boolean hideInHelp(io.izzel.taboolib.module.command.base.BaseSubCommand baseSubCommand) { return baseSubCommand != null && baseSubCommand.hideInHelp(); } diff --git a/src/main/scala/me/skymc/taboolib/commands/internal/BaseSubCommand.java b/src/main/scala/io/izzel/taboolib/module/command/base/BaseSubCommand.java similarity index 83% rename from src/main/scala/me/skymc/taboolib/commands/internal/BaseSubCommand.java rename to src/main/scala/io/izzel/taboolib/module/command/base/BaseSubCommand.java index a244d06..6d6b40e 100644 --- a/src/main/scala/me/skymc/taboolib/commands/internal/BaseSubCommand.java +++ b/src/main/scala/io/izzel/taboolib/module/command/base/BaseSubCommand.java @@ -1,8 +1,6 @@ -package me.skymc.taboolib.commands.internal; +package io.izzel.taboolib.module.command.base; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.commands.internal.type.CommandArgument; -import me.skymc.taboolib.commands.internal.type.CommandType; +import io.izzel.taboolib.module.locale.TLocale; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -34,8 +32,8 @@ public abstract class BaseSubCommand { return new String[0]; } - public CommandArgument[] getArguments() { - return new CommandArgument[0]; + public Argument[] getArguments() { + return new Argument[0]; } public CommandType getType() { diff --git a/src/main/scala/me/skymc/taboolib/commands/internal/type/CommandField.java b/src/main/scala/io/izzel/taboolib/module/command/base/CommandField.java similarity index 89% rename from src/main/scala/me/skymc/taboolib/commands/internal/type/CommandField.java rename to src/main/scala/io/izzel/taboolib/module/command/base/CommandField.java index 77dd269..3e3d2f3 100644 --- a/src/main/scala/me/skymc/taboolib/commands/internal/type/CommandField.java +++ b/src/main/scala/io/izzel/taboolib/module/command/base/CommandField.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.commands.internal.type; +package io.izzel.taboolib.module.command.base; import java.lang.reflect.Field; diff --git a/src/main/scala/me/skymc/taboolib/commands/internal/type/CommandTab.java b/src/main/scala/io/izzel/taboolib/module/command/base/CommandTab.java similarity index 77% rename from src/main/scala/me/skymc/taboolib/commands/internal/type/CommandTab.java rename to src/main/scala/io/izzel/taboolib/module/command/base/CommandTab.java index bfa552d..0d13172 100644 --- a/src/main/scala/me/skymc/taboolib/commands/internal/type/CommandTab.java +++ b/src/main/scala/io/izzel/taboolib/module/command/base/CommandTab.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.commands.internal.type; +package io.izzel.taboolib.module.command.base; import java.util.List; diff --git a/src/main/scala/me/skymc/taboolib/commands/internal/type/CommandType.java b/src/main/scala/io/izzel/taboolib/module/command/base/CommandType.java similarity index 66% rename from src/main/scala/me/skymc/taboolib/commands/internal/type/CommandType.java rename to src/main/scala/io/izzel/taboolib/module/command/base/CommandType.java index 957c300..713c158 100644 --- a/src/main/scala/me/skymc/taboolib/commands/internal/type/CommandType.java +++ b/src/main/scala/io/izzel/taboolib/module/command/base/CommandType.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.commands.internal.type; +package io.izzel.taboolib.module.command.base; /** * @author Bkm016 diff --git a/src/main/scala/me/skymc/taboolib/commands/internal/type/CommandRegister.java b/src/main/scala/io/izzel/taboolib/module/command/base/SubCommand.java similarity index 79% rename from src/main/scala/me/skymc/taboolib/commands/internal/type/CommandRegister.java rename to src/main/scala/io/izzel/taboolib/module/command/base/SubCommand.java index 8f10049..1d08471 100644 --- a/src/main/scala/me/skymc/taboolib/commands/internal/type/CommandRegister.java +++ b/src/main/scala/io/izzel/taboolib/module/command/base/SubCommand.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.commands.internal.type; +package io.izzel.taboolib.module.command.base; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -11,7 +11,7 @@ import java.lang.annotation.Target; */ @Target({ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) -public @interface CommandRegister { +public @interface SubCommand { double priority() default 0; diff --git a/src/main/scala/me/skymc/taboolib/commands/builder/SimpleCommandBuilder.java b/src/main/scala/io/izzel/taboolib/module/command/lite/CommandBuilder.java similarity index 65% rename from src/main/scala/me/skymc/taboolib/commands/builder/SimpleCommandBuilder.java rename to src/main/scala/io/izzel/taboolib/module/command/lite/CommandBuilder.java index de03b95..7192200 100644 --- a/src/main/scala/me/skymc/taboolib/commands/builder/SimpleCommandBuilder.java +++ b/src/main/scala/io/izzel/taboolib/module/command/lite/CommandBuilder.java @@ -1,11 +1,8 @@ -package me.skymc.taboolib.commands.builder; +package io.izzel.taboolib.module.command.lite; import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import me.skymc.taboolib.commands.builder.type.CompleterCommand; -import me.skymc.taboolib.commands.builder.type.CompleterTab; -import me.skymc.taboolib.commands.internal.TCommandHandler; -import me.skymc.taboolib.string.ArrayUtils; +import io.izzel.taboolib.module.command.TCommandHandler; +import io.izzel.taboolib.util.ArrayUtil; import org.bukkit.plugin.Plugin; import java.util.ArrayList; @@ -16,10 +13,10 @@ import java.util.List; * @Since 2018-08-27 8:42 * @BuilderLevel 1.0 */ -public class SimpleCommandBuilder { +public class CommandBuilder { public static final CompleterTab EMPTY_COMPLETER_TAB = ((sender, args) -> new ArrayList<>()); - public static final CompleterCommand EMPTY_COMPLETER_COMMAND = ((sender, args) -> false); + public static final CompleterCommand EMPTY_COMPLETER_COMMAND = ((sender, args) -> {}); private String command; private Plugin plugin; @@ -30,81 +27,73 @@ public class SimpleCommandBuilder { private String permissionMessage; private CompleterTab completerTab = EMPTY_COMPLETER_TAB; private CompleterCommand completerCommand = EMPTY_COMPLETER_COMMAND; - private boolean silence; private boolean forceRegister; private boolean build; - SimpleCommandBuilder(String command, Plugin plugin) { + CommandBuilder(String command, Plugin plugin) { this.command = command; this.plugin = plugin; this.description = ""; this.usage = "/" + command; this.aliases = new ArrayList<>(); - this.silence = false; this.build = false; } - public static SimpleCommandBuilder create(String command, Plugin plugin) { - return new SimpleCommandBuilder(command.toLowerCase(), plugin); + public static CommandBuilder create(String command, Plugin plugin) { + return new CommandBuilder(command.toLowerCase(), plugin); } - public SimpleCommandBuilder command(String command) { + public CommandBuilder command(String command) { this.command = command; return this; } - public SimpleCommandBuilder plugin(Plugin plugin) { + public CommandBuilder plugin(Plugin plugin) { this.plugin = plugin; return this; } - public SimpleCommandBuilder description(String description) { + public CommandBuilder description(String description) { this.description = description; return this; } - public SimpleCommandBuilder usage(String usage) { + public CommandBuilder usage(String usage) { this.usage = usage; return this; } - public SimpleCommandBuilder aliases(String... aliases) { - this.aliases = ArrayUtils.asList(aliases); + public CommandBuilder aliases(String... aliases) { + this.aliases = ArrayUtil.asList(aliases); return this; } - public SimpleCommandBuilder permission(String permission) { + public CommandBuilder permission(String permission) { this.permission = permission; return this; } - public SimpleCommandBuilder permissionMessage(String permissionMessage) { + public CommandBuilder permissionMessage(String permissionMessage) { this.permissionMessage = permissionMessage; return this; } - public SimpleCommandBuilder execute(CompleterCommand completerCommand) { + public CommandBuilder execute(CompleterCommand completerCommand) { this.completerCommand = completerCommand; return this; } - public SimpleCommandBuilder tab(CompleterTab completerTab) { + public CommandBuilder tab(CompleterTab completerTab) { this.completerTab = completerTab; return this; } - @Deprecated - public SimpleCommandBuilder silence() { - this.silence = true; - return this; - } - - public SimpleCommandBuilder forceRegister() { + public CommandBuilder forceRegister() { this.forceRegister = true; return this; } - public SimpleCommandBuilder build() { + public CommandBuilder build() { Preconditions.checkNotNull(plugin, "缺少 \"plugin\" 部分"); Preconditions.checkNotNull(command, "缺少 \"command\" 部分"); Preconditions.checkNotNull(completerCommand, "缺少 \"CompleterCommand\" 部分"); @@ -121,12 +110,8 @@ public class SimpleCommandBuilder { permission, permissionMessage, (sender, command, s, args) -> { - try { - return completerCommand.execute(sender, args); - } catch (Throwable t) { - t.printStackTrace(); - } - return false; + completerCommand.execute(sender, args); + return true; }, (sender, command, s, args) -> { try { @@ -134,9 +119,8 @@ public class SimpleCommandBuilder { } catch (Throwable t) { t.printStackTrace(); } - return Lists.newArrayList(); - }, - silence); + return null; + }); build = true; return this; } @@ -183,10 +167,6 @@ public class SimpleCommandBuilder { return completerCommand; } - public boolean isSilence() { - return silence; - } - public boolean isForceRegister() { return forceRegister; } diff --git a/src/main/scala/me/skymc/taboolib/commands/builder/type/CompleterCommand.java b/src/main/scala/io/izzel/taboolib/module/command/lite/CompleterCommand.java similarity index 63% rename from src/main/scala/me/skymc/taboolib/commands/builder/type/CompleterCommand.java rename to src/main/scala/io/izzel/taboolib/module/command/lite/CompleterCommand.java index c152b75..f901ae9 100644 --- a/src/main/scala/me/skymc/taboolib/commands/builder/type/CompleterCommand.java +++ b/src/main/scala/io/izzel/taboolib/module/command/lite/CompleterCommand.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.commands.builder.type; +package io.izzel.taboolib.module.command.lite; import org.bukkit.command.CommandSender; @@ -9,6 +9,6 @@ import org.bukkit.command.CommandSender; */ public interface CompleterCommand { - boolean execute(CommandSender sender, String[] args); + void execute(CommandSender sender, String[] args); } \ No newline at end of file diff --git a/src/main/scala/me/skymc/taboolib/commands/builder/type/CompleterTab.java b/src/main/scala/io/izzel/taboolib/module/command/lite/CompleterTab.java similarity index 84% rename from src/main/scala/me/skymc/taboolib/commands/builder/type/CompleterTab.java rename to src/main/scala/io/izzel/taboolib/module/command/lite/CompleterTab.java index edd6f08..72b928c 100644 --- a/src/main/scala/me/skymc/taboolib/commands/builder/type/CompleterTab.java +++ b/src/main/scala/io/izzel/taboolib/module/command/lite/CompleterTab.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.commands.builder.type; +package io.izzel.taboolib.module.command.lite; import org.bukkit.command.CommandSender; diff --git a/src/main/scala/io/izzel/taboolib/module/compat/EconomyHook.java b/src/main/scala/io/izzel/taboolib/module/compat/EconomyHook.java new file mode 100644 index 0000000..20cc306 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/module/compat/EconomyHook.java @@ -0,0 +1,55 @@ +package io.izzel.taboolib.module.compat; + +import io.izzel.taboolib.module.inject.TFunction; +import net.milkbowl.vault.economy.Economy; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.plugin.RegisteredServiceProvider; + +/** + * @Author 坏黑 + * @Since 2019-07-05 18:50 + */ +@TFunction(enable = "init") +public class EconomyHook { + + private static Economy economy; + + static void init() { + if (Bukkit.getPluginManager().getPlugin("Vault") == null) { + return; + } + RegisteredServiceProvider l = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); + if (l != null) { + economy = l.getProvider(); + } + } + + public static void remove(OfflinePlayer p, double d) { + economy.withdrawPlayer(p, d); + } + + public static void add(OfflinePlayer p, double d) { + economy.depositPlayer(p, d); + } + + public static void set(OfflinePlayer p, double d) { + add(p, d - get(p)); + } + + public static double get(OfflinePlayer p) { + return economy.getBalance(p); + } + + public static void create(OfflinePlayer p) { + economy.createPlayerAccount(p); + } + + public static boolean exists() { + return economy != null; + } + + public static net.milkbowl.vault.economy.Economy getEconomy() { + return economy; + } +} diff --git a/src/main/scala/io/izzel/taboolib/module/compat/PermissionHook.java b/src/main/scala/io/izzel/taboolib/module/compat/PermissionHook.java new file mode 100644 index 0000000..b2bc5d5 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/module/compat/PermissionHook.java @@ -0,0 +1,39 @@ +package io.izzel.taboolib.module.compat; + +import io.izzel.taboolib.module.inject.TFunction; +import net.milkbowl.vault.permission.Permission; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.RegisteredServiceProvider; + +import java.util.Arrays; + +@TFunction(enable = "init") +public class PermissionHook { + + private static Permission perms; + + static void init() { + if (Bukkit.getPluginManager().getPlugin("Vault") == null) { + return; + } + RegisteredServiceProvider rsp = Bukkit.getServer().getServicesManager().getRegistration(Permission.class); + perms = rsp.getProvider(); + } + + public static Permission getPermission() { + return perms; + } + + public static void addPermission(Player player, String perm) { + perms.playerAdd(player, perm); + } + + public static void removePermission(Player player, String perm) { + perms.playerRemove(player, perm); + } + + public static boolean hasPermission(Player player, String perm) { + return perms.playerHas(player, perm) || Arrays.stream(perms.getPlayerGroups(player)).anyMatch(group -> perms.groupHas(player.getWorld(), group, perm)); + } +} diff --git a/src/main/scala/com/ilummc/tlib/compat/PlaceholderHook.java b/src/main/scala/io/izzel/taboolib/module/compat/PlaceholderHook.java similarity index 87% rename from src/main/scala/com/ilummc/tlib/compat/PlaceholderHook.java rename to src/main/scala/io/izzel/taboolib/module/compat/PlaceholderHook.java index c0b26c8..17efce8 100644 --- a/src/main/scala/com/ilummc/tlib/compat/PlaceholderHook.java +++ b/src/main/scala/io/izzel/taboolib/module/compat/PlaceholderHook.java @@ -1,15 +1,17 @@ -package com.ilummc.tlib.compat; +package io.izzel.taboolib.module.compat; import me.clip.placeholderapi.PlaceholderAPI; +import io.izzel.taboolib.module.inject.TFunction; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +@TFunction(enable = "init") public abstract class PlaceholderHook { private static PlaceholderHook impl; - public static void init() { + static void init() { if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { impl = new PlaceholderImpl(); } else { diff --git a/src/main/scala/me/skymc/taboolib/support/SupportWorldGuard.java b/src/main/scala/io/izzel/taboolib/module/compat/WorldGuardHook.java similarity index 94% rename from src/main/scala/me/skymc/taboolib/support/SupportWorldGuard.java rename to src/main/scala/io/izzel/taboolib/module/compat/WorldGuardHook.java index 836967c..1b43426 100644 --- a/src/main/scala/me/skymc/taboolib/support/SupportWorldGuard.java +++ b/src/main/scala/io/izzel/taboolib/module/compat/WorldGuardHook.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.support; +package io.izzel.taboolib.module.compat; import com.google.common.base.Preconditions; import com.sk89q.worldedit.bukkit.BukkitAdapter; @@ -19,13 +19,13 @@ import java.util.stream.Collectors; /** * @Author AgarthaLib */ -public class SupportWorldGuard { +public class WorldGuardHook { - public static final SupportWorldGuard INSTANCE = new SupportWorldGuard(); + public static final WorldGuardHook INSTANCE = new WorldGuardHook(); private WorldGuardPlugin worldGuard; private Method getRegionManager; - public SupportWorldGuard() { + public WorldGuardHook() { Preconditions.checkNotNull(Bukkit.getServer().getPluginManager().getPlugin("WorldGuard"), "WorldGuard was not found."); worldGuard = WorldGuardPlugin.inst(); if (!worldGuard.getDescription().getVersion().startsWith("7")) { diff --git a/src/main/scala/me/skymc/taboolib/common/configuration/TConfiguration.java b/src/main/scala/io/izzel/taboolib/module/config/TConfig.java similarity index 57% rename from src/main/scala/me/skymc/taboolib/common/configuration/TConfiguration.java rename to src/main/scala/io/izzel/taboolib/module/config/TConfig.java index 8c948ce..db84d0d 100644 --- a/src/main/scala/me/skymc/taboolib/common/configuration/TConfiguration.java +++ b/src/main/scala/io/izzel/taboolib/module/config/TConfig.java @@ -1,12 +1,12 @@ -package me.skymc.taboolib.common.configuration; +package io.izzel.taboolib.module.config; import com.google.common.collect.Maps; -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.logger.TLogger; -import com.ilummc.tlib.resources.TLocale; -import com.ilummc.tlib.util.Ref; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.locale.logger.TLogger; +import io.izzel.taboolib.util.Files; +import io.izzel.taboolib.util.Ref; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; @@ -22,56 +22,36 @@ import java.util.Optional; * @Author sky * @Since 2018-09-08 15:00 */ -public class TConfiguration extends YamlConfiguration { +public class TConfig extends YamlConfiguration { private static Map> files = Maps.newHashMap(); private File file; private Runnable runnable; - private TConfiguration(File file, Plugin plugin) { + private TConfig(File file, Plugin plugin) { files.computeIfAbsent(plugin.getName(), name -> new ArrayList<>()).add(file); this.file = file; reload(); - TLib.getTLib().getConfigWatcher().addSimpleListener(this.file, this::reload); - TabooLib.debug("Loaded TConfiguration \"" + file.getName() + "\" from Plugin \"" + plugin.getName() + "\""); + TConfigWatcher.getInst().addSimpleListener(this.file, this::reload); + TabooLibAPI.debug("Loaded TConfiguration \"" + file.getName() + "\" from Plugin \"" + plugin.getName() + "\""); } public static Map> getFiles() { return files; } - /** - * 创建配置文件 - * - * @param file 文件 - * @return {@link TConfiguration} - */ - public static TConfiguration create(File file) { - return new TConfiguration(file, Ref.getCallerPlugin(Ref.getCallerClass(3).orElse(Main.class))); + public static TConfig create(File file) { + return new TConfig(file, Ref.getCallerPlugin(Ref.getCallerClass(3).orElse(TabooLib.class))); } - /** - * 创建配置文件 - * - * @param file 文件 - * @param plugin 插件 - * @return {@link TConfiguration} - */ - public static TConfiguration create(File file, Plugin plugin) { - return new TConfiguration(file, plugin); + public static TConfig create(File file, Plugin plugin) { + return new TConfig(file, plugin); } - /** - * 从插件里释放文件并创建 - * - * @param plugin 插件 - * @param path 目录 - * @return {@link TConfiguration} - */ - public static TConfiguration createInResource(Plugin plugin, String path) { + public static TConfig create(Plugin plugin, String path) { File file = new File(plugin.getDataFolder(), path); if (!file.exists()) { - plugin.saveResource(path, true); + Files.releaseResource(plugin, path, false); } return create(file, plugin); } @@ -89,7 +69,7 @@ public class TConfiguration extends YamlConfiguration { } public void release() { - TLib.getTLib().getConfigWatcher().removeListener(file); + TConfigWatcher.getInst().removeListener(file); } public void reload() { @@ -111,7 +91,7 @@ public class TConfiguration extends YamlConfiguration { return file; } - public TConfiguration listener(Runnable runnable) { + public TConfig listener(Runnable runnable) { this.runnable = runnable; return this; } diff --git a/src/main/scala/com/ilummc/tlib/inject/TConfigWatcher.java b/src/main/scala/io/izzel/taboolib/module/config/TConfigWatcher.java similarity index 93% rename from src/main/scala/com/ilummc/tlib/inject/TConfigWatcher.java rename to src/main/scala/io/izzel/taboolib/module/config/TConfigWatcher.java index 95ef971..9c3b6b1 100644 --- a/src/main/scala/com/ilummc/tlib/inject/TConfigWatcher.java +++ b/src/main/scala/io/izzel/taboolib/module/config/TConfigWatcher.java @@ -1,4 +1,4 @@ -package com.ilummc.tlib.inject; +package io.izzel.taboolib.module.config; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.apache.commons.lang3.tuple.Triple; @@ -19,6 +19,7 @@ import java.util.function.Consumer; */ public class TConfigWatcher { + private static TConfigWatcher configWatcher = new TConfigWatcher(); private final ScheduledExecutorService service = Executors.newScheduledThreadPool(1, new BasicThreadFactory.Builder().namingPattern("TConfigWatcherService-%d").build()); private final Map>> map = new HashMap<>(); @@ -40,6 +41,10 @@ public class TConfigWatcher { }, 1000, 100, TimeUnit.MILLISECONDS); } + public static TConfigWatcher getInst() { + return configWatcher; + } + public void addSimpleListener(File file, Runnable runnable) { addListener(file, null, obj -> runnable.run()); } diff --git a/src/main/scala/me/skymc/taboolib/mysql/IColumn.java b/src/main/scala/io/izzel/taboolib/module/db/IColumn.java similarity index 78% rename from src/main/scala/me/skymc/taboolib/mysql/IColumn.java rename to src/main/scala/io/izzel/taboolib/module/db/IColumn.java index 6a5f90d..8653ff7 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/IColumn.java +++ b/src/main/scala/io/izzel/taboolib/module/db/IColumn.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.mysql; +package io.izzel.taboolib.module.db; /** * @Author 坏黑 diff --git a/src/main/scala/me/skymc/taboolib/mysql/IHost.java b/src/main/scala/io/izzel/taboolib/module/db/IHost.java similarity index 95% rename from src/main/scala/me/skymc/taboolib/mysql/IHost.java rename to src/main/scala/io/izzel/taboolib/module/db/IHost.java index 5adf5fa..2b5ee64 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/IHost.java +++ b/src/main/scala/io/izzel/taboolib/module/db/IHost.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.mysql; +package io.izzel.taboolib.module.db; import org.bukkit.plugin.Plugin; diff --git a/src/main/scala/io/izzel/taboolib/module/db/local/Local.java b/src/main/scala/io/izzel/taboolib/module/db/local/Local.java new file mode 100644 index 0000000..472dc77 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/module/db/local/Local.java @@ -0,0 +1,39 @@ +package io.izzel.taboolib.module.db.local; + +import com.google.common.collect.Maps; +import io.izzel.taboolib.module.inject.TSchedule; +import io.izzel.taboolib.util.Ref; + +import java.util.Map; +import java.util.Optional; + +/** + * @Author 坏黑 + * @Since 2019-07-06 15:24 + */ +public class Local { + + private static Map plugins = Maps.newConcurrentMap(); + + @TSchedule(delay = 20 * 30, period = 20 * 30, async = true) + public static void saveFiles() { + plugins.values().forEach(LocalPlugin::saveFiles); + } + + public static void saveFiles(String name) { + Optional.ofNullable(plugins.get(name)).ifPresent(LocalPlugin::saveFiles); + } + + public static void clearFiles(String name) { + Optional.ofNullable(plugins.remove(name)).ifPresent(LocalPlugin::clearFiles); + } + + public static LocalPlugin get(String name) { + return plugins.computeIfAbsent(name, LocalPlugin::new); + } + + public static LocalPlugin get() { + Class callerClass = Ref.getCallerClass(3).orElse(null); + return get(callerClass == null ? "TabooLib" : Ref.getCallerPlugin(callerClass).getName()); + } +} diff --git a/src/main/scala/com/ilummc/tlib/annotations/PluginInstance.java b/src/main/scala/io/izzel/taboolib/module/db/local/LocalFile.java similarity index 66% rename from src/main/scala/com/ilummc/tlib/annotations/PluginInstance.java rename to src/main/scala/io/izzel/taboolib/module/db/local/LocalFile.java index 9e10b55..96127f8 100644 --- a/src/main/scala/com/ilummc/tlib/annotations/PluginInstance.java +++ b/src/main/scala/io/izzel/taboolib/module/db/local/LocalFile.java @@ -1,13 +1,18 @@ -package com.ilummc.tlib.annotations; +package io.izzel.taboolib.module.db.local; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +/** + * @Author sky + * @Since 2018-09-14 23:45 + */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) -public @interface PluginInstance { +public @interface LocalFile { String value(); -} + +} \ No newline at end of file diff --git a/src/main/scala/io/izzel/taboolib/module/db/local/LocalLoader.java b/src/main/scala/io/izzel/taboolib/module/db/local/LocalLoader.java new file mode 100644 index 0000000..940e37e --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/module/db/local/LocalLoader.java @@ -0,0 +1,41 @@ +package io.izzel.taboolib.module.db.local; + +import io.izzel.taboolib.TabooLibLoader; +import io.izzel.taboolib.module.locale.logger.TLogger; +import org.bukkit.plugin.Plugin; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; + +/** + * @Author 坏黑 + * @Since 2019-07-06 17:35 + */ +public class LocalLoader implements TabooLibLoader.Loader { + + @Override + public void preLoad(Plugin plugin, Class loadClass) { + for (Field field : loadClass.getDeclaredFields()) { + LocalFile annotation = field.getAnnotation(LocalFile.class); + if (annotation == null) { + continue; + } + Object instance = null; + // 如果是非静态类型 + if (!Modifier.isStatic(field.getModifiers())) { + // 是否为主类 + if (loadClass.equals(plugin.getClass())) { + instance = plugin; + } else { + TLogger.getGlobalLogger().error(field.getName() + " is not a static field. (" + loadClass.getName() + ")"); + continue; + } + } + field.setAccessible(true); + try { + field.set(instance, Local.get(plugin.getName()).get(annotation.value())); + } catch (IllegalAccessException ignored) { + } + } + } +} diff --git a/src/main/scala/io/izzel/taboolib/module/db/local/LocalPlayer.java b/src/main/scala/io/izzel/taboolib/module/db/local/LocalPlayer.java new file mode 100644 index 0000000..50489d7 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/module/db/local/LocalPlayer.java @@ -0,0 +1,73 @@ +package io.izzel.taboolib.module.db.local; + +import com.google.common.collect.Maps; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.module.inject.TSchedule; +import io.izzel.taboolib.util.Files; +import me.skymc.taboolib.database.PlayerDataManager; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.io.File; +import java.util.Map; +import java.util.UUID; + +/** + * @Author 坏黑 + * @Since 2019-07-06 17:43 + */ +public class LocalPlayer { + + private static Map files = Maps.newConcurrentMap(); + + public static FileConfiguration get(OfflinePlayer player) { + return TabooLibAPI.isOriginLoaded() ? PlayerDataManager.getPlayerData(player) : files.computeIfAbsent(toName(player), n -> Files.load(toFile(n))); + } + + @TSchedule(delay = 20 * 30, period = 20 * 30, async = true) + public static void saveFiles() { + files.forEach((name, file) -> { + try { + file.save(toFile(name)); + } catch (Throwable t) { + t.printStackTrace(); + } + }); + } + + @TSchedule(delay = 20 * 30, period = 20 * 30, async = true) + public static void checkFile() { + files.forEach((name, file) -> { + if (toPlayer(name) == null) { + try { + files.remove(name).save(toFile(name)); + } catch (Throwable t) { + t.printStackTrace(); + } + } + }); + } + + public static File getFolder() { + return Files.folder(TabooLib.getConfig().getString("LOCAL-PLAYER")); + } + + private static File toFile(String name) { + return Files.file(getFolder(), name + ".yml"); + } + + private static String toName(OfflinePlayer player) { + return isUniqueIdMode() ? player.getUniqueId().toString() : player.getName(); + } + + private static boolean isUniqueIdMode() { + return TabooLib.getConfig().getBoolean("LOCAL-PLAYER-UUID"); + } + + private static Player toPlayer(String name) { + return isUniqueIdMode() ? Bukkit.getPlayer(UUID.fromString(name)) : Bukkit.getPlayerExact(name); + } +} diff --git a/src/main/scala/io/izzel/taboolib/module/db/local/LocalPlugin.java b/src/main/scala/io/izzel/taboolib/module/db/local/LocalPlugin.java new file mode 100644 index 0000000..283470f --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/module/db/local/LocalPlugin.java @@ -0,0 +1,71 @@ +package io.izzel.taboolib.module.db.local; + +import com.google.common.collect.Maps; +import io.izzel.taboolib.util.Files; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.util.Map; + +/** + * @Author 坏黑 + * @Since 2019-07-06 16:55 + */ +public class LocalPlugin { + + private String name; + private Map files = Maps.newConcurrentMap(); + + public LocalPlugin(String name) { + this.name = name; + } + + public FileConfiguration get(String name) { + return files.computeIfAbsent(fixName(name), n -> Files.load(toFile(n))); + } + + public FileConfiguration getFile(String name) { + return files.getOrDefault(fixName(name), new YamlConfiguration()); + } + + public FileConfiguration addFile(String name) { + FileConfiguration file = Files.load(toFile(name)); + files.put(fixName(name), file); + return file; + } + + public FileConfiguration clearFile(String name) { + return files.remove(fixName(name)); + } + + public void clearFiles() { + files.clear(); + } + + public void saveFiles() { + files.forEach((name, file) -> { + try { + file.save(toFile(name)); + } catch (Throwable t) { + t.printStackTrace(); + } + }); + } + + private File toFile(String name) { + return Files.file("plugins/" + this.name + "/" + fixName(name)); + } + + private String fixName(String name) { + return name.endsWith(".yml") ? name : name + ".yml"; + } + + public String getName() { + return name; + } + + public Map getFiles() { + return files; + } +} diff --git a/src/main/scala/me/skymc/taboolib/mysql/hikari/HikariHandler.java b/src/main/scala/io/izzel/taboolib/module/db/source/DBSource.java similarity index 66% rename from src/main/scala/me/skymc/taboolib/mysql/hikari/HikariHandler.java rename to src/main/scala/io/izzel/taboolib/module/db/source/DBSource.java index aa3fc79..874f47c 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/hikari/HikariHandler.java +++ b/src/main/scala/io/izzel/taboolib/module/db/source/DBSource.java @@ -1,14 +1,13 @@ -package me.skymc.taboolib.mysql.hikari; +package io.izzel.taboolib.module.db.source; -import com.google.common.base.Preconditions; -import com.ilummc.tlib.resources.TLocale; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.fileutils.ConfigUtils; -import me.skymc.taboolib.mysql.IHost; -import me.skymc.taboolib.mysql.builder.SQLHost; -import me.skymc.taboolib.mysql.sqlite.SQLiteHost; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.config.TConfig; +import io.izzel.taboolib.module.inject.TInject; +import io.izzel.taboolib.module.db.IHost; +import io.izzel.taboolib.module.db.sql.SQLHost; +import io.izzel.taboolib.module.db.sqlite.SQLiteHost; import org.bukkit.configuration.file.FileConfiguration; import javax.sql.DataSource; @@ -18,17 +17,18 @@ import java.util.concurrent.ConcurrentHashMap; * @Author sky * @Since 2018-05-16 21:59 */ -public class HikariHandler { +public class DBSource { - private static ConcurrentHashMap dataSource = new ConcurrentHashMap<>(); - private static FileConfiguration settings = ConfigUtils.saveDefaultConfig(Main.getInst(), "hikarisettings.yml"); + @TInject("datasource.yml") + private static TConfig settings; + private static ConcurrentHashMap dataSource = new ConcurrentHashMap<>(); - public static DataSource createDataSource(IHost host) { - return createDataSource(host, null); + public static DataSource create(IHost host) { + return create(host, null); } - public static HikariDataSource createDataSource(IHost host, HikariConfig hikariConfig) { - MapDataSource mapDataSource = dataSource.computeIfAbsent(host, x -> new MapDataSource(x, new HikariDataSource(hikariConfig == null ? createConfig(host) : hikariConfig))); + public static DataSource create(IHost host, HikariConfig hikariConfig) { + DBSourceData mapDataSource = dataSource.computeIfAbsent(host, x -> new DBSourceData(x, new HikariDataSource(hikariConfig == null ? createConfig(host) : hikariConfig))); mapDataSource.getActivePlugin().getAndIncrement(); if (mapDataSource.getActivePlugin().get() == 1) { TLocale.Logger.info("MYSQL-HIKARI.CREATE-SUCCESS", host.getPlugin().getName(), host.getConnectionUrlSimple()); @@ -39,13 +39,12 @@ public class HikariHandler { } public static void closeDataSourceForce() { - Preconditions.checkArgument(Main.isDisable(), "Cannot be invoked when the server is running."); dataSource.values().forEach(x -> x.getHikariDataSource().close()); } public static void closeDataSource(IHost host) { if (host != null && dataSource.containsKey(host)) { - MapDataSource mapDataSource = dataSource.get(host); + DBSourceData mapDataSource = dataSource.get(host); if (mapDataSource.getActivePlugin().getAndDecrement() <= 1) { mapDataSource.getHikariDataSource().close(); dataSource.remove(host); @@ -84,33 +83,13 @@ public class HikariHandler { return config; } - @Deprecated - public static DataSource createDataSource(SQLHost host) { - return createDataSource((IHost) host, null); - } - - @Deprecated - public static HikariConfig createConfig(SQLHost host) { - return createConfig((IHost) host); - } - - @Deprecated - public static HikariDataSource createDataSource(SQLHost host, HikariConfig hikariConfig) { - return createDataSource((IHost) host, hikariConfig); - } - - @Deprecated - public static void closeDataSource(SQLHost host) { - closeDataSource((IHost) host); - } - // ********************************* // // Getter and Setter // // ********************************* - public static ConcurrentHashMap getDataSource() { + public static ConcurrentHashMap getDataSource() { return dataSource; } diff --git a/src/main/scala/me/skymc/taboolib/mysql/hikari/MapDataSource.java b/src/main/scala/io/izzel/taboolib/module/db/source/DBSourceData.java similarity index 77% rename from src/main/scala/me/skymc/taboolib/mysql/hikari/MapDataSource.java rename to src/main/scala/io/izzel/taboolib/module/db/source/DBSourceData.java index 17a95c9..909e16b 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/hikari/MapDataSource.java +++ b/src/main/scala/io/izzel/taboolib/module/db/source/DBSourceData.java @@ -1,7 +1,7 @@ -package me.skymc.taboolib.mysql.hikari; +package io.izzel.taboolib.module.db.source; import com.zaxxer.hikari.HikariDataSource; -import me.skymc.taboolib.mysql.IHost; +import io.izzel.taboolib.module.db.IHost; import java.util.concurrent.atomic.AtomicInteger; @@ -9,13 +9,13 @@ import java.util.concurrent.atomic.AtomicInteger; * @Author sky * @Since 2018-05-17 23:47 */ -public class MapDataSource { +public class DBSourceData { private IHost host; private AtomicInteger activePlugin; private HikariDataSource hikariDataSource; - MapDataSource(IHost host, HikariDataSource hikariDataSource) { + DBSourceData(IHost host, HikariDataSource hikariDataSource) { this.host = host; this.activePlugin = new AtomicInteger(); this.hikariDataSource = hikariDataSource; diff --git a/src/main/scala/me/skymc/taboolib/mysql/builder/SQLColumn.java b/src/main/scala/io/izzel/taboolib/module/db/sql/SQLColumn.java similarity index 97% rename from src/main/scala/me/skymc/taboolib/mysql/builder/SQLColumn.java rename to src/main/scala/io/izzel/taboolib/module/db/sql/SQLColumn.java index d154939..1945262 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/builder/SQLColumn.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sql/SQLColumn.java @@ -1,7 +1,7 @@ -package me.skymc.taboolib.mysql.builder; +package io.izzel.taboolib.module.db.sql; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.mysql.IColumn; +import io.izzel.taboolib.util.Strings; +import io.izzel.taboolib.module.db.IColumn; import java.util.Arrays; diff --git a/src/main/scala/me/skymc/taboolib/mysql/builder/SQLColumnOption.java b/src/main/scala/io/izzel/taboolib/module/db/sql/SQLColumnOption.java similarity index 92% rename from src/main/scala/me/skymc/taboolib/mysql/builder/SQLColumnOption.java rename to src/main/scala/io/izzel/taboolib/module/db/sql/SQLColumnOption.java index bedc9de..93711bd 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/builder/SQLColumnOption.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sql/SQLColumnOption.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.mysql.builder; +package io.izzel.taboolib.module.db.sql; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/mysql/builder/SQLColumnType.java b/src/main/scala/io/izzel/taboolib/module/db/sql/SQLColumnType.java similarity index 98% rename from src/main/scala/me/skymc/taboolib/mysql/builder/SQLColumnType.java rename to src/main/scala/io/izzel/taboolib/module/db/sql/SQLColumnType.java index a882ac8..36098a2 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/builder/SQLColumnType.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sql/SQLColumnType.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.mysql.builder; +package io.izzel.taboolib.module.db.sql; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/mysql/builder/SQLExecutor.java b/src/main/scala/io/izzel/taboolib/module/db/sql/SQLExecutor.java similarity index 95% rename from src/main/scala/me/skymc/taboolib/mysql/builder/SQLExecutor.java rename to src/main/scala/io/izzel/taboolib/module/db/sql/SQLExecutor.java index a6846ab..5eb0dee 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/builder/SQLExecutor.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sql/SQLExecutor.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.mysql.builder; +package io.izzel.taboolib.module.db.sql; import java.sql.Connection; import java.sql.PreparedStatement; diff --git a/src/main/scala/me/skymc/taboolib/mysql/builder/SQLHost.java b/src/main/scala/io/izzel/taboolib/module/db/sql/SQLHost.java similarity index 93% rename from src/main/scala/me/skymc/taboolib/mysql/builder/SQLHost.java rename to src/main/scala/io/izzel/taboolib/module/db/sql/SQLHost.java index 96fa4ea..5e3e87d 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/builder/SQLHost.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sql/SQLHost.java @@ -1,11 +1,11 @@ -package me.skymc.taboolib.mysql.builder; +package io.izzel.taboolib.module.db.sql; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.mysql.IHost; -import me.skymc.taboolib.string.ArrayUtils; +import io.izzel.taboolib.module.db.IHost; +import io.izzel.taboolib.util.Strings; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.plugin.Plugin; +import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @@ -21,7 +21,7 @@ public class SQLHost extends IHost { private String port; private String password; private String database; - private List flags = ArrayUtils.asList("characterEncoding=utf-8", "useSSL=false"); + private List flags = Arrays.asList("characterEncoding=utf-8", "useSSL=false"); public SQLHost(ConfigurationSection section, Plugin plugin) { this(section, plugin, false); diff --git a/src/main/scala/me/skymc/taboolib/mysql/builder/SQLTable.java b/src/main/scala/io/izzel/taboolib/module/db/sql/SQLTable.java similarity index 82% rename from src/main/scala/me/skymc/taboolib/mysql/builder/SQLTable.java rename to src/main/scala/io/izzel/taboolib/module/db/sql/SQLTable.java index 159e046..cd09876 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/builder/SQLTable.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sql/SQLTable.java @@ -1,12 +1,10 @@ -package me.skymc.taboolib.mysql.builder; +package io.izzel.taboolib.module.db.sql; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.mysql.IColumn; -import me.skymc.taboolib.mysql.builder.query.RunnableQuery; -import me.skymc.taboolib.mysql.builder.query.RunnableUpdate; -import me.skymc.taboolib.string.ArrayUtils; - -import java.util.Arrays; +import io.izzel.taboolib.module.db.IColumn; +import io.izzel.taboolib.module.db.sql.query.RunnableQuery; +import io.izzel.taboolib.module.db.sql.query.RunnableUpdate; +import io.izzel.taboolib.util.ArrayUtil; +import io.izzel.taboolib.util.Strings; /** * @Author sky @@ -32,19 +30,19 @@ public class SQLTable { } public SQLTable column(IColumn column) { - columns = columns == null ? new IColumn[] {column} : ArrayUtils.arrayAppend(columns, column); + columns = columns == null ? new IColumn[] {column} : ArrayUtil.arrayAppend(columns, column); return this; } @Deprecated public SQLTable addColumn(SQLColumn sqlColumn) { - columns = columns == null ? new SQLColumn[] {sqlColumn} : ArrayUtils.arrayAppend(columns, sqlColumn); + columns = columns == null ? new SQLColumn[] {sqlColumn} : ArrayUtil.arrayAppend(columns, sqlColumn); return this; } public String createQuery() { StringBuilder builder = new StringBuilder(); - Arrays.stream(columns).forEach(sqlColumn -> builder.append(sqlColumn.convertToCommand()).append(", ")); + java.util.Arrays.stream(columns).forEach(sqlColumn -> builder.append(sqlColumn.convertToCommand()).append(", ")); return Strings.replaceWithOrder("create table if not exists `{0}` ({1})", tableName, builder.substring(0, builder.length() - 2)); } diff --git a/src/main/scala/me/skymc/taboolib/mysql/builder/query/RunnableQuery.java b/src/main/scala/io/izzel/taboolib/module/db/sql/query/RunnableQuery.java similarity index 96% rename from src/main/scala/me/skymc/taboolib/mysql/builder/query/RunnableQuery.java rename to src/main/scala/io/izzel/taboolib/module/db/sql/query/RunnableQuery.java index c3f016d..7d4fecc 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/builder/query/RunnableQuery.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sql/query/RunnableQuery.java @@ -1,7 +1,7 @@ -package me.skymc.taboolib.mysql.builder.query; +package io.izzel.taboolib.module.db.sql.query; -import com.ilummc.tlib.logger.TLogger; -import me.skymc.taboolib.mysql.builder.SQLExecutor; +import io.izzel.taboolib.module.locale.logger.TLogger; +import io.izzel.taboolib.module.db.sql.SQLExecutor; import javax.sql.DataSource; import java.sql.Connection; diff --git a/src/main/scala/me/skymc/taboolib/mysql/builder/query/RunnableUpdate.java b/src/main/scala/io/izzel/taboolib/module/db/sql/query/RunnableUpdate.java similarity index 94% rename from src/main/scala/me/skymc/taboolib/mysql/builder/query/RunnableUpdate.java rename to src/main/scala/io/izzel/taboolib/module/db/sql/query/RunnableUpdate.java index 91cdb50..ba3e3a3 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/builder/query/RunnableUpdate.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sql/query/RunnableUpdate.java @@ -1,7 +1,7 @@ -package me.skymc.taboolib.mysql.builder.query; +package io.izzel.taboolib.module.db.sql.query; -import com.ilummc.tlib.logger.TLogger; -import me.skymc.taboolib.mysql.builder.SQLExecutor; +import io.izzel.taboolib.module.locale.logger.TLogger; +import io.izzel.taboolib.module.db.sql.SQLExecutor; import javax.sql.DataSource; import java.sql.Connection; diff --git a/src/main/scala/me/skymc/taboolib/mysql/builder/query/TaskResult.java b/src/main/scala/io/izzel/taboolib/module/db/sql/query/TaskResult.java similarity index 81% rename from src/main/scala/me/skymc/taboolib/mysql/builder/query/TaskResult.java rename to src/main/scala/io/izzel/taboolib/module/db/sql/query/TaskResult.java index 21acd8d..c41b358 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/builder/query/TaskResult.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sql/query/TaskResult.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.mysql.builder.query; +package io.izzel.taboolib.module.db.sql.query; import java.sql.ResultSet; import java.sql.SQLException; diff --git a/src/main/scala/me/skymc/taboolib/mysql/builder/query/TaskStatement.java b/src/main/scala/io/izzel/taboolib/module/db/sql/query/TaskStatement.java similarity index 82% rename from src/main/scala/me/skymc/taboolib/mysql/builder/query/TaskStatement.java rename to src/main/scala/io/izzel/taboolib/module/db/sql/query/TaskStatement.java index 58d1707..5cc031b 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/builder/query/TaskStatement.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sql/query/TaskStatement.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.mysql.builder.query; +package io.izzel.taboolib.module.db.sql.query; import java.sql.PreparedStatement; import java.sql.SQLException; diff --git a/src/main/scala/me/skymc/taboolib/mysql/sqlite/SQLiteColumn.java b/src/main/scala/io/izzel/taboolib/module/db/sqlite/SQLiteColumn.java similarity index 97% rename from src/main/scala/me/skymc/taboolib/mysql/sqlite/SQLiteColumn.java rename to src/main/scala/io/izzel/taboolib/module/db/sqlite/SQLiteColumn.java index c28cf07..2014f7d 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/sqlite/SQLiteColumn.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sqlite/SQLiteColumn.java @@ -1,7 +1,7 @@ -package me.skymc.taboolib.mysql.sqlite; +package io.izzel.taboolib.module.db.sqlite; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.mysql.IColumn; +import io.izzel.taboolib.util.Strings; +import io.izzel.taboolib.module.db.IColumn; import java.util.Arrays; diff --git a/src/main/scala/me/skymc/taboolib/mysql/sqlite/SQLiteColumnOption.java b/src/main/scala/io/izzel/taboolib/module/db/sqlite/SQLiteColumnOption.java similarity index 91% rename from src/main/scala/me/skymc/taboolib/mysql/sqlite/SQLiteColumnOption.java rename to src/main/scala/io/izzel/taboolib/module/db/sqlite/SQLiteColumnOption.java index 4967b0e..b2c4f39 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/sqlite/SQLiteColumnOption.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sqlite/SQLiteColumnOption.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.mysql.sqlite; +package io.izzel.taboolib.module.db.sqlite; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/mysql/sqlite/SQLiteColumnType.java b/src/main/scala/io/izzel/taboolib/module/db/sqlite/SQLiteColumnType.java similarity index 92% rename from src/main/scala/me/skymc/taboolib/mysql/sqlite/SQLiteColumnType.java rename to src/main/scala/io/izzel/taboolib/module/db/sqlite/SQLiteColumnType.java index 894aa9a..f156166 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/sqlite/SQLiteColumnType.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sqlite/SQLiteColumnType.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.mysql.sqlite; +package io.izzel.taboolib.module.db.sqlite; /** * @Author 坏黑 diff --git a/src/main/scala/me/skymc/taboolib/mysql/sqlite/SQLiteHost.java b/src/main/scala/io/izzel/taboolib/module/db/sqlite/SQLiteHost.java similarity index 93% rename from src/main/scala/me/skymc/taboolib/mysql/sqlite/SQLiteHost.java rename to src/main/scala/io/izzel/taboolib/module/db/sqlite/SQLiteHost.java index 7d0928d..47df378 100644 --- a/src/main/scala/me/skymc/taboolib/mysql/sqlite/SQLiteHost.java +++ b/src/main/scala/io/izzel/taboolib/module/db/sqlite/SQLiteHost.java @@ -1,6 +1,6 @@ -package me.skymc.taboolib.mysql.sqlite; +package io.izzel.taboolib.module.db.sqlite; -import me.skymc.taboolib.mysql.IHost; +import io.izzel.taboolib.module.db.IHost; import org.bukkit.plugin.Plugin; import java.io.File; diff --git a/src/main/scala/com/ilummc/tlib/annotations/Dependencies.java b/src/main/scala/io/izzel/taboolib/module/dependency/Dependencies.java similarity index 86% rename from src/main/scala/com/ilummc/tlib/annotations/Dependencies.java rename to src/main/scala/io/izzel/taboolib/module/dependency/Dependencies.java index a87a8d7..50a1164 100644 --- a/src/main/scala/com/ilummc/tlib/annotations/Dependencies.java +++ b/src/main/scala/io/izzel/taboolib/module/dependency/Dependencies.java @@ -1,4 +1,4 @@ -package com.ilummc.tlib.annotations; +package io.izzel.taboolib.module.dependency; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/scala/com/ilummc/tlib/annotations/Dependency.java b/src/main/scala/io/izzel/taboolib/module/dependency/Dependency.java similarity index 81% rename from src/main/scala/com/ilummc/tlib/annotations/Dependency.java rename to src/main/scala/io/izzel/taboolib/module/dependency/Dependency.java index 9c706c9..26f459f 100644 --- a/src/main/scala/com/ilummc/tlib/annotations/Dependency.java +++ b/src/main/scala/io/izzel/taboolib/module/dependency/Dependency.java @@ -1,6 +1,4 @@ -package com.ilummc.tlib.annotations; - -import com.ilummc.tlib.dependency.TDependency; +package io.izzel.taboolib.module.dependency; import java.lang.annotation.*; diff --git a/src/main/scala/io/izzel/taboolib/module/dependency/TDependency.java b/src/main/scala/io/izzel/taboolib/module/dependency/TDependency.java new file mode 100644 index 0000000..31f5fc4 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/module/dependency/TDependency.java @@ -0,0 +1,62 @@ +package io.izzel.taboolib.module.dependency; + +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.util.Files; + +import java.io.File; +import java.util.Arrays; + +public class TDependency { + + // 阿里 http://maven.aliyun.com/nexus/content/groups/public + public static final String MAVEN_REPO = "http://repo1.maven.org/maven2"; + + /** + * 请求一个插件作为依赖,这个插件将会在所有已经添加的 Jenkins 仓库、Maven 仓库寻找 + *

+ * 阻塞线程进行下载/加载 + * + * @param args 插件名称,下载地址(可选) + * @return 是否成功加载了依赖 + */ + public static boolean requestPlugin(String... args) { + return false; + } + + /** + * 请求一个库作为依赖,这个库将会在 Maven Central、oss.sonatype 以及自定义的 Maven 仓库寻找 + *

+ * 阻塞线程进行下载/加载 + * + * @param type 依赖名,格式为 groupId:artifactId:version + * @return 是否成功加载库,如果加载成功,插件将可以任意调用使用的类 + */ + public static boolean requestLib(String type, String repo, String url) { + // 清理大小为 0 的依赖文件 + File libFolder = new File(TabooLib.getPlugin().getDataFolder(), "/libs"); + if (libFolder.exists()) { + Arrays.stream(libFolder.listFiles()).filter(listFile -> listFile.length() == 0).forEach(File::delete); + } + if (type.matches(".*:.*:.*")) { + String[] arr = type.split(":"); + File file = new File(TabooLib.getPlugin().getDataFolder(), "/libs/" + String.join("-", arr) + ".jar"); + if (file.exists()) { + TDependencyLoader.addToPath(TabooLib.getPlugin(), file); + return true; + } else { + if (downloadMaven(repo, arr[0], arr[1], arr[2], file, url)) { + TDependencyLoader.addToPath(TabooLib.getPlugin(), file); + return true; + } else { + return false; + } + } + } + return false; + } + + private static boolean downloadMaven(String url, String groupId, String artifactId, String version, File target, String dl) { + Files.toFile(Files.readFromURL(dl.length() == 0 ? url + "/" + groupId.replace('.', '/') + "/" + artifactId + "/" + version + "/" + artifactId + "-" + version + ".jar" : dl, ""), Files.file(target)); + return target.length() > 0; + } +} diff --git a/src/main/scala/io/izzel/taboolib/module/dependency/TDependencyInjector.java b/src/main/scala/io/izzel/taboolib/module/dependency/TDependencyInjector.java new file mode 100644 index 0000000..c35294c --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/module/dependency/TDependencyInjector.java @@ -0,0 +1,40 @@ +package io.izzel.taboolib.module.dependency; + +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.module.locale.TLocale; +import org.bukkit.plugin.Plugin; + +/** + * @author Izzel_Aliz + */ +public class TDependencyInjector { + + public static Dependency[] getDependencies(Class clazz) { + Dependency[] dependencies = new Dependency[0]; + Dependencies d = clazz.getAnnotation(Dependencies.class); + if (d != null) { + dependencies = d.value(); + } + Dependency d2 = clazz.getAnnotation(Dependency.class); + if (d2 != null) { + dependencies = new Dependency[] {d2}; + } + return dependencies; + } + + public static void inject(Plugin plugin, Class clazz) { + inject(plugin.getName(), clazz); + } + + public static void inject(String name, Class clazz) { + for (Dependency dependency : getDependencies(clazz)) { + if (dependency.type() == Dependency.Type.LIBRARY) { + if (TDependency.requestLib(dependency.maven(), dependency.mavenRepo(), dependency.url())) { + TabooLibAPI.debug(" Loaded " + String.join(":", dependency.maven()) + " (" + name + ")"); + } else { + TLocale.Logger.warn("DEPENDENCY.LIBRARY-LOAD-FAIL", name, String.join(":", dependency.maven())); + } + } + } + } +} diff --git a/src/main/scala/com/ilummc/tlib/dependency/TDependencyLoader.java b/src/main/scala/io/izzel/taboolib/module/dependency/TDependencyLoader.java similarity index 95% rename from src/main/scala/com/ilummc/tlib/dependency/TDependencyLoader.java rename to src/main/scala/io/izzel/taboolib/module/dependency/TDependencyLoader.java index 3c52502..e9efb01 100644 --- a/src/main/scala/com/ilummc/tlib/dependency/TDependencyLoader.java +++ b/src/main/scala/io/izzel/taboolib/module/dependency/TDependencyLoader.java @@ -1,4 +1,4 @@ -package com.ilummc.tlib.dependency; +package io.izzel.taboolib.module.dependency; import org.bukkit.plugin.Plugin; diff --git a/src/main/scala/me/skymc/taboolib/common/playercontainer/Container.java b/src/main/scala/io/izzel/taboolib/module/inject/Container.java similarity index 88% rename from src/main/scala/me/skymc/taboolib/common/playercontainer/Container.java rename to src/main/scala/io/izzel/taboolib/module/inject/Container.java index 2d9dcbf..c5319fe 100644 --- a/src/main/scala/me/skymc/taboolib/common/playercontainer/Container.java +++ b/src/main/scala/io/izzel/taboolib/module/inject/Container.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.playercontainer; +package io.izzel.taboolib.module.inject; /** * @author sky diff --git a/src/main/scala/me/skymc/taboolib/common/playercontainer/PlayerContainer.java b/src/main/scala/io/izzel/taboolib/module/inject/PlayerContainer.java similarity index 87% rename from src/main/scala/me/skymc/taboolib/common/playercontainer/PlayerContainer.java rename to src/main/scala/io/izzel/taboolib/module/inject/PlayerContainer.java index 3f35b81..a586d9d 100644 --- a/src/main/scala/me/skymc/taboolib/common/playercontainer/PlayerContainer.java +++ b/src/main/scala/io/izzel/taboolib/module/inject/PlayerContainer.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.playercontainer; +package io.izzel.taboolib.module.inject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/scala/me/skymc/taboolib/common/playercontainer/PlayerContainerLoader.java b/src/main/scala/io/izzel/taboolib/module/inject/PlayerContainerLoader.java similarity index 84% rename from src/main/scala/me/skymc/taboolib/common/playercontainer/PlayerContainerLoader.java rename to src/main/scala/io/izzel/taboolib/module/inject/PlayerContainerLoader.java index 5cbc001..7fff410 100644 --- a/src/main/scala/me/skymc/taboolib/common/playercontainer/PlayerContainerLoader.java +++ b/src/main/scala/io/izzel/taboolib/module/inject/PlayerContainerLoader.java @@ -1,9 +1,7 @@ -package me.skymc.taboolib.common.playercontainer; +package io.izzel.taboolib.module.inject; -import com.ilummc.tlib.logger.TLogger; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.TabooLibLoader; -import org.bukkit.Bukkit; +import io.izzel.taboolib.TabooLibLoader; +import io.izzel.taboolib.module.locale.logger.TLogger; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -21,13 +19,10 @@ import java.util.concurrent.ConcurrentHashMap; * @Author sky * @Since 2018-09-14 23:45 */ +@TListener public class PlayerContainerLoader implements Listener, TabooLibLoader.Loader { - Map> pluginContainer = new ConcurrentHashMap<>(); - - PlayerContainerLoader() { - Bukkit.getPluginManager().registerEvents(this, TabooLib.instance()); - } + static Map> pluginContainer = new ConcurrentHashMap<>(); @Override public void postLoad(Plugin plugin, Class pluginClass) { diff --git a/src/main/scala/me/skymc/taboolib/common/function/TFunction.java b/src/main/scala/io/izzel/taboolib/module/inject/TFunction.java similarity index 90% rename from src/main/scala/me/skymc/taboolib/common/function/TFunction.java rename to src/main/scala/io/izzel/taboolib/module/inject/TFunction.java index 4bc3925..15905d2 100644 --- a/src/main/scala/me/skymc/taboolib/common/function/TFunction.java +++ b/src/main/scala/io/izzel/taboolib/module/inject/TFunction.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.function; +package io.izzel.taboolib.module.inject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/scala/me/skymc/taboolib/common/function/TFunctionLoader.java b/src/main/scala/io/izzel/taboolib/module/inject/TFunctionLoader.java similarity index 82% rename from src/main/scala/me/skymc/taboolib/common/function/TFunctionLoader.java rename to src/main/scala/io/izzel/taboolib/module/inject/TFunctionLoader.java index 1ab3d4e..115dc33 100644 --- a/src/main/scala/me/skymc/taboolib/common/function/TFunctionLoader.java +++ b/src/main/scala/io/izzel/taboolib/module/inject/TFunctionLoader.java @@ -1,8 +1,8 @@ -package me.skymc.taboolib.common.function; +package io.izzel.taboolib.module.inject; -import com.ilummc.tlib.logger.TLogger; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.TabooLibLoader; +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.TabooLibLoader; +import io.izzel.taboolib.module.locale.logger.TLogger; import org.bukkit.plugin.Plugin; import java.lang.reflect.Method; @@ -26,7 +26,7 @@ public class TFunctionLoader implements TabooLibLoader.Loader { } method.setAccessible(true); method.invoke(null); - TabooLib.debug("Function " + pluginClass.getSimpleName() + " loaded. (" + plugin.getName() + ")"); + TabooLibAPI.debug("Function " + pluginClass.getSimpleName() + " loaded. (" + plugin.getName() + ")"); } catch (NoSuchMethodException ignore) { } catch (Exception e) { TLogger.getGlobalLogger().warn("TFunction load Failed: " + pluginClass.getName()); @@ -47,7 +47,7 @@ public class TFunctionLoader implements TabooLibLoader.Loader { } method.setAccessible(true); method.invoke(null); - TabooLib.debug("Function " + pluginClass.getSimpleName() + " unloaded. (" + plugin.getName() + ")"); + TabooLibAPI.debug("Function " + pluginClass.getSimpleName() + " unloaded. (" + plugin.getName() + ")"); } catch (NoSuchMethodException ignore) { } catch (Exception e) { TLogger.getGlobalLogger().warn("TFunction unload Failed: " + pluginClass.getName()); diff --git a/src/main/scala/me/skymc/taboolib/common/inject/TInject.java b/src/main/scala/io/izzel/taboolib/module/inject/TInject.java similarity index 89% rename from src/main/scala/me/skymc/taboolib/common/inject/TInject.java rename to src/main/scala/io/izzel/taboolib/module/inject/TInject.java index c1d9e5d..08b617e 100644 --- a/src/main/scala/me/skymc/taboolib/common/inject/TInject.java +++ b/src/main/scala/io/izzel/taboolib/module/inject/TInject.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.inject; +package io.izzel.taboolib.module.inject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/scala/me/skymc/taboolib/common/inject/TInjectLoader.java b/src/main/scala/io/izzel/taboolib/module/inject/TInjectLoader.java similarity index 77% rename from src/main/scala/me/skymc/taboolib/common/inject/TInjectLoader.java rename to src/main/scala/io/izzel/taboolib/module/inject/TInjectLoader.java index d0423bb..acb4189 100644 --- a/src/main/scala/me/skymc/taboolib/common/inject/TInjectLoader.java +++ b/src/main/scala/io/izzel/taboolib/module/inject/TInjectLoader.java @@ -1,15 +1,15 @@ -package me.skymc.taboolib.common.inject; +package io.izzel.taboolib.module.inject; import com.google.common.collect.Maps; -import com.ilummc.tlib.logger.TLogger; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.TabooLibLoader; -import me.skymc.taboolib.commands.builder.SimpleCommandBuilder; -import me.skymc.taboolib.common.configuration.TConfiguration; -import me.skymc.taboolib.common.packet.TPacketHandler; -import me.skymc.taboolib.common.packet.TPacketListener; -import me.skymc.taboolib.cooldown.seconds.CooldownPack2; -import me.skymc.taboolib.cooldown.seconds.CooldownUtils2; +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.TabooLibLoader; +import io.izzel.taboolib.module.command.lite.CommandBuilder; +import io.izzel.taboolib.module.config.TConfig; +import io.izzel.taboolib.module.locale.logger.TLogger; +import io.izzel.taboolib.module.packet.TPacketHandler; +import io.izzel.taboolib.module.packet.TPacketListener; +import io.izzel.taboolib.util.lite.cooldown.Cooldown; +import io.izzel.taboolib.util.lite.cooldown.Cooldowns; import org.bukkit.plugin.Plugin; import java.lang.reflect.Field; @@ -50,17 +50,17 @@ public class TInjectLoader implements TabooLibLoader.Loader { } }); // TConfiguration Inject - injectTypes.put(TConfiguration.class, (plugin, field, args, instance) -> { + injectTypes.put(TConfig.class, (plugin, field, args, instance) -> { try { - field.set(instance, TConfiguration.createInResource(plugin, args.length == 0 ? "config.yml" : args[0])); + field.set(instance, TConfig.create(plugin, args.length == 0 ? "config.yml" : args[0])); } catch (Exception e) { e.printStackTrace(); } }); // SimpleCommandBuilder Inject - injectTypes.put(SimpleCommandBuilder.class, (plugin, field, args, instance) -> { + injectTypes.put(CommandBuilder.class, (plugin, field, args, instance) -> { try { - SimpleCommandBuilder builder = (SimpleCommandBuilder) field.get(instance); + CommandBuilder builder = (CommandBuilder) field.get(instance); if (builder.isBuild()) { TLogger.getGlobalLogger().error("Command was registered. (" + field.getType().getName() + ")"); } else { @@ -74,9 +74,9 @@ public class TInjectLoader implements TabooLibLoader.Loader { } }); // CooldownPack Inject - injectTypes.put(CooldownPack2.class, (plugin, field, args, instance) -> { + injectTypes.put(Cooldown.class, (plugin, field, args, instance) -> { try { - CooldownUtils2.register((CooldownPack2) field.get(instance), plugin); + Cooldowns.register((Cooldown) field.get(instance), plugin); } catch (Throwable t) { t.printStackTrace(); } @@ -103,7 +103,7 @@ public class TInjectLoader implements TabooLibLoader.Loader { if (pluginClass.equals(plugin.getClass())) { instance = plugin; } else { - TLogger.getGlobalLogger().error(declaredField.getName() + " is not a static field. (" + declaredField.getType().getName() + ")"); + TLogger.getGlobalLogger().error(declaredField.getName() + " is not a static field. (" + pluginClass.getName() + ")"); continue; } } @@ -125,7 +125,7 @@ public class TInjectLoader implements TabooLibLoader.Loader { if (pluginClass.equals(plugin.getClass())) { instance = plugin; } else { - TLogger.getGlobalLogger().error(declaredField.getName() + " is not a static field. (" + declaredField.getType().getName() + ")"); + TLogger.getGlobalLogger().error(declaredField.getName() + " is not a static field. (" + pluginClass.getName() + ")"); continue; } } @@ -133,7 +133,7 @@ public class TInjectLoader implements TabooLibLoader.Loader { if (tInjectTask != null) { inject(plugin, declaredField, instance, annotation, tInjectTask); } else { - TLogger.getGlobalLogger().error(declaredField.getName() + " is an invalid inject type. (" + declaredField.getType().getName() + ")"); + TLogger.getGlobalLogger().error(declaredField.getName() + " is an invalid inject type. (" + pluginClass.getName() + ")"); } } } @@ -142,7 +142,7 @@ public class TInjectLoader implements TabooLibLoader.Loader { try { field.setAccessible(true); injectTask.run(plugin, field, annotation.value(), instance); - TabooLib.debug(field.getName() + " injected. (" + field.getType().getName() + ")"); + TabooLibAPI.debug(field.getName() + " injected. (" + field.getType().getName() + ")"); } catch (Throwable e) { TLogger.getGlobalLogger().error(field.getName() + " inject failed: " + e.getMessage() + " (" + field.getType().getName() + ")"); if (e.getMessage() == null) { diff --git a/src/main/scala/me/skymc/taboolib/common/inject/TInjectTask.java b/src/main/scala/io/izzel/taboolib/module/inject/TInjectTask.java similarity index 84% rename from src/main/scala/me/skymc/taboolib/common/inject/TInjectTask.java rename to src/main/scala/io/izzel/taboolib/module/inject/TInjectTask.java index 8dc7b76..e0f342a 100644 --- a/src/main/scala/me/skymc/taboolib/common/inject/TInjectTask.java +++ b/src/main/scala/io/izzel/taboolib/module/inject/TInjectTask.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.inject; +package io.izzel.taboolib.module.inject; import org.bukkit.plugin.Plugin; diff --git a/src/main/scala/me/skymc/taboolib/listener/TListener.java b/src/main/scala/io/izzel/taboolib/module/inject/TListener.java similarity index 94% rename from src/main/scala/me/skymc/taboolib/listener/TListener.java rename to src/main/scala/io/izzel/taboolib/module/inject/TListener.java index 2ce6682..4f2d4ae 100644 --- a/src/main/scala/me/skymc/taboolib/listener/TListener.java +++ b/src/main/scala/io/izzel/taboolib/module/inject/TListener.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.listener; +package io.izzel.taboolib.module.inject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/scala/me/skymc/taboolib/listener/TListenerHandler.java b/src/main/scala/io/izzel/taboolib/module/inject/TListenerHandler.java similarity index 77% rename from src/main/scala/me/skymc/taboolib/listener/TListenerHandler.java rename to src/main/scala/io/izzel/taboolib/module/inject/TListenerHandler.java index 92243bd..2d2bd62 100644 --- a/src/main/scala/me/skymc/taboolib/listener/TListenerHandler.java +++ b/src/main/scala/io/izzel/taboolib/module/inject/TListenerHandler.java @@ -1,18 +1,15 @@ -package me.skymc.taboolib.listener; +package io.izzel.taboolib.module.inject; -import com.ilummc.tlib.logger.TLogger; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.TabooLibLoader; -import me.skymc.taboolib.cronus.util.StringExpression; -import me.skymc.taboolib.events.TPluginEnableEvent; -import me.skymc.taboolib.methods.ReflectionUtils; +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.TabooLibLoader; +import io.izzel.taboolib.Version; +import io.izzel.taboolib.module.locale.logger.TLogger; +import io.izzel.taboolib.cronus.util.StringExpression; +import io.izzel.taboolib.util.Strings; +import io.izzel.taboolib.util.Reflection; import org.bukkit.Bukkit; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; -import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.plugin.Plugin; import java.lang.reflect.Method; @@ -22,8 +19,7 @@ import java.util.*; * @Author sky * @Since 2018-08-22 13:48 */ -@TListener -public class TListenerHandler implements Listener { +public class TListenerHandler { private static HashMap> listeners = new HashMap<>(); @@ -52,7 +48,7 @@ public class TListenerHandler implements Listener { try { TListener tListener = pluginClass.getAnnotation(TListener.class); // 检查版本 - if (!new StringExpression(tListener.version()).isSelect(TabooLib.getVersionNumber())) { + if (!new StringExpression(tListener.version()).isSelect(Version.getCurrentVersion().getVersionInt())) { continue; } // 检查注册条件 @@ -62,16 +58,16 @@ public class TListenerHandler implements Listener { } } // 实例化监听器 - Listener listener = plugin.getClass().equals(pluginClass) ? (Listener) plugin : (Listener) ReflectionUtils.instantiateObject(pluginClass); + Listener listener = plugin.getClass().equals(pluginClass) ? (Listener) plugin : (Listener) Reflection.instantiateObject(pluginClass); try { listeners.computeIfAbsent(plugin.getName(), name -> new ArrayList<>()).add(listener); - TabooLib.debug("Listener " + listener.getClass().getSimpleName() + " setup successfully. (" + plugin.getName() + ")"); + TabooLibAPI.debug("Listener " + listener.getClass().getSimpleName() + " setup successfully. (" + plugin.getName() + ")"); } catch (Exception e) { TLogger.getGlobalLogger().warn("TListener setup Failed: " + pluginClass.getName()); e.printStackTrace(); } } catch (Exception e) { - TabooLib.debug("Listener " + pluginClass.getSimpleName() + "(" + plugin.getName() + ")" + " setup failed: " + e.toString()); + TabooLibAPI.debug("Listener " + pluginClass.getSimpleName() + "(" + plugin.getName() + ")" + " setup failed: " + e.toString()); } } } @@ -124,7 +120,7 @@ public class TListenerHandler implements Listener { } // 注册监听 Bukkit.getPluginManager().registerEvents(listener, plugin); - TabooLib.debug("Listener " + listener.getClass().getSimpleName() + " registered. (" + plugin.getName() + ")"); + TabooLibAPI.debug("Listener " + listener.getClass().getSimpleName() + " registered. (" + plugin.getName() + ")"); } }); } @@ -169,21 +165,4 @@ public class TListenerHandler implements Listener { public static HashMap> getListeners() { return listeners; } - - @EventHandler(priority = EventPriority.LOW) - public void onPluginEnable(TPluginEnableEvent e) { - try { - setupListener(e.getPlugin()); - Bukkit.getScheduler().runTask(TabooLib.instance(), () -> registerListener(e.getPlugin())); - } catch (Exception ignored) { - } - } - - @EventHandler - public void onPluginDisable(PluginDisableEvent e) { - try { - cancelListener(e.getPlugin()); - } catch (Exception ignored) { - } - } } diff --git a/src/main/scala/me/skymc/taboolib/common/schedule/TSchedule.java b/src/main/scala/io/izzel/taboolib/module/inject/TSchedule.java similarity index 90% rename from src/main/scala/me/skymc/taboolib/common/schedule/TSchedule.java rename to src/main/scala/io/izzel/taboolib/module/inject/TSchedule.java index c83281d..90b1b7b 100644 --- a/src/main/scala/me/skymc/taboolib/common/schedule/TSchedule.java +++ b/src/main/scala/io/izzel/taboolib/module/inject/TSchedule.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.schedule; +package io.izzel.taboolib.module.inject; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/scala/me/skymc/taboolib/common/schedule/TScheduleData.java b/src/main/scala/io/izzel/taboolib/module/inject/TScheduleData.java similarity index 92% rename from src/main/scala/me/skymc/taboolib/common/schedule/TScheduleData.java rename to src/main/scala/io/izzel/taboolib/module/inject/TScheduleData.java index 15ab627..befedce 100644 --- a/src/main/scala/me/skymc/taboolib/common/schedule/TScheduleData.java +++ b/src/main/scala/io/izzel/taboolib/module/inject/TScheduleData.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.schedule; +package io.izzel.taboolib.module.inject; import org.bukkit.scheduler.BukkitRunnable; diff --git a/src/main/scala/me/skymc/taboolib/common/schedule/TScheduleLoader.java b/src/main/scala/io/izzel/taboolib/module/inject/TScheduleLoader.java similarity index 69% rename from src/main/scala/me/skymc/taboolib/common/schedule/TScheduleLoader.java rename to src/main/scala/io/izzel/taboolib/module/inject/TScheduleLoader.java index a093291..b6510bd 100644 --- a/src/main/scala/me/skymc/taboolib/common/schedule/TScheduleLoader.java +++ b/src/main/scala/io/izzel/taboolib/module/inject/TScheduleLoader.java @@ -1,14 +1,10 @@ -package me.skymc.taboolib.common.schedule; +package io.izzel.taboolib.module.inject; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import com.ilummc.tlib.logger.TLogger; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.TabooLibLoader; -import org.bukkit.Bukkit; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.server.PluginEnableEvent; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.TabooLibLoader; +import io.izzel.taboolib.module.locale.logger.TLogger; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitRunnable; @@ -16,18 +12,20 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.List; import java.util.Map; -import java.util.Optional; /** * @Author 坏黑 * @Since 2018-12-15 15:09 */ -public class TScheduleLoader implements Listener, TabooLibLoader.Loader { +public class TScheduleLoader implements TabooLibLoader.Loader { - private Map> schedules = Maps.newHashMap(); + static Map> schedules = Maps.newHashMap(); - TScheduleLoader() { - Bukkit.getPluginManager().registerEvents(this, TabooLib.instance()); + public static void run(Plugin plugin) { + List list = schedules.get(plugin.getName()); + if (list != null) { + list.forEach(data -> run(plugin, data.getRunnable(), data.getAnnotation().delay(), data.getAnnotation().period(), data.getAnnotation().async())); + } } public static void run(Plugin plugin, BukkitRunnable runnable, int delay, int period, boolean async) { @@ -38,13 +36,6 @@ public class TScheduleLoader implements Listener, TabooLibLoader.Loader { } } - @EventHandler - public void onEnable(PluginEnableEvent e) { - Optional.ofNullable(schedules.remove(e.getPlugin().getName())).ifPresent(list -> list.forEach(scheduleData -> { - run(e.getPlugin(), scheduleData.getRunnable(), scheduleData.getAnnotation().delay(), scheduleData.getAnnotation().period(), scheduleData.getAnnotation().async()); - })); - } - @Override public void postLoad(Plugin plugin, Class loadClass) { for (Method method : loadClass.getDeclaredMethods()) { @@ -61,7 +52,7 @@ public class TScheduleLoader implements Listener, TabooLibLoader.Loader { } method.setAccessible(true); // 如果是本插件 - if (plugin.equals(TabooLib.instance())) { + if (plugin.equals(TabooLib.getPlugin())) { run(plugin, new BukkitRunnable() { @Override diff --git a/src/main/scala/me/skymc/taboolib/common/versioncontrol/SimpleClassVisitor.java b/src/main/scala/io/izzel/taboolib/module/lite/SimpleClassVisitor.java similarity index 97% rename from src/main/scala/me/skymc/taboolib/common/versioncontrol/SimpleClassVisitor.java rename to src/main/scala/io/izzel/taboolib/module/lite/SimpleClassVisitor.java index b17c54c..1cd94fe 100644 --- a/src/main/scala/me/skymc/taboolib/common/versioncontrol/SimpleClassVisitor.java +++ b/src/main/scala/io/izzel/taboolib/module/lite/SimpleClassVisitor.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.versioncontrol; +package io.izzel.taboolib.module.lite; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; diff --git a/src/main/scala/me/skymc/taboolib/common/util/SimpleCounter.java b/src/main/scala/io/izzel/taboolib/module/lite/SimpleCounter.java similarity index 95% rename from src/main/scala/me/skymc/taboolib/common/util/SimpleCounter.java rename to src/main/scala/io/izzel/taboolib/module/lite/SimpleCounter.java index 430857f..1630a61 100644 --- a/src/main/scala/me/skymc/taboolib/common/util/SimpleCounter.java +++ b/src/main/scala/io/izzel/taboolib/module/lite/SimpleCounter.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.util; +package io.izzel.taboolib.module.lite; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/inventory/TEquipment.java b/src/main/scala/io/izzel/taboolib/module/lite/SimpleEquip.java similarity index 80% rename from src/main/scala/me/skymc/taboolib/inventory/TEquipment.java rename to src/main/scala/io/izzel/taboolib/module/lite/SimpleEquip.java index 4e131ec..e6d16d0 100644 --- a/src/main/scala/me/skymc/taboolib/inventory/TEquipment.java +++ b/src/main/scala/io/izzel/taboolib/module/lite/SimpleEquip.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.inventory; +package io.izzel.taboolib.module.lite; import com.google.common.collect.Maps; import org.bukkit.entity.Player; @@ -12,7 +12,7 @@ import java.util.Map; * @Author 坏黑 * @Since 2019-04-25 22:01 */ -public enum TEquipment { +public enum SimpleEquip { HAND(EquipmentSlot.HAND, -1), @@ -29,7 +29,7 @@ public enum TEquipment { private EquipmentSlot bukkit; private int slot; - TEquipment(EquipmentSlot bukkit, int slot) { + SimpleEquip(EquipmentSlot bukkit, int slot) { this.bukkit = bukkit; this.slot = slot; } @@ -50,13 +50,13 @@ public enum TEquipment { } } - public static TEquipment fromBukkit(EquipmentSlot bukkit) { + public static SimpleEquip fromBukkit(EquipmentSlot bukkit) { return Arrays.stream(values()).filter(tEquipment -> tEquipment.bukkit == bukkit).findFirst().orElse(null); } - public static Map getItems(Player player) { - Map map = Maps.newHashMap(); - for (TEquipment equipment : values()) { + public static Map getItems(Player player) { + Map map = Maps.newHashMap(); + for (SimpleEquip equipment : values()) { map.put(equipment, equipment.getItem(player)); } return map; diff --git a/src/main/scala/me/skymc/taboolib/common/util/SimpleI18n.java b/src/main/scala/io/izzel/taboolib/module/lite/SimpleI18n.java similarity index 60% rename from src/main/scala/me/skymc/taboolib/common/util/SimpleI18n.java rename to src/main/scala/io/izzel/taboolib/module/lite/SimpleI18n.java index 017cfcf..6053a3a 100644 --- a/src/main/scala/me/skymc/taboolib/common/util/SimpleI18n.java +++ b/src/main/scala/io/izzel/taboolib/module/lite/SimpleI18n.java @@ -1,13 +1,12 @@ -package me.skymc.taboolib.common.util; +package io.izzel.taboolib.module.lite; -import com.ilummc.tlib.resources.TLocaleLoader; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.common.function.TFunction; -import me.skymc.taboolib.common.nms.NMSHandler; -import me.skymc.taboolib.common.nms.nbt.NBTCompound; -import me.skymc.taboolib.fileutils.ConfigUtils; -import me.skymc.taboolib.fileutils.FileUtils; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.Version; +import io.izzel.taboolib.module.locale.TLocaleLoader; +import io.izzel.taboolib.module.inject.TFunction; +import io.izzel.taboolib.module.nms.NMS; +import io.izzel.taboolib.module.nms.nbt.NBTCompound; +import io.izzel.taboolib.util.Files; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Entity; @@ -31,15 +30,15 @@ public class SimpleI18n { private static boolean released; static void init() { - File localeFile = getLocaleFile(TabooLib.instance()); + File localeFile = getLocaleFile(TabooLib.getPlugin()); if (localeFile == null) { lang = new YamlConfiguration(); } else { - lang = ConfigUtils.load(TabooLib.instance(), localeFile); + lang = Files.load(localeFile); } if (lang.getInt("version") < 3 && !released) { released = true; - FileUtils.deleteAllFile(new File(Main.getInst().getDataFolder(), "simpleI18n")); + Files.deepDelete(new File(TabooLib.getPlugin().getDataFolder(), "simpleI18n")); init(); } } @@ -57,7 +56,7 @@ public class SimpleI18n { } public static String getName(Entity entity) { - return entity == null ? "-" : lang.getString(NMSHandler.getHandler().getName(entity).replace(".", "_"), entity.getName()); + return entity == null ? "-" : lang.getString(NMS.handle().getName(entity).replace(".", "_"), entity.getName()); } public static String getName(ItemStack item) { @@ -68,35 +67,35 @@ public class SimpleI18n { if (itemMeta instanceof BookMeta && ((BookMeta) itemMeta).getTitle() != null) { return ((BookMeta) itemMeta).getTitle(); } - if (TabooLib.getVersionNumber() < 11100) { + if (!Version.isAfter(Version.v1_11)) { if (item.getType().name().equals("MONSTER_EGG")) { - NBTCompound nbtCompound = NMSHandler.getHandler().loadNBT(item); + NBTCompound nbtCompound = NMS.handle().loadNBT(item); if (nbtCompound.containsKey("EntityTag")) { return lang.getString("item_monsterPlacer_name") + " " + lang.getString("entity_" + nbtCompound.get("EntityTag").asCompound().get("id").asString() + "_name"); } return lang.getString("item_monsterPlacer_name"); } - } else if (TabooLib.getVersionNumber() < 11300) { + } else if (!Version.isAfter(Version.v1_13)) { if (itemMeta instanceof SpawnEggMeta) { String spawnEggType = lang.getString("entity_" + ((SpawnEggMeta) itemMeta).getSpawnedType().getEntityClass().getSimpleName().replace(".", "_") + "_name"); if (spawnEggType != null) { - return lang.getString(NMSHandler.getHandler().getName(item).replace(".", "_"), item.getType().name().toLowerCase().replace("_", "")) + " " + spawnEggType; + return lang.getString(NMS.handle().getName(item).replace(".", "_"), item.getType().name().toLowerCase().replace("_", "")) + " " + spawnEggType; } } } - return lang.getString(NMSHandler.getHandler().getName(item).replace(".", "_"), item.getType().name().toLowerCase().replace("_", "")); + return lang.getString(NMS.handle().getName(item).replace(".", "_"), item.getType().name().toLowerCase().replace("_", "")); } private static void releaseLocales(Plugin plugin) { - TLocaleLoader.getLocalePriority().stream().filter(localeName -> !new File(plugin.getDataFolder(), "simpleI18n/" + getVersion() + "/" + localeName + ".yml").exists() && plugin.getResource("simpleI18n/" + getVersion() + "/" + localeName + ".yml") != null).forEach(localeName -> plugin.saveResource("simpleI18n/" + getVersion() + "/" + localeName + ".yml", true)); + TLocaleLoader.getLocalePriority().stream().filter(localeName -> !new File("plugins/TabooLib/simpleI18n/" + getVersion() + "/" + localeName + ".yml").exists() && plugin.getResource("simpleI18n/" + getVersion() + "/" + localeName + ".yml") != null).forEach(localeName -> plugin.saveResource("simpleI18n/" + getVersion() + "/" + localeName + ".yml", true)); } private static File getLocaleFile(Plugin plugin) { releaseLocales(plugin); - return TLocaleLoader.getLocalePriority().stream().map(localeName -> new File(plugin.getDataFolder(), "simpleI18n/" + getVersion() + "/" + localeName + ".yml")).filter(File::exists).findFirst().orElse(null); + return TLocaleLoader.getLocalePriority().stream().map(localeName -> new File("plugins/TabooLib/simpleI18n/" + getVersion() + "/" + localeName + ".yml")).filter(File::exists).findFirst().orElse(null); } private static String getVersion() { - return TabooLib.getVersionNumber() < 11300 ? "low" : "high"; + return Version.isAfter(Version.v1_13) ? "high" : "low"; } } diff --git a/src/main/scala/me/skymc/taboolib/common/util/SimpleIterator.java b/src/main/scala/io/izzel/taboolib/module/lite/SimpleIterator.java similarity index 96% rename from src/main/scala/me/skymc/taboolib/common/util/SimpleIterator.java rename to src/main/scala/io/izzel/taboolib/module/lite/SimpleIterator.java index 88ce0be..f64f2c4 100644 --- a/src/main/scala/me/skymc/taboolib/common/util/SimpleIterator.java +++ b/src/main/scala/io/izzel/taboolib/module/lite/SimpleIterator.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.util; +package io.izzel.taboolib.module.lite; import com.google.common.collect.Lists; diff --git a/src/main/scala/me/skymc/taboolib/common/versioncontrol/SimpleMethodVisitor.java b/src/main/scala/io/izzel/taboolib/module/lite/SimpleMethodVisitor.java similarity index 98% rename from src/main/scala/me/skymc/taboolib/common/versioncontrol/SimpleMethodVisitor.java rename to src/main/scala/io/izzel/taboolib/module/lite/SimpleMethodVisitor.java index 292d81a..8c61071 100644 --- a/src/main/scala/me/skymc/taboolib/common/versioncontrol/SimpleMethodVisitor.java +++ b/src/main/scala/io/izzel/taboolib/module/lite/SimpleMethodVisitor.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.versioncontrol; +package io.izzel.taboolib.module.lite; import org.objectweb.asm.*; diff --git a/src/main/scala/me/skymc/taboolib/common/util/SimpleReflection.java b/src/main/scala/io/izzel/taboolib/module/lite/SimpleReflection.java similarity index 99% rename from src/main/scala/me/skymc/taboolib/common/util/SimpleReflection.java rename to src/main/scala/io/izzel/taboolib/module/lite/SimpleReflection.java index c499ada..5b0c8bf 100644 --- a/src/main/scala/me/skymc/taboolib/common/util/SimpleReflection.java +++ b/src/main/scala/io/izzel/taboolib/module/lite/SimpleReflection.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.util; +package io.izzel.taboolib.module.lite; import com.google.common.collect.Maps; diff --git a/src/main/scala/me/skymc/taboolib/common/versioncontrol/SimpleVersionControl.java b/src/main/scala/io/izzel/taboolib/module/lite/SimpleVersionControl.java similarity index 88% rename from src/main/scala/me/skymc/taboolib/common/versioncontrol/SimpleVersionControl.java rename to src/main/scala/io/izzel/taboolib/module/lite/SimpleVersionControl.java index 1a1fc41..2e52361 100644 --- a/src/main/scala/me/skymc/taboolib/common/versioncontrol/SimpleVersionControl.java +++ b/src/main/scala/io/izzel/taboolib/module/lite/SimpleVersionControl.java @@ -1,10 +1,10 @@ -package me.skymc.taboolib.common.versioncontrol; +package io.izzel.taboolib.module.lite; import com.google.common.collect.Lists; -import com.ilummc.tlib.util.asm.AsmClassLoader; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.fileutils.FileUtils; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.Version; +import io.izzel.taboolib.util.Files; +import io.izzel.taboolib.util.asm.AsmClassLoader; import org.bukkit.plugin.Plugin; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; @@ -35,11 +35,11 @@ public class SimpleVersionControl { } public static SimpleVersionControl create() { - return new SimpleVersionControl().to(TabooLib.getVersion()).plugin(Main.getInst()); + return new SimpleVersionControl().to(Version.getBukkitVersion()).plugin(TabooLib.getPlugin()); } public static SimpleVersionControl create(String toVersion) { - return new SimpleVersionControl().to(toVersion).plugin(Main.getInst()); + return new SimpleVersionControl().to(toVersion).plugin(TabooLib.getPlugin()); } public static SimpleVersionControl createSimple(String target, String... from) { @@ -113,7 +113,7 @@ public class SimpleVersionControl { if (useCache && cacheClasses.containsKey(target)) { return cacheClasses.get(target); } - ClassReader classReader = new ClassReader(FileUtils.getResource(plugin, target.replace(".", "/") + ".class")); + ClassReader classReader = new ClassReader(Files.getResource(plugin, target.replace(".", "/") + ".class")); ClassWriter classWriter = new ClassWriter(0); ClassVisitor classVisitor = new SimpleClassVisitor(this, classWriter); classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES); diff --git a/src/main/scala/com/ilummc/tlib/resources/TLocale.java b/src/main/scala/io/izzel/taboolib/module/locale/TLocale.java similarity index 83% rename from src/main/scala/com/ilummc/tlib/resources/TLocale.java rename to src/main/scala/io/izzel/taboolib/module/locale/TLocale.java index 1b41f23..7620c9d 100644 --- a/src/main/scala/com/ilummc/tlib/resources/TLocale.java +++ b/src/main/scala/io/izzel/taboolib/module/locale/TLocale.java @@ -1,16 +1,15 @@ -package com.ilummc.tlib.resources; +package io.izzel.taboolib.module.locale; -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.bungee.api.ChatColor; -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 io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.module.locale.logger.TLoggerManager; +import io.izzel.taboolib.module.nms.NMS; +import io.izzel.taboolib.module.tellraw.TellrawCreator; +import io.izzel.taboolib.util.Ref; +import io.izzel.taboolib.util.Strings; +import io.izzel.taboolib.util.chat.ChatColor; +import io.izzel.taboolib.util.chat.ComponentSerializer; +import io.izzel.taboolib.util.chat.TextComponent; import me.clip.placeholderapi.PlaceholderAPI; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.common.nms.NMSHandler; -import me.skymc.taboolib.json.tellraw.TellrawCreator; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -58,19 +57,19 @@ public class TLocale { public static String asString(String path, String... args) { try { - return asString(path, Ref.getCallerClass(3).orElse(Main.class), args); + return asString(path, Ref.getCallerClass(3).orElse(TabooLib.class), args); } catch (Exception e) { - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("FETCH-LOCALE-ERROR"), path)); - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.getMessage())); + TabooLib.getLogger().error(Strings.replaceWithOrder(TabooLib.getInst().getInternal().getString("FETCH-LOCALE-ERROR"), path)); + TabooLib.getLogger().error(Strings.replaceWithOrder(TabooLib.getInst().getInternal().getString("LOCALE-ERROR-REASON"), e.getMessage())); return "§4<" + path + "§4>"; } } public static List asStringList(String path, String... args) { try { - return asStringList(path, Ref.getCallerClass(3).orElse(Main.class), args); + return asStringList(path, Ref.getCallerClass(3).orElse(TabooLib.class), args); } catch (Exception e) { - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.getMessage())); + TabooLib.getLogger().error(Strings.replaceWithOrder(TabooLib.getInst().getInternal().getString("LOCALE-ERROR-REASON"), e.getMessage())); return Collections.singletonList("§4<" + path + "§4>"); } } @@ -97,18 +96,18 @@ public class TLocale { } public static void sendTitle(Player player, String title, String subTitle, int fadein, int stay, int fadeout) { - NMSHandler.getHandler().sendTitle(player, title, fadein, stay, fadeout, subTitle, fadein, stay, fadeout); + NMS.handle().sendTitle(player, title, fadein, stay, fadeout, subTitle, fadein, stay, fadeout); } public static void sendActionBar(Player player, String text) { - NMSHandler.getHandler().sendActionBar(player, text); + NMS.handle().sendActionBar(player, text); } } public static final class Translate extends TLocale { public static boolean isPlaceholderUseDefault() { - return Main.getInst().getConfig().getBoolean("LOCALE.USE_PAPI", false); + return TabooLib.getConfig().getBoolean("LOCALE.USE_PAPI", false); } public static boolean isPlaceholderPluginEnabled() { diff --git a/src/main/scala/com/ilummc/tlib/resources/TLocaleInstance.java b/src/main/scala/io/izzel/taboolib/module/locale/TLocaleInstance.java similarity index 87% rename from src/main/scala/com/ilummc/tlib/resources/TLocaleInstance.java rename to src/main/scala/io/izzel/taboolib/module/locale/TLocaleInstance.java index 5994aa2..8effd83 100644 --- a/src/main/scala/com/ilummc/tlib/resources/TLocaleInstance.java +++ b/src/main/scala/io/izzel/taboolib/module/locale/TLocaleInstance.java @@ -1,10 +1,9 @@ -package com.ilummc.tlib.resources; +package io.izzel.taboolib.module.locale; import com.google.common.collect.ImmutableList; -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.resources.type.TLocaleText; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.TabooLib; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.module.locale.type.TLocaleText; +import io.izzel.taboolib.util.Strings; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; @@ -12,7 +11,10 @@ import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import javax.annotation.concurrent.ThreadSafe; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; @@ -59,8 +61,8 @@ class TLocaleInstance { } }); } catch (Exception | Error e) { - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("SEND-LOCALE-ERROR"), path)); - TLib.getTLib().getLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("LOCALE-ERROR-REASON"), e.toString())); + TabooLib.getLogger().error(Strings.replaceWithOrder(TabooLib.getInst().getInternal().getString("SEND-LOCALE-ERROR"), path)); + TabooLib.getLogger().error(Strings.replaceWithOrder(TabooLib.getInst().getInternal().getString("LOCALE-ERROR-REASON"), e.toString())); } } diff --git a/src/main/scala/com/ilummc/tlib/resources/TLocaleLoader.java b/src/main/scala/io/izzel/taboolib/module/locale/TLocaleLoader.java similarity index 66% rename from src/main/scala/com/ilummc/tlib/resources/TLocaleLoader.java rename to src/main/scala/io/izzel/taboolib/module/locale/TLocaleLoader.java index 749e222..ef0a6b1 100644 --- a/src/main/scala/com/ilummc/tlib/resources/TLocaleLoader.java +++ b/src/main/scala/io/izzel/taboolib/module/locale/TLocaleLoader.java @@ -1,15 +1,13 @@ -package com.ilummc.tlib.resources; +package io.izzel.taboolib.module.locale; -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.annotations.TLocalePlugin; -import com.ilummc.tlib.logger.TLogger; -import com.ilummc.tlib.resources.type.*; -import com.ilummc.tlib.util.IO; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.fileutils.ConfigUtils; -import me.skymc.taboolib.fileutils.FileUtils; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.module.locale.type.*; +import io.izzel.taboolib.module.config.TConfigWatcher; +import io.izzel.taboolib.module.locale.logger.TLogger; +import io.izzel.taboolib.util.Files; +import io.izzel.taboolib.util.IO; +import io.izzel.taboolib.util.Strings; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; @@ -26,7 +24,7 @@ public class TLocaleLoader { private static final Map map = new ConcurrentHashMap<>(); - public static void init() { + static { ConfigurationSerialization.registerClass(TLocaleText.class, "TEXT"); ConfigurationSerialization.registerClass(TLocaleJson.class, "JSON"); ConfigurationSerialization.registerClass(TLocaleBook.class, "BOOK"); @@ -37,7 +35,7 @@ public class TLocaleLoader { } public static void sendTo(Plugin plugin, String path, CommandSender sender, String... args) { - TabooLib.debug(plugin, "TLocaleLoader.sendTo: " + plugin + ", path: " + path + ", sender: " + sender + ", args: " + Arrays.asList(args)); + TabooLibAPI.debug(plugin, "TLocaleLoader.sendTo: " + plugin + ", path: " + path + ", sender: " + sender + ", args: " + Arrays.asList(args)); if (Bukkit.isPrimaryThread()) { Optional.ofNullable(map.get(plugin.getName())).ifPresent(localeInstance -> localeInstance.sendTo(path, sender, args)); } else { @@ -48,7 +46,7 @@ public class TLocaleLoader { } public static String asString(Plugin plugin, String path, String... args) { - TabooLib.debug(plugin, "TLocaleLoader.asString: " + plugin.getName() + ", path: " + path + ", args: " + Arrays.asList(args)); + TabooLibAPI.debug(plugin, "TLocaleLoader.asString: " + plugin.getName() + ", path: " + path + ", args: " + Arrays.asList(args)); TLocaleInstance tLocaleInstance = map.get(plugin.getName()); if (tLocaleInstance != null) { return tLocaleInstance.asString(path, args); @@ -58,7 +56,7 @@ public class TLocaleLoader { } public static List asStringList(Plugin plugin, String path, String... args) { - TabooLib.debug(plugin, "TLocaleLoader.asStringList: " + plugin + ", path: " + path + ", args: " + Arrays.asList(args)); + TabooLibAPI.debug(plugin, "TLocaleLoader.asStringList: " + plugin + ", path: " + path + ", args: " + Arrays.asList(args)); TLocaleInstance tLocaleInstance = map.get(plugin.getName()); if (tLocaleInstance != null) { return tLocaleInstance.asStringList(path, args); @@ -67,12 +65,6 @@ public class TLocaleLoader { } } - /** - * 载入语言文件 - * - * @param plugin 载入插件 - * @param isCover 是否覆盖 - */ public static void load(Plugin plugin, boolean isCover) { try { if (isLoadLocale(plugin, isCover)) { @@ -82,53 +74,54 @@ public class TLocaleLoader { return; } // 加载文件 - YamlConfiguration localeConfiguration = ConfigUtils.loadYaml(plugin, localeFile); + YamlConfiguration localeConfiguration = Files.loadYaml(localeFile); YamlConfiguration localeConfigurationAtStream = getLocaleAtStream(plugin, localeFile); // 载入配置 loadPluginLocale(plugin, localeFile, localeConfiguration, localeConfigurationAtStream); // 注册监听 - TLib.getTLib().getConfigWatcher().removeListener(localeFile); - TLib.getTLib().getConfigWatcher().addListener(localeFile, null, obj -> { - loadPluginLocale(plugin, localeFile, ConfigUtils.loadYaml(plugin, localeFile), getLocaleAtStream(plugin, localeFile)); - }); + TConfigWatcher.getInst().removeListener(localeFile); + TConfigWatcher.getInst().addListener(localeFile, null, obj -> loadPluginLocale(plugin, localeFile, Files.loadYaml(localeFile), getLocaleAtStream(plugin, localeFile))); } } catch (Exception e) { - errorLogger("ERROR-LOADING-LANG", plugin.getName(), e.toString()); - e.printStackTrace(); + errorLogger("ERROR-LOADING-LANG", plugin.getName(), e.toString() + "\n" + e.getStackTrace()[0].toString()); } } + public static void unload(Plugin plugin) { + map.remove(plugin.getName()); + } + public static boolean isLocaleLoaded(Plugin plugin) { return map.containsKey(plugin.getName()); } public static boolean isDependWithTabooLib(Plugin plugin) { - return plugin.getClass().getAnnotation(TLocalePlugin.class) != null || plugin.getDescription().getDepend().contains(Main.getInst().getName()) || plugin.getDescription().getSoftDepend().contains(Main.getInst().getName()); + return plugin.getClass().getSuperclass().getSimpleName().equals("TabooPlugin"); } public static List getLocalePriority() { - return Main.getInst().getConfig().contains("LOCALE.PRIORITY") ? Main.getInst().getConfig().getStringList("LOCALE.PRIORITY") : Collections.singletonList("zh_CN"); + return TabooLib.getConfig().contains("LOCALE.PRIORITY") ? TabooLib.getConfig().getStringList("LOCALE.PRIORITY") : Collections.singletonList("zh_CN"); } private static boolean isLoadLocale(Plugin plugin, boolean isCover) { - return (isCover || !isLocaleLoaded(plugin)) && (plugin.equals(Main.getInst()) || isDependWithTabooLib(plugin)); + return isCover || !isLocaleLoaded(plugin); } private static void infoLogger(String path, String... args) { - TLogger.getGlobalLogger().info(Strings.replaceWithOrder(TLib.getInternalLanguage().getString(path), args)); + TLogger.getGlobalLogger().info(Strings.replaceWithOrder(io.izzel.taboolib.TabooLib.getInst().getInternal().getString(path), args)); } private static void errorLogger(String path, String... args) { - TLogger.getGlobalLogger().error(Strings.replaceWithOrder(TLib.getInternalLanguage().getString(path), args)); + TLogger.getGlobalLogger().error(Strings.replaceWithOrder(io.izzel.taboolib.TabooLib.getInst().getInternal().getString(path), args)); } private static File getLocaleFile(Plugin plugin) { releaseLocales(plugin); - return getLocalePriority().stream().map(localeName -> new File(plugin.getDataFolder(), "lang/" + localeName + ".yml")).filter(File::exists).findFirst().orElse(null); + return getLocalePriority().stream().map(localeName -> new File("plugins/" + plugin.getName() + "/lang/" + localeName + ".yml")).filter(File::exists).findFirst().orElse(null); } private static void releaseLocales(Plugin plugin) { - getLocalePriority().stream().filter(localeName -> !new File(plugin.getDataFolder(), "lang/" + localeName + ".yml").exists() && plugin.getResource("lang/" + localeName + ".yml") != null).forEach(localeName -> plugin.saveResource("lang/" + localeName + ".yml", true)); + getLocalePriority().stream().filter(localeName -> !new File("plugins/" + plugin.getName() + "/lang/" + localeName + ".yml").exists() && plugin.getResource("lang/" + localeName + ".yml") != null).forEach(localeName -> plugin.saveResource("lang/" + localeName + ".yml", true)); } private static TLocaleInstance getLocaleInstance(Plugin plugin) { @@ -138,11 +131,10 @@ public class TLocaleLoader { } private static YamlConfiguration getLocaleAtStream(Plugin plugin, File localeFile) { - InputStream localeInputSteam = FileUtils.getResource(plugin, "lang/" + localeFile.getName()); + InputStream localeInputSteam = Files.getResource(plugin, "lang/" + localeFile.getName()); try { - String yamlText = new String(IO.readFully(localeInputSteam), Charset.forName("utf-8")); YamlConfiguration yaml = new YamlConfiguration(); - yaml.loadFromString(yamlText); + yaml.loadFromString(IO.readFully(localeInputSteam, Charset.forName("utf-8"))); return yaml; } catch (Exception ignored) { return null; diff --git a/src/main/scala/io/izzel/taboolib/module/locale/TLocaleSender.java b/src/main/scala/io/izzel/taboolib/module/locale/TLocaleSender.java new file mode 100644 index 0000000..f5f013d --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/module/locale/TLocaleSender.java @@ -0,0 +1,19 @@ +package io.izzel.taboolib.module.locale; + +import org.bukkit.command.CommandSender; + +import java.util.List; + +/** + * @Author sky + * @Since 2018-05-12 13:58 + */ +public interface TLocaleSender { + + void sendTo(CommandSender sender, String... args); + + String asString(String... args); + + List asStringList(String... args); + +} diff --git a/src/main/scala/com/ilummc/tlib/resources/TLocaleSerialize.java b/src/main/scala/io/izzel/taboolib/module/locale/TLocaleSerialize.java similarity index 98% rename from src/main/scala/com/ilummc/tlib/resources/TLocaleSerialize.java rename to src/main/scala/io/izzel/taboolib/module/locale/TLocaleSerialize.java index 3155d74..7f3b662 100644 --- a/src/main/scala/com/ilummc/tlib/resources/TLocaleSerialize.java +++ b/src/main/scala/io/izzel/taboolib/module/locale/TLocaleSerialize.java @@ -1,4 +1,4 @@ -package com.ilummc.tlib.resources; +package io.izzel.taboolib.module.locale; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.ConfigurationSerializable; diff --git a/src/main/scala/com/ilummc/tlib/logger/TLogger.java b/src/main/scala/io/izzel/taboolib/module/locale/logger/TLogger.java similarity index 67% rename from src/main/scala/com/ilummc/tlib/logger/TLogger.java rename to src/main/scala/io/izzel/taboolib/module/locale/logger/TLogger.java index 2b3b664..f74b152 100644 --- a/src/main/scala/com/ilummc/tlib/logger/TLogger.java +++ b/src/main/scala/io/izzel/taboolib/module/locale/logger/TLogger.java @@ -1,9 +1,8 @@ -package com.ilummc.tlib.logger; +package io.izzel.taboolib.module.locale.logger; -import com.ilummc.tlib.resources.TLocale; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; +import io.izzel.taboolib.TabooLibAPI; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.util.Strings; import net.md_5.bungee.BungeeCord; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Bukkit; @@ -13,13 +12,32 @@ public class TLogger { public static final int VERBOSE = 0, FINEST = 1, FINE = 2, INFO = 3, WARN = 4, ERROR = 5, FATAL = 6; - private static TLogger globalLogger = new TLogger("§8[§3§lTabooLib§8][§r{1}§8] §f{2}", Main.getInst(), TLogger.FINE); private final String pattern; - private String name; + private final String name; private int level; + public TLogger(String pattern, Plugin plugin, int level) { + this.pattern = pattern; + this.name = plugin.getName(); + this.level = level; + } + + public TLogger(String pattern, String name, int level) { + this.pattern = pattern; + this.name = name; + this.level = level; + } + public static TLogger getGlobalLogger() { - return globalLogger; + return io.izzel.taboolib.TabooLib.getLogger(); + } + + public static TLogger getUnformatted(Plugin plugin) { + return new TLogger("§8[§3§l{0}§8][§r{1}§8] §f{2}", plugin, TLogger.FINE); + } + + public static TLogger getUnformatted(String name) { + return new TLogger("§8[§3§l{0}§8][§r{1}§8] §f{2}", name, TLogger.FINE); } public String getPattern() { @@ -38,93 +56,73 @@ public class TLogger { this.level = level; } - public TLogger(String pattern, Plugin plugin, int level) { - this.pattern = pattern; - this.name = plugin.getName(); - this.level = level; - } - - public TLogger(String pattern, String name, int level) { - this.pattern = pattern; - this.name = name; - this.level = level; - } - public void verbose(String msg) { if (level <= VERBOSE) { - if (TabooLib.isSpigot()) { - Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§f全部", TLocale.Translate.setColored(msg))); + if (TabooLibAPI.isBukkit()) { + Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§fVERBOSE", TLocale.Translate.setColored(msg))); } else { - BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§f全部", TLocale.Translate.setColored(msg)))); + BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§fVERBOSE", TLocale.Translate.setColored(msg)))); } } } public void finest(String msg) { if (level <= FINEST) { - if (TabooLib.isSpigot()) { - Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§e良好", TLocale.Translate.setColored(msg))); + if (TabooLibAPI.isBukkit()) { + Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§eFINEST", TLocale.Translate.setColored(msg))); } else { - BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§e良好", TLocale.Translate.setColored(msg)))); + BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§eFINEST", TLocale.Translate.setColored(msg)))); } } } public void fine(String msg) { if (level <= FINE) { - if (TabooLib.isSpigot()) { - Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§a正常", TLocale.Translate.setColored(msg))); + if (TabooLibAPI.isBukkit()) { + Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§aFINE", TLocale.Translate.setColored(msg))); } else { - BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§a正常", TLocale.Translate.setColored(msg)))); + BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§aFINE", TLocale.Translate.setColored(msg)))); } } } public void info(String msg) { if (level <= INFO) { - if (TabooLib.isSpigot()) { - Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§b信息", TLocale.Translate.setColored(msg))); + if (TabooLibAPI.isBukkit()) { + Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§bINFO", TLocale.Translate.setColored(msg))); } else { - BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§b信息", TLocale.Translate.setColored(msg)))); + BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§bINFO", TLocale.Translate.setColored(msg)))); } } } public void warn(String msg) { if (level <= WARN) { - if (TabooLib.isSpigot()) { - Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§6警告", "§6" + TLocale.Translate.setColored(msg))); + if (TabooLibAPI.isBukkit()) { + Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§6WARN", "§6" + TLocale.Translate.setColored(msg))); } else { - BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§6警告", "§6" + TLocale.Translate.setColored(msg)))); + BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§6WARN", "§6" + TLocale.Translate.setColored(msg)))); } } } public void error(String msg) { if (level <= ERROR) { - if (TabooLib.isSpigot()) { - Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§c错误", "§c" + TLocale.Translate.setColored(msg))); + if (TabooLibAPI.isBukkit()) { + Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§cERROR", "§c" + TLocale.Translate.setColored(msg))); } else { - BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§c错误", "§c" + TLocale.Translate.setColored(msg)))); + BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§cERROR", "§c" + TLocale.Translate.setColored(msg)))); } } } public void fatal(String msg) { if (level <= FATAL) { - if (TabooLib.isSpigot()) { - Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§4致命错误", "§4" + TLocale.Translate.setColored(msg))); + if (TabooLibAPI.isBukkit()) { + Bukkit.getConsoleSender().sendMessage(Strings.replaceWithOrder(pattern, name, "§4FATAL", "§4" + TLocale.Translate.setColored(msg))); } else { - BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§4致命错误", "§4" + TLocale.Translate.setColored(msg)))); + BungeeCord.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(Strings.replaceWithOrder(pattern, name, "§4FATAL", "§4" + TLocale.Translate.setColored(msg)))); } } } - - public static TLogger getUnformatted(Plugin plugin) { - return new TLogger("§8[§3§l{0}§8][§r{1}§8] §f{2}", plugin, TLogger.FINE); - } - - public static TLogger getUnformatted(String name) { - return new TLogger("§8[§3§l{0}§8][§r{1}§8] §f{2}", name, TLogger.FINE); - } } diff --git a/src/main/scala/com/ilummc/tlib/inject/TLoggerManager.java b/src/main/scala/io/izzel/taboolib/module/locale/logger/TLoggerManager.java similarity index 88% rename from src/main/scala/com/ilummc/tlib/inject/TLoggerManager.java rename to src/main/scala/io/izzel/taboolib/module/locale/logger/TLoggerManager.java index 98f30f4..0522804 100644 --- a/src/main/scala/com/ilummc/tlib/inject/TLoggerManager.java +++ b/src/main/scala/io/izzel/taboolib/module/locale/logger/TLoggerManager.java @@ -1,6 +1,5 @@ -package com.ilummc.tlib.inject; +package io.izzel.taboolib.module.locale.logger; -import com.ilummc.tlib.logger.TLogger; import org.bukkit.plugin.Plugin; import java.util.HashMap; diff --git a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleActionBar.java b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleActionBar.java similarity index 85% rename from src/main/scala/com/ilummc/tlib/resources/type/TLocaleActionBar.java rename to src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleActionBar.java index ec7296c..5679094 100644 --- a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleActionBar.java +++ b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleActionBar.java @@ -1,11 +1,10 @@ -package com.ilummc.tlib.resources.type; +package io.izzel.taboolib.module.locale.type; import com.google.common.collect.Maps; -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.display.ActionUtils; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.locale.TLocaleSerialize; +import io.izzel.taboolib.module.compat.PlaceholderHook; +import io.izzel.taboolib.util.Strings; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.SerializableAs; diff --git a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleBook.java b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleBook.java similarity index 84% rename from src/main/scala/com/ilummc/tlib/resources/type/TLocaleBook.java rename to src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleBook.java index 24c8008..66251c6 100644 --- a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleBook.java +++ b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleBook.java @@ -1,14 +1,14 @@ -package com.ilummc.tlib.resources.type; +package io.izzel.taboolib.module.locale.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 io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.locale.TLocaleSerialize; +import io.izzel.taboolib.module.tellraw.TellrawJson; +import io.izzel.taboolib.util.book.BookFormatter; +import io.izzel.taboolib.util.book.builder.BookBuilder; +import io.izzel.taboolib.util.Strings; +import io.izzel.taboolib.util.chat.ComponentSerializer; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.entity.Player; @@ -77,9 +77,9 @@ public class TLocaleBook extends TLocaleSerialize { public void run() { BookFormatter.forceOpen((Player) sender, bookBuilder.build()); } - }.runTask(Main.getInst()); + }.runTask(TabooLib.getPlugin()); } - }.runTaskAsynchronously(Main.getInst()); + }.runTaskAsynchronously(TabooLib.getPlugin()); } private String format(TellrawJson jsonPage, CommandSender sender, String[] args) { diff --git a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleBossBar.java b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleBossBar.java similarity index 79% rename from src/main/scala/com/ilummc/tlib/resources/type/TLocaleBossBar.java rename to src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleBossBar.java index 62261ca..c4c4b7b 100644 --- a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleBossBar.java +++ b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleBossBar.java @@ -1,14 +1,14 @@ -package com.ilummc.tlib.resources.type; +package io.izzel.taboolib.module.locale.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 io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.locale.TLocaleSerialize; +import io.izzel.taboolib.util.Strings; 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.bukkit.util.NumberConversions; import org.inventivetalent.bossbar.BossBar; import org.inventivetalent.bossbar.BossBarAPI; @@ -72,7 +72,14 @@ public class TLocaleBossBar extends TLocaleSerialize { } 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)); + return new TLocaleBossBar( + map.getOrDefault("text", "§4* Invalid Text*").toString(), + getColor(String.valueOf(map.get("color"))), + getStyle(String.valueOf(map.get("style"))), + NumberConversions.toFloat(map.getOrDefault("progress", 1)), + NumberConversions.toInt(map.getOrDefault("timeout", 20)), + NumberConversions.toInt(map.getOrDefault("timeout-interval", 2)), + isPlaceholderEnabled(map)); } private static BossBarAPI.Color getColor(String color) { diff --git a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleJson.java b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleJson.java similarity index 90% rename from src/main/scala/com/ilummc/tlib/resources/type/TLocaleJson.java rename to src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleJson.java index 456f862..6eb160b 100644 --- a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleJson.java +++ b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleJson.java @@ -1,21 +1,19 @@ -package com.ilummc.tlib.resources.type; +package io.izzel.taboolib.module.locale.type; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.bungee.api.chat.*; -import com.ilummc.tlib.bungee.chat.ComponentSerializer; -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.inventory.ItemUtils; -import me.skymc.taboolib.json.tellraw.TellrawJson; -import me.skymc.taboolib.other.NumberUtils; -import me.skymc.taboolib.string.VariableFormatter; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.locale.TLocaleSerialize; +import io.izzel.taboolib.module.compat.PlaceholderHook; +import io.izzel.taboolib.module.tellraw.TellrawJson; +import io.izzel.taboolib.util.Strings; +import io.izzel.taboolib.util.Variables; +import io.izzel.taboolib.util.chat.*; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.SerializableAs; +import org.bukkit.util.NumberConversions; import javax.annotation.concurrent.ThreadSafe; import java.util.*; @@ -88,7 +86,7 @@ public class TLocaleJson extends TLocaleSerialize { } else { // 这个参数节点并没有找到,于是随便放点字符串进去 builder.addAll(Arrays.asList(TextComponent.fromLegacyText(text))); - TLib.getTLib().getLogger().warn(Strings.replaceWithOrder(TLib.getInternalLanguage().getString("MISSING-ARGUMENT"), node)); + TabooLib.getLogger().warn(Strings.replaceWithOrder(TabooLib.getInst().getInternal().getString("MISSING-ARGUMENT"), node)); } // 有可能一开头就是 <@xxx>,然后 split 出来就少了一些,于是直接加上 if (index < template.length) { @@ -171,7 +169,7 @@ public class TLocaleJson extends TLocaleSerialize { // 遍历本页文本 for (int i = 0; i < textList.size(); i++) { // 捕捉变量 - for (VariableFormatter.Variable variable : new VariableFormatter(TLocale.Translate.setColored(textList.get(i)), pattern).find().getVariableList()) { + for (Variables.Variable variable : new Variables(TLocale.Translate.setColored(textList.get(i)), pattern).find().getVariableList()) { // 如果是变量 if (variable.isVariable()) { String[] split = variable.getText().split("@"); @@ -199,9 +197,6 @@ public class TLocaleJson extends TLocaleSerialize { // 文本 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()); } @@ -212,7 +207,7 @@ public class TLocaleJson extends TLocaleSerialize { pageJson.clickCommand(args.get("command").toString()); } if (args.containsKey("page")) { - pageJson.clickChangePage(NumberUtils.getInteger(args.get("page").toString())); + pageJson.clickChangePage(NumberConversions.toInt(args.get("page").toString())); } if (args.containsKey("url")) { pageJson.clickOpenURL(args.get("url").toString()); diff --git a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleSound.java b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleSound.java similarity index 92% rename from src/main/scala/com/ilummc/tlib/resources/type/TLocaleSound.java rename to src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleSound.java index 5aec6e1..aeb2310 100644 --- a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleSound.java +++ b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleSound.java @@ -1,8 +1,8 @@ -package com.ilummc.tlib.resources.type; +package io.izzel.taboolib.module.locale.type; import com.google.common.collect.Maps; -import com.ilummc.tlib.resources.TLocaleSerialize; -import me.skymc.taboolib.sound.SoundPack; +import io.izzel.taboolib.module.locale.TLocaleSerialize; +import io.izzel.taboolib.util.lite.SoundPack; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.entity.Player; diff --git a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleText.java b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleText.java similarity index 93% rename from src/main/scala/com/ilummc/tlib/resources/type/TLocaleText.java rename to src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleText.java index fc5e587..b4b1166 100644 --- a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleText.java +++ b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleText.java @@ -1,13 +1,11 @@ -package com.ilummc.tlib.resources.type; +package io.izzel.taboolib.module.locale.type; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; -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.Main; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.locale.TLocaleSerialize; +import io.izzel.taboolib.util.Strings; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.SerializableAs; diff --git a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleTitle.java b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleTitle.java similarity index 92% rename from src/main/scala/com/ilummc/tlib/resources/type/TLocaleTitle.java rename to src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleTitle.java index 1b1a710..f29cc7b 100644 --- a/src/main/scala/com/ilummc/tlib/resources/type/TLocaleTitle.java +++ b/src/main/scala/io/izzel/taboolib/module/locale/type/TLocaleTitle.java @@ -1,10 +1,9 @@ -package com.ilummc.tlib.resources.type; +package io.izzel.taboolib.module.locale.type; import com.google.common.collect.Maps; -import com.ilummc.tlib.resources.TLocale; -import com.ilummc.tlib.resources.TLocaleSerialize; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.display.TitleUtils; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.locale.TLocaleSerialize; +import io.izzel.taboolib.util.Strings; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.SerializableAs; import org.bukkit.entity.Player; diff --git a/src/main/scala/me/skymc/taboolib/common/nms/NMSHandler.java b/src/main/scala/io/izzel/taboolib/module/nms/NMS.java similarity index 60% rename from src/main/scala/me/skymc/taboolib/common/nms/NMSHandler.java rename to src/main/scala/io/izzel/taboolib/module/nms/NMS.java index 843fa49..f3dc202 100644 --- a/src/main/scala/me/skymc/taboolib/common/nms/NMSHandler.java +++ b/src/main/scala/io/izzel/taboolib/module/nms/NMS.java @@ -1,8 +1,9 @@ -package me.skymc.taboolib.common.nms; +package io.izzel.taboolib.module.nms; -import me.skymc.taboolib.common.function.TFunction; -import me.skymc.taboolib.common.nms.nbt.NBTCompound; -import me.skymc.taboolib.common.versioncontrol.SimpleVersionControl; +import io.izzel.taboolib.module.inject.TFunction; +import io.izzel.taboolib.module.lite.SimpleVersionControl; +import io.izzel.taboolib.module.nms.nbt.NBTCompound; +import org.bukkit.Particle; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -12,22 +13,26 @@ import org.bukkit.inventory.ItemStack; * @Since 2018-11-09 14:38 */ @TFunction(enable = "init") -public abstract class NMSHandler { +public abstract class NMS { - private static NMSHandler handler; + private static NMS impl; - public static NMSHandler getHandler() { - return handler; + public static NMS handle() { + return impl; } static void init() { try { - handler = (NMSHandler) SimpleVersionControl.createNMS("me.skymc.taboolib.common.nms.NMSHandlerImpl").translate().newInstance(); + impl = (NMS) SimpleVersionControl.createNMS("io.izzel.taboolib.module.nms.NMSImpl").translate().newInstance(); } catch (Exception e) { e.printStackTrace(); } } + abstract public boolean isRunning(); + + abstract public Object toPacketPlayOutWorldParticles(Particle var1, boolean var2, float var3, float var4, float var5, float var6, float var7, float var8, float var9, int var10, Object var11); + abstract public double[] getTPS(); abstract public String getName(ItemStack itemStack); diff --git a/src/main/scala/me/skymc/taboolib/common/nms/NMSHandlerImpl.java b/src/main/scala/io/izzel/taboolib/module/nms/NMSImpl.java similarity index 81% rename from src/main/scala/me/skymc/taboolib/common/nms/NMSHandlerImpl.java rename to src/main/scala/io/izzel/taboolib/module/nms/NMSImpl.java index e856d65..e42f5e6 100644 --- a/src/main/scala/me/skymc/taboolib/common/nms/NMSHandlerImpl.java +++ b/src/main/scala/io/izzel/taboolib/module/nms/NMSImpl.java @@ -1,17 +1,20 @@ -package me.skymc.taboolib.common.nms; +package io.izzel.taboolib.module.nms; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.common.nms.nbt.NBTCompound; -import me.skymc.taboolib.common.nms.nbt.NBTList; -import me.skymc.taboolib.common.packet.TPacketHandler; -import me.skymc.taboolib.common.util.SimpleReflection; -import me.skymc.taboolib.nms.NMSUtils; +import io.izzel.taboolib.Version; +import io.izzel.taboolib.module.lite.SimpleReflection; +import io.izzel.taboolib.module.nms.nbt.NBTCompound; +import io.izzel.taboolib.module.nms.nbt.NBTList; +import io.izzel.taboolib.module.packet.TPacketHandler; import net.minecraft.server.v1_12_R1.ChatMessageType; import net.minecraft.server.v1_12_R1.EntityVillager; import net.minecraft.server.v1_12_R1.MinecraftServer; import net.minecraft.server.v1_12_R1.NBTTagCompound; import net.minecraft.server.v1_13_R2.IRegistry; import net.minecraft.server.v1_8_R3.*; +import org.bukkit.Bukkit; +import org.bukkit.Particle; +import org.bukkit.craftbukkit.v1_12_R1.CraftParticle; +import org.bukkit.craftbukkit.v1_13_R2.CraftServer; import org.bukkit.craftbukkit.v1_13_R2.entity.CraftVillager; import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack; import org.bukkit.entity.Entity; @@ -28,9 +31,8 @@ import java.util.Map; * @Author 坏黑 * @Since 2018-11-09 14:42 */ -public class NMSHandlerImpl extends NMSHandler { +public class NMSImpl extends NMS { - private final int VERSION = TabooLib.getVersionNumber(); private Field entityTypesField; static { @@ -47,16 +49,27 @@ public class NMSHandlerImpl extends NMSHandler { SimpleReflection.saveField(NBTTagCompound.class); } - public NMSHandlerImpl() { - if (TabooLib.getVersionNumber() >= 11300) { - for (Field declaredField : NMSUtils.getNMSClass("Entity").getDeclaredFields()) { + public NMSImpl() { + if (Version.isAfter(Version.v1_13)) { + SimpleReflection.saveField(net.minecraft.server.v1_12_R1.Entity.class); + for (Field declaredField : SimpleReflection.getFields(net.minecraft.server.v1_12_R1.Entity.class).values()) { if (declaredField.getType().getSimpleName().equals("EntityTypes")) { - declaredField.setAccessible(true); entityTypesField = declaredField; break; } } } + SimpleReflection.saveField(MinecraftServer.class); + } + + @Override + public boolean isRunning() { + return !SimpleReflection.getFieldValue(MinecraftServer.class, ((CraftServer) Bukkit.getServer()).getServer(), "hasStopped", false); + } + + @Override + public Object toPacketPlayOutWorldParticles(Particle var1, boolean var2, float var3, float var4, float var5, float var6, float var7, float var8, float var9, int var10, Object var11) { + return new net.minecraft.server.v1_12_R1.PacketPlayOutWorldParticles(CraftParticle.toNMS(var1), var2, var3, var4, var5, var6, var7, var8, var9, var10, CraftParticle.toData(var1, var11)); } @Override @@ -67,13 +80,13 @@ public class NMSHandlerImpl extends NMSHandler { @Override public String getName(ItemStack itemStack) { Object nmsItem = CraftItemStack.asNMSCopy(itemStack); - if (TabooLib.getVersionNumber() >= 11300) { + if (Version.isAfter(Version.v1_13)) { String name = ((net.minecraft.server.v1_8_R3.ItemStack) nmsItem).getItem().getName(); if (itemStack.getItemMeta() instanceof PotionMeta) { name += ".effect." + ((net.minecraft.server.v1_8_R3.ItemStack) nmsItem).getTag().getString("Potion").replaceAll("minecraft:(strong_|long_)?", ""); } return name; - } else if (TabooLib.getVersionNumber() >= 11100) { + } else if (Version.isAfter(Version.v1_11)) { String name = ((net.minecraft.server.v1_12_R1.ItemStack) nmsItem).getItem().a((net.minecraft.server.v1_12_R1.ItemStack) nmsItem); if (itemStack.getItemMeta() instanceof PotionMeta) { return name.replace("item.", "") + ".effect." + ((net.minecraft.server.v1_8_R3.ItemStack) nmsItem).getTag().getString("Potion").replaceAll("(minecraft:)?(strong_|long_)?", ""); @@ -90,10 +103,10 @@ public class NMSHandlerImpl extends NMSHandler { @Override public String getName(Entity entity) { - if (TabooLib.getVersionNumber() >= 11400) { + if (Version.isAfter(Version.v1_14)) { net.minecraft.server.v1_14_R1.MinecraftKey minecraftKey = net.minecraft.server.v1_14_R1.EntityTypes.getName(((org.bukkit.craftbukkit.v1_14_R1.entity.CraftEntity) entity).getHandle().getEntityType()); return "entity.minecraft." + minecraftKey.getKey(); - } else if (TabooLib.getVersionNumber() == 11300) { + } else if (Version.isAfter(Version.v1_13)) { try { String name = "entity.minecraft." + IRegistry.ENTITY_TYPE.getKey((net.minecraft.server.v1_13_R2.EntityTypes) entityTypesField.get(((org.bukkit.craftbukkit.v1_13_R2.entity.CraftEntity) entity).getHandle())).getKey(); if (entity instanceof Villager && ((CraftVillager) entity).getCareer() != null) { @@ -177,7 +190,7 @@ public class NMSHandlerImpl extends NMSHandler { @Override public void sendActionBar(Player player, String text) { - if (TabooLib.getVersionNumber() > 11100) { + if (Version.isAfter(Version.v1_12)) { TPacketHandler.sendPacket(player, new net.minecraft.server.v1_12_R1.PacketPlayOutChat(new net.minecraft.server.v1_12_R1.ChatComponentText(String.valueOf(text)), ChatMessageType.GAME_INFO)); } else { TPacketHandler.sendPacket(player, new PacketPlayOutChat(new ChatComponentText(String.valueOf(text)), (byte) 2)); @@ -188,7 +201,7 @@ public class NMSHandlerImpl extends NMSHandler { public ItemStack _NBT(ItemStack itemStack, Object compound) { Object nmsItem = CraftItemStack.asNMSCopy(itemStack); try { - ((net.minecraft.server.v1_8_R3.ItemStack) nmsItem).setTag((net.minecraft.server.v1_8_R3.NBTTagCompound) toNBTBase((me.skymc.taboolib.common.nms.nbt.NBTBase) compound)); + ((net.minecraft.server.v1_8_R3.ItemStack) nmsItem).setTag((net.minecraft.server.v1_8_R3.NBTTagCompound) toNBTBase((io.izzel.taboolib.module.nms.nbt.NBTBase) compound)); } catch (Throwable t) { t.printStackTrace(); } @@ -206,7 +219,7 @@ public class NMSHandlerImpl extends NMSHandler { return new NBTCompound(); } - private Object toNBTBase(me.skymc.taboolib.common.nms.nbt.NBTBase base) { + private Object toNBTBase(io.izzel.taboolib.module.nms.nbt.NBTBase base) { switch (base.getType().getId()) { case 1: return new NBTTagByte(base.asByte()); @@ -228,13 +241,13 @@ public class NMSHandlerImpl extends NMSHandler { return new NBTTagString(base.asString()); case 9: Object nmsList = new NBTTagList(); - for (me.skymc.taboolib.common.nms.nbt.NBTBase value : base.asList()) { + for (io.izzel.taboolib.module.nms.nbt.NBTBase value : base.asList()) { // 1.14+ - if (TabooLib.getVersionNumber() >= 11400) { + if (Version.isAfter(Version.v1_14)) { ((net.minecraft.server.v1_14_R1.NBTTagList) nmsList).add(((net.minecraft.server.v1_14_R1.NBTTagList) nmsList).size(), (net.minecraft.server.v1_14_R1.NBTBase) toNBTBase(value)); } // 1.13 - else if (TabooLib.getVersionNumber() == 11300) { + else if (Version.isAfter(Version.v1_13)) { ((net.minecraft.server.v1_13_R2.NBTTagList) nmsList).add((net.minecraft.server.v1_13_R2.NBTBase) toNBTBase(value)); } // 1.12- @@ -245,7 +258,7 @@ public class NMSHandlerImpl extends NMSHandler { return nmsList; case 10: Object nmsTag = new net.minecraft.server.v1_8_R3.NBTTagCompound(); - for (Map.Entry entry : base.asCompound().entrySet()) { + for (Map.Entry entry : base.asCompound().entrySet()) { ((Map) SimpleReflection.getFieldValue(NBTTagCompound.class, nmsTag, "map")).put(entry.getKey(), toNBTBase(entry.getValue())); } return nmsTag; @@ -257,33 +270,33 @@ public class NMSHandlerImpl extends NMSHandler { if (base instanceof net.minecraft.server.v1_8_R3.NBTTagCompound) { NBTCompound nbtCompound = new NBTCompound(); for (Map.Entry entry : ((Map) SimpleReflection.getFieldValue(NBTTagCompound.class, base, "map")).entrySet()) { - nbtCompound.put(entry.getKey(), (me.skymc.taboolib.common.nms.nbt.NBTBase) fromNBTBase(entry.getValue())); + nbtCompound.put(entry.getKey(), (io.izzel.taboolib.module.nms.nbt.NBTBase) fromNBTBase(entry.getValue())); } return nbtCompound; } else if (base instanceof NBTTagList) { NBTList nbtList = new NBTList(); for (Object v : (List) SimpleReflection.getFieldValue(NBTTagList.class, base, "list")) { - nbtList.add((me.skymc.taboolib.common.nms.nbt.NBTBase) fromNBTBase(v)); + nbtList.add((io.izzel.taboolib.module.nms.nbt.NBTBase) fromNBTBase(v)); } return nbtList; } else if (base instanceof NBTTagString) { - return new me.skymc.taboolib.common.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagString.class, base, "data", "")); + return new io.izzel.taboolib.module.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagString.class, base, "data", "")); } else if (base instanceof NBTTagDouble) { - return new me.skymc.taboolib.common.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagDouble.class, base, "data", 0D)); + return new io.izzel.taboolib.module.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagDouble.class, base, "data", 0D)); } else if (base instanceof NBTTagInt) { - return new me.skymc.taboolib.common.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagInt.class, base, "data", 0)); + return new io.izzel.taboolib.module.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagInt.class, base, "data", 0)); } else if (base instanceof NBTTagFloat) { - return new me.skymc.taboolib.common.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagFloat.class, base, "data", (float) 0)); + return new io.izzel.taboolib.module.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagFloat.class, base, "data", (float) 0)); } else if (base instanceof NBTTagShort) { - return new me.skymc.taboolib.common.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagShort.class, base, "data", (short) 0)); + return new io.izzel.taboolib.module.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagShort.class, base, "data", (short) 0)); } else if (base instanceof NBTTagLong) { - return new me.skymc.taboolib.common.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagLong.class, base, "data", 0L)); + return new io.izzel.taboolib.module.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagLong.class, base, "data", 0L)); } else if (base instanceof NBTTagByte) { - return new me.skymc.taboolib.common.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagByte.class, base, "data", (byte) 0D)); + return new io.izzel.taboolib.module.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagByte.class, base, "data", (byte) 0D)); } else if (base instanceof NBTTagIntArray) { - return new me.skymc.taboolib.common.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagIntArray.class, base, "data", new int[0])); + return new io.izzel.taboolib.module.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagIntArray.class, base, "data", new int[0])); } else if (base instanceof NBTTagByteArray) { - return new me.skymc.taboolib.common.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagByteArray.class, base, "data", new byte[0])); + return new io.izzel.taboolib.module.nms.nbt.NBTBase(SimpleReflection.getFieldValue(NBTTagByteArray.class, base, "data", new byte[0])); } return null; } diff --git a/src/main/scala/me/skymc/taboolib/common/nms/nbt/NBTBase.java b/src/main/scala/io/izzel/taboolib/module/nms/nbt/NBTBase.java similarity index 98% rename from src/main/scala/me/skymc/taboolib/common/nms/nbt/NBTBase.java rename to src/main/scala/io/izzel/taboolib/module/nms/nbt/NBTBase.java index ad5ebce..d76f69b 100644 --- a/src/main/scala/me/skymc/taboolib/common/nms/nbt/NBTBase.java +++ b/src/main/scala/io/izzel/taboolib/module/nms/nbt/NBTBase.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.nms.nbt; +package io.izzel.taboolib.module.nms.nbt; import java.util.Arrays; import java.util.Objects; diff --git a/src/main/scala/me/skymc/taboolib/common/nms/nbt/NBTCompound.java b/src/main/scala/io/izzel/taboolib/module/nms/nbt/NBTCompound.java similarity index 98% rename from src/main/scala/me/skymc/taboolib/common/nms/nbt/NBTCompound.java rename to src/main/scala/io/izzel/taboolib/module/nms/nbt/NBTCompound.java index d7a34ef..f475678 100644 --- a/src/main/scala/me/skymc/taboolib/common/nms/nbt/NBTCompound.java +++ b/src/main/scala/io/izzel/taboolib/module/nms/nbt/NBTCompound.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.nms.nbt; +package io.izzel.taboolib.module.nms.nbt; import com.google.common.collect.Maps; diff --git a/src/main/scala/me/skymc/taboolib/common/nms/nbt/NBTList.java b/src/main/scala/io/izzel/taboolib/module/nms/nbt/NBTList.java similarity index 96% rename from src/main/scala/me/skymc/taboolib/common/nms/nbt/NBTList.java rename to src/main/scala/io/izzel/taboolib/module/nms/nbt/NBTList.java index 83a47c3..06ed845 100644 --- a/src/main/scala/me/skymc/taboolib/common/nms/nbt/NBTList.java +++ b/src/main/scala/io/izzel/taboolib/module/nms/nbt/NBTList.java @@ -1,8 +1,7 @@ -package me.skymc.taboolib.common.nms.nbt; - -import com.google.common.collect.Lists; +package io.izzel.taboolib.module.nms.nbt; import java.util.*; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.UnaryOperator; @@ -14,7 +13,7 @@ import java.util.stream.Stream; */ public class NBTList extends NBTBase implements List { - private List value = Lists.newCopyOnWriteArrayList(); + private List value = new CopyOnWriteArrayList<>(); public NBTList() { super(0); diff --git a/src/main/scala/me/skymc/taboolib/common/nms/nbt/NBTType.java b/src/main/scala/io/izzel/taboolib/module/nms/nbt/NBTType.java similarity index 90% rename from src/main/scala/me/skymc/taboolib/common/nms/nbt/NBTType.java rename to src/main/scala/io/izzel/taboolib/module/nms/nbt/NBTType.java index b1769cd..21f06d1 100644 --- a/src/main/scala/me/skymc/taboolib/common/nms/nbt/NBTType.java +++ b/src/main/scala/io/izzel/taboolib/module/nms/nbt/NBTType.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.nms.nbt; +package io.izzel.taboolib.module.nms.nbt; /** * @Author 坏黑 diff --git a/src/main/scala/me/skymc/taboolib/common/packet/TPacketHandler.java b/src/main/scala/io/izzel/taboolib/module/packet/TPacketHandler.java similarity index 87% rename from src/main/scala/me/skymc/taboolib/common/packet/TPacketHandler.java rename to src/main/scala/io/izzel/taboolib/module/packet/TPacketHandler.java index 5a00d14..4dee6a7 100644 --- a/src/main/scala/me/skymc/taboolib/common/packet/TPacketHandler.java +++ b/src/main/scala/io/izzel/taboolib/module/packet/TPacketHandler.java @@ -1,10 +1,10 @@ -package me.skymc.taboolib.common.packet; +package io.izzel.taboolib.module.packet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import me.skymc.taboolib.common.packet.channel.ChannelExecutor; -import me.skymc.taboolib.common.versioncontrol.SimpleVersionControl; -import me.skymc.taboolib.listener.TListener; +import io.izzel.taboolib.module.packet.channel.ChannelExecutor; +import io.izzel.taboolib.module.lite.SimpleVersionControl; +import io.izzel.taboolib.module.inject.TListener; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -30,7 +30,7 @@ public class TPacketHandler implements Listener { public TPacketHandler() { try { - channelExecutor = (ChannelExecutor) SimpleVersionControl.createNMS("me.skymc.taboolib.common.packet.channel.InternalChannelExecutor").translate().newInstance(); + channelExecutor = (ChannelExecutor) SimpleVersionControl.createNMS("io.izzel.taboolib.module.packet.channel.InternalChannelExecutor").translate().newInstance(); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/scala/me/skymc/taboolib/common/packet/TPacketListener.java b/src/main/scala/io/izzel/taboolib/module/packet/TPacketListener.java similarity index 88% rename from src/main/scala/me/skymc/taboolib/common/packet/TPacketListener.java rename to src/main/scala/io/izzel/taboolib/module/packet/TPacketListener.java index 03bc82b..cc36ce4 100644 --- a/src/main/scala/me/skymc/taboolib/common/packet/TPacketListener.java +++ b/src/main/scala/io/izzel/taboolib/module/packet/TPacketListener.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.packet; +package io.izzel.taboolib.module.packet; import org.bukkit.entity.Player; diff --git a/src/main/scala/me/skymc/taboolib/common/packet/channel/ChannelExecutor.java b/src/main/scala/io/izzel/taboolib/module/packet/channel/ChannelExecutor.java similarity index 96% rename from src/main/scala/me/skymc/taboolib/common/packet/channel/ChannelExecutor.java rename to src/main/scala/io/izzel/taboolib/module/packet/channel/ChannelExecutor.java index 20143cb..e0c0045 100644 --- a/src/main/scala/me/skymc/taboolib/common/packet/channel/ChannelExecutor.java +++ b/src/main/scala/io/izzel/taboolib/module/packet/channel/ChannelExecutor.java @@ -1,10 +1,10 @@ -package me.skymc.taboolib.common.packet.channel; +package io.izzel.taboolib.module.packet.channel; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; -import me.skymc.taboolib.common.packet.TPacketHandler; +import io.izzel.taboolib.module.packet.TPacketHandler; import org.bukkit.entity.Player; import java.util.Collection; diff --git a/src/main/scala/me/skymc/taboolib/common/packet/channel/InternalChannelExecutor.java b/src/main/scala/io/izzel/taboolib/module/packet/channel/InternalChannelExecutor.java similarity index 88% rename from src/main/scala/me/skymc/taboolib/common/packet/channel/InternalChannelExecutor.java rename to src/main/scala/io/izzel/taboolib/module/packet/channel/InternalChannelExecutor.java index bbaf842..3b59a64 100644 --- a/src/main/scala/me/skymc/taboolib/common/packet/channel/InternalChannelExecutor.java +++ b/src/main/scala/io/izzel/taboolib/module/packet/channel/InternalChannelExecutor.java @@ -1,6 +1,6 @@ -package me.skymc.taboolib.common.packet.channel; +package io.izzel.taboolib.module.packet.channel; -import com.ilummc.tlib.logger.TLogger; +import io.izzel.taboolib.module.locale.logger.TLogger; import io.netty.channel.Channel; import net.minecraft.server.v1_8_R3.Packet; import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer; diff --git a/src/main/scala/me/skymc/taboolib/json/tellraw/TellrawCreator.java b/src/main/scala/io/izzel/taboolib/module/tellraw/TellrawCreator.java similarity index 71% rename from src/main/scala/me/skymc/taboolib/json/tellraw/TellrawCreator.java rename to src/main/scala/io/izzel/taboolib/module/tellraw/TellrawCreator.java index d65397c..a792500 100644 --- a/src/main/scala/me/skymc/taboolib/json/tellraw/TellrawCreator.java +++ b/src/main/scala/io/izzel/taboolib/module/tellraw/TellrawCreator.java @@ -1,26 +1,26 @@ -package me.skymc.taboolib.json.tellraw; +package io.izzel.taboolib.module.tellraw; -import me.skymc.taboolib.common.loader.Instantiable; -import me.skymc.taboolib.common.versioncontrol.SimpleVersionControl; -import me.skymc.taboolib.json.tellraw.internal.AbstractTellraw; +import io.izzel.taboolib.module.inject.TFunction; +import io.izzel.taboolib.module.lite.SimpleVersionControl; +import io.izzel.taboolib.module.tellraw.internal.AbstractTellraw; import org.bukkit.Bukkit; /** * @Author 坏黑 * @Since 2018-11-07 22:58 */ -@Instantiable("TabooLib|TellrawCreator") +@TFunction(enable = "init") public class TellrawCreator { private static AbstractTellraw abstractTellraw; private static boolean viaVersionLoaded; private static boolean protocolSupportLoaded; - public TellrawCreator() { + public static void init() { viaVersionLoaded = Bukkit.getPluginManager().getPlugin("ViaVersion") != null; protocolSupportLoaded = Bukkit.getPluginManager().getPlugin("ProtocolSupport") != null; try { - abstractTellraw = (AbstractTellraw) SimpleVersionControl.createNMS("me.skymc.taboolib.json.tellraw.internal.InternalTellraw").translate().newInstance(); + abstractTellraw = (AbstractTellraw) SimpleVersionControl.createNMS("io.izzel.taboolib.module.tellraw.internal.InternalTellraw").translate().newInstance(); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/scala/me/skymc/taboolib/json/tellraw/TellrawJson.java b/src/main/scala/io/izzel/taboolib/module/tellraw/TellrawJson.java similarity index 89% rename from src/main/scala/me/skymc/taboolib/json/tellraw/TellrawJson.java rename to src/main/scala/io/izzel/taboolib/module/tellraw/TellrawJson.java index 12e0fb0..3ce5607 100644 --- a/src/main/scala/me/skymc/taboolib/json/tellraw/TellrawJson.java +++ b/src/main/scala/io/izzel/taboolib/module/tellraw/TellrawJson.java @@ -1,11 +1,9 @@ -package me.skymc.taboolib.json.tellraw; +package io.izzel.taboolib.module.tellraw; -import com.ilummc.tlib.bungee.api.chat.*; -import com.ilummc.tlib.bungee.chat.ComponentSerializer; -import com.ilummc.tlib.resources.TLocale; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.string.ArrayUtils; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.util.ArrayUtil; +import io.izzel.taboolib.util.Strings; +import io.izzel.taboolib.util.chat.*; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -13,10 +11,7 @@ import org.bukkit.inventory.ItemStack; import protocolsupport.api.ProtocolSupportAPI; import us.myles.ViaVersion.api.Via; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.stream.Collectors; /** @@ -26,11 +21,10 @@ import java.util.stream.Collectors; */ public class TellrawJson { - private int bukkitVersion = TabooLib.getVersionNumber(); private List components = new ArrayList<>(); private List componentsLatest = new ArrayList<>(); private Map itemTag = new HashMap<>(); - private List nbtWhitelist = ArrayUtils.asList( + private List nbtWhitelist = ArrayUtil.asList( // 附魔 "ench", // 附魔书 @@ -113,13 +107,13 @@ public class TellrawJson { public TellrawJson append(String text) { appendComponents(); - componentsLatest.addAll(ArrayUtils.asList(TextComponent.fromLegacyText(text))); + componentsLatest.addAll(Arrays.asList(TextComponent.fromLegacyText(text))); return this; } public TellrawJson append(TellrawJson json) { appendComponents(); - componentsLatest.addAll(ArrayUtils.asList(json.getComponentsAll())); + componentsLatest.addAll(Arrays.asList(json.getComponentsAll())); itemTag.putAll(json.itemTag); return this; } @@ -188,7 +182,7 @@ public class TellrawJson { } private void setLatestComponent(BaseComponent... component) { - componentsLatest.addAll(ArrayUtils.asList(component)); + componentsLatest.addAll(Arrays.asList(component)); } private void appendComponents() { @@ -203,17 +197,13 @@ public class TellrawJson { // ********************************* public void setComponents(BaseComponent[] components) { - this.components = ArrayUtils.asList(components); + this.components = Arrays.asList(components); } public BaseComponent[] getComponents() { return components.toArray(new BaseComponent[0]); } - public int getBukkitVersion() { - return bukkitVersion; - } - public List getComponentsLatest() { return componentsLatest; } diff --git a/src/main/scala/me/skymc/taboolib/json/tellraw/TellrawVersion.java b/src/main/scala/io/izzel/taboolib/module/tellraw/TellrawVersion.java similarity index 76% rename from src/main/scala/me/skymc/taboolib/json/tellraw/TellrawVersion.java rename to src/main/scala/io/izzel/taboolib/module/tellraw/TellrawVersion.java index 81bc02d..c52526f 100644 --- a/src/main/scala/me/skymc/taboolib/json/tellraw/TellrawVersion.java +++ b/src/main/scala/io/izzel/taboolib/module/tellraw/TellrawVersion.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.json.tellraw; +package io.izzel.taboolib.module.tellraw; /** * @Author 坏黑 diff --git a/src/main/scala/me/skymc/taboolib/json/tellraw/internal/AbstractTellraw.java b/src/main/scala/io/izzel/taboolib/module/tellraw/internal/AbstractTellraw.java similarity index 82% rename from src/main/scala/me/skymc/taboolib/json/tellraw/internal/AbstractTellraw.java rename to src/main/scala/io/izzel/taboolib/module/tellraw/internal/AbstractTellraw.java index f20ad06..1dfa35c 100644 --- a/src/main/scala/me/skymc/taboolib/json/tellraw/internal/AbstractTellraw.java +++ b/src/main/scala/io/izzel/taboolib/module/tellraw/internal/AbstractTellraw.java @@ -1,6 +1,6 @@ -package me.skymc.taboolib.json.tellraw.internal; +package io.izzel.taboolib.module.tellraw.internal; -import me.skymc.taboolib.json.tellraw.TellrawVersion; +import io.izzel.taboolib.module.tellraw.TellrawVersion; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; diff --git a/src/main/scala/me/skymc/taboolib/json/tellraw/internal/InternalTellraw.java b/src/main/scala/io/izzel/taboolib/module/tellraw/internal/InternalTellraw.java similarity index 88% rename from src/main/scala/me/skymc/taboolib/json/tellraw/internal/InternalTellraw.java rename to src/main/scala/io/izzel/taboolib/module/tellraw/internal/InternalTellraw.java index 32bf0ef..0cecd9d 100644 --- a/src/main/scala/me/skymc/taboolib/json/tellraw/internal/InternalTellraw.java +++ b/src/main/scala/io/izzel/taboolib/module/tellraw/internal/InternalTellraw.java @@ -1,10 +1,10 @@ -package me.skymc.taboolib.json.tellraw.internal; +package io.izzel.taboolib.module.tellraw.internal; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.common.packet.TPacketHandler; -import me.skymc.taboolib.common.util.SimpleReflection; -import me.skymc.taboolib.inventory.ItemUtils; -import me.skymc.taboolib.json.tellraw.TellrawVersion; +import io.izzel.taboolib.Version; +import io.izzel.taboolib.util.item.Items; +import io.izzel.taboolib.module.lite.SimpleReflection; +import io.izzel.taboolib.module.packet.TPacketHandler; +import io.izzel.taboolib.module.tellraw.TellrawVersion; import net.minecraft.server.v1_8_R3.*; import org.bukkit.Material; import org.bukkit.block.ShulkerBox; @@ -13,6 +13,7 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BlockStateMeta; +import org.bukkit.inventory.meta.ItemMeta; import java.util.List; import java.util.Map; @@ -23,8 +24,6 @@ import java.util.Map; */ public class InternalTellraw implements AbstractTellraw { - private int bukkitVersion = TabooLib.getVersionNumber(); - public InternalTellraw() { SimpleReflection.saveField(NBTTagCompound.class, "map"); SimpleReflection.saveField(NBTTagList.class, "list"); @@ -74,10 +73,12 @@ public class InternalTellraw implements AbstractTellraw { ItemStack[] contentsClone = new ItemStack[contents.length]; for (int i = 0; i < contents.length; i++) { ItemStack content = contents[i]; - if (!ItemUtils.isNull(content)) { + if (!Items.isNull(content)) { ItemStack contentClone = new ItemStack(Material.STONE, content.getAmount(), content.getDurability()); if (content.getItemMeta().hasDisplayName()) { - ItemUtils.setName(contentClone, content.getItemMeta().getDisplayName()); + ItemMeta itemMeta = contentClone.getItemMeta(); + itemMeta.setDisplayName(content.getItemMeta().getDisplayName()); + contentClone.setItemMeta(itemMeta); } contentsClone[i] = contentClone; } @@ -127,7 +128,7 @@ public class InternalTellraw implements AbstractTellraw { if (i != 0) { builder.append(','); } - if (version == TellrawVersion.HIGH_VERSION || (this.bukkitVersion >= 11200 && version == TellrawVersion.CURRENT_VERSION)) { + if (version == TellrawVersion.HIGH_VERSION || (Version.isAfter(Version.v1_12) && version == TellrawVersion.CURRENT_VERSION)) { builder.append(list.get(i)); } else { builder.append(i).append(':').append(list.get(i)); diff --git a/src/main/scala/me/skymc/taboolib/string/ArrayUtils.java b/src/main/scala/io/izzel/taboolib/util/ArrayUtil.java similarity index 74% rename from src/main/scala/me/skymc/taboolib/string/ArrayUtils.java rename to src/main/scala/io/izzel/taboolib/util/ArrayUtil.java index b2da4df..17c96f5 100644 --- a/src/main/scala/me/skymc/taboolib/string/ArrayUtils.java +++ b/src/main/scala/io/izzel/taboolib/util/ArrayUtil.java @@ -1,9 +1,5 @@ -package me.skymc.taboolib.string; +package io.izzel.taboolib.util; -import com.ilummc.tlib.util.Strings; - -import java.io.*; -import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -14,7 +10,7 @@ import java.util.stream.IntStream; * @author Bkm016 * @since 2018-04-16 */ -public class ArrayUtils { +public class ArrayUtil { public static int indexOf(T[] array, T obj) { return array == null || array.length == 0 ? -1 : IntStream.range(0, array.length).filter(i -> array[i] != null && array[i].equals(obj)).findFirst().orElse(-1); @@ -47,29 +43,20 @@ public class ArrayUtils { @SuppressWarnings("SuspiciousSystemArraycopy") public static T arrayExpand(T oldArray, int expand) { - int length = Array.getLength(oldArray); - Object newArray = Array.newInstance(oldArray.getClass().getComponentType(), length + expand); + int length = java.lang.reflect.Array.getLength(oldArray); + Object newArray = java.lang.reflect.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); + int length = java.lang.reflect.Array.getLength(oldArray); + Object newArray = java.lang.reflect.Array.newInstance(oldArray.getClass().getComponentType(), length + expand); System.arraycopy(oldArray, 0, newArray, expand, length); return (T) newArray; } - public static T cloneAsByte(T obj) throws IOException, ClassNotFoundException { - 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(); - } - public static T skipEmpty(T obj) { return skipEmpty(obj, null); } diff --git a/src/main/scala/io/izzel/taboolib/util/Files.java b/src/main/scala/io/izzel/taboolib/util/Files.java new file mode 100644 index 0000000..c01d766 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/util/Files.java @@ -0,0 +1,269 @@ +package io.izzel.taboolib.util; + +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.common.plugin.InternalPlugin; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.*; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.channels.FileChannel; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.jar.JarFile; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +/** + * @author sky + */ +public class Files { + + public static List getClasses(Plugin plugin) { + return getClasses(plugin, new String[0]); + } + + public static List getClasses(Plugin plugin, String[] ignore) { + List classes = new CopyOnWriteArrayList<>(); + URL url = plugin.getClass().getProtectionDomain().getCodeSource().getLocation(); + try { + File src; + try { + src = new File(url.toURI()); + } catch (URISyntaxException e) { + src = new File(url.getPath()); + } + new JarFile(src).stream().filter(entry -> entry.getName().endsWith(".class")).forEach(entry -> { + String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6); + try { + if (Arrays.stream(ignore).noneMatch(className::startsWith)) { + classes.add(Class.forName(className, false, plugin.getClass().getClassLoader())); + } + } catch (Throwable ignored) { + } + }); + } catch (Throwable ignored) { + } + return classes; + } + + public static InputStream getResource(String filename) { + return getResource(TabooLib.getPlugin(), filename); + } + + public static InputStream getResource(Plugin plugin, String filename) { + return plugin instanceof InternalPlugin ? getResourceTabooLib(filename) : plugin.getClass().getClassLoader().getResourceAsStream(filename); + } + + public static InputStream getResourceTabooLib(String filename) { + try { + ZipFile zipFile = new ZipFile(new File("TabooLib.jar")); + ZipEntry entry = zipFile.getEntry(filename); + if (entry != null) { + return zipFile.getInputStream(entry); + } + } catch (IOException e) { + e.printStackTrace(); + } + return TabooLib.class.getResourceAsStream(filename); + } + + public static void releaseResource(Plugin plugin, String path, boolean replace) { + File file = new File(plugin.getDataFolder(), path); + if (!file.exists() || replace) { + toFile(getResource(plugin, path), Files.file(file)); + } + } + + public static void toFile(String in, File file) { + try (FileWriter fileWriter = new FileWriter(file); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) { + bufferedWriter.write(in); + bufferedWriter.flush(); + } catch (Exception ignored) { + } + } + + public static void toFile(InputStream inputStream, File file) { + try (FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos)) { + byte[] buf = new byte[1024]; + int len; + while ((len = inputStream.read(buf)) > 0) { + bos.write(buf, 0, len); + } + bos.flush(); + } catch (Exception ignored) { + } + } + + public static File file(File path, String filePath) { + return file(new File(path, filePath)); + } + + public static File file(String filePath) { + return file(new File(filePath)); + } + + public static File file(File file) { + if (!file.exists()) { + folder(file); + try { + file.createNewFile(); + } catch (Throwable t) { + t.printStackTrace(); + } + } + return file; + } + + public static File folder(File path, String filePath) { + return folder(new File(path, filePath)); + } + + public static File folder(String filePath) { + return folder(new File(filePath)); + } + + public static File folder(File file) { + if (!file.exists()) { + String filePath = file.getPath(); + int index = filePath.lastIndexOf(File.separator); + String folderPath; + File folder; + if ((index >= 0) && (!(folder = new File(filePath.substring(0, index))).exists())) { + folder.mkdirs(); + } + } + return file; + } + + public static void deepDelete(File file) { + if (!file.exists()) { + return; + } + if (file.isFile()) { + file.delete(); + return; + } + for (File file1 : Objects.requireNonNull(file.listFiles())) { + deepDelete(file1); + } + file.delete(); + } + + public static void deepCopy(String originFileName, String targetFileName) { + File originFile = new File(originFileName); + File targetFile = new File(targetFileName); + if (!targetFile.exists()) { + if (!originFile.isDirectory()) { + file(targetFile); + } else { + targetFile.mkdirs(); + } + } + if (originFile.isDirectory()) { + for (File file : Objects.requireNonNull(originFile.listFiles())) { + if (file.isDirectory()) { + deepCopy(file.getAbsolutePath(), targetFileName + "/" + file.getName()); + } else { + weekCopy(file, new File(targetFileName + "/" + file.getName())); + } + } + } else { + weekCopy(originFile, targetFile); + } + } + + public static void weekCopy(File file1, File file2) { + try (FileInputStream fileIn = new FileInputStream(file1); + FileOutputStream fileOut = new FileOutputStream(file2); + FileChannel channelIn = fileIn.getChannel(); + FileChannel channelOut = fileOut.getChannel()) { + channelIn.transferTo(0, channelIn.size(), channelOut); + } catch (IOException t) { + t.printStackTrace(); + } + } + + public static String readFromURL(String url, String def) { + String s = readFromURL(url, 1024); + return s == null ? def : s; + } + + public static String readFromURL(String url, int size) { + URLConnection conn = null; + BufferedInputStream bin = null; + try { + conn = new URL(url).openConnection(); + bin = new BufferedInputStream(conn.getInputStream()); + return readFromStream(bin, size, conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding()); + } catch (IOException e) { + e.printStackTrace(); + } finally { + IO.close(conn); + IO.closeQuietly(bin); + } + return null; + } + + public static String readFromFile(File file, int size, String encode) { + try (FileInputStream fin = new FileInputStream(file); BufferedInputStream bin = new BufferedInputStream(fin)) { + return readFromStream(fin, size, encode); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + public static String readFromStream(InputStream in, int size, String encode) { + try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { + byte[] b = new byte[size]; + int i; + while ((i = in.read(b)) > 0) { + bos.write(b, 0, i); + } + return new String(bos.toByteArray(), encode); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + public static String encodeYAML(FileConfiguration file) { + return Base64Coder.encodeLines(file.saveToString().getBytes()).replaceAll("\\s+", ""); + } + + public static FileConfiguration decodeYAML(String args) { + return YamlConfiguration.loadConfiguration(new StringReader(Base64Coder.decodeString(args))); + } + + public static FileConfiguration load(File file) { + return loadYaml(file); + } + + public static YamlConfiguration loadYaml( File file) { + YamlConfiguration configuration = new YamlConfiguration(); + try { + String yaml = com.google.common.io.Files.toString(file, Charset.forName("utf-8")); + configuration.loadFromString(yaml); + return configuration; + } catch (Exception e) { + e.printStackTrace(); + } + return configuration; + } + + private static Class getCaller(Class obj) { + try { + return Class.forName(Thread.currentThread().getStackTrace()[3].getClassName(), false, obj.getClassLoader()); + } catch (ClassNotFoundException ignored) { + } + return null; + } +} diff --git a/src/main/scala/me/skymc/taboolib/common/io/IOUtils.java b/src/main/scala/io/izzel/taboolib/util/IO.java similarity index 74% rename from src/main/scala/me/skymc/taboolib/common/io/IOUtils.java rename to src/main/scala/io/izzel/taboolib/util/IO.java index 49f3da8..4dcd9e9 100644 --- a/src/main/scala/me/skymc/taboolib/common/io/IOUtils.java +++ b/src/main/scala/io/izzel/taboolib/util/IO.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.io; +package io.izzel.taboolib.util; import java.io.*; import java.net.HttpURLConnection; @@ -6,12 +6,23 @@ import java.net.ServerSocket; import java.net.Socket; import java.net.URLConnection; import java.nio.channels.Selector; +import java.nio.charset.Charset; -/** - * from org.apache.commons.io - * support for 1.14 - */ -public class IOUtils { +public class IO { + + public static String readFully(InputStream inputStream, Charset charset) throws IOException { + return new String(readFully(inputStream), charset); + } + + public static byte[] readFully(InputStream inputStream) throws IOException { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + byte[] buf = new byte[1024]; + int len = 0; + while ((len = inputStream.read(buf)) > 0) { + stream.write(buf, 0, len); + } + return stream.toByteArray(); + } public static void close(URLConnection v) { if (v instanceof HttpURLConnection) { diff --git a/src/main/scala/com/ilummc/tlib/util/Ref.java b/src/main/scala/io/izzel/taboolib/util/Ref.java similarity index 93% rename from src/main/scala/com/ilummc/tlib/util/Ref.java rename to src/main/scala/io/izzel/taboolib/util/Ref.java index bd9c35b..8d05d90 100644 --- a/src/main/scala/com/ilummc/tlib/util/Ref.java +++ b/src/main/scala/io/izzel/taboolib/util/Ref.java @@ -1,9 +1,8 @@ -package com.ilummc.tlib.util; +package io.izzel.taboolib.util; import com.google.gson.annotations.SerializedName; -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.util.asm.AsmAnalyser; -import me.skymc.taboolib.Main; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.util.asm.AsmAnalyser; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.objectweb.asm.ClassReader; @@ -38,12 +37,6 @@ public class Ref { public static List getDeclaredFields(Class clazz, int excludeModifiers, boolean cache) { try { - - // 特殊判断 - if (clazz == TLib.class) { - return Arrays.asList(clazz.getDeclaredFields()); - } - List fields; if ((fields = cachedFields.get(clazz.getName())) != null) { return fields; @@ -100,6 +93,9 @@ public class Ref { } public static Plugin getCallerPlugin(Class callerClass) { + if (callerClass.getName().startsWith("io.izzel.taboolib") || callerClass.getName().startsWith("io.izzel.tlibscala")) { + return TabooLib.getPlugin(); + } try { return JavaPlugin.getProvidingPlugin(callerClass); } catch (Exception ignored) { @@ -110,7 +106,7 @@ public class Ref { Object o = pluginF.get(loader); return (JavaPlugin) o; } catch (Exception e) { - return Main.getInst(); + return TabooLib.getPlugin(); } } } diff --git a/src/main/scala/me/skymc/taboolib/methods/ReflectionUtils.java b/src/main/scala/io/izzel/taboolib/util/Reflection.java similarity index 99% rename from src/main/scala/me/skymc/taboolib/methods/ReflectionUtils.java rename to src/main/scala/io/izzel/taboolib/util/Reflection.java index eede188..5ee962f 100644 --- a/src/main/scala/me/skymc/taboolib/methods/ReflectionUtils.java +++ b/src/main/scala/io/izzel/taboolib/util/Reflection.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.methods; +package io.izzel.taboolib.util; import org.bukkit.Bukkit; @@ -25,9 +25,9 @@ import java.util.Map; * @author DarkBlade12 * @version 1.1 */ -public final class ReflectionUtils { +public final class Reflection { // Prevent accidental construction - private ReflectionUtils() { + private Reflection() { } /** diff --git a/src/main/scala/me/skymc/taboolib/string/StringUtils.java b/src/main/scala/io/izzel/taboolib/util/Strings.java similarity index 67% rename from src/main/scala/me/skymc/taboolib/string/StringUtils.java rename to src/main/scala/io/izzel/taboolib/util/Strings.java index 20a24d5..8530124 100644 --- a/src/main/scala/me/skymc/taboolib/string/StringUtils.java +++ b/src/main/scala/io/izzel/taboolib/util/Strings.java @@ -1,15 +1,51 @@ -package me.skymc.taboolib.string; +package io.izzel.taboolib.util; + +import com.google.common.collect.Lists; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -/** - * @author sky - * @since 2018年2月6日 下午1:28:38 - */ -public class StringUtils { - - public static String hashKeyForDisk(String key) { +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; + } + + public static String replaceWithOrder(String template, String... args) { + return replaceWithOrder(template, Lists.newArrayList(args).toArray()); + } + + /** + * 优化过的 String#replace,比默认快了大概 5 倍 + * + * @param template 模板替换文件 + * @param args 替换的参数 + * @return 替换好的字符串 + */ + public static String replaceWithOrder(String template, Object... args) { + if (args.length == 0 || template.length() == 0) { + return template; + } + char[] arr = template.toCharArray(); + StringBuilder stringBuilder = new StringBuilder(template.length()); + for (int i = 0; i < arr.length; i++) { + if (arr[i] == '{' && Character.isDigit(arr[Math.min(i + 1, arr.length - 1)]) + && arr[Math.min(i + 1, arr.length - 1)] - '0' < args.length + && arr[Math.min(i + 2, arr.length - 1)] == '}') { + stringBuilder.append(args[arr[i + 1] - '0']); + i += 2; + } else { + stringBuilder.append(arr[i]); + } + } + return stringBuilder.toString(); + } + + public static String hashKeyForDisk(String key) { String cacheKey; try { final MessageDigest mDigest = MessageDigest.getInstance("MD5"); @@ -21,18 +57,6 @@ public class StringUtils { return cacheKey; } - private static String bytesToHexString(byte[] bytes) { - StringBuilder sb = new StringBuilder(); - for (byte aByte : bytes) { - String hex = Integer.toHexString(0xFF & aByte); - if (hex.length() == 1) { - sb.append('0'); - } - sb.append(hex); - } - return sb.toString(); - } - public static double similarDegree(String strA, String strB){ String newStrA = removeSign(max(strA, strB)); String newStrB = removeSign(min(strA, strB)); @@ -45,6 +69,18 @@ public class StringUtils { } } + private static String bytesToHexString(byte[] bytes) { + StringBuilder sb = new StringBuilder(); + for (byte aByte : bytes) { + String hex = Integer.toHexString(0xFF & aByte); + if (hex.length() == 1) { + sb.append('0'); + } + sb.append(hex); + } + return sb.toString(); + } + private static String max(String strA, String strB) { return strA.length() >= strB.length() ? strA : strB; } @@ -100,5 +136,4 @@ public class StringUtils { } return new String(result); } - } diff --git a/src/main/scala/me/skymc/taboolib/timeutil/TimeFormatter.java b/src/main/scala/io/izzel/taboolib/util/Times.java similarity index 93% rename from src/main/scala/me/skymc/taboolib/timeutil/TimeFormatter.java rename to src/main/scala/io/izzel/taboolib/util/Times.java index edb73d3..d4a184f 100644 --- a/src/main/scala/me/skymc/taboolib/timeutil/TimeFormatter.java +++ b/src/main/scala/io/izzel/taboolib/util/Times.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.timeutil; +package io.izzel.taboolib.util; import java.util.concurrent.TimeUnit; @@ -6,7 +6,7 @@ import java.util.concurrent.TimeUnit; * @author sky * @since 2018-04-10 22:11:04 */ -public class TimeFormatter { +public class Times { private long days; private long hours; @@ -14,7 +14,7 @@ public class TimeFormatter { private long seconds; private long milliseconds; - public TimeFormatter(long millisecond) { + public Times(long millisecond) { days = TimeUnit.MILLISECONDS.toDays(millisecond); hours = TimeUnit.MILLISECONDS.toHours(millisecond) - days * 24L; minutes = TimeUnit.MILLISECONDS.toMinutes(millisecond) - TimeUnit.MILLISECONDS.toHours(millisecond) * 60L; diff --git a/src/main/scala/me/skymc/taboolib/string/VariableFormatter.java b/src/main/scala/io/izzel/taboolib/util/Variables.java similarity index 88% rename from src/main/scala/me/skymc/taboolib/string/VariableFormatter.java rename to src/main/scala/io/izzel/taboolib/util/Variables.java index 84567e0..7ee842c 100644 --- a/src/main/scala/me/skymc/taboolib/string/VariableFormatter.java +++ b/src/main/scala/io/izzel/taboolib/util/Variables.java @@ -1,6 +1,4 @@ -package me.skymc.taboolib.string; - -import com.ilummc.tlib.util.Strings; +package io.izzel.taboolib.util; import java.util.ArrayList; import java.util.List; @@ -11,34 +9,34 @@ import java.util.regex.Pattern; * @Author sky * @Since 2018-05-27 11:33 */ -public class VariableFormatter { +public class Variables { private Pattern pattern; private String text; private String textOrigin; private List variableList = new ArrayList<>(); - public VariableFormatter(String text) { + public Variables(String text) { this(text, "<([^<>]+)>"); } - public VariableFormatter(String text, String regex) { + public Variables(String text, String regex) { this(text, Pattern.compile(regex)); } - public VariableFormatter(String text, Pattern pattern) { + public Variables(String text, Pattern pattern) { this.text = text; this.textOrigin = text; this.pattern = pattern; } - public VariableFormatter reset() { + public Variables reset() { text = textOrigin; variableList.clear(); return this; } - public VariableFormatter find() { + public Variables find() { reset(); Matcher matcher = pattern.matcher(text); while (matcher.find()) { diff --git a/src/main/scala/com/ilummc/tlib/util/asm/AsmAnalyser.java b/src/main/scala/io/izzel/taboolib/util/asm/AsmAnalyser.java similarity index 96% rename from src/main/scala/com/ilummc/tlib/util/asm/AsmAnalyser.java rename to src/main/scala/io/izzel/taboolib/util/asm/AsmAnalyser.java index 58ce0d5..e1a81e2 100644 --- a/src/main/scala/com/ilummc/tlib/util/asm/AsmAnalyser.java +++ b/src/main/scala/io/izzel/taboolib/util/asm/AsmAnalyser.java @@ -1,4 +1,4 @@ -package com.ilummc.tlib.util.asm; +package io.izzel.taboolib.util.asm; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; diff --git a/src/main/scala/com/ilummc/tlib/util/asm/AsmClassLoader.java b/src/main/scala/io/izzel/taboolib/util/asm/AsmClassLoader.java similarity index 93% rename from src/main/scala/com/ilummc/tlib/util/asm/AsmClassLoader.java rename to src/main/scala/io/izzel/taboolib/util/asm/AsmClassLoader.java index e65beeb..72ea750 100644 --- a/src/main/scala/com/ilummc/tlib/util/asm/AsmClassLoader.java +++ b/src/main/scala/io/izzel/taboolib/util/asm/AsmClassLoader.java @@ -1,4 +1,4 @@ -package com.ilummc.tlib.util.asm; +package io.izzel.taboolib.util.asm; public class AsmClassLoader extends ClassLoader { diff --git a/src/main/scala/com/ilummc/tlib/util/asm/AsmClassTransformer.java b/src/main/scala/io/izzel/taboolib/util/asm/AsmClassTransformer.java similarity index 99% rename from src/main/scala/com/ilummc/tlib/util/asm/AsmClassTransformer.java rename to src/main/scala/io/izzel/taboolib/util/asm/AsmClassTransformer.java index 7819a46..a4048d0 100644 --- a/src/main/scala/com/ilummc/tlib/util/asm/AsmClassTransformer.java +++ b/src/main/scala/io/izzel/taboolib/util/asm/AsmClassTransformer.java @@ -1,4 +1,4 @@ -package com.ilummc.tlib.util.asm; +package io.izzel.taboolib.util.asm; import org.bukkit.Bukkit; diff --git a/src/main/scala/me/skymc/taboolib/bookformatter/BookAchievement.java b/src/main/scala/io/izzel/taboolib/util/book/BookAchievement.java similarity index 98% rename from src/main/scala/me/skymc/taboolib/bookformatter/BookAchievement.java rename to src/main/scala/io/izzel/taboolib/util/book/BookAchievement.java index c6fb671..352aee0 100644 --- a/src/main/scala/me/skymc/taboolib/bookformatter/BookAchievement.java +++ b/src/main/scala/io/izzel/taboolib/util/book/BookAchievement.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.bookformatter; +package io.izzel.taboolib.util.book; import org.bukkit.Achievement; diff --git a/src/main/scala/me/skymc/taboolib/bookformatter/BookFormatter.java b/src/main/scala/io/izzel/taboolib/util/book/BookFormatter.java similarity index 52% rename from src/main/scala/me/skymc/taboolib/bookformatter/BookFormatter.java rename to src/main/scala/io/izzel/taboolib/util/book/BookFormatter.java index 0931219..37cf2c4 100644 --- a/src/main/scala/me/skymc/taboolib/bookformatter/BookFormatter.java +++ b/src/main/scala/io/izzel/taboolib/util/book/BookFormatter.java @@ -1,8 +1,6 @@ -package me.skymc.taboolib.bookformatter; +package io.izzel.taboolib.util.book; -import me.skymc.taboolib.bookformatter.builder.BookBuilder; -import me.skymc.taboolib.events.CustomBookOpenEvent; -import org.bukkit.Bukkit; +import io.izzel.taboolib.util.book.builder.BookBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -15,33 +13,6 @@ public final class BookFormatter { * @param p the player * @param book the book to be opened */ - public static void openPlayer(Player p, ItemStack book) { - CustomBookOpenEvent event = new CustomBookOpenEvent(p, book, false); - //Call the CustomBookOpenEvent - Bukkit.getPluginManager().callEvent(event); - //Check if it's cancelled - if(event.isCancelled()) { - return; - } - - //Close inventory currently - p.closeInventory(); - //Store the previous item - ItemStack hand = p.getItemInHand(); - p.setItemInHand(event.getBook()); - - //Opening the GUI - BookReflection.openBook(p, event.getBook(), event.getHand() == CustomBookOpenEvent.Hand.OFF_HAND); - - //Returning whatever was on hand. - p.setItemInHand(hand); - } - - /** - * Opens a book GUI to the player, Bypass the {@link CustomBookOpenEvent} - * @param p the player - * @param book the book to be opened - */ public static void forceOpen(Player p, ItemStack book) { //Close inventory currently p.closeInventory(); diff --git a/src/main/scala/me/skymc/taboolib/bookformatter/BookReflection.java b/src/main/scala/io/izzel/taboolib/util/book/BookReflection.java similarity index 97% rename from src/main/scala/me/skymc/taboolib/bookformatter/BookReflection.java rename to src/main/scala/io/izzel/taboolib/util/book/BookReflection.java index b090544..d3ed8a6 100644 --- a/src/main/scala/me/skymc/taboolib/bookformatter/BookReflection.java +++ b/src/main/scala/io/izzel/taboolib/util/book/BookReflection.java @@ -1,10 +1,9 @@ -package me.skymc.taboolib.bookformatter; +package io.izzel.taboolib.util.book; -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 io.izzel.taboolib.util.chat.BaseComponent; +import io.izzel.taboolib.util.chat.TextComponent; +import io.izzel.taboolib.util.chat.ComponentSerializer; +import io.izzel.taboolib.module.locale.logger.TLogger; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -14,7 +13,6 @@ 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; diff --git a/src/main/scala/me/skymc/taboolib/bookformatter/action/ClickAction.java b/src/main/scala/io/izzel/taboolib/util/book/action/ClickAction.java similarity index 96% rename from src/main/scala/me/skymc/taboolib/bookformatter/action/ClickAction.java rename to src/main/scala/io/izzel/taboolib/util/book/action/ClickAction.java index 428c447..ec68a81 100644 --- a/src/main/scala/me/skymc/taboolib/bookformatter/action/ClickAction.java +++ b/src/main/scala/io/izzel/taboolib/util/book/action/ClickAction.java @@ -1,6 +1,6 @@ -package me.skymc.taboolib.bookformatter.action; +package io.izzel.taboolib.util.book.action; -import com.ilummc.tlib.bungee.api.chat.ClickEvent; +import io.izzel.taboolib.util.chat.ClickEvent; /** * @author sky diff --git a/src/main/scala/me/skymc/taboolib/bookformatter/action/HoverAction.java b/src/main/scala/io/izzel/taboolib/util/book/action/HoverAction.java similarity index 93% rename from src/main/scala/me/skymc/taboolib/bookformatter/action/HoverAction.java rename to src/main/scala/io/izzel/taboolib/util/book/action/HoverAction.java index 48bad9f..3f8c53a 100644 --- a/src/main/scala/me/skymc/taboolib/bookformatter/action/HoverAction.java +++ b/src/main/scala/io/izzel/taboolib/util/book/action/HoverAction.java @@ -1,10 +1,10 @@ -package me.skymc.taboolib.bookformatter.action; +package io.izzel.taboolib.util.book.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 io.izzel.taboolib.util.chat.BaseComponent; +import io.izzel.taboolib.util.chat.HoverEvent; +import io.izzel.taboolib.util.chat.TextComponent; +import io.izzel.taboolib.util.book.BookAchievement; +import io.izzel.taboolib.util.book.BookReflection; import org.bukkit.Achievement; import org.bukkit.entity.Entity; import org.bukkit.inventory.ItemStack; @@ -55,7 +55,7 @@ public interface HoverAction { * @return a new HoverAction instance */ static HoverAction showItem(ItemStack item) { - return new SimpleHoverAction(HoverEvent.Action.SHOW_ITEM, BookReflection.itemToComponents(item)); + return new SimpleHoverAction(HoverEvent.Action.SHOW_ITEM, io.izzel.taboolib.util.book.BookReflection.itemToComponents(item)); } /** diff --git a/src/main/scala/me/skymc/taboolib/bookformatter/builder/BookBuilder.java b/src/main/scala/io/izzel/taboolib/util/book/builder/BookBuilder.java similarity index 91% rename from src/main/scala/me/skymc/taboolib/bookformatter/builder/BookBuilder.java rename to src/main/scala/io/izzel/taboolib/util/book/builder/BookBuilder.java index d79d6f5..239d2f6 100644 --- a/src/main/scala/me/skymc/taboolib/bookformatter/builder/BookBuilder.java +++ b/src/main/scala/io/izzel/taboolib/util/book/builder/BookBuilder.java @@ -1,7 +1,7 @@ -package me.skymc.taboolib.bookformatter.builder; +package io.izzel.taboolib.util.book.builder; -import com.ilummc.tlib.bungee.api.chat.BaseComponent; -import me.skymc.taboolib.bookformatter.BookReflection; +import io.izzel.taboolib.util.chat.BaseComponent; +import io.izzel.taboolib.util.book.BookReflection; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; @@ -93,7 +93,7 @@ public class BookBuilder { * @return the BookBuilder's calling instance */ public BookBuilder pages(BaseComponent[]... pages) { - BookReflection.setPages(meta, pages); + io.izzel.taboolib.util.book.BookReflection.setPages(meta, pages); return this; } @@ -103,7 +103,7 @@ public class BookBuilder { * @return the BookBuilder's calling instance */ public BookBuilder pages(List pages) { - BookReflection.setPages(meta, pages.toArray(new BaseComponent[0][])); + io.izzel.taboolib.util.book.BookReflection.setPages(meta, pages.toArray(new BaseComponent[0][])); return this; } diff --git a/src/main/scala/me/skymc/taboolib/bookformatter/builder/PageBuilder.java b/src/main/scala/io/izzel/taboolib/util/book/builder/PageBuilder.java similarity index 82% rename from src/main/scala/me/skymc/taboolib/bookformatter/builder/PageBuilder.java rename to src/main/scala/io/izzel/taboolib/util/book/builder/PageBuilder.java index f95e033..3675af2 100644 --- a/src/main/scala/me/skymc/taboolib/bookformatter/builder/PageBuilder.java +++ b/src/main/scala/io/izzel/taboolib/util/book/builder/PageBuilder.java @@ -1,12 +1,8 @@ -package me.skymc.taboolib.bookformatter.builder; +package io.izzel.taboolib.util.book.builder; -import com.ilummc.tlib.bungee.api.chat.*; -import me.skymc.taboolib.string.ArrayUtils; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; +import io.izzel.taboolib.util.ArrayUtil; +import io.izzel.taboolib.util.chat.BaseComponent; +import io.izzel.taboolib.util.chat.TextComponent; /** * @author sky @@ -22,7 +18,7 @@ public class PageBuilder { * @return the PageBuilder's calling instance */ public PageBuilder add(String text) { - Arrays.stream(TextComponent.fromLegacyText(text)).forEach(component -> this.text = ArrayUtils.arrayAppend(this.text, component)); + java.util.Arrays.stream(TextComponent.fromLegacyText(text)).forEach(component -> this.text = ArrayUtil.arrayAppend(this.text, component)); return this; } @@ -32,7 +28,7 @@ public class PageBuilder { * @return the PageBuilder's calling instance */ public PageBuilder add(BaseComponent component) { - this.text = ArrayUtils.arrayAppend(this.text, component); + this.text = ArrayUtil.arrayAppend(this.text, component); return this; } @@ -42,7 +38,7 @@ public class PageBuilder { * @return the PageBuilder's calling instance */ public PageBuilder add(BaseComponent... components) { - Arrays.stream(components).forEach(component -> this.text = ArrayUtils.arrayAppend(this.text, component)); + java.util.Arrays.stream(components).forEach(component -> this.text = ArrayUtil.arrayAppend(this.text, component)); return this; } diff --git a/src/main/scala/me/skymc/taboolib/bookformatter/builder/TextBuilder.java b/src/main/scala/io/izzel/taboolib/util/book/builder/TextBuilder.java similarity index 81% rename from src/main/scala/me/skymc/taboolib/bookformatter/builder/TextBuilder.java rename to src/main/scala/io/izzel/taboolib/util/book/builder/TextBuilder.java index 34a271c..a587ac7 100644 --- a/src/main/scala/me/skymc/taboolib/bookformatter/builder/TextBuilder.java +++ b/src/main/scala/io/izzel/taboolib/util/book/builder/TextBuilder.java @@ -1,8 +1,11 @@ -package me.skymc.taboolib.bookformatter.builder; +package io.izzel.taboolib.util.book.builder; -import com.ilummc.tlib.bungee.api.chat.*; -import me.skymc.taboolib.bookformatter.action.ClickAction; -import me.skymc.taboolib.bookformatter.action.HoverAction; +import io.izzel.taboolib.util.chat.BaseComponent; +import io.izzel.taboolib.util.chat.ClickEvent; +import io.izzel.taboolib.util.chat.HoverEvent; +import io.izzel.taboolib.util.chat.TextComponent; +import io.izzel.taboolib.util.book.action.ClickAction; +import io.izzel.taboolib.util.book.action.HoverAction; /** * @author sky diff --git a/src/main/scala/com/ilummc/tlib/bungee/api/chat/BaseComponent.java b/src/main/scala/io/izzel/taboolib/util/chat/BaseComponent.java similarity index 93% rename from src/main/scala/com/ilummc/tlib/bungee/api/chat/BaseComponent.java rename to src/main/scala/io/izzel/taboolib/util/chat/BaseComponent.java index 493fc45..c16b044 100644 --- a/src/main/scala/com/ilummc/tlib/bungee/api/chat/BaseComponent.java +++ b/src/main/scala/io/izzel/taboolib/util/chat/BaseComponent.java @@ -1,7 +1,4 @@ -package com.ilummc.tlib.bungee.api.chat; - -import com.ilummc.tlib.bungee.api.ChatColor; -import com.ilummc.tlib.bungee.api.chat.ComponentBuilder.FormatRetention; +package io.izzel.taboolib.util.chat; import java.util.ArrayList; import java.util.List; @@ -129,7 +126,7 @@ public abstract class BaseComponent { } BaseComponent(BaseComponent old) { - copyFormatting(old, FormatRetention.ALL, true); + copyFormatting(old, ComponentBuilder.FormatRetention.ALL, true); if (old.getExtra() != null) { for (BaseComponent extra : old.getExtra()) { @@ -145,7 +142,7 @@ public abstract class BaseComponent { * @param component the component to copy from */ public void copyFormatting(BaseComponent component) { - copyFormatting(component, FormatRetention.ALL, true); + copyFormatting(component, ComponentBuilder.FormatRetention.ALL, true); } /** @@ -156,7 +153,7 @@ public abstract class BaseComponent { * component */ public void copyFormatting(BaseComponent component, boolean replace) { - copyFormatting(component, FormatRetention.ALL, replace); + copyFormatting(component, ComponentBuilder.FormatRetention.ALL, replace); } /** @@ -167,8 +164,8 @@ public abstract class BaseComponent { * @param replace if already set formatting should be replaced by the new * component */ - public void copyFormatting(BaseComponent component, FormatRetention retention, boolean replace) { - if (retention == FormatRetention.EVENTS || retention == FormatRetention.ALL) { + public void copyFormatting(BaseComponent component, ComponentBuilder.FormatRetention retention, boolean replace) { + if (retention == ComponentBuilder.FormatRetention.EVENTS || retention == ComponentBuilder.FormatRetention.ALL) { if (replace || clickEvent == null) { setClickEvent(component.getClickEvent()); } @@ -176,7 +173,7 @@ public abstract class BaseComponent { setHoverEvent(component.getHoverEvent()); } } - if (retention == FormatRetention.FORMATTING || retention == FormatRetention.ALL) { + if (retention == ComponentBuilder.FormatRetention.FORMATTING || retention == ComponentBuilder.FormatRetention.ALL) { if (replace || color == null) { setColor(component.getColorRaw()); } @@ -206,12 +203,12 @@ public abstract class BaseComponent { * * @param retention the formatting to retain */ - public void retain(FormatRetention retention) { - if (retention == FormatRetention.FORMATTING || retention == FormatRetention.NONE) { + public void retain(ComponentBuilder.FormatRetention retention) { + if (retention == ComponentBuilder.FormatRetention.FORMATTING || retention == ComponentBuilder.FormatRetention.NONE) { setClickEvent(null); setHoverEvent(null); } - if (retention == FormatRetention.EVENTS || retention == FormatRetention.NONE) { + if (retention == ComponentBuilder.FormatRetention.EVENTS || retention == ComponentBuilder.FormatRetention.NONE) { setColor(null); setBold(null); setItalic(null); @@ -238,7 +235,7 @@ public abstract class BaseComponent { @Deprecated public BaseComponent duplicateWithoutFormatting() { BaseComponent component = duplicate(); - component.retain(FormatRetention.NONE); + component.retain(ComponentBuilder.FormatRetention.NONE); return component; } diff --git a/src/main/scala/com/ilummc/tlib/bungee/chat/BaseComponentSerializer.java b/src/main/scala/io/izzel/taboolib/util/chat/BaseComponentSerializer.java similarity index 95% rename from src/main/scala/com/ilummc/tlib/bungee/chat/BaseComponentSerializer.java rename to src/main/scala/io/izzel/taboolib/util/chat/BaseComponentSerializer.java index e01e51a..a7be0db 100644 --- a/src/main/scala/com/ilummc/tlib/bungee/chat/BaseComponentSerializer.java +++ b/src/main/scala/io/izzel/taboolib/util/chat/BaseComponentSerializer.java @@ -1,13 +1,9 @@ -package com.ilummc.tlib.bungee.chat; +package io.izzel.taboolib.util.chat; import com.google.common.base.Preconditions; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; -import com.ilummc.tlib.bungee.api.ChatColor; -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 java.util.Arrays; import java.util.HashSet; diff --git a/src/main/scala/com/ilummc/tlib/bungee/api/ChatColor.java b/src/main/scala/io/izzel/taboolib/util/chat/ChatColor.java similarity index 99% rename from src/main/scala/com/ilummc/tlib/bungee/api/ChatColor.java rename to src/main/scala/io/izzel/taboolib/util/chat/ChatColor.java index 752b7be..1a895f4 100644 --- a/src/main/scala/com/ilummc/tlib/bungee/api/ChatColor.java +++ b/src/main/scala/io/izzel/taboolib/util/chat/ChatColor.java @@ -1,4 +1,4 @@ -package com.ilummc.tlib.bungee.api; +package io.izzel.taboolib.util.chat; import java.util.HashMap; import java.util.Map; diff --git a/src/main/scala/com/ilummc/tlib/bungee/api/ChatMessageType.java b/src/main/scala/io/izzel/taboolib/util/chat/ChatMessageType.java similarity index 81% rename from src/main/scala/com/ilummc/tlib/bungee/api/ChatMessageType.java rename to src/main/scala/io/izzel/taboolib/util/chat/ChatMessageType.java index 788cf5e..4429e41 100644 --- a/src/main/scala/com/ilummc/tlib/bungee/api/ChatMessageType.java +++ b/src/main/scala/io/izzel/taboolib/util/chat/ChatMessageType.java @@ -1,4 +1,4 @@ -package com.ilummc.tlib.bungee.api; +package io.izzel.taboolib.util.chat; /** * Represents the position on the screen where a message will appear. diff --git a/src/main/scala/com/ilummc/tlib/bungee/api/chat/ClickEvent.java b/src/main/scala/io/izzel/taboolib/util/chat/ClickEvent.java similarity index 96% rename from src/main/scala/com/ilummc/tlib/bungee/api/chat/ClickEvent.java rename to src/main/scala/io/izzel/taboolib/util/chat/ClickEvent.java index c7124e8..1a302b2 100644 --- a/src/main/scala/com/ilummc/tlib/bungee/api/chat/ClickEvent.java +++ b/src/main/scala/io/izzel/taboolib/util/chat/ClickEvent.java @@ -1,4 +1,4 @@ -package com.ilummc.tlib.bungee.api.chat; +package io.izzel.taboolib.util.chat; /** * @author md_5 diff --git a/src/main/scala/com/ilummc/tlib/bungee/api/chat/ComponentBuilder.java b/src/main/scala/io/izzel/taboolib/util/chat/ComponentBuilder.java similarity index 99% rename from src/main/scala/com/ilummc/tlib/bungee/api/chat/ComponentBuilder.java rename to src/main/scala/io/izzel/taboolib/util/chat/ComponentBuilder.java index 1b0100f..b5bdf48 100644 --- a/src/main/scala/com/ilummc/tlib/bungee/api/chat/ComponentBuilder.java +++ b/src/main/scala/io/izzel/taboolib/util/chat/ComponentBuilder.java @@ -1,7 +1,6 @@ -package com.ilummc.tlib.bungee.api.chat; +package io.izzel.taboolib.util.chat; import com.google.common.base.Preconditions; -import com.ilummc.tlib.bungee.api.ChatColor; import java.util.ArrayList; import java.util.List; diff --git a/src/main/scala/com/ilummc/tlib/bungee/chat/ComponentSerializer.java b/src/main/scala/io/izzel/taboolib/util/chat/ComponentSerializer.java similarity index 89% rename from src/main/scala/com/ilummc/tlib/bungee/chat/ComponentSerializer.java rename to src/main/scala/io/izzel/taboolib/util/chat/ComponentSerializer.java index 6d19961..f91c0c0 100644 --- a/src/main/scala/com/ilummc/tlib/bungee/chat/ComponentSerializer.java +++ b/src/main/scala/io/izzel/taboolib/util/chat/ComponentSerializer.java @@ -1,12 +1,8 @@ -package com.ilummc.tlib.bungee.chat; +package io.izzel.taboolib.util.chat; import com.google.gson.*; -import com.ilummc.tlib.bungee.api.chat.BaseComponent; -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/scala/com/ilummc/tlib/bungee/api/chat/HoverEvent.java b/src/main/scala/io/izzel/taboolib/util/chat/HoverEvent.java similarity index 94% rename from src/main/scala/com/ilummc/tlib/bungee/api/chat/HoverEvent.java rename to src/main/scala/io/izzel/taboolib/util/chat/HoverEvent.java index 1825ce4..7313068 100644 --- a/src/main/scala/com/ilummc/tlib/bungee/api/chat/HoverEvent.java +++ b/src/main/scala/io/izzel/taboolib/util/chat/HoverEvent.java @@ -1,4 +1,4 @@ -package com.ilummc.tlib.bungee.api.chat; +package io.izzel.taboolib.util.chat; import java.util.Arrays; diff --git a/src/main/scala/com/ilummc/tlib/bungee/api/chat/TextComponent.java b/src/main/scala/io/izzel/taboolib/util/chat/TextComponent.java similarity index 98% rename from src/main/scala/com/ilummc/tlib/bungee/api/chat/TextComponent.java rename to src/main/scala/io/izzel/taboolib/util/chat/TextComponent.java index 28d935c..6c7652f 100644 --- a/src/main/scala/com/ilummc/tlib/bungee/api/chat/TextComponent.java +++ b/src/main/scala/io/izzel/taboolib/util/chat/TextComponent.java @@ -3,9 +3,7 @@ // (powered by Fernflower decompiler) // -package com.ilummc.tlib.bungee.api.chat; - -import com.ilummc.tlib.bungee.api.ChatColor; +package io.izzel.taboolib.util.chat; import java.beans.ConstructorProperties; import java.util.ArrayList; diff --git a/src/main/scala/com/ilummc/tlib/bungee/chat/TextComponentSerializer.java b/src/main/scala/io/izzel/taboolib/util/chat/TextComponentSerializer.java similarity index 89% rename from src/main/scala/com/ilummc/tlib/bungee/chat/TextComponentSerializer.java rename to src/main/scala/io/izzel/taboolib/util/chat/TextComponentSerializer.java index 9fccef9..4f6dee7 100644 --- a/src/main/scala/com/ilummc/tlib/bungee/chat/TextComponentSerializer.java +++ b/src/main/scala/io/izzel/taboolib/util/chat/TextComponentSerializer.java @@ -3,11 +3,9 @@ // (powered by Fernflower decompiler) // -package com.ilummc.tlib.bungee.chat; +package io.izzel.taboolib.util.chat; import com.google.gson.*; -import com.ilummc.tlib.bungee.api.chat.BaseComponent; -import com.ilummc.tlib.bungee.api.chat.TextComponent; import java.lang.reflect.Type; import java.util.List; diff --git a/src/main/scala/com/ilummc/tlib/bungee/api/chat/TranslatableComponent.java b/src/main/scala/io/izzel/taboolib/util/chat/TranslatableComponent.java similarity index 98% rename from src/main/scala/com/ilummc/tlib/bungee/api/chat/TranslatableComponent.java rename to src/main/scala/io/izzel/taboolib/util/chat/TranslatableComponent.java index 23e3864..1683af6 100644 --- a/src/main/scala/com/ilummc/tlib/bungee/api/chat/TranslatableComponent.java +++ b/src/main/scala/io/izzel/taboolib/util/chat/TranslatableComponent.java @@ -1,6 +1,4 @@ -package com.ilummc.tlib.bungee.api.chat; - -import com.ilummc.tlib.bungee.api.ChatColor; +package io.izzel.taboolib.util.chat; import java.util.ArrayList; import java.util.List; diff --git a/src/main/scala/com/ilummc/tlib/bungee/chat/TranslatableComponentSerializer.java b/src/main/scala/io/izzel/taboolib/util/chat/TranslatableComponentSerializer.java similarity index 90% rename from src/main/scala/com/ilummc/tlib/bungee/chat/TranslatableComponentSerializer.java rename to src/main/scala/io/izzel/taboolib/util/chat/TranslatableComponentSerializer.java index e2be31f..dfbd165 100644 --- a/src/main/scala/com/ilummc/tlib/bungee/chat/TranslatableComponentSerializer.java +++ b/src/main/scala/io/izzel/taboolib/util/chat/TranslatableComponentSerializer.java @@ -3,11 +3,9 @@ // (powered by Fernflower decompiler) // -package com.ilummc.tlib.bungee.chat; +package io.izzel.taboolib.util.chat; import com.google.gson.*; -import com.ilummc.tlib.bungee.api.chat.BaseComponent; -import com.ilummc.tlib.bungee.api.chat.TranslatableComponent; import java.lang.reflect.Type; import java.util.Arrays; diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/ItemBuilder.java b/src/main/scala/io/izzel/taboolib/util/item/ItemBuilder.java similarity index 88% rename from src/main/scala/me/skymc/taboolib/inventory/builder/ItemBuilder.java rename to src/main/scala/io/izzel/taboolib/util/item/ItemBuilder.java index b418223..6de7988 100644 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/ItemBuilder.java +++ b/src/main/scala/io/izzel/taboolib/util/item/ItemBuilder.java @@ -1,9 +1,8 @@ -package me.skymc.taboolib.inventory.builder; +package io.izzel.taboolib.util.item; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.string.ArrayUtils; -import org.bukkit.Bukkit; +import io.izzel.taboolib.Version; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.util.ArrayUtil; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.OfflinePlayer; @@ -16,7 +15,6 @@ import org.bukkit.inventory.meta.*; import org.bukkit.potion.PotionData; import org.bukkit.potion.PotionEffect; -import java.util.Arrays; import java.util.List; /** @@ -88,7 +86,7 @@ public class ItemBuilder { } public ItemBuilder lore(String... lore) { - itemMeta.setLore(ArrayUtils.asList(lore)); + itemMeta.setLore(ArrayUtil.asList(lore)); return this; } @@ -119,7 +117,7 @@ public class ItemBuilder { public ItemBuilder banner(Pattern... patterns) { if (itemMeta instanceof BannerMeta) { - Arrays.stream(patterns).forEach(pattern -> ((BannerMeta) itemMeta).addPattern(pattern)); + java.util.Arrays.stream(patterns).forEach(pattern -> ((BannerMeta) itemMeta).addPattern(pattern)); } return this; } @@ -167,7 +165,7 @@ public class ItemBuilder { } public ItemBuilder unbreakable(boolean value) { - if (TabooLib.getVersionNumber() >= 12000) { + if (Version.isAfter(Version.v1_12)) { itemMeta.setUnbreakable(value); } else { itemMeta.spigot().setUnbreakable(value); @@ -192,14 +190,4 @@ public class ItemBuilder { } return buildItem; } - - /** - * 从文本中获取物品(name:名字;lore:描述||描述;material:材质) - * - * @param str - * @return - */ - public static ItemStack fromString(String str) { - return null; - } } diff --git a/src/main/scala/io/izzel/taboolib/util/item/Items.java b/src/main/scala/io/izzel/taboolib/util/item/Items.java new file mode 100644 index 0000000..1a3a444 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/util/item/Items.java @@ -0,0 +1,286 @@ +package io.izzel.taboolib.util.item; + +import io.izzel.taboolib.Version; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.lite.SimpleI18n; +import io.izzel.taboolib.module.nms.NMS; +import io.izzel.taboolib.module.nms.nbt.NBTBase; +import io.izzel.taboolib.module.nms.nbt.NBTCompound; +import io.izzel.taboolib.module.nms.nbt.NBTList; +import io.izzel.taboolib.util.lite.Numbers; +import org.bukkit.Color; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.NumberConversions; + +import java.util.List; + +/** + * @Author 坏黑 + * @Since 2019-07-05 16:44 + */ +public class Items { + + public final static Integer[] INVENTORY_CENTER = { + 10, 11, 12, 13, 14, 15, 16, + 19, 20, 21, 22, 23, 24, 25, + 28, 29, 30, 31, 32, 33, 34, + 37, 38, 39, 40, 41, 42, 43 + }; + + public static String getName(ItemStack item) { + return SimpleI18n.getCustomName(item); + } + + public static boolean isNull(ItemStack item) { + return item == null || item.getType().equals(Material.AIR); + } + + public static boolean hasLore(ItemStack i, String a) { + return hasLore(i) && i.getItemMeta().getLore().toString().contains(a); + } + + public static boolean hasLore(ItemStack i) { + return !isNull(i) && i.getItemMeta().hasLore(); + } + + public static boolean hasName(ItemStack i) { + return !isNull(i) && i.getItemMeta().hasDisplayName(); + } + + public static Material asMaterial(String args) { + try { + Material material = Material.getMaterial(args.toUpperCase()); + return material != null ? material : Material.getMaterial(Integer.valueOf(args)); + } catch (Exception e) { + return Material.STONE; + } + } + + 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 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 ItemFlag asItemFlag(String flag) { + try { + return ItemFlag.valueOf(flag); + } 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); + } + } + + public static String asAttribute(String name) { + switch (name.toLowerCase()) { + case "damage": + return "generic.attackDamage"; + case "attackspeed": + return "generic.attackSpeed"; + case "health": + return "generic.maxHealth"; + case "speed": + return "generic.movementSpeed"; + case "knockback": + return "generic.knockbackResistance"; + case "armor": + return "generic.armor"; + case "luck": + return "generic.luck"; + default: + return null; + } + } + + public static ItemStack replaceLore(ItemStack item, String loreOld, String loreNew) { + if (hasLore(item)) { + ItemMeta meta = item.getItemMeta(); + List lore = meta.getLore(); + for (int i = 0; i < lore.size(); i++) { + lore.set(i, lore.get(i).replace(loreOld, loreNew)); + } + meta.setLore(lore); + item.setItemMeta(meta); + } + return item; + } + + public static boolean checkItem(Player player, ItemStack item, int amount, boolean remove) { + return checkItem(player.getInventory(), item, amount, remove); + } + + public static boolean checkItem(Inventory inventory, ItemStack item, int amount, boolean remove) { + int hasAmount = 0; + for (ItemStack _item : inventory) { + if (item.isSimilar(_item)) { + hasAmount += _item.getAmount(); + } + } + if (hasAmount < amount) { + return false; + } + int requireAmount = amount; + for (int i = 0; i < inventory.getSize() && remove; i++) { + ItemStack _item = inventory.getItem(i); + if (_item != null && _item.isSimilar(item)) { + if (_item.getAmount() < requireAmount) { + inventory.setItem(i, null); + requireAmount -= _item.getAmount(); + } else if (_item.getAmount() == requireAmount) { + inventory.setItem(i, null); + return true; + } else { + _item.setAmount(_item.getAmount() - requireAmount); + return true; + } + } + } + return true; + } + + public static ItemStack loadItem(ConfigurationSection section) { + 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(section.getString("name")); + } + // 描述 + if (section.contains("lore")) { + meta.setLore(section.getStringList("lore")); + } + // 附魔 + if (section.contains("enchant")) { + for (String preEnchant : section.getConfigurationSection("enchant").getKeys(false)) { + Enchantment enchant = asEnchantment(preEnchant); + if (enchant != null) { + meta.addEnchant(enchant, section.getInt("enchant." + preEnchant), true); + } else { + TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ENCHANTS", preEnchant); + } + } + } + // 标签 + if (section.contains("flags") && Version.isAfter(Version.v1_8)) { + 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, + NumberConversions.toInt(section.getString("potions." + prePotionName).split("-")[0]), + NumberConversions.toInt(section.getString("potions." + prePotionName).split("-")[1]) - 1), true); + } else { + TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", prePotionName); + } + } + } + // 元数据 + item.setItemMeta(meta); + // 数据 + NBTCompound nbt = NMS.handle().loadNBT(item); + // 物品标签 + if (section.contains("nbt")) { + for (String name : section.getConfigurationSection("nbt").getKeys(false)) { + Object obj = section.get("nbt." + name); + if (obj instanceof String) { + nbt.put(name, new NBTBase(obj.toString())); + } else if (obj instanceof Double) { + nbt.put(name, new NBTBase(NumberConversions.toDouble(obj))); + } else if (obj instanceof Integer) { + nbt.put(name, new NBTBase(NumberConversions.toInt(obj))); + } else if (obj instanceof Long) { + nbt.put(name, new NBTBase(NumberConversions.toLong(obj))); + } + } + } + // 物品属性 + if (section.contains("attributes")) { + NBTList attr = new NBTList(); + for (String hand : section.getConfigurationSection("attributes").getKeys(false)) { + for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) { + if (asAttribute(name) != null) { + try { + NBTCompound a = new NBTCompound(); + String num = section.getString("attributes." + hand + "." + name); + if (num.endsWith("%")) { + a.put("Amount", new NBTBase(NumberConversions.toDouble(num.substring(0, num.length() - 1)) / 100D)); + a.put("Operation", new NBTBase(1)); + } else { + a.put("Amount", new NBTBase(NumberConversions.toDouble(num))); + a.put("Operation", new NBTBase(0)); + } + a.put("AttributeName", new NBTBase(asAttribute(name))); + a.put("UUIDMost", new NBTBase(Numbers.getRandom().nextInt(Integer.MAX_VALUE))); + a.put("UUIDLeast", new NBTBase(Numbers.getRandom().nextInt(Integer.MAX_VALUE))); + a.put("Name", new NBTBase(asAttribute(name))); + if (!hand.equals("all")) { + a.put("Slot", new NBTBase(hand)); + } + attr.add(a); + } catch (Exception ignored) { + } + } else { + TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", name); + } + } + } + nbt.put("AttributeModifiers", attr); + } + return NMS.handle().saveNBT(item, nbt); + } +} diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickEvent.java b/src/main/scala/io/izzel/taboolib/util/item/inventory/ClickEvent.java similarity index 95% rename from src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickEvent.java rename to src/main/scala/io/izzel/taboolib/util/item/inventory/ClickEvent.java index 913797f..6d50c32 100644 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickEvent.java +++ b/src/main/scala/io/izzel/taboolib/util/item/inventory/ClickEvent.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.inventory.builder.v2; +package io.izzel.taboolib.util.item.inventory; import org.bukkit.entity.Player; import org.bukkit.event.Event; diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickListener.java b/src/main/scala/io/izzel/taboolib/util/item/inventory/ClickListener.java similarity index 96% rename from src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickListener.java rename to src/main/scala/io/izzel/taboolib/util/item/inventory/ClickListener.java index 5cbb4b7..3aab994 100644 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickListener.java +++ b/src/main/scala/io/izzel/taboolib/util/item/inventory/ClickListener.java @@ -1,6 +1,6 @@ -package me.skymc.taboolib.inventory.builder.v2; +package io.izzel.taboolib.util.item.inventory; -import me.skymc.taboolib.listener.TListener; +import io.izzel.taboolib.module.inject.TListener; import org.bukkit.Bukkit; import org.bukkit.entity.HumanEntity; import org.bukkit.event.EventHandler; diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickListener1_9.java b/src/main/scala/io/izzel/taboolib/util/item/inventory/ClickListenerOffhand.java similarity index 78% rename from src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickListener1_9.java rename to src/main/scala/io/izzel/taboolib/util/item/inventory/ClickListenerOffhand.java index 206f02e..4296c2e 100644 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickListener1_9.java +++ b/src/main/scala/io/izzel/taboolib/util/item/inventory/ClickListenerOffhand.java @@ -1,6 +1,6 @@ -package me.skymc.taboolib.inventory.builder.v2; +package io.izzel.taboolib.util.item.inventory; -import me.skymc.taboolib.listener.TListener; +import io.izzel.taboolib.module.inject.TListener; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerSwapHandItemsEvent; @@ -10,7 +10,7 @@ import org.bukkit.event.player.PlayerSwapHandItemsEvent; * @Since 2019-05-21 22:04 */ @TListener(version = ">=10900") -class ClickListener1_9 implements Listener { +class ClickListenerOffhand implements Listener { @EventHandler public void onSwap(PlayerSwapHandItemsEvent e) { diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickTask.java b/src/main/scala/io/izzel/taboolib/util/item/inventory/ClickTask.java similarity index 71% rename from src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickTask.java rename to src/main/scala/io/izzel/taboolib/util/item/inventory/ClickTask.java index fec7922..c474756 100644 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickTask.java +++ b/src/main/scala/io/izzel/taboolib/util/item/inventory/ClickTask.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.inventory.builder.v2; +package io.izzel.taboolib.util.item.inventory; /** * @Author 坏黑 diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickType.java b/src/main/scala/io/izzel/taboolib/util/item/inventory/ClickType.java similarity index 67% rename from src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickType.java rename to src/main/scala/io/izzel/taboolib/util/item/inventory/ClickType.java index 5af5852..cb16edc 100644 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/ClickType.java +++ b/src/main/scala/io/izzel/taboolib/util/item/inventory/ClickType.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.inventory.builder.v2; +package io.izzel.taboolib.util.item.inventory; /** * @Author 坏黑 diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/CloseTask.java b/src/main/scala/io/izzel/taboolib/util/item/inventory/CloseTask.java similarity index 79% rename from src/main/scala/me/skymc/taboolib/inventory/builder/v2/CloseTask.java rename to src/main/scala/io/izzel/taboolib/util/item/inventory/CloseTask.java index 3e672a8..587aedc 100644 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/CloseTask.java +++ b/src/main/scala/io/izzel/taboolib/util/item/inventory/CloseTask.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.inventory.builder.v2; +package io.izzel.taboolib.util.item.inventory; import org.bukkit.event.inventory.InventoryCloseEvent; diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/MenuBuilder.java b/src/main/scala/io/izzel/taboolib/util/item/inventory/MenuBuilder.java similarity index 95% rename from src/main/scala/me/skymc/taboolib/inventory/builder/v2/MenuBuilder.java rename to src/main/scala/io/izzel/taboolib/util/item/inventory/MenuBuilder.java index 835fa52..8921eee 100644 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/MenuBuilder.java +++ b/src/main/scala/io/izzel/taboolib/util/item/inventory/MenuBuilder.java @@ -1,8 +1,8 @@ -package me.skymc.taboolib.inventory.builder.v2; +package io.izzel.taboolib.util.item.inventory; import com.google.common.collect.Maps; -import com.ilummc.tlib.util.Ref; -import me.skymc.taboolib.Main; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.util.Ref; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.Inventory; @@ -35,7 +35,7 @@ public class MenuBuilder { } public static MenuBuilder builder() { - return new MenuBuilder(Ref.getCallerPlugin(Ref.getCallerClass(3).orElse(Main.class))); + return new MenuBuilder(Ref.getCallerPlugin(Ref.getCallerClass(3).orElse(TabooLib.class))); } public MenuBuilder lockHand() { diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/MenuHolder.java b/src/main/scala/io/izzel/taboolib/util/item/inventory/MenuHolder.java similarity index 90% rename from src/main/scala/me/skymc/taboolib/inventory/builder/v2/MenuHolder.java rename to src/main/scala/io/izzel/taboolib/util/item/inventory/MenuHolder.java index 09912d3..44ee84f 100644 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/v2/MenuHolder.java +++ b/src/main/scala/io/izzel/taboolib/util/item/inventory/MenuHolder.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.inventory.builder.v2; +package io.izzel.taboolib.util.item.inventory; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; diff --git a/src/main/scala/io/izzel/taboolib/util/lite/Catchers.java b/src/main/scala/io/izzel/taboolib/util/lite/Catchers.java new file mode 100644 index 0000000..ff04a86 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/util/lite/Catchers.java @@ -0,0 +1,70 @@ +package io.izzel.taboolib.util.lite; + +import io.izzel.taboolib.TabooLib; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +import java.util.HashMap; +import java.util.LinkedList; + +public class Catchers implements Listener { + + private static HashMap> playerdata = new HashMap<>(); + + public static HashMap> getPlayerdata() { + return playerdata; + } + + public static boolean contains(Player player) { + return playerdata.containsKey(player.getName()) && playerdata.get(player.getName()).size() > 0; + } + + public static void call(Player player, Catcher catcher) { + if (!playerdata.containsKey(player.getName())) { + playerdata.put(player.getName(), new LinkedList<>()); + } + playerdata.get(player.getName()).add(catcher.before()); + } + + @EventHandler + public void quit(PlayerQuitEvent e) { + playerdata.remove(e.getPlayer().getName()); + } + + @EventHandler + public void chat(AsyncPlayerChatEvent e) { + if (playerdata.containsKey(e.getPlayer().getName()) && contains(e.getPlayer())) { + e.setCancelled(true); + // 1.14 supported. + Bukkit.getScheduler().runTask(TabooLib.getPlugin(), () -> { + // 退出 + if (e.getMessage().equalsIgnoreCase("quit()")) { + playerdata.get(e.getPlayer().getName()).removeFirst().cancel(); + } + // 默认 + else { + Catcher catcher = playerdata.get(e.getPlayer().getName()).getFirst(); + // 如果终止引导 + if (!catcher.after(e.getMessage())) { + playerdata.get(e.getPlayer().getName()).removeFirst(); + } else { + catcher.before(); + } + } + }); + } + } + + public interface Catcher { + + Catcher before(); + + boolean after(String message); + + void cancel(); + } +} diff --git a/src/main/scala/me/skymc/taboolib/fileutils/TLogs.java b/src/main/scala/io/izzel/taboolib/util/lite/Logs.java similarity index 66% rename from src/main/scala/me/skymc/taboolib/fileutils/TLogs.java rename to src/main/scala/io/izzel/taboolib/util/lite/Logs.java index 49f6c89..5f51572 100644 --- a/src/main/scala/me/skymc/taboolib/fileutils/TLogs.java +++ b/src/main/scala/io/izzel/taboolib/util/lite/Logs.java @@ -1,13 +1,14 @@ -package me.skymc.taboolib.fileutils; +package io.izzel.taboolib.util.lite; -import com.ilummc.tlib.resources.TLocale; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.commands.internal.BaseMainCommand; -import me.skymc.taboolib.commands.internal.BaseSubCommand; -import me.skymc.taboolib.commands.internal.TCommand; -import me.skymc.taboolib.commands.internal.type.CommandArgument; -import me.skymc.taboolib.commands.internal.type.CommandRegister; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.module.locale.TLocale; +import io.izzel.taboolib.module.command.base.BaseCommand; +import io.izzel.taboolib.module.command.base.BaseMainCommand; +import io.izzel.taboolib.module.command.base.BaseSubCommand; +import io.izzel.taboolib.module.command.base.Argument; +import io.izzel.taboolib.module.command.base.SubCommand; +import io.izzel.taboolib.util.Files; +import io.izzel.taboolib.util.Strings; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -20,12 +21,11 @@ import java.text.SimpleDateFormat; /** * @author sky */ -@TCommand( - name = "tabooliblogs", - aliases = {"tlog", "tlogs"}, +@BaseCommand( + name = "tLogs", permission = "taboolib.admin" ) -public class TLogs extends BaseMainCommand { +public class Logs extends BaseMainCommand { private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); @@ -34,7 +34,7 @@ public class TLogs extends BaseMainCommand { return TLocale.asString("COMMANDS.TLOGS.COMMAND-TITLE"); } - @CommandRegister(priority = 0) + @SubCommand(priority = 0) BaseSubCommand info = new BaseSubCommand() { @Override public String getLabel() { @@ -47,10 +47,10 @@ public class TLogs extends BaseMainCommand { } @Override - public CommandArgument[] getArguments() { - return new CommandArgument[] { - new CommandArgument(TLocale.asString("COMMANDS.TLOGS.INFO.ARGUMENTS.0")), - new CommandArgument(TLocale.asString("COMMANDS.TLOGS.INFO.ARGUMENTS.1")) + public Argument[] getArguments() { + return new Argument[] { + new Argument(TLocale.asString("COMMANDS.TLOGS.INFO.ARGUMENTS.0")), + new Argument(TLocale.asString("COMMANDS.TLOGS.INFO.ARGUMENTS.1")) }; } @@ -63,7 +63,7 @@ public class TLogs extends BaseMainCommand { } }; - @CommandRegister(priority = 1) + @SubCommand(priority = 1) BaseSubCommand error = new BaseSubCommand() { @Override public String getLabel() { @@ -76,10 +76,10 @@ public class TLogs extends BaseMainCommand { } @Override - public CommandArgument[] getArguments() { - return new CommandArgument[] { - new CommandArgument(TLocale.asString("COMMANDS.TLOGS.ERROR.ARGUMENTS.0")), - new CommandArgument(TLocale.asString("COMMANDS.TLOGS.ERROR.ARGUMENTS.1")) + public Argument[] getArguments() { + return new Argument[] { + new Argument(TLocale.asString("COMMANDS.TLOGS.ERROR.ARGUMENTS.0")), + new Argument(TLocale.asString("COMMANDS.TLOGS.ERROR.ARGUMENTS.1")) }; } @@ -92,7 +92,7 @@ public class TLogs extends BaseMainCommand { } }; - @CommandRegister(priority = 2) + @SubCommand(priority = 2) BaseSubCommand warning = new BaseSubCommand() { @Override public String getLabel() { @@ -105,10 +105,10 @@ public class TLogs extends BaseMainCommand { } @Override - public CommandArgument[] getArguments() { - return new CommandArgument[] { - new CommandArgument(TLocale.asString("COMMANDS.TLOGS.WARNING.ARGUMENTS.0")), - new CommandArgument(TLocale.asString("COMMANDS.TLOGS.WARNING.ARGUMENTS.1")) + public Argument[] getArguments() { + return new Argument[] { + new Argument(TLocale.asString("COMMANDS.TLOGS.WARNING.ARGUMENTS.0")), + new Argument(TLocale.asString("COMMANDS.TLOGS.WARNING.ARGUMENTS.1")) }; } @@ -146,9 +146,8 @@ public class TLogs extends BaseMainCommand { } public static void write(File file, String format, String text) { - Bukkit.getScheduler().runTask(TabooLib.instance(), () -> { - FileUtils.createNewFileAndPath(file); - try (FileWriter writer = new FileWriter(file, true)) { + Bukkit.getScheduler().runTask(TabooLib.getPlugin(), () -> { + try (FileWriter writer = new FileWriter(Files.file(file), true)) { writer.write(Strings.replaceWithOrder(format, dateFormat.format(System.currentTimeMillis()), text)); } catch (Exception ignored) { } diff --git a/src/main/scala/io/izzel/taboolib/util/lite/Numbers.java b/src/main/scala/io/izzel/taboolib/util/lite/Numbers.java new file mode 100644 index 0000000..caec533 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/util/lite/Numbers.java @@ -0,0 +1,48 @@ +package io.izzel.taboolib.util.lite; + +import java.text.DecimalFormat; +import java.util.Random; + +/** + * @Author 坏黑 + * @Since 2019-07-05 19:02 + */ +public class Numbers { + + private static Random random = new Random(); + private static DecimalFormat doubleFormat = new DecimalFormat("#.##"); + + public static Random getRandom() { + return random; + } + + public static Double format(Double num) { + return Double.valueOf(doubleFormat.format(num)); + } + + public static int getRandomInteger(Number num1, Number num2) { + int min = Math.min(num1.intValue(), num2.intValue()); + int max = Math.max(num1.intValue(), num2.intValue()); + return (int) (random.nextDouble() * (max - min) + min); + } + + public static double getRandomDouble(Number num1, Number num2) { + double min = Math.min(num1.doubleValue(), num2.doubleValue()); + double max = Math.max(num1.doubleValue(), num2.doubleValue()); + return random.nextDouble() * (max - min) + min; + } + + public static Boolean getBoolean(String str) { + if (str == null || str.isEmpty()) { + return false; + } + char var = str.charAt(0); + if (var == 'y' || var == 'Y' || var == 't' || var == 'T' || var == '1') { + return true; + } + if (var == 'n' || var == 'N' || var == 'f' || var == 'F' || var == '0') { + return false; + } + return false; + } +} diff --git a/src/main/scala/io/izzel/taboolib/util/lite/Particles.java b/src/main/scala/io/izzel/taboolib/util/lite/Particles.java new file mode 100644 index 0000000..66c3fb5 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/util/lite/Particles.java @@ -0,0 +1,967 @@ +package io.izzel.taboolib.util.lite; + +import io.izzel.taboolib.Version; +import io.izzel.taboolib.module.nms.NMS; +import io.izzel.taboolib.module.packet.TPacketHandler; +import io.izzel.taboolib.util.Reflection; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.block.data.BlockData; +import org.bukkit.configuration.MemorySection; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.material.MaterialData; +import org.bukkit.util.NumberConversions; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Random; + +/** + * ParticleEffect Library + *

+ * This library was created by @DarkBlade12 and allows you to display all Minecraft particle effects on a Bukkit server + *

+ * You are welcome to use it, modify it and redistribute it under the following conditions: + *

+ *

+ * Special thanks: + *

+ *

+ * It would be nice if you provide credit to me if you use this class in a published project + * + * @author DarkBlade12 + * @version 1.8 + */ +public enum Particles { + + BARRIER, + BLOCK_CRACK(ParticleProperty.REQUIRES_DATA), + BLOCK_DUST(ParticleProperty.REQUIRES_DATA), + BUBBLE_COLUMN_UP(13), + BUBBLE_POP(13), + CLOUD, + CRIT, + CRIT_MAGIC, + CURRENT_DOWN(13), + DAMAGE_INDICATOR(9), + DOLPHIN(13), + DRAGON_BREATH(9), + DRIP_LAVA, + DRIP_WATER, + ENCHANTMENT_TABLE, + END_ROD(9), + EXPLOSION_HUGE, + EXPLOSION_LARGE, + EXPLOSION_NORMAL, + FALLING_DUST(10), + FIREWORKS_SPARK, + FLAME, + FOOTSTEP(0, 12), + HEART, + ITEM_CRACK(ParticleProperty.REQUIRES_DATA), + ITEM_TAKE, + LAVA, + MOB_APPEARANCE, + NAUTILUS(13), + NOTE(ParticleProperty.COLORABLE), + PORTAL, + REDSTONE(ParticleProperty.COLORABLE), + SLIME, + SMOKE_LARGE, + SMOKE_NORMAL, + SNOW_SHOVEL, + SNOWBALL, + SPELL, + SPELL_INSTANT, + SPELL_MOB(ParticleProperty.COLORABLE), + SPELL_MOB_AMBIENT(ParticleProperty.COLORABLE), + SPELL_WITCH, + SPIT(11), + SQUID_INK(13), + SUSPENDED, + SUSPENDED_DEPTH(0, 12), + SWEEP_ATTACK(9), + TOTEM(11), + TOWN_AURA, + VILLAGER_ANGRY, + VILLAGER_HAPPY, + WATER_BUBBLE, + WATER_DROP, + WATER_SPLASH, + WATER_WAKE, + ; + + private static int mcVersion = NumberConversions.toInt(Version.getBukkitVersion().split("_")[1]); + private org.bukkit.Particle bukkitParticle; + private final List properties; + private int min, max; + + Particles(ParticleProperty... properties) { + this(0, 0, properties); + } + + Particles(int min, ParticleProperty... properties) { + this(min, 0, properties); + } + + Particles(int min, int max, ParticleProperty... properties) { + this.properties = Arrays.asList(properties); + this.min = min; + this.max = max; + try { + bukkitParticle = org.bukkit.Particle.valueOf(this.name()); + } catch (IllegalArgumentException ex) { + bukkitParticle = null; + } + } + + public org.bukkit.Particle getBukkitParticle() { + return bukkitParticle; + } + + public int getMinimumVersion() { + return min; + } + + public int getMaximumVersion() { + return max; + } + + + /** + * Determine if this particle effect has a specific property + * + * @param property Property tested + * @return Whether it has the property or not + */ + public boolean hasProperty(ParticleProperty property) { + return properties.contains(property); + } + + /** + * Determine if this particle effect is supported by your current server version + * + * @return Whether the particle effect is supported or not + */ + public boolean isSupported() { + if (min != 0 && min > mcVersion) { + return false; + } + if (max != 0 && max < mcVersion) { + return false; + } + return bukkitParticle != null; + } + + /** + * Returns the particle effect with the given name + * + * @param name Name of the particle effect + * @return The particle effect + */ + public static Particles fromName(String name) { + for (Particles effect : values()) { + if (effect.name().equalsIgnoreCase(name)) { + if (!effect.isSupported()) { + throw new ParticleVersionException(); + } + return effect; + } + } + throw new IllegalArgumentException("ParticleEffect " + name + " doesn't exist."); + } + + /** + * Determine if the distance between @param location and one of the players exceeds 256 + * + * @param location Location to check + * @return Whether the distance exceeds 256 or not + */ + private static boolean isLongDistance(Location location, List players) { + String world = location.getWorld().getName(); + for (Player player : players) { + if (player == null) { + continue; + } + Location playerLocation = player.getLocation(); + if (!world.equals(playerLocation.getWorld().getName()) || playerLocation.distanceSquared(location) < 65536) { + continue; + } + return true; + } + return false; + } + + /** + * Determine if the data type for a particle effect is correct + * + * @param effect Particle effect + * @param data Particle data + * @return Whether the data type is correct or not + */ + private static boolean isDataCorrect(Particles effect, Object data) { + return ((effect == BLOCK_CRACK || effect == BLOCK_DUST) && (mcVersion < 13 ? data instanceof MaterialData : data instanceof BlockData)) || (effect == ITEM_CRACK && data instanceof ItemStack); + } + + /** + * Determine if the color type for a particle effect is correct + * + * @param effect Particle effect + * @param color Particle color + * @return Whether the color type is correct or not + */ + private static boolean isColorCorrect(Particles effect, ParticleColor color) { + return ((effect == SPELL_MOB || effect == SPELL_MOB_AMBIENT || effect == REDSTONE) && color instanceof OrdinaryColor) || (effect == NOTE && color instanceof NoteColor); + } + + /** + * Displays a particle effect which is only visible for all players within a certain range in the world of @param center + * + * @param offsetX Maximum distance particles can fly away from the center on the x-axis + * @param offsetY Maximum distance particles can fly away from the center on the y-axis + * @param offsetZ Maximum distance particles can fly away from the center on the z-axis + * @param speed Display speed of the particles + * @param amount Amount of particles + * @param center Center location of the effect + * @param range Range of the visibility + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ObjectException If the particle effect requires additional data + * @throws IllegalArgumentException If the particle effect requires water and none is at the center location + */ + public void display(double offsetX, double offsetY, double offsetZ, double speed, int amount, Location center, double range) throws ParticleVersionException, ObjectException, IllegalArgumentException { + if (!isSupported()) { + throw new ParticleVersionException(); + } + if (hasProperty(ParticleProperty.REQUIRES_DATA)) { + throw new ObjectException("This particle effect requires additional data"); + } + /*if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { + throw new IllegalArgumentException("There is no water at the center location"); + }*/ + new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256, null).sendTo(center, range); + } + + /** + * Displays a particle effect which is only visible for the specified players + * + * @param offsetX Maximum distance particles can fly away from the center on the x-axis + * @param offsetY Maximum distance particles can fly away from the center on the y-axis + * @param offsetZ Maximum distance particles can fly away from the center on the z-axis + * @param speed Display speed of the particles + * @param amount Amount of particles + * @param center Center location of the effect + * @param players Receivers of the effect + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ObjectException If the particle effect requires additional data + * @throws IllegalArgumentException If the particle effect requires water and none is at the center location + */ + public void display(double offsetX, double offsetY, double offsetZ, double speed, int amount, Location center, List players) throws ParticleVersionException, ObjectException, IllegalArgumentException { + if (!isSupported()) { + throw new ParticleVersionException(); + } + if (hasProperty(ParticleProperty.REQUIRES_DATA)) { + throw new ObjectException("This particle effect requires additional data"); + } + /*if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { + throw new IllegalArgumentException("There is no water at the center location"); + }*/ + new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), null).sendTo(center, players); + } + + /** + * Displays a single particle which is colored and only visible for all players within a certain range in the world of @param center + * + * @param color Color of the particle + * @param offsetX Maximum distance particles can fly away from the center on the x-axis + * @param offsetY Maximum distance particles can fly away from the center on the y-axis + * @param offsetZ Maximum distance particles can fly away from the center on the z-axis + * @param amount Amount of particles + * @param center Center location of the effect + * @param range Range of the visibility + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleColorException If the particle effect is not colorable or the color type is incorrect + */ + public void display(ParticleColor color, double offsetX, double offsetY, double offsetZ, int amount, Location center, double range) throws ParticleVersionException, ParticleColorException { + if (!isSupported()) { + throw new ParticleVersionException(); + } + if (!hasProperty(ParticleProperty.COLORABLE)) { + throw new ParticleColorException("This particle effect is not colorable"); + } + if (!isColorCorrect(this, color)) { + throw new ParticleColorException("The particle color type is incorrect"); + } + new ParticlePacket(this, offsetX, offsetY, offsetZ, 1, amount, range > 256, color).sendTo(center, range); + } + + /** + * Displays a single particle which is colored and only visible for the specified players + * + * @param color Color of the particle + * @param offsetX Maximum distance particles can fly away from the center on the x-axis + * @param offsetY Maximum distance particles can fly away from the center on the y-axis + * @param offsetZ Maximum distance particles can fly away from the center on the z-axis + * @param amount Amount of particles + * @param center Center location of the effect + * @param players Receivers of the effect + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleColorException If the particle effect is not colorable or the color type is incorrect + */ + public void display(ParticleColor color, double offsetX, double offsetY, double offsetZ, int amount, Location center, List players) throws ParticleVersionException, ParticleColorException { + if (!isSupported()) { + throw new ParticleVersionException(); + } + if (!hasProperty(ParticleProperty.COLORABLE)) { + throw new ParticleColorException("This particle effect is not colorable"); + } + if (!isColorCorrect(this, color)) { + throw new ParticleColorException("The particle color type is incorrect"); + } + new ParticlePacket(this, offsetX, offsetY, offsetZ, 1, amount, isLongDistance(center, players), color).sendTo(center, players); + } + + /** + * Displays a particle effect which requires additional data and is only visible for the specified players + * + * @param data Data of the effect + * @param offsetX Maximum distance particles can fly away from the center on the x-axis + * @param offsetY Maximum distance particles can fly away from the center on the y-axis + * @param offsetZ Maximum distance particles can fly away from the center on the z-axis + * @param speed Display speed of the particles + * @param amount Amount of particles + * @param center Center location of the effect + * @param players Receivers of the effect + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ObjectException If the particle effect does not require additional data or if the data type is incorrect + */ + public void display(Object data, double offsetX, double offsetY, double offsetZ, double speed, int amount, Location center, List players) throws ParticleVersionException, ObjectException { + if (!isSupported()) { + throw new ParticleVersionException(); + } + if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { + throw new ObjectException("This particle effect does not require additional data"); + } + if (!isDataCorrect(this, data)) { + throw new ObjectException("The particle data type is incorrect"); + } + new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), data).sendTo(center, players); + } + + /** + * Represents the property of a particle effect + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.7 + */ + public enum ParticleProperty { + /** + * The particle effect requires water to be displayed + */ + @Deprecated + REQUIRES_WATER, + /** + * The particle effect requires block or item data to be displayed + */ + REQUIRES_DATA, + /** + * The particle effect uses the offsets as direction values + */ + @Deprecated + DIRECTIONAL, + /** + * The particle effect uses the offsets as color values + */ + COLORABLE + } + + /** + * Represents the color for effects like {@link Particles#SPELL_MOB}, {@link Particles#SPELL_MOB_AMBIENT}, {@link Particles#REDSTONE} and {@link Particles#NOTE} + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.7 + */ + public static abstract class ParticleColor { + /** + * Returns the value for the offsetX field + * + * @return The offsetX value + */ + public abstract float getValueX(); + + /** + * Returns the value for the offsetY field + * + * @return The offsetY value + */ + public abstract float getValueY(); + + /** + * Returns the value for the offsetZ field + * + * @return The offsetZ value + */ + public abstract float getValueZ(); + } + + /** + * Represents the color for effects like {@link Particles#SPELL_MOB}, {@link Particles#SPELL_MOB_AMBIENT} and {@link Particles#NOTE} + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.7 + */ + public static class OrdinaryColor extends ParticleColor { + private final int red; + private final int green; + private final int blue; + + /** + * Construct a new ordinary color + * + * @param red Red value of the RGB format + * @param green Green value of the RGB format + * @param blue Blue value of the RGB format + * @throws IllegalArgumentException If one of the values is lower than 0 or higher than 255 + */ + public OrdinaryColor(int red, int green, int blue) throws IllegalArgumentException { + if (red < 0) { + throw new IllegalArgumentException("The red value is lower than 0"); + } + if (red > 255) { + throw new IllegalArgumentException("The red value is higher than 255"); + } + this.red = red; + if (green < 0) { + throw new IllegalArgumentException("The green value is lower than 0"); + } + if (green > 255) { + throw new IllegalArgumentException("The green value is higher than 255"); + } + this.green = green; + if (blue < 0) { + throw new IllegalArgumentException("The blue value is lower than 0"); + } + if (blue > 255) { + throw new IllegalArgumentException("The blue value is higher than 255"); + } + this.blue = blue; + } + + /** + * Construct a new ordinary color + * + * @param color Bukkit color + */ + public OrdinaryColor(Color color) { + this(color.getRed(), color.getGreen(), color.getBlue()); + } + + /** + * Returns the red value of the RGB format + * + * @return The red value + */ + public int getRed() { + return red; + } + + /** + * Returns the green value of the RGB format + * + * @return The green value + */ + public int getGreen() { + return green; + } + + /** + * Returns the blue value of the RGB format + * + * @return The blue value + */ + public int getBlue() { + return blue; + } + + /** + * Returns the red value divided by 255 + * + * @return The offsetX value + */ + + public float getValueX() { + return (float) red / 255F; + } + + /** + * Returns the green value divided by 255 + * + * @return The offsetY value + */ + + public float getValueY() { + return (float) green / 255F; + } + + /** + * Returns the blue value divided by 255 + * + * @return The offsetZ value + */ + + public float getValueZ() { + return (float) blue / 255F; + } + } + + /** + * Represents the color for the {@link Particles#NOTE} effect + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.7 + */ + public static final class NoteColor extends ParticleColor { + private final int note; + + /** + * Construct a new note color + * + * @param note Note id which determines color + * @throws IllegalArgumentException If the note value is lower than 0 or higher than 24 + */ + public NoteColor(int note) throws IllegalArgumentException { + if (note < 0) { + throw new IllegalArgumentException("The note value is lower than 0"); + } + if (note > 24) { + throw new IllegalArgumentException("The note value is higher than 24"); + } + this.note = note; + } + + /** + * Returns the note value divided by 24 + * + * @return The offsetX value + */ + + public float getValueX() { + return (float) note / 24F; + } + + /** + * Returns zero because the offsetY value is unused + * + * @return zero + */ + + public float getValueY() { + return 0; + } + + /** + * Returns zero because the offsetZ value is unused + * + * @return zero + */ + + public float getValueZ() { + return 0; + } + + } + + public enum ParticleShape { + POINT, NEAR, BAR, EXCLAMATION, SPOT + } + + public static class Particle { + private static Random random = new Random(); + + private Particles effect; + private ParticleShape shape; + private OrdinaryColor color; + + private byte typeCode; + + public Particle(Particles effect, ParticleShape shape, OrdinaryColor color) { + this.effect = effect; + this.shape = shape; + this.color = color; + + this.typeCode = (byte) (effect == Particles.NOTE ? 2 : (effect.hasProperty(ParticleProperty.COLORABLE) ? 1 : 0)); + } + + public String toString() { + return effect.name() + " in shape " + shape.name() + (typeCode != 0 ? " with color \"R" + (typeCode == 1 ? color.getRed() + " G" + color.getGreen() + " B" + color.getBlue() : "random") + "\"" : ""); + } + + public void send(LivingEntity en, List p) { + if (p.isEmpty()) { + return; + } + + Location lc = en.getEyeLocation(); + switch (shape) { + case POINT: + sendParticle(lc.add(0, 1, 0), p, 0.1, 0.1, 0.1, 1); + break; + case NEAR: + sendParticle(lc.add(random.nextDouble() * 1.2 - 0.6, random.nextDouble() * 2 - en.getEyeHeight(), random.nextDouble() * 1.2 - 0.6), p, 0.1, 0.1, 0.1, 1); + break; + case BAR: + sendParticle(lc.add(0, 1, 0), p, 0.01, 0.15, 0.01, 3); + break; + case EXCLAMATION: + sendParticle(lc.add(0, 0.9, 0), p, 0.001, 0.001, 0.001, 2); // POINT + sendParticle(lc.add(0, 0.7, 0), p, 0.01, 0.2, 0.01, 4); // BAR + break; + case SPOT: + sendParticle(lc.add(0, 0.2, 0), p, 0.2, 0.4, 0.2, 15); + break; + } + } + + private void sendParticle(Location lc, List p, double offX, double offY, double offZ, int amount) { + switch (typeCode) { + case 1: + effect.display(color, offX, offY, offZ, amount, lc, p); + break; + case 2: + Particles.NOTE.display(new Particles.NoteColor(random.nextInt(24)), offX, offY, offZ, amount, lc, /*p.getPlayer(),*/ p); + break; + case 0: + effect.display(offX, offY, offZ, 0.001, amount, lc, p); + break; + } + } + + public static Particle deserialize(Map map) { + return new Particle(Particles.fromName((String) map.get("particleEffect")), ParticleShape.valueOf(((String) map.get("particleShape")).toUpperCase()), new OrdinaryColor(Color.deserialize(((MemorySection) map.get("particleColor")).getValues(false)))); + } + } + + /** + * Represents a runtime exception that is thrown either if the displayed particle effect requires data and has none or vice-versa or if the data type is incorrect + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.6 + */ + private static final class ObjectException extends RuntimeException { + private static final long serialVersionUID = 3203085387160737484L; + + /** + * Construct a new particle data exception + * + * @param message Message that will be logged + */ + public ObjectException(String message) { + super(message); + } + } + + /** + * Represents a runtime exception that is thrown either if the displayed particle effect is not colorable or if the particle color type is incorrect + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.7 + */ + private static final class ParticleColorException extends RuntimeException { + private static final long serialVersionUID = 3203085387160737484L; + + /** + * Construct a new particle color exception + * + * @param message Message that will be logged + */ + public ParticleColorException(String message) { + super(message); + } + } + + /** + * Represents a runtime exception that is thrown if the displayed particle effect requires a newer version + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.6 + */ + private static final class ParticleVersionException extends RuntimeException { + private static final long serialVersionUID = 3203085387160737484L; + + /** + * Construct a new particle version exception + */ + public ParticleVersionException() { + super("This particle effect is not supported by your server version"); + } + } + + /** + * Represents a particle effect packet with all attributes which is used for sending packets to the players + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.5 + */ + public static final class ParticlePacket { + private static boolean initialized; + /*private static Class enumParticle; + private static String ver; + private static String pack;*/ + private final Particles effect; + private float offsetX; + private float offsetY; + private float offsetZ; + private final float speed; + private int amount; + private int size = 1; + private final boolean longDistance; + private Object data; + private Object packet; + + private int timesSending = 1; + + /** + * Construct a new particle packet + * + * @param effect Particle effect + * @param offsetX Maximum distance particles can fly away from the center on the x-axis + * @param offsetY Maximum distance particles can fly away from the center on the y-axis + * @param offsetZ Maximum distance particles can fly away from the center on the z-axis + * @param speed Display speed of the particles + * @param amount Amount of particles + * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 + * @param data Data of the effect + * @throws IllegalArgumentException If the speed or amount is lower than 0 + */ + public ParticlePacket(Particles effect, double offsetX, double offsetY, double offsetZ, double speed, int amount, boolean longDistance, Object data) throws IllegalArgumentException { + initialize(); + if (speed < 0) { + throw new IllegalArgumentException("The speed is lower than 0"); + } + if (amount < 0) { + throw new IllegalArgumentException("The amount is lower than 0"); + } + this.effect = effect; + this.offsetX = (float) offsetX; + this.offsetY = (float) offsetY; + this.offsetZ = (float) offsetZ; + this.speed = (float) speed; + this.amount = amount; + this.longDistance = longDistance; + this.data = data; + } + + /** + * Construct a new particle packet of a single particle flying into a determined direction + * + * @param effect Particle effect + * @param direction Direction of the particle + * @param speed Display speed of the particle + * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 + * @param data Data of the effect + * @throws IllegalArgumentException If the speed is lower than 0 + */ + /*public ParticlePacket(ParticleEffect effect, Vector direction, float speed, boolean longDistance, Object data) throws IllegalArgumentException { + this(effect, (float) direction.getX(), (float) direction.getY(), (float) direction.getZ(), speed, 0, longDistance, data); + }*/ + + /** + * Initializes and sets initialized to true if it succeeds + *

+ * Note: These fields only have to be initialized once, so it will return if initialized is already set to true + */ + public static void initialize() { + if (initialized) { + return; + } + initialized = true; + } + + /** + * Determine if packet is initialized + * + * @return Whether these fields are initialized or not + */ + public static boolean isInitialized() { + return initialized; + } + + /** + * Initializes packet with all set values + * + * @param center Center location of the effect + * @throws PacketInstantiationException If instantion fails due to an unknown error + */ + private void initializePacket(Location center) throws PacketInstantiationException { + if (packet != null) { + return; + } + try { + //int tmpAmount = amount; + if (effect.hasProperty(ParticleProperty.COLORABLE) && data instanceof ParticleColor) { + if (mcVersion < 13 || data instanceof NoteColor) { + ParticleColor color = (ParticleColor) data; + offsetX = color.getValueX(); + offsetY = color.getValueY(); + offsetZ = color.getValueZ(); + timesSending = amount < 2 ? 1 : amount; + amount = 0; + data = null; + if (color instanceof OrdinaryColor && ((OrdinaryColor) color).getRed() == 0) { + offsetX = Float.MIN_NORMAL; + } + } else if (mcVersion >= 13 && data instanceof OrdinaryColor) { + data = getDustColor((OrdinaryColor) data, size); + } + } + this.packet = NMS.handle().toPacketPlayOutWorldParticles(effect.getBukkitParticle(), longDistance, (float) center.getX(), (float) center.getY(), (float) center.getZ(), offsetX, offsetY, offsetZ, speed, amount, data); + } catch (Throwable exception) { + throw new PacketInstantiationException("Packet instantiation failed", exception); + } + } + + public static Object getDustColor(OrdinaryColor color, int size) { + try { + return Reflection.instantiateObject(Class.forName("org.bukkit.Particle$DustOptions"), Color.fromBGR(color.getBlue(), color.getGreen(), color.getRed()), size); + } catch (Throwable e) { + e.printStackTrace(); + } + return null; + } + + /** + * Sends the packet to a single player and caches it + * + * @param center Center location of the effect + * @param player Receiver of the packet + * @throws PacketInstantiationException If instantion fails due to an unknown error + * @throws PacketSendingException If sending fails due to an unknown error + */ + public void sendTo(Location center, Player player) throws PacketInstantiationException, PacketSendingException { + initializePacket(center); + try { + if (timesSending == 1) { + TPacketHandler.sendPacket(player, packet); + } else { + for (int i = 0; i < timesSending; i++) { + TPacketHandler.sendPacket(player, packet); + } + } + //sendPacket.invoke(playerConnection.get(getHandle.invoke(player)), packet); + //((CraftPlayer) player).getHandle().playerConnection.sendPacket(packet); + } catch (Throwable exception) { + throw new PacketSendingException("Failed to send the packet to player '" + player.getName() + "'", exception); + } + } + + /** + * Sends the packet to all players in the list + * + * @param center Center location of the effect + * @param players Receivers of the packet + * @throws IllegalArgumentException If the player list is empty + */ + public void sendTo(Location center, List players) throws IllegalArgumentException { + if (players.isEmpty()) { + throw new IllegalArgumentException("The player list is empty"); + } + for (Player player : players) { + sendTo(center, player); + } + } + + /** + * Sends the packet to all players in a certain range + * + * @param center Center location of the effect + * @param range Range in which players will receive the packet (Maximum range for particles is usually 16, but it can differ for some types) + * @throws IllegalArgumentException If the range is lower than 1 + */ + public void sendTo(Location center, double range) throws IllegalArgumentException { + if (range < 1) { + throw new IllegalArgumentException("The range is lower than 1"); + } + String worldName = center.getWorld().getName(); + double squared = range * range; + for (Player player : Bukkit.getOnlinePlayers()) { + if (!player.getWorld().getName().equals(worldName) || player.getLocation().distanceSquared(center) > squared) { + continue; + } + sendTo(center, player); + } + } + + /** + * Represents a runtime exception that is thrown if packet instantiation fails + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.4 + */ + private static final class PacketInstantiationException extends RuntimeException { + private static final long serialVersionUID = 3203085387160737484L; + + /** + * Construct a new packet instantiation exception + * + * @param message Message that will be logged + * @param cause Cause of the exception + */ + public PacketInstantiationException(String message, Throwable cause) { + super(message, cause); + } + } + + /** + * Represents a runtime exception that is thrown if packet sending fails + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.4 + */ + private static final class PacketSendingException extends RuntimeException { + private static final long serialVersionUID = 3203085387160737484L; + + /** + * Construct a new packet sending exception + * + * @param message Message that will be logged + * @param cause Cause of the exception + */ + public PacketSendingException(String message, Throwable cause) { + super(message, cause); + } + } + } +} \ No newline at end of file diff --git a/src/main/scala/me/skymc/taboolib/scoreboard/ScoreboardUtil.java b/src/main/scala/io/izzel/taboolib/util/lite/Scoreboards.java similarity index 55% rename from src/main/scala/me/skymc/taboolib/scoreboard/ScoreboardUtil.java rename to src/main/scala/io/izzel/taboolib/util/lite/Scoreboards.java index 6085975..c9d6649 100644 --- a/src/main/scala/me/skymc/taboolib/scoreboard/ScoreboardUtil.java +++ b/src/main/scala/io/izzel/taboolib/util/lite/Scoreboards.java @@ -1,68 +1,49 @@ -package me.skymc.taboolib.scoreboard; +package io.izzel.taboolib.util.lite; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; -import org.bukkit.scoreboard.Scoreboard; import java.util.*; +import java.util.stream.IntStream; -public class ScoreboardUtil { +public class Scoreboards { - private ScoreboardUtil() { - } - - public static String[] cutUnranked(String[] content) { - String[] elements = Arrays.copyOf(content, 16); - - if (elements[0] == null) { - elements[0] = "Unamed board"; - } - - if (elements[0].length() > 32) { - elements[0] = elements[0].substring(0, 32); - } - - for (int i = 1; i < elements.length; i++) { - if (elements[i] != null) { - if (elements[i].length() > 40) { - elements[i] = elements[i].substring(0, 40); - } - } - } - - return elements; - } - - public static String cutRankedTitle(String title) { + static String fixTitle(String title) { if (title == null) { return "Unamed board"; } - if (title.length() > 32) { return title.substring(0, 32); } - return title; } - public static HashMap cutRanked(Map content) { - HashMap elements = new HashMap<>(content); + static String[] fixLines(String[] content) { + String[] elements = Arrays.copyOf(content, 16); + if (elements[0] == null) { + elements[0] = "Unamed board"; + } + if (elements[0].length() > 32) { + elements[0] = elements[0].substring(0, 32); + } + IntStream.range(1, elements.length).filter(i -> elements[i] != null).filter(i -> elements[i].length() > 40).forEach(i -> elements[i] = elements[i].substring(0, 40)); + return elements; + } + static HashMap fixLines(Map content) { + HashMap elements = new HashMap<>(content); while (elements.size() > 15) { String minimumKey = (String) elements.keySet().toArray()[0]; int minimum = elements.get(minimumKey); - for (String string : elements.keySet()) { if (elements.get(string) < minimum || (elements.get(string) == minimum && string.compareTo(minimumKey) < 0)) { minimumKey = string; minimum = elements.get(string); } } - elements.remove(minimumKey); } - for (String string : new ArrayList<>(elements.keySet())) { if (string != null) { if (string.length() <= 40) { @@ -73,27 +54,20 @@ public class ScoreboardUtil { } } } - return elements; - } - public static Scoreboard unrankedSidebarDisplay(Player p, String... elements) { - elements = cutUnranked(elements); - + public static org.bukkit.scoreboard.Scoreboard display(Player p, String... elements) { + elements = fixLines(elements); try { if (p.getScoreboard() == null || p.getScoreboard() == Bukkit.getScoreboardManager().getMainScoreboard() || p.getScoreboard().getObjectives().size() != 1) { p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); } - if (p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)) == null) { p.getScoreboard().registerNewObjective(p.getUniqueId().toString().substring(0, 16), "dummy"); p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)).setDisplaySlot(DisplaySlot.SIDEBAR); } - - p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).setDisplayName(elements[0]); - for (int i = 1; i < elements.length; i++) { if (elements[i] != null) { if (p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(elements[i]).getScore() != 16 - i) { @@ -105,11 +79,9 @@ public class ScoreboardUtil { } } } - } } } - for (String entry : p.getScoreboard().getEntries()) { boolean toErase = true; for (String element : elements) { @@ -118,53 +90,37 @@ public class ScoreboardUtil { break; } } - if (toErase) { p.getScoreboard().resetScores(entry); } - } - return p.getScoreboard(); } catch (Exception e) { return null; } } - public static boolean unrankedSidebarDisplay(Collection players, String[] elements) { - for (Player player : players) { - if (unrankedSidebarDisplay(player, elements) == null) { - return false; - } - } - - return true; + public static boolean display(Collection players, String[] elements) { + return players.stream().noneMatch(player -> display(player, elements) == null); } - public static boolean unrankedSidebarDisplay(Collection players, Scoreboard board, String... elements) { + public static boolean display(Collection players, org.bukkit.scoreboard.Scoreboard board, String... elements) { try { String objName = "COLLAB-SB-WINTER"; - if (board == null) { board = Bukkit.getScoreboardManager().getNewScoreboard(); } - - elements = cutUnranked(elements); - + elements = fixLines(elements); for (Player player : players) { if (player.getScoreboard() != board) { player.setScoreboard(board); } } - if (board.getObjective(objName) == null) { board.registerNewObjective(objName, "dummy"); board.getObjective(objName).setDisplaySlot(DisplaySlot.SIDEBAR); } - - board.getObjective(DisplaySlot.SIDEBAR).setDisplayName(elements[0]); - for (int i = 1; i < elements.length; i++) { if (elements[i] != null && board.getObjective(DisplaySlot.SIDEBAR).getScore(elements[i]).getScore() != 16 - i) { board.getObjective(DisplaySlot.SIDEBAR).getScore(elements[i]).setScore(16 - i); @@ -175,10 +131,8 @@ public class ScoreboardUtil { } } } - } } - for (String entry : board.getEntries()) { boolean toErase = true; for (String element : elements) { @@ -187,104 +141,10 @@ public class ScoreboardUtil { break; } } - if (toErase) { board.resetScores(entry); } - } - - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - public static boolean rankedSidebarDisplay(Player p, String title, Map elements) { - try { - title = cutRankedTitle(title); - elements = cutRanked(elements); - - if (p.getScoreboard() == null || p.getScoreboard() == Bukkit.getScoreboardManager().getMainScoreboard() || p.getScoreboard().getObjectives().size() != 1) { - p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - } - - if (p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)) == null) { - p.getScoreboard().registerNewObjective(p.getUniqueId().toString().substring(0, 16), "dummy"); - p.getScoreboard().getObjective(p.getUniqueId().toString().substring(0, 16)).setDisplaySlot(DisplaySlot.SIDEBAR); - } - p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).setDisplayName(title); - - for (String string : elements.keySet()) { - if (p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(string).getScore() != elements.get(string)) { - p.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(string).setScore(elements.get(string)); - } - } - - for (String string : new ArrayList<>(p.getScoreboard().getEntries())) { - if (!elements.keySet().contains(string)) { - p.getScoreboard().resetScores(string); - } - } - - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - public static boolean rankedSidebarDisplay(Collection players, String title, Map elements) { - for (Player player : players) { - if (!rankedSidebarDisplay(player, title, elements)) { - return false; - } - } - - return true; - } - - public static boolean rankedSidebarDisplay(Collection players, String title, Map elements, Scoreboard board) { - try { - title = cutRankedTitle(title); - elements = cutRanked(elements); - - String objName = "COLLAB-SB-WINTER"; - - if (board == null) { - board = Bukkit.getScoreboardManager().getNewScoreboard(); - } - - - for (Player player : players) { - if (player.getScoreboard() != board) { - player.setScoreboard(board); - } - } - - if (board.getObjective(objName) == null) { - board.registerNewObjective(objName, "dummy"); - board.getObjective(objName).setDisplaySlot(DisplaySlot.SIDEBAR); - } - - - board.getObjective(DisplaySlot.SIDEBAR).setDisplayName(title); - - - for (String string : elements.keySet()) { - if (board.getObjective(DisplaySlot.SIDEBAR).getScore(string).getScore() != elements.get(string)) { - board.getObjective(DisplaySlot.SIDEBAR).getScore(string).setScore(elements.get(string)); - } - } - - for (String string : new ArrayList<>(board.getEntries())) { - if (!elements.keySet().contains(string)) { - board.resetScores(string); - } - } - - return true; } catch (Exception e) { e.printStackTrace(); diff --git a/src/main/scala/me/skymc/taboolib/javascript/ScriptHandler.java b/src/main/scala/io/izzel/taboolib/util/lite/Scripts.java similarity index 88% rename from src/main/scala/me/skymc/taboolib/javascript/ScriptHandler.java rename to src/main/scala/io/izzel/taboolib/util/lite/Scripts.java index 3c61d93..2a7bb68 100644 --- a/src/main/scala/me/skymc/taboolib/javascript/ScriptHandler.java +++ b/src/main/scala/io/izzel/taboolib/util/lite/Scripts.java @@ -1,9 +1,8 @@ -package me.skymc.taboolib.javascript; +package io.izzel.taboolib.util.lite; -import com.ilummc.tlib.logger.TLogger; +import io.izzel.taboolib.module.locale.logger.TLogger; import jdk.nashorn.api.scripting.NashornScriptEngineFactory; -import me.skymc.taboolib.common.function.TFunction; -import org.bukkit.configuration.file.FileConfiguration; +import io.izzel.taboolib.module.inject.TFunction; import javax.script.Compilable; import javax.script.CompiledScript; @@ -16,7 +15,7 @@ import java.util.Objects; * @Since 2018-06-02 22:48 */ @TFunction(enable = "init") -public class ScriptHandler { +public class Scripts { private static ScriptEngine scriptEngine; private static ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); diff --git a/src/main/scala/io/izzel/taboolib/util/lite/Servers.java b/src/main/scala/io/izzel/taboolib/util/lite/Servers.java new file mode 100644 index 0000000..2e13e99 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/util/lite/Servers.java @@ -0,0 +1,47 @@ +package io.izzel.taboolib.util.lite; + +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.lang.reflect.Field; + +/** + * @Author 坏黑 + * @Since 2019-07-05 18:53 + */ +public class Servers { + + public static void setEnchantmentAcceptingNew(boolean value) { + try { + Field f = Enchantment.class.getDeclaredField("acceptingNew"); + f.setAccessible(true); + f.set(null, value); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + public static Player getAttackerInDamageEvent(EntityDamageByEntityEvent e) { + if (e.getDamager() instanceof Player) { + return (Player) e.getDamager(); + } else if (e.getDamager() instanceof Projectile && ((Projectile) e.getDamager()).getShooter() instanceof Player) { + return (Player) ((Projectile) e.getDamager()).getShooter(); + } else { + return null; + } + } + + public static LivingEntity getLivingAttackerInDamageEvent(EntityDamageByEntityEvent e) { + if (e.getDamager() instanceof LivingEntity) { + return (LivingEntity) e.getDamager(); + } else if (e.getDamager() instanceof Projectile && ((Projectile) e.getDamager()).getShooter() instanceof LivingEntity) { + return (LivingEntity) ((Projectile) e.getDamager()).getShooter(); + } else { + return null; + } + } +} diff --git a/src/main/scala/io/izzel/taboolib/util/lite/SoundPack.java b/src/main/scala/io/izzel/taboolib/util/lite/SoundPack.java new file mode 100644 index 0000000..58de17f --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/util/lite/SoundPack.java @@ -0,0 +1,117 @@ +package io.izzel.taboolib.util.lite; + +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.Version; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +public class SoundPack { + + private Sound sound; + private Float a; + private Float b; + private int delay; + + public SoundPack() { + this.sound = Sound.valueOf(getModifiedSound("ENTITY_VILLAGER_NO")); + this.a = 1.0F; + this.b = 1.0F; + } + + public SoundPack(Sound sound, float a, float b) { + this(sound, a, b, 0); + } + + public SoundPack(Sound sound, float a, float b, int delay) { + this.sound = sound; + this.a = a; + this.b = b; + this.delay = delay; + } + + public SoundPack(String s) { + parse(s); + } + + public void play(Player p) { + Bukkit.getScheduler().runTaskLater(TabooLib.getPlugin(), () -> p.playSound(p.getLocation(), this.sound, this.a, this.b), delay); + } + + public void play(Location l) { + Bukkit.getScheduler().runTaskLater(TabooLib.getPlugin(), () -> l.getWorld().playSound(l, this.sound, this.a, this.b), delay); + } + + public void parse(String s) { + try { + String[] split = s.split("-"); + this.sound = Sound.valueOf(getModifiedSound(split[0])); + this.a = Float.parseFloat(split[1]); + this.b = Float.parseFloat(split[2]); + this.delay = split.length > 3 ? Integer.parseInt(split[3]) : 0; + } catch (Exception var3) { + this.sound = Sound.valueOf(getModifiedSound("ENTITY_VILLAGER_NO")); + this.a = 1.0F; + this.b = 1.0F; + this.delay = 0; + } + } + + public static String getModifiedSound(String str) { + if (Version.isBefore(Version.v1_9)) { + str = str.replace("BLOCK_FIRE_EXTINGUISH", "FIZZ"); + str = str.replace("BLOCK_NOTE_HAT", "NOTE_STICKS"); + str = str.replace("ENTITY_SHEEP_DEATH", "SHEEP_IDLE"); + str = str.replace("ENTITY_LLAMA_ANGRY", "HORSE_HIT"); + str = str.replace("BLOCK_BREWING_STAND_BREW", "CREEPER_HISS"); + str = str.replace("ENTITY_SHULKER_TELEPORT", "ENDERMAN_TELEPORT"); + str = str.replace("ENTITY_ZOMBIE_ATTACK_IRON_DOOR", "ZOMBIE_METAL"); + str = str.replace("BLOCK_GRAVEL_BREAK", "DIG_GRAVEL"); + str = str.replace("BLOCK_SNOW_BREAK", "DIG_SNOW"); + str = str.replace("BLOCK_GRAVEL_BREAK", "DIG_GRAVEL"); + str = str.replace("ENTITY_PLAYER_LEVELUP", "LEVEL_UP"); + str = str.replace("ENTITY_SNOWBALL_THROW", "SHOOT_ARROW"); + str = str.replace("PLAYER_ATTACK_CRIT", "ITEM_BREAK"); + str = str.replace("ENDERMEN", "ENDERMAN"); + str = str.replace("ARROW_SHOOT", "SHOOT_ARROW"); + str = str.replace("ENDERMAN_HURT", "ENDERMAN_HIT"); + str = str.replace("BLAZE_HURT", "BLAZE_HIT"); + str = str.replace("_FLAP", "_WINGS"); + str = str.replaceAll("ENTITY_|GENERIC_|BLOCK_|_AMBIENT|_BREAK|UI_BUTTON_|EXPERIENCE_", ""); + } + return str; + } + + // ********************************* + // + // Getter and Setter + // + // ********************************* + + public Sound getSound() { + return sound; + } + + public Float getA() { + return a; + } + + public Float getB() { + return b; + } + + public int getDelay() { + return delay; + } + + @Override + public String toString() { + return "SoundPack{" + + "sound=" + sound + + ", a=" + a + + ", b=" + b + + ", delay=" + delay + + '}'; + } +} diff --git a/src/main/scala/me/skymc/taboolib/object/WeightCollection.java b/src/main/scala/io/izzel/taboolib/util/lite/Weights.java similarity index 93% rename from src/main/scala/me/skymc/taboolib/object/WeightCollection.java rename to src/main/scala/io/izzel/taboolib/util/lite/Weights.java index d5d48f9..e168fa7 100644 --- a/src/main/scala/me/skymc/taboolib/object/WeightCollection.java +++ b/src/main/scala/io/izzel/taboolib/util/lite/Weights.java @@ -1,6 +1,4 @@ -package me.skymc.taboolib.object; - -import me.skymc.taboolib.other.NumberUtils; +package io.izzel.taboolib.util.lite; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; @@ -13,7 +11,7 @@ import java.util.concurrent.CopyOnWriteArrayList; * @Since 2018-05-07 16:18 */ @ThreadSafe -public class WeightCollection { +public class Weights { private final List weightList = new CopyOnWriteArrayList<>(); @@ -37,7 +35,7 @@ public class WeightCollection { public WeightObject getWeight() { int weightSum = weightList.stream().mapToInt(WeightObject::getWeightNumber).sum(); if (weightSum > 0) { - Integer m = 0, n = NumberUtils.getRandom().nextInt(weightSum); + Integer m = 0, n = Numbers.getRandom().nextInt(weightSum); for (WeightObject weightObject : weightList) { if (m <= n && n < m + weightObject.getWeightNumber()) { return weightObject; diff --git a/src/main/scala/io/izzel/taboolib/util/lite/cooldown/Cooldown.java b/src/main/scala/io/izzel/taboolib/util/lite/cooldown/Cooldown.java new file mode 100644 index 0000000..6879292 --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/util/lite/cooldown/Cooldown.java @@ -0,0 +1,72 @@ +package io.izzel.taboolib.util.lite.cooldown; + +import java.util.HashMap; + +public class Cooldown { + + private String plugin; + private String name; + private long seconds; + + private HashMap data = new HashMap<>(); + + public Cooldown(String n, int s) { + this.name = n; + this.seconds = s; + this.plugin = "null"; + } + + public Cooldown(String n, long s) { + this.name = n; + this.seconds = s; + this.plugin = "null"; + } + + public String getPackName() { + return name; + } + + public long getPackSeconds() { + return seconds; + } + + public String getPlugin() { + return plugin; + } + + public void setPlugin(String p) { + this.plugin = p; + } + + public void unRegister(String player) { + data.remove(player); + } + + public long getCooldown(String player) { + return getCooldown(player, 0); + } + + public long getCooldown(String player, long cutSeconds) { + if (!data.containsKey(player)) { + return 0; + } + long difference = ((System.currentTimeMillis() + cutSeconds) - data.get(player)); + return difference >= seconds ? 0 : seconds - difference; + } + + public boolean isCooldown(String player) { + return isCooldown(player, 0L); + } + + public boolean isCooldown(String player, long cutSeconds) { + if (!data.containsKey(player)) { + data.put(player, System.currentTimeMillis()); + return false; + } + if (getCooldown(player, cutSeconds) <= 0) { + data.put(player, System.currentTimeMillis()); + return false; + } + return true; + } +} diff --git a/src/main/scala/io/izzel/taboolib/util/lite/cooldown/Cooldowns.java b/src/main/scala/io/izzel/taboolib/util/lite/cooldown/Cooldowns.java new file mode 100644 index 0000000..ade2c6b --- /dev/null +++ b/src/main/scala/io/izzel/taboolib/util/lite/cooldown/Cooldowns.java @@ -0,0 +1,47 @@ +package io.izzel.taboolib.util.lite.cooldown; + +import io.izzel.taboolib.module.inject.TListener; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.plugin.Plugin; + +import java.util.concurrent.ConcurrentHashMap; + +@TListener +public class Cooldowns implements Listener { + + private static ConcurrentHashMap list = new ConcurrentHashMap<>(); + + public static ConcurrentHashMap getCooldownPacks() { + return list; + } + + public static void register(Cooldown pack) { + list.put(pack.getPackName(), pack); + } + + public static void register(Cooldown pack, Plugin plugin) { + pack.setPlugin(plugin.getName()); + list.put(pack.getPackName(), pack); + } + + public static void unregister(String name) { + list.remove(name); + } + + private static void unregister(Cooldown pack) { + list.remove(pack.getPackName()); + } + + @EventHandler + public void quit(PlayerQuitEvent e) { + list.values().stream().filter(pack -> !pack.isCooldown(e.getPlayer().getName(), 0)).forEach(pack -> pack.unRegister(e.getPlayer().getName())); + } + + @EventHandler + public void disable(PluginDisableEvent e) { + list.values().stream().filter(pack -> pack.getPlugin().equals(e.getPlugin().getName())).forEach(Cooldowns::unregister); + } +} diff --git a/src/main/scala/me/skymc/taboolib/plugin/PluginLoadState.java b/src/main/scala/io/izzel/taboolib/util/plugin/PluginLoadState.java similarity index 92% rename from src/main/scala/me/skymc/taboolib/plugin/PluginLoadState.java rename to src/main/scala/io/izzel/taboolib/util/plugin/PluginLoadState.java index 59b7250..23bf8e0 100644 --- a/src/main/scala/me/skymc/taboolib/plugin/PluginLoadState.java +++ b/src/main/scala/io/izzel/taboolib/util/plugin/PluginLoadState.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.plugin; +package io.izzel.taboolib.util.plugin; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/plugin/PluginLoadStateType.java b/src/main/scala/io/izzel/taboolib/util/plugin/PluginLoadStateType.java similarity index 90% rename from src/main/scala/me/skymc/taboolib/plugin/PluginLoadStateType.java rename to src/main/scala/io/izzel/taboolib/util/plugin/PluginLoadStateType.java index 15c98b3..640acd9 100644 --- a/src/main/scala/me/skymc/taboolib/plugin/PluginLoadStateType.java +++ b/src/main/scala/io/izzel/taboolib/util/plugin/PluginLoadStateType.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.plugin; +package io.izzel.taboolib.util.plugin; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/plugin/PluginUnloadState.java b/src/main/scala/io/izzel/taboolib/util/plugin/PluginUnloadState.java similarity index 91% rename from src/main/scala/me/skymc/taboolib/plugin/PluginUnloadState.java rename to src/main/scala/io/izzel/taboolib/util/plugin/PluginUnloadState.java index 5e94809..6c38687 100644 --- a/src/main/scala/me/skymc/taboolib/plugin/PluginUnloadState.java +++ b/src/main/scala/io/izzel/taboolib/util/plugin/PluginUnloadState.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.plugin; +package io.izzel.taboolib.util.plugin; /** * @Author sky diff --git a/src/main/scala/me/skymc/taboolib/plugin/PluginUtils.java b/src/main/scala/io/izzel/taboolib/util/plugin/PluginUtils.java similarity index 93% rename from src/main/scala/me/skymc/taboolib/plugin/PluginUtils.java rename to src/main/scala/io/izzel/taboolib/util/plugin/PluginUtils.java index e243c47..6b562d1 100644 --- a/src/main/scala/me/skymc/taboolib/plugin/PluginUtils.java +++ b/src/main/scala/io/izzel/taboolib/util/plugin/PluginUtils.java @@ -1,9 +1,7 @@ -package me.skymc.taboolib.plugin; +package io.izzel.taboolib.util.plugin; import com.google.common.base.Joiner; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.events.TPluginEnableEvent; -import me.skymc.taboolib.events.TPluginLoadEvent; +import io.izzel.taboolib.TabooLib; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; @@ -51,7 +49,7 @@ public class PluginUtils { for (File pluginFile : new File("plugins").listFiles()) { if (pluginFile.getName().endsWith(".jar")) { try { - PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(pluginFile); + PluginDescriptionFile desc = TabooLib.getPlugin().getPluginLoader().getPluginDescription(pluginFile); if (desc.getName().equalsIgnoreCase(name)) { return pluginFile; } @@ -184,7 +182,7 @@ public class PluginUtils { } public static boolean isIgnored(Plugin plugin) { - return plugin.equals(Main.getInst()); + return plugin.getName().equalsIgnoreCase("TabooLib"); } private static PluginLoadState load(Plugin plugin) { @@ -202,7 +200,7 @@ public class PluginUtils { for (File plugin : Objects.requireNonNull(pluginDir.listFiles())) { if (plugin.getName().endsWith(".jar")) { try { - PluginDescriptionFile desc = Main.getInst().getPluginLoader().getPluginDescription(plugin); + PluginDescriptionFile desc = TabooLib.getPlugin().getPluginLoader().getPluginDescription(plugin); if (desc.getName().equalsIgnoreCase(name)) { pluginFile = plugin; break; @@ -220,17 +218,7 @@ public class PluginUtils { } catch (InvalidPluginException e) { return new PluginLoadState(PluginLoadStateType.INVALID_PLUGIN, e.toString()); } - try { - Bukkit.getPluginManager().callEvent(new TPluginLoadEvent(target)); - } catch (Exception e) { - e.printStackTrace(); - } target.onLoad(); - try { - Bukkit.getPluginManager().callEvent(new TPluginEnableEvent(target)); - } catch (Exception e) { - e.printStackTrace(); - } Bukkit.getPluginManager().enablePlugin(target); return new PluginLoadState(PluginLoadStateType.LOADED, "null"); } diff --git a/src/main/scala/me/skymc/taboolib/common/serialize/DoNotSerialize.java b/src/main/scala/io/izzel/taboolib/util/serialize/DoNotSerialize.java similarity index 89% rename from src/main/scala/me/skymc/taboolib/common/serialize/DoNotSerialize.java rename to src/main/scala/io/izzel/taboolib/util/serialize/DoNotSerialize.java index f6cee54..44fc677 100644 --- a/src/main/scala/me/skymc/taboolib/common/serialize/DoNotSerialize.java +++ b/src/main/scala/io/izzel/taboolib/util/serialize/DoNotSerialize.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.serialize; +package io.izzel.taboolib.util.serialize; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializable.java b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializable.java similarity index 94% rename from src/main/scala/me/skymc/taboolib/common/serialize/TSerializable.java rename to src/main/scala/io/izzel/taboolib/util/serialize/TSerializable.java index f57ae2a..02f8fc4 100644 --- a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializable.java +++ b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializable.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.serialize; +package io.izzel.taboolib.util.serialize; import java.nio.charset.StandardCharsets; import java.util.Base64; diff --git a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializeCollection.java b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializeCollection.java similarity index 89% rename from src/main/scala/me/skymc/taboolib/common/serialize/TSerializeCollection.java rename to src/main/scala/io/izzel/taboolib/util/serialize/TSerializeCollection.java index 0b418da..2793e95 100644 --- a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializeCollection.java +++ b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializeCollection.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.serialize; +package io.izzel.taboolib.util.serialize; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializeCustom.java b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializeCustom.java similarity index 89% rename from src/main/scala/me/skymc/taboolib/common/serialize/TSerializeCustom.java rename to src/main/scala/io/izzel/taboolib/util/serialize/TSerializeCustom.java index 9f85ef5..d84ef6e 100644 --- a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializeCustom.java +++ b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializeCustom.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.serialize; +package io.izzel.taboolib.util.serialize; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializeMap.java b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializeMap.java similarity index 88% rename from src/main/scala/me/skymc/taboolib/common/serialize/TSerializeMap.java rename to src/main/scala/io/izzel/taboolib/util/serialize/TSerializeMap.java index 27fcd43..cb923b0 100644 --- a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializeMap.java +++ b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializeMap.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.serialize; +package io.izzel.taboolib.util.serialize; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializer.java b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializer.java similarity index 96% rename from src/main/scala/me/skymc/taboolib/common/serialize/TSerializer.java rename to src/main/scala/io/izzel/taboolib/util/serialize/TSerializer.java index e8a9cae..92e17f0 100644 --- a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializer.java +++ b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializer.java @@ -1,9 +1,8 @@ -package me.skymc.taboolib.common.serialize; +package io.izzel.taboolib.util.serialize; -import ch.njol.skript.classes.ConfigurationSerializer; import com.google.common.collect.Maps; import com.google.gson.*; -import me.skymc.taboolib.common.util.SimpleReflection; +import io.izzel.taboolib.module.lite.SimpleReflection; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.serialization.ConfigurationSerializable; @@ -23,10 +22,6 @@ public class TSerializer { private static Map generated = Maps.newHashMap(); - public static T read(String value, Class type) { - return ConfigurationSerializer.deserializeCS(value, type); - } - public static TSerializable read(TSerializable serializable, String serializedString) { try { JsonObject jsonObject = (JsonObject) new JsonParser().parse(serializedString); @@ -92,12 +87,7 @@ public class TSerializer { return serializable; } - public static String write(ConfigurationSerializable serializable) { - return ConfigurationSerializer.serializeCS(serializable); - } - public static String write(TSerializable serializable) { - SimpleReflection.checkAndSave(serializable.getClass()); JsonObject jsonObject = new JsonObject(); JsonObject serializeObject = new JsonObject(); for (Field declaredField : serializable.getClass().getDeclaredFields()) { diff --git a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializerElement.java b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializerElement.java similarity index 81% rename from src/main/scala/me/skymc/taboolib/common/serialize/TSerializerElement.java rename to src/main/scala/io/izzel/taboolib/util/serialize/TSerializerElement.java index 9ad5932..5f4a7e5 100644 --- a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializerElement.java +++ b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializerElement.java @@ -1,4 +1,4 @@ -package me.skymc.taboolib.common.serialize; +package io.izzel.taboolib.util.serialize; /** * @Author 坏黑 diff --git a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializerElementGeneral.java b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializerElementGeneral.java similarity index 97% rename from src/main/scala/me/skymc/taboolib/common/serialize/TSerializerElementGeneral.java rename to src/main/scala/io/izzel/taboolib/util/serialize/TSerializerElementGeneral.java index 1697dd1..452a250 100644 --- a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializerElementGeneral.java +++ b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializerElementGeneral.java @@ -1,6 +1,6 @@ -package me.skymc.taboolib.common.serialize; +package io.izzel.taboolib.util.serialize; -import me.skymc.taboolib.other.NumberUtils; +import io.izzel.taboolib.util.lite.Numbers; import org.bukkit.Location; import org.bukkit.inventory.ItemStack; @@ -150,7 +150,7 @@ public enum TSerializerElementGeneral { @Override public Boolean read(String value) { try { - return NumberUtils.getBooleanAbbreviation(value); + return Numbers.getBoolean(value); } catch (Throwable t) { t.printStackTrace(); } diff --git a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializerExample.java b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializerExample.java similarity index 93% rename from src/main/scala/me/skymc/taboolib/common/serialize/TSerializerExample.java rename to src/main/scala/io/izzel/taboolib/util/serialize/TSerializerExample.java index 504ad7d..4c9910d 100644 --- a/src/main/scala/me/skymc/taboolib/common/serialize/TSerializerExample.java +++ b/src/main/scala/io/izzel/taboolib/util/serialize/TSerializerExample.java @@ -1,9 +1,9 @@ -package me.skymc.taboolib.common.serialize; +package io.izzel.taboolib.util.serialize; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import me.skymc.taboolib.string.ArrayUtils; +import io.izzel.taboolib.util.ArrayUtil; import java.util.List; import java.util.Map; @@ -19,7 +19,7 @@ public class TSerializerExample { SimpleData data = new SimpleData(); // 修改参数 data.number = 9999; - data.list.addAll(ArrayUtils.asList(111D, 222D)); + data.list.addAll(ArrayUtil.asList(111D, 222D)); data.map.putAll(ImmutableMap.of("a", "b", "c", "d")); // 序列化 String value = data.write(); diff --git a/src/main/scala/me/skymc/taboolib/itagapi/TagDataHandler.java b/src/main/scala/io/izzel/taboolib/util/tag/TagDataHandler.java similarity index 64% rename from src/main/scala/me/skymc/taboolib/itagapi/TagDataHandler.java rename to src/main/scala/io/izzel/taboolib/util/tag/TagDataHandler.java index d021ad5..f9ea860 100644 --- a/src/main/scala/me/skymc/taboolib/itagapi/TagDataHandler.java +++ b/src/main/scala/io/izzel/taboolib/util/tag/TagDataHandler.java @@ -1,19 +1,15 @@ -package me.skymc.taboolib.itagapi; +package io.izzel.taboolib.util.tag; -import com.google.common.base.Preconditions; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.common.function.TFunction; -import me.skymc.taboolib.packet.PacketUtils; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.module.inject.TFunction; +import io.izzel.taboolib.module.inject.TListener; 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; import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Team; @@ -25,28 +21,12 @@ import java.util.UUID; * @Since 2018-05-23 0:37 */ @TFunction(enable = "init") +@TListener public class TagDataHandler implements Listener { - private static TagDataHandler handler; + private static TagDataHandler handler = new TagDataHandler() ; private HashMap playersData = new HashMap<>(); - static void init() { - Preconditions.checkArgument(handler == null, "TagDataHandler is already instanced!"); - handler = new TagDataHandler(); - // 注册监听 - Bukkit.getPluginManager().registerEvents(handler, TabooLib.instance()); - // 启动相关功能 - new BukkitRunnable() { - - @Override - public void run() { - if (PacketUtils.isProtocolLibEnabled() && Main.getInst().getConfig().getBoolean("TABLIST-PACKET", true)) { - TagPacket.inst(); - } - } - }.runTask(TabooLib.instance()); - } - public TagPlayerData unregisterPlayerData(Player player) { return playersData.remove(player.getUniqueId()); } @@ -86,27 +66,13 @@ public class TagDataHandler implements Listener { 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()); } // ********************************* @@ -135,7 +101,7 @@ public class TagDataHandler implements Listener { entryTeam.setPrefix(playerData.getPrefix()); entryTeam.setSuffix(playerData.getSuffix()); // 傻逼 BedWarsRel 我草你妈的 - if (TabooLib.instance().getConfig().getBoolean("TABLIST-AUTO-CLEAN-TEAM", true)) { + if (TabooLib.getConfig().getBoolean("TABLIST-AUTO-CLEAN-TEAM", true)) { TagUtils.cleanEmptyTeamInScoreboard(scoreboard); } } @@ -148,7 +114,7 @@ public class TagDataHandler implements Listener { Scoreboard scoreboard = TagUtils.getScoreboardComputeIfAbsent(player); TagUtils.cleanEntryInScoreboard(scoreboard, playerData.getNameDisplay()); // 傻逼 BedWarsRel 我草你妈的 - if (TabooLib.instance().getConfig().getBoolean("TABLIST-AUTO-CLEAN-TEAM", true)) { + if (TabooLib.getConfig().getBoolean("TABLIST-AUTO-CLEAN-TEAM", true)) { TagUtils.cleanEmptyTeamInScoreboard(scoreboard); } } @@ -170,24 +136,6 @@ public class TagDataHandler implements Listener { 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 diff --git a/src/main/scala/me/skymc/taboolib/itagapi/TagPlayerData.java b/src/main/scala/io/izzel/taboolib/util/tag/TagPlayerData.java similarity index 87% rename from src/main/scala/me/skymc/taboolib/itagapi/TagPlayerData.java rename to src/main/scala/io/izzel/taboolib/util/tag/TagPlayerData.java index b7ceb67..d533ed1 100644 --- a/src/main/scala/me/skymc/taboolib/itagapi/TagPlayerData.java +++ b/src/main/scala/io/izzel/taboolib/util/tag/TagPlayerData.java @@ -1,11 +1,9 @@ -package me.skymc.taboolib.itagapi; +package io.izzel.taboolib.util.tag; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.Main; -import org.bukkit.Bukkit; +import io.izzel.taboolib.TabooLib; +import io.izzel.taboolib.util.Strings; import org.bukkit.entity.Player; -import java.text.MessageFormat; import java.util.Objects; import java.util.UUID; @@ -30,7 +28,7 @@ public class TagPlayerData { } public String getTeamHash() { - return Main.getInst().getConfig().getBoolean("TABLIST-SORT") ? String.valueOf(Objects.hash(prefix)) : nameOrigin; + return TabooLib.getPlugin().getConfig().getBoolean("TABLIST-SORT") ? String.valueOf(Objects.hash(prefix)) : nameOrigin; } public TagPlayerData reset() { diff --git a/src/main/scala/me/skymc/taboolib/itagapi/TagUtils.java b/src/main/scala/io/izzel/taboolib/util/tag/TagUtils.java similarity index 95% rename from src/main/scala/me/skymc/taboolib/itagapi/TagUtils.java rename to src/main/scala/io/izzel/taboolib/util/tag/TagUtils.java index e0bcb8d..31a9afa 100644 --- a/src/main/scala/me/skymc/taboolib/itagapi/TagUtils.java +++ b/src/main/scala/io/izzel/taboolib/util/tag/TagUtils.java @@ -1,6 +1,6 @@ -package me.skymc.taboolib.itagapi; +package io.izzel.taboolib.util.tag; -import com.ilummc.tlib.logger.TLogger; +import io.izzel.taboolib.module.locale.logger.TLogger; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.scoreboard.Scoreboard; diff --git a/src/main/scala/com/ilummc/tlibscala/AsyncTask.scala b/src/main/scala/io/lzzel/tlibscala/AsyncTask.scala similarity index 94% rename from src/main/scala/com/ilummc/tlibscala/AsyncTask.scala rename to src/main/scala/io/lzzel/tlibscala/AsyncTask.scala index 274372d..f9b788c 100644 --- a/src/main/scala/com/ilummc/tlibscala/AsyncTask.scala +++ b/src/main/scala/io/lzzel/tlibscala/AsyncTask.scala @@ -1,4 +1,4 @@ -package com.ilummc.tlibscala +package io.lzzel.tlibscala import org.bukkit.plugin.Plugin diff --git a/src/main/scala/com/ilummc/tlibscala/Example.scala b/src/main/scala/io/lzzel/tlibscala/Example.scala similarity index 67% rename from src/main/scala/com/ilummc/tlibscala/Example.scala rename to src/main/scala/io/lzzel/tlibscala/Example.scala index 2453916..aed96f6 100644 --- a/src/main/scala/com/ilummc/tlibscala/Example.scala +++ b/src/main/scala/io/lzzel/tlibscala/Example.scala @@ -1,4 +1,4 @@ -package com.ilummc.tlibscala +package io.lzzel.tlibscala import Prelude._ import org.bukkit.Material @@ -14,15 +14,10 @@ class Example extends JavaPlugin with Listener { @EventHandler def onJoin(event: PlayerJoinEvent): Unit = { event.getPlayer.sendActionBar("2333") - val tick = event.getPlayer.getFishTicks - event.getPlayer.setFishTicks(tick + 10) - event.getPlayer.displaySidebar("标题", Map("2333" -> 1)) event.getPlayer.displaySidebarUnranked("", "", "") - event.getPlayer.openSign(event.getPlayer.getWorld.getBlockAt(0, 0, 0)) event.getPlayer.setVelocity(1.0, 2.0, 3.0) - if (event.getPlayer.withdraw(100)) - event.getPlayer.getInventory.addItem(new ItemStack(Material.DIAMOND)) - event.getPlayer.openAnvil() + event.getPlayer.withdraw(100) + event.getPlayer.getInventory.addItem(new ItemStack(Material.DIAMOND)) event.getPlayer << "locale.node" << "node.2" event.getPlayer.teleport(event.getPlayer.getLocation + (1, 2, 3)) Task { diff --git a/src/main/scala/com/ilummc/tlibscala/Implicits.scala b/src/main/scala/io/lzzel/tlibscala/Implicits.scala similarity index 87% rename from src/main/scala/com/ilummc/tlibscala/Implicits.scala rename to src/main/scala/io/lzzel/tlibscala/Implicits.scala index 9ed88a5..1568974 100644 --- a/src/main/scala/com/ilummc/tlibscala/Implicits.scala +++ b/src/main/scala/io/lzzel/tlibscala/Implicits.scala @@ -1,6 +1,6 @@ -package com.ilummc.tlibscala +package io.lzzel.tlibscala -import com.ilummc.tlibscala.runtime.{RichLocation, RichOfflinePlayer, RichPlayer, RichVector} +import io.lzzel.tlibscala.runtime.{RichLocation, RichOfflinePlayer, RichPlayer, RichVector} import org.bukkit.entity.Player import org.bukkit.util.Vector import org.bukkit.{Location, OfflinePlayer, World, util} diff --git a/src/main/scala/com/ilummc/tlibscala/Prelude.scala b/src/main/scala/io/lzzel/tlibscala/Prelude.scala similarity index 95% rename from src/main/scala/com/ilummc/tlibscala/Prelude.scala rename to src/main/scala/io/lzzel/tlibscala/Prelude.scala index 443365a..e2db6f7 100644 --- a/src/main/scala/com/ilummc/tlibscala/Prelude.scala +++ b/src/main/scala/io/lzzel/tlibscala/Prelude.scala @@ -1,6 +1,6 @@ -package com.ilummc.tlibscala +package io.lzzel.tlibscala -import com.ilummc.tlib.resources.TLocale.Logger +import io.izzel.taboolib.module.locale.TLocale.Logger import org.bukkit.Bukkit import org.bukkit.event.{Event, EventException, EventPriority, Listener} import org.bukkit.plugin.{EventExecutor, Plugin} diff --git a/src/main/scala/com/ilummc/tlibscala/ScalaTaskExecutor.scala b/src/main/scala/io/lzzel/tlibscala/ScalaTaskExecutor.scala similarity index 94% rename from src/main/scala/com/ilummc/tlibscala/ScalaTaskExecutor.scala rename to src/main/scala/io/lzzel/tlibscala/ScalaTaskExecutor.scala index da1b997..35eed5c 100644 --- a/src/main/scala/com/ilummc/tlibscala/ScalaTaskExecutor.scala +++ b/src/main/scala/io/lzzel/tlibscala/ScalaTaskExecutor.scala @@ -1,4 +1,4 @@ -package com.ilummc.tlibscala +package io.lzzel.tlibscala import org.bukkit.scheduler.BukkitRunnable @@ -10,7 +10,6 @@ private[tlibscala] class ScalaTaskExecutor(task: => Any) extends BukkitRunnable case e: Throwable => throw e } } - } object ScalaTaskExecutor { diff --git a/src/main/scala/com/ilummc/tlibscala/Task.scala b/src/main/scala/io/lzzel/tlibscala/Task.scala similarity index 94% rename from src/main/scala/com/ilummc/tlibscala/Task.scala rename to src/main/scala/io/lzzel/tlibscala/Task.scala index 267ff07..a34b8a5 100644 --- a/src/main/scala/com/ilummc/tlibscala/Task.scala +++ b/src/main/scala/io/lzzel/tlibscala/Task.scala @@ -1,4 +1,4 @@ -package com.ilummc.tlibscala +package io.lzzel.tlibscala import org.bukkit.plugin.Plugin diff --git a/src/main/scala/com/ilummc/tlibscala/runtime/RichLocation.scala b/src/main/scala/io/lzzel/tlibscala/runtime/RichLocation.scala similarity index 93% rename from src/main/scala/com/ilummc/tlibscala/runtime/RichLocation.scala rename to src/main/scala/io/lzzel/tlibscala/runtime/RichLocation.scala index ef8bcf2..8e74abb 100644 --- a/src/main/scala/com/ilummc/tlibscala/runtime/RichLocation.scala +++ b/src/main/scala/io/lzzel/tlibscala/runtime/RichLocation.scala @@ -1,4 +1,4 @@ -package com.ilummc.tlibscala.runtime +package io.lzzel.tlibscala.runtime import org.bukkit.Location diff --git a/src/main/scala/io/lzzel/tlibscala/runtime/RichOfflinePlayer.scala b/src/main/scala/io/lzzel/tlibscala/runtime/RichOfflinePlayer.scala new file mode 100644 index 0000000..49aac50 --- /dev/null +++ b/src/main/scala/io/lzzel/tlibscala/runtime/RichOfflinePlayer.scala @@ -0,0 +1,28 @@ +package io.lzzel.tlibscala.runtime + +import io.izzel.taboolib.module.compat.EconomyHook +import io.izzel.taboolib.util.item.ItemBuilder +import org.bukkit.OfflinePlayer +import org.bukkit.inventory.ItemStack + +class RichOfflinePlayer(private val offlinePlayer: OfflinePlayer) { + + def getSkullItem: ItemStack = new ItemBuilder(offlinePlayer).build() + + def getMoney: Double = EconomyHook.get(offlinePlayer) + + def withdraw(x: Double): Unit = EconomyHook.remove(offlinePlayer, x) + + def deposit(x: Double): Unit = EconomyHook.add(offlinePlayer, x) + + def hasMoney(x: Double): Boolean = EconomyHook.get(offlinePlayer) >= x + +} + +object RichOfflinePlayer { + + implicit def player2rich(player: OfflinePlayer): RichOfflinePlayer = new RichOfflinePlayer(player) + + implicit def rich2player(player: RichOfflinePlayer): OfflinePlayer = player.offlinePlayer + +} \ No newline at end of file diff --git a/src/main/scala/io/lzzel/tlibscala/runtime/RichPlayer.scala b/src/main/scala/io/lzzel/tlibscala/runtime/RichPlayer.scala new file mode 100644 index 0000000..38688c7 --- /dev/null +++ b/src/main/scala/io/lzzel/tlibscala/runtime/RichPlayer.scala @@ -0,0 +1,40 @@ +package io.lzzel.tlibscala.runtime + +import io.izzel.taboolib.module.locale.TLocale +import io.izzel.taboolib.module.compat.PermissionHook +import io.izzel.taboolib.util.lite.Scoreboards +import org.bukkit.entity.Player + +class RichPlayer(private val player: Player) extends RichOfflinePlayer(player) { + + def sendActionBar(x: String): Unit = TLocale.Display.sendActionBar(player, x) + + def displaySidebarUnranked(title: String, elements: Array[String]): Unit = Scoreboards.display(player, elements: _*) + + def displaySidebarUnranked(title: String, elements: List[String]): Unit = Scoreboards.display(player, elements: _*) + + def displaySidebarUnranked(title: String, elements: String*): Unit = Scoreboards.display(player, elements: _*) + + def addPermission(perm: String): Unit = PermissionHook.addPermission(player, perm) + + def removePermission(perm: String): Unit = PermissionHook.removePermission(player, perm) + + def sendTitle(title: String, subtitle: String, fadein: Int, stay: Int, fadeout: Int): Unit = TLocale.Display.sendTitle(player, title, subtitle, fadein, stay, fadeout) + + def sendLocalizedMessage(node: String, params: String*): Unit = TLocale.sendTo(player, node, params: _*) + + def locale(node: String, params: String*): Unit = sendLocalizedMessage(node, params: _*) + + def <<(text: String): RichPlayer = { + player.sendMessage(text) + this + } +} + +object RichPlayer { + + implicit def player2rich(player: Player): RichPlayer = new RichPlayer(player) + + implicit def rich2player(player: RichPlayer): Player = player.player + +} diff --git a/src/main/scala/com/ilummc/tlibscala/runtime/RichVector.scala b/src/main/scala/io/lzzel/tlibscala/runtime/RichVector.scala similarity index 71% rename from src/main/scala/com/ilummc/tlibscala/runtime/RichVector.scala rename to src/main/scala/io/lzzel/tlibscala/runtime/RichVector.scala index 557dd3d..f12a79a 100644 --- a/src/main/scala/com/ilummc/tlibscala/runtime/RichVector.scala +++ b/src/main/scala/io/lzzel/tlibscala/runtime/RichVector.scala @@ -1,19 +1,16 @@ -package com.ilummc.tlibscala.runtime +package io.lzzel.tlibscala.runtime import org.bukkit.util.Vector class RichVector(private val vector: Vector) { - def +(vec: (Double, Double, Double)): Vector = - vector.setX(vector.getX + vec._1).setY(vector.getY + vec._2).setZ(vector.getZ + vec._3) - + def +(vec: (Double, Double, Double)): Vector = vector.setX(vector.getX + vec._1).setY(vector.getY + vec._2).setZ(vector.getZ + vec._3) def -(vec: (Double, Double, Double)): Vector = this.+(-vec._1, -vec._2, -vec._3) def *(x: Double): Vector = vector.multiply(x) def /(x: Double): Vector = this * (1 / x) - } object RichVector { diff --git a/src/main/scala/me/skymc/taboolib/Main.java b/src/main/scala/me/skymc/taboolib/Main.java deleted file mode 100644 index 322d709..0000000 --- a/src/main/scala/me/skymc/taboolib/Main.java +++ /dev/null @@ -1,238 +0,0 @@ -package me.skymc.taboolib; - -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.filter.TLoggerFilter; -import me.skymc.taboolib.database.GlobalDataManager; -import me.skymc.taboolib.database.PlayerDataManager; -import me.skymc.taboolib.economy.EcoUtils; -import me.skymc.taboolib.fileutils.ConfigUtils; -import me.skymc.taboolib.listener.TListenerHandler; -import me.skymc.taboolib.mysql.hikari.HikariHandler; -import me.skymc.taboolib.mysql.protect.MySQLConnection; -import me.skymc.taboolib.other.NumberUtils; -import me.skymc.taboolib.playerdata.DataUtils; -import me.skymc.taboolib.socket.TabooLibClient; -import me.skymc.taboolib.socket.TabooLibServer; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitRunnable; - -import java.io.File; -import java.util.Random; - -/** - * @author sky - */ -public class Main extends JavaPlugin { - - public Main() { - inst = this; - } - - public enum StorageType { - LOCAL, SQL - } - - private static Plugin inst; - private static File playerDataFolder; - private static File serverDataFolder; - private static StorageType storageType = StorageType.LOCAL; - private static boolean disable = false; - private static boolean started = false; - private static boolean isInternetOnline = false; - private FileConfiguration config = null; - - @Override - public FileConfiguration getConfig() { - return config; - } - - @Override - public void saveDefaultConfig() { - reloadConfig(); - } - - @Override - public void reloadConfig() { - File file = new File(getDataFolder(), "config.yml"); - if (!file.exists()) { - saveResource("config.yml", true); - } - config = ConfigUtils.load(this, file); - } - - @Override - public void onLoad() { - disable = false; - // 载入配置文件 - saveDefaultConfig(); - // 载入日志过滤 - TLoggerFilter.preInit(); - // 载入扩展 - TabooLibLoader.setupAddons(); - // 载入牛逼东西 - TLib.init(); - TLib.injectPluginManager(); - // 载入插件设置 - TabooLibLoader.setup(); - // 载入大饼 - TLib.initPost(); - } - - @Override - public void onEnable() { - // 载入日志过滤 - TLoggerFilter.postInit(); - // 注册插件配置 - TabooLibLoader.register(); - // 启动数据库储存方法 - if (getStorageType() == StorageType.SQL) { - GlobalDataManager.SQLMethod.startSQLMethod(); - } - // 文件保存 - Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> DataUtils.saveAllCaches(), 20, 20 * 120); - Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> PlayerDataManager.saveAllCaches(true, false), 20, 20 * 60); - // 文件监控 - TLib.getTLib().getConfigWatcher().addSimpleListener(new File(getDataFolder(), "config.yml"), this::reloadConfig); - // 插件联动 - new BukkitRunnable() { - - @Override - public void run() { - // 本地通讯网络终端 - if (getConfig().getBoolean("SERVER")) { - TabooLibServer.main(new String[0]); - } - // 本地通讯网络 - TabooLibClient.init(); - } - }.runTask(this); - // 启动 - started = true; - } - - @Override - public void onDisable() { - disable = true; - // 注销插件 - TabooLibLoader.unregister(); - // 保存数据 - Bukkit.getOnlinePlayers().forEach(x -> DataUtils.saveOnline(x.getName())); - // 结束线程 - Bukkit.getScheduler().cancelTasks(this); - // 保存插件数据 - DataUtils.saveAllCaches(); - // 保存玩家数据 - PlayerDataManager.saveAllPlayers(false, true); - // 注销连接池 - HikariHandler.closeDataSourceForce(); - // 注销监听器 - TListenerHandler.cancelListeners(); - // 结束数据库储存方法 - if (getStorageType() == StorageType.SQL) { - GlobalDataManager.SQLMethod.cancelSQLMethod(); - } - // 清理数据 - if (getStorageType() == StorageType.LOCAL && getConfig().getBoolean("DELETE-DATA")) { - getPlayerDataFolder().delete(); - } - // 清理数据 - if (getStorageType() == StorageType.SQL && getConfig().getBoolean("DELETE-VARIABLE")) { - GlobalDataManager.clearInvalidVariables(); - } - // 卸载牛逼玩意儿 - TLib.unload(); - // 关闭服务器 - Bukkit.shutdown(); - } - - // ********************************* - // - // Getter and Setter - // - // ********************************* - - public static Plugin getInst() { - return inst; - } - - public static String getPrefix() { - return "§8[§3§lTabooLib§8] §7"; - } - - 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 boolean isStarted() { - return started; - } - - 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; - } - - @Deprecated - public static Random getRandom() { - return NumberUtils.getRandom(); - } - - @Deprecated - public static String getTablePrefix() { - return inst.getConfig().getString("MYSQL.PREFIX"); - } - - @Deprecated - public static MySQLConnection getConnection() { - return null; - } - - @Deprecated - public static net.milkbowl.vault.economy.Economy getEconomy() { - return EcoUtils.getEconomy(); - } - - // ********************************* - // - // Private Setter - // - // ********************************* - - static void setIsInternetOnline(boolean isInternetOnline) { - Main.isInternetOnline = isInternetOnline; - } - - static void setPlayerDataFolder(File playerDataFolder) { - Main.playerDataFolder = playerDataFolder; - } - - static void setServerDataFolder(File serverDataFolder) { - Main.serverDataFolder = serverDataFolder; - } - - static void setStorageType(StorageType storageType) { - Main.storageType = storageType; - } -} diff --git a/src/main/scala/me/skymc/taboolib/TabooLib.java b/src/main/scala/me/skymc/taboolib/TabooLib.java deleted file mode 100644 index 6c41809..0000000 --- a/src/main/scala/me/skymc/taboolib/TabooLib.java +++ /dev/null @@ -1,169 +0,0 @@ -package me.skymc.taboolib; - -import me.skymc.taboolib.common.nms.NMSHandler; -import me.skymc.taboolib.other.NumberUtils; -import me.skymc.taboolib.playerdata.DataUtils; -import net.md_5.bungee.api.ChatColor; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; - -import java.util.Arrays; -import java.util.UUID; - -/** - * @author sky - */ -public class TabooLib { - - private static boolean spigot = false; - private static boolean silent = false; - - static { - try { - // 判断是否为独立客户端运行,不是判断 Bukkit 与 Spigot - Class.forName("org.bukkit.Bukkit"); - spigot = true; - } catch (Exception ignored) { - } - } - - /** - * 获取主类对象,因 Main 名称容易造成混淆所以转移至此 - */ - public static Main instance() { - return (Main) Main.getInst(); - } - - /** - * 插件是否为 TabooLib(沙雕方法) - */ - public static boolean isTabooLib(Plugin plugin) { - return plugin.equals(instance()) || plugin.getName().equals("TabooLib"); - } - - /** - * 插件是否依赖于 TabooLib(依赖或软兼容) - */ - public static boolean isDependTabooLib(Plugin plugin) { - return plugin.getDescription().getDepend().contains("TabooLib") || plugin.getDescription().getSoftDepend().contains("TabooLib"); - } - - /** - * 是否为 Spigot 核心,因 TabooLib 可在 BungeeCord 上运行所以添加此方法 - */ - public static boolean isSpigot() { - return spigot; - } - - /** - * 是否为静默模式 - */ - public static boolean isSilent() { - return silent; - } - - /** - * 设置静默模式,启用后将关闭部分提示 - */ - public static void setSilent(boolean silent) { - TabooLib.silent = silent; - } - - /** - * 获取 TabooLib 插件版本 - */ - public static double getPluginVersion() { - return NumberUtils.getDouble(Main.getInst().getDescription().getVersion()); - } - - /** - * 获取服务端版本 - */ - public static String getVersion() { - return Bukkit.getServer().getClass().getName().split("\\.")[3]; - } - - /** - * 获取服务端版本数字 - */ - public static int getVersionNumber() { - return getVerint(); - } - - /** - * 重置服务器序列号 - */ - public static void resetServerUID() { - DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString()); - } - - /** - * 是否为调试模式 - */ - public static boolean isDebug() { - return DataUtils.getPluginData("TabooLibrary", instance()).getBoolean("debug"); - } - - /** - * 切换调试模式 - */ - public static void setDebug(boolean debug) { - DataUtils.getPluginData("TabooLibrary", instance()).set("debug", debug); - } - - /** - * 发送调试信息 - */ - public static void debug(String... args) { - debug(instance(), args); - } - - /** - * 发送调试信息 - */ - public static void debug(Plugin plugin, String... args) { - if (TabooLib.isDebug()) { - Arrays.stream(args).forEach(var -> Bukkit.getConsoleSender().sendMessage(ChatColor.DARK_RED + "[TabooLib - DEBUG][" + plugin.getName() + "] " + ChatColor.RED + var)); - } - } - - /** - * 获取服务器序列号 - */ - public static String getServerUID() { - if (!DataUtils.getPluginData("TabooLibrary", null).contains("serverUID")) { - DataUtils.getPluginData("TabooLibrary", null).set("serverUID", UUID.randomUUID().toString()); - } - return DataUtils.getPluginData("TabooLibrary", null).getString("serverUID"); - } - - /** - * 获取服务器 TPS - */ - public static double[] getTPS() { - return NMSHandler.getHandler().getTPS(); - } - - @Deprecated - public static int getVerint() { - String version = getVersion(); - if (version.startsWith("v1_7")) { - return 10700; - } else if (version.startsWith("v1_8")) { - return 10800; - } else if (version.startsWith("v1_9")) { - return 10900; - } else if (version.startsWith("v1_10")) { - return 11000; - } else if (version.startsWith("v1_11")) { - return 11100; - } else if (version.startsWith("v1_12")) { - return 11200; - } else if (version.startsWith("v1_13")) { - return 11300; - } else if (version.startsWith("v1_14")) { - return 11400; - } - return 0; - } -} diff --git a/src/main/scala/me/skymc/taboolib/TabooLibDatabase.java b/src/main/scala/me/skymc/taboolib/TabooLibDatabase.java deleted file mode 100644 index 772b759..0000000 --- a/src/main/scala/me/skymc/taboolib/TabooLibDatabase.java +++ /dev/null @@ -1,128 +0,0 @@ -package me.skymc.taboolib; - -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.mysql.builder.SQLColumn; -import me.skymc.taboolib.mysql.builder.SQLColumnType; -import me.skymc.taboolib.mysql.builder.SQLHost; -import me.skymc.taboolib.mysql.builder.SQLTable; -import me.skymc.taboolib.mysql.hikari.HikariHandler; -import me.skymc.taboolib.string.StringUtils; -import org.bukkit.Bukkit; - -import javax.sql.DataSource; -import java.util.HashMap; - -/** - * @Author sky - * @Since 2018-08-23 17:15 - */ -public class TabooLibDatabase { - - private static SQLHost host; - private static DataSource dataSource; - private static HashMap tables = new HashMap<>(); - - static void init() { - if (Main.getStorageType() != Main.StorageType.SQL) { - return; - } - // 数据库地址 - host = new SQLHost( - // 地址 - Main.getInst().getConfig().getString("MYSQL.HOST"), - // 用户 - Main.getInst().getConfig().getString("MYSQL.USER"), - // 端口 - Main.getInst().getConfig().getString("MYSQL.POST"), - // 密码 - Main.getInst().getConfig().getString("MYSQL.PASSWORD"), - // 数据库 - Main.getInst().getConfig().getString("MYSQL.DATABASE"), TabooLib.instance()); - // 连接数据库 - try { - dataSource = HikariHandler.createDataSource(host); - } catch (Exception ignored) { - TLocale.Logger.error("NOTIFY.ERROR-CONNECTION-FAIL"); - return; - } - // 创建各项数据表 - createTableWithPlayerData(); - createTableWithPluginData(); - createTableWithServerUUID(); - } - - /** - * 创建玩家数据表 - */ - static void createTableWithPlayerData() { - SQLTable table = new SQLTable(Main.getTablePrefix() + "_playerdata", SQLColumn.PRIMARY_KEY_ID, new SQLColumn(SQLColumnType.TEXT, "username"), new SQLColumn(SQLColumnType.TEXT, "configuration")); - table.executeUpdate(table.createQuery()).dataSource(dataSource).run(); - tables.put("playerdata", table); - } - - /** - * 创建插件数据表 - */ - static void createTableWithPluginData() { - SQLTable table = new SQLTable(Main.getTablePrefix() + "_plugindata", SQLColumn.PRIMARY_KEY_ID, new SQLColumn(SQLColumnType.TEXT, "name"), new SQLColumn(SQLColumnType.TEXT, "variable"), new SQLColumn(SQLColumnType.TEXT, "upgrade")); - table.executeUpdate(table.createQuery()).dataSource(dataSource).run(); - tables.put("plugindata", table); - } - - /** - * 创建服务器数据表 - */ - static void createTableWithServerUUID() { - SQLTable table = new SQLTable(Main.getTablePrefix() + "_serveruuid", SQLColumn.PRIMARY_KEY_ID, new SQLColumn(SQLColumnType.TEXT, "uuid"), new SQLColumn(SQLColumnType.TEXT, "hash")); - table.executeUpdate(table.createQuery()).dataSource(dataSource).run(); - tables.put("serveruuid", table); - // 获取当前服务器信息 - String hash = getServerHash(TabooLib.getServerUID()); - if (hash == null) { - // 写入序列号 - table.executeUpdate("insert into " + table.getTableName() + " values(null, ?, ?)") - .dataSource(dataSource) - .statement(s -> { - s.setString(1, TabooLib.getServerUID()); - s.setString(2, StringUtils.hashKeyForDisk(Main.getInst().getDataFolder().getPath())); - }).run(); - } else if (!hash.equals(StringUtils.hashKeyForDisk(Main.getInst().getDataFolder().getPath()))) { - TLocale.Logger.error("NOTIFY.ERROR-SERVER-KEY"); - TabooLib.resetServerUID(); - Bukkit.shutdown(); - } - } - - /** - * 获取服务器序列号对应的目录哈希值 - * - * @param uuid 服务器序列号 - * @return 目录哈希值 - */ - public static String getServerHash(String uuid) { - SQLTable table = tables.get("serveruuid"); - return table.executeQuery("select * from " + table.getTableName() + " where uuid = ?") - .dataSource(dataSource) - .statement(s -> s.setString(1, uuid)) - .resultNext(r -> r.getString("hash")) - .run(null, ""); - } - - // ********************************* - // - // Getter and Setter - // - // ********************************* - - public static SQLHost getHost() { - return host; - } - - public static HashMap getTables() { - return tables; - } - - public static DataSource getDataSource() { - return dataSource; - } -} diff --git a/src/main/scala/me/skymc/taboolib/TabooLibLoader.java b/src/main/scala/me/skymc/taboolib/TabooLibLoader.java deleted file mode 100644 index 8048b8f..0000000 --- a/src/main/scala/me/skymc/taboolib/TabooLibLoader.java +++ /dev/null @@ -1,305 +0,0 @@ -package me.skymc.taboolib; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.annotations.Dependency; -import com.ilummc.tlib.dependency.TDependencyLoader; -import com.ilummc.tlib.inject.TDependencyInjector; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.bstats.Metrics; -import me.skymc.taboolib.deprecated.TabooLibDeprecated; -import me.skymc.taboolib.events.TPluginEnableEvent; -import me.skymc.taboolib.fileutils.FileUtils; -import me.skymc.taboolib.listener.TListener; -import me.skymc.taboolib.listener.TListenerHandler; -import me.skymc.taboolib.methods.ReflectionUtils; -import me.skymc.taboolib.playerdata.DataUtils; -import org.bukkit.Bukkit; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.server.PluginDisableEvent; -import org.bukkit.plugin.Plugin; - -import java.io.File; -import java.io.InputStream; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.net.InetAddress; -import java.util.*; - -/** - * @Author sky - * @Since 2018-08-23 17:04 - */ -@TListener -public class TabooLibLoader implements Listener { - - /* - 关于 TabooLib 各项自动化接口的执行顺序 - - [ENABLING] - 第一阶段:运行 @TInject(Instance Inject) - 第二阶段(先后):实例化 @TListener -> 实例化 @Instantiable - 第三阶段(并行):运行 @TFunction & 运行 @TInject - - [ENABLED] - 第三阶段:注册 @TListener - */ - - static TabooLibDeprecated tabooLibDeprecated; - static Map> pluginClasses = Maps.newHashMap(); - static List loaders = Lists.newArrayList(); - static List tasks = Lists.newArrayList(); - static boolean started; - - static void setup() { - testInternet(); - setupDataFolder(); - setupDatabase(); - setupLibraries(); - } - - static void register() { - setupClasses(); - preLoadClasses(); - registerListener(); - registerMetrics(); - postLoadClasses(); - try { - tabooLibDeprecated = new TabooLibDeprecated(); - } catch (Exception e) { - e.printStackTrace(); - } - Bukkit.getScheduler().runTask(TabooLib.instance(), () -> { - for (Runnable task : tasks) { - try { - task.run(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - - static void unregister() { - unloadClasses(); - try { - tabooLibDeprecated.unregister(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static TabooLibDeprecated getTabooLibDeprecated() { - return tabooLibDeprecated; - } - - public static Optional> getPluginClasses(Plugin plugin) { - return Optional.ofNullable(pluginClasses.get(plugin.getName())); - } - - public static List getPluginClassSafely(Plugin plugin) { - List classes = pluginClasses.get(plugin.getName()); - return classes == null ? new ArrayList<>() : new ArrayList<>(classes); - } - - public static void runTaskOnEnabled(Runnable runnable) { - if (Main.isStarted()) { - Bukkit.getScheduler().runTask(TabooLib.instance(), () -> { - try { - runnable.run(); - } catch (Throwable t) { - t.printStackTrace(); - } - }); - } else { - tasks.add(runnable); - } - } - - static boolean isLoader(Class pluginClass) { - return !Loader.class.equals(pluginClass) && Loader.class.isAssignableFrom(pluginClass); - } - - static void preLoadClasses() { - pluginClasses.forEach((key, classes) -> classes.forEach(pluginClass -> preLoadClass(Bukkit.getPluginManager().getPlugin(key), pluginClass))); - } - - static void postLoadClasses() { - pluginClasses.forEach((key, classes) -> classes.forEach(pluginClass -> postLoadClass(Bukkit.getPluginManager().getPlugin(key), pluginClass))); - } - - static void unloadClasses() { - pluginClasses.forEach((key, classes) -> classes.forEach(pluginClass -> unloadClass(Bukkit.getPluginManager().getPlugin(key), pluginClass))); - } - - static void registerListener() { - TListenerHandler.setupListeners(); - Bukkit.getScheduler().runTask(TabooLib.instance(), TListenerHandler::registerListeners); - } - - static void registerMetrics() { - Metrics metrics = new Metrics(TabooLib.instance()); - metrics.addCustomChart(new Metrics.SingleLineChart("plugins_using_taboolib", () -> Math.toIntExact(Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(plugin -> plugin.getDescription().getDepend().contains("TabooLib")).count()))); - } - - static void setupDataFolder() { - Main.setPlayerDataFolder(FileUtils.folder(Main.getInst().getConfig().getString("DATAURL.PLAYER-DATA"))); - Main.setServerDataFolder(FileUtils.folder(Main.getInst().getConfig().getString("DATAURL.SERVER-DATA"))); - } - - static void setupDatabase() { - DataUtils.addPluginData("TabooLibrary", null); - Main.setStorageType(Main.StorageType.LOCAL); -// Main.setStorageType(Main.getInst().getConfig().getBoolean("MYSQL.ENABLE") ? Main.StorageType.SQL : Main.StorageType.LOCAL); -// TabooLibDatabase.init(); - } - - static void setupAddons() { - File origin = new File(TabooLib.instance().getDataFolder(), "Addons/TabooLibDeprecated.jar"); - origin.delete(); - // 傻逼 Gradle 的 shadow 插件会将所有 jar 排除 - // https://github.com/johnrengelman/shadow/issues/276 - TabooLib.instance().saveResource("Addons/TabooLibDeprecated", true); - File from = new File(TabooLib.instance().getDataFolder(), "Addons/TabooLibDeprecated"); - from.renameTo(origin); - from.delete(); - File file = new File(TabooLib.instance().getDataFolder(), "Addons"); - if (file.exists()) { - Arrays.stream(file.listFiles()).forEach(listFile -> TDependencyLoader.addToPath(TabooLib.instance(), listFile)); - } - } - - static void setupLibraries() { - if (Main.isOfflineVersion()) { - Arrays.stream(TDependencyInjector.getDependencies(TLib.getTLib())).filter(dependency -> dependency.type() == Dependency.Type.LIBRARY && dependency.maven().matches(".*:.*:.*")).map(dependency -> String.join("-", dependency.maven().split(":")) + ".jar").forEach(fileName -> { - 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)); - } - }); - } - } - - static void testInternet() { - try { - InetAddress inetAddress = InetAddress.getByName(Main.getInst().getConfig().getString("TEST-URL", "aliyun.com")); - Main.setIsInternetOnline(inetAddress.isReachable(10000)); - } catch (Exception ignored) { - } - if (!Main.isInternetOnline() && !Main.isOfflineVersion() && !Main.isLibrariesExists()) { - TLocale.Logger.error("TLIB.LOAD-FAIL-OFFLINE", Main.getInst().getDescription().getVersion()); - for (; ; ) { - // 停止主线程 - } - } - } - - static void setupClasses(Plugin plugin) { - if (TabooLib.isTabooLib(plugin) || TabooLib.isDependTabooLib(plugin)) { - try { - long time = System.currentTimeMillis(); - List classes; - IgnoreClasses annotation = plugin.getClass().getAnnotation(IgnoreClasses.class); - if (annotation != null) { - classes = FileUtils.getClasses(plugin, annotation.value()); - } else { - classes = FileUtils.getClasses(plugin); - } - TabooLib.debug("Saved " + classes.size() + " classes (" + plugin.getName() + ") (" + (System.currentTimeMillis() - time) + "ms)"); - pluginClasses.put(plugin.getName(), classes); - } catch (Exception ignored) { - } - } - } - - static void setupClasses() { - Arrays.stream(Bukkit.getPluginManager().getPlugins()).forEach(TabooLibLoader::setupClasses); - pluginClasses.get("TabooLib").stream().filter(TabooLibLoader::isLoader).forEach(pluginClass -> { - try { - loaders.add((Loader) ReflectionUtils.instantiateObject(pluginClass)); - } catch (Exception e) { - e.printStackTrace(); - } - loaders.sort(Comparator.comparingInt(Loader::priority)); - }); - } - - static void preLoadClass(Plugin plugin, Class loadClass) { - loaders.forEach(loader -> { - try { - loader.preLoad(plugin, loadClass); - } catch (NoClassDefFoundError ignore) { - } catch (Throwable e) { - e.printStackTrace(); - } - }); - } - - static void postLoadClass(Plugin plugin, Class loadClass) { - loaders.forEach(loader -> { - try { - loader.postLoad(plugin, loadClass); - } catch (NoClassDefFoundError ignore) { - } catch (Throwable e) { - e.printStackTrace(); - } - }); - } - - static void unloadClass(Plugin plugin, Class loadClass) { - loaders.forEach(loader -> { - try { - loader.unload(plugin, loadClass); - } catch (NoClassDefFoundError ignore) { - } catch (Throwable e) { - e.printStackTrace(); - } - }); - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onEnablePre(TPluginEnableEvent e) { - setupClasses(e.getPlugin()); - Optional.ofNullable(pluginClasses.get(e.getPlugin().getName())).ifPresent(classes -> classes.forEach(pluginClass -> preLoadClass(e.getPlugin(), pluginClass))); - } - - @EventHandler - public void onEnablePost(TPluginEnableEvent e) { - Optional.ofNullable(pluginClasses.get(e.getPlugin().getName())).ifPresent(classes -> classes.forEach(pluginClass -> postLoadClass(e.getPlugin(), pluginClass))); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onDisable(PluginDisableEvent e) { - Optional.ofNullable(pluginClasses.remove(e.getPlugin().getName())).ifPresent(classes -> classes.forEach(pluginClass -> unloadClass(e.getPlugin(), pluginClass))); - } - - public interface Loader { - - default void preLoad(Plugin plugin, Class loadClass) { - } - - default void postLoad(Plugin plugin, Class loadClass) { - } - - default void unload(Plugin plugin, Class cancelClass) { - } - - default int priority() { - return 0; - } - } - - @Target(ElementType.TYPE) - @Retention(RetentionPolicy.RUNTIME) - public @interface IgnoreClasses { - - String[] value(); - - } -} diff --git a/src/main/scala/me/skymc/taboolib/anvil/AnvilContainer.java b/src/main/scala/me/skymc/taboolib/anvil/AnvilContainer.java deleted file mode 100644 index 0ebfc47..0000000 --- a/src/main/scala/me/skymc/taboolib/anvil/AnvilContainer.java +++ /dev/null @@ -1,29 +0,0 @@ -package me.skymc.taboolib.anvil; - -import org.bukkit.entity.Player; - -/** - * @Author sky - * @Since 2018-09-08 15:47 - */ -public class AnvilContainer extends net.minecraft.server.v1_12_R1.ContainerAnvil { - - public AnvilContainer(net.minecraft.server.v1_12_R1.EntityHuman player) { - super(player.inventory, player.world, new net.minecraft.server.v1_12_R1.BlockPosition(0, 0, 0), player); - } - - @Override - public boolean a(net.minecraft.server.v1_12_R1.EntityHuman player) { - return true; - } - - public static void openAnvil(Player p) { - net.minecraft.server.v1_12_R1.EntityPlayer player = ((org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer) p).getHandle(); - AnvilContainer container = new AnvilContainer(player); - int c = player.nextContainerCounter(); - player.playerConnection.sendPacket(new net.minecraft.server.v1_12_R1.PacketPlayOutOpenWindow(c, "minecraft:anvil", new net.minecraft.server.v1_12_R1.ChatMessage("Repairing"), 0)); - player.activeContainer = container; - player.activeContainer.windowId = c; - player.activeContainer.addSlotListener(player); - } -} \ No newline at end of file diff --git a/src/main/scala/me/skymc/taboolib/anvil/AnvilContainerAPI.java b/src/main/scala/me/skymc/taboolib/anvil/AnvilContainerAPI.java deleted file mode 100644 index 904910c..0000000 --- a/src/main/scala/me/skymc/taboolib/anvil/AnvilContainerAPI.java +++ /dev/null @@ -1,44 +0,0 @@ -package me.skymc.taboolib.anvil; - -import com.ilummc.tlib.util.asm.AsmClassLoader; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.common.loader.Instantiable; -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; - -/** - * @author sky - */ -@Instantiable("AnvilContainerAPI") -public class AnvilContainerAPI implements Listener { - - private static Class impl; - - public AnvilContainerAPI() { - try { - impl = AsmClassLoader.createNewClass("me.skymc.taboolib.anvil.AnvilContainer", AnvilContainerGenerator.generate()); - Bukkit.getPluginManager().registerEvents(this, TabooLib.instance()); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void openAnvil(Player player) { - try { - impl.getMethod("openAnvil", Player.class).invoke(impl, player); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @EventHandler - public void example(PlayerCommandPreprocessEvent e) { - if (e.getMessage().equalsIgnoreCase("/anvilExample") && e.getPlayer().hasPermission("taboolib.admin")) { - e.setCancelled(true); - openAnvil(e.getPlayer()); - } - } -} diff --git a/src/main/scala/me/skymc/taboolib/anvil/AnvilContainerGenerator.java b/src/main/scala/me/skymc/taboolib/anvil/AnvilContainerGenerator.java deleted file mode 100644 index eda7cf3..0000000 --- a/src/main/scala/me/skymc/taboolib/anvil/AnvilContainerGenerator.java +++ /dev/null @@ -1,142 +0,0 @@ -package me.skymc.taboolib.anvil; - -import me.skymc.taboolib.TabooLib; -import org.objectweb.asm.*; - -/** - * @author idea - */ -public class AnvilContainerGenerator { - - public static byte[] generate() { - String version = TabooLib.getVersion(); - ClassWriter cw = new ClassWriter(0); - FieldVisitor fv; - MethodVisitor mv; - AnnotationVisitor av0; - cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, "me/skymc/taboolib/anvil/AnvilContainer", null, "net/minecraft/server/" + version + "/ContainerAnvil", null); - cw.visitSource("AnvilContainer.java", null); - { - mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "(Lnet/minecraft/server/" + version + "/EntityHuman;)V", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(12, l0); - mv.visitVarInsn(Opcodes.ALOAD, 0); - mv.visitVarInsn(Opcodes.ALOAD, 1); - mv.visitFieldInsn(Opcodes.GETFIELD, "net/minecraft/server/" + version + "/EntityHuman", "inventory", "Lnet/minecraft/server/" + version + "/PlayerInventory;"); - mv.visitVarInsn(Opcodes.ALOAD, 1); - mv.visitFieldInsn(Opcodes.GETFIELD, "net/minecraft/server/" + version + "/EntityHuman", "world", "Lnet/minecraft/server/" + version + "/World;"); - mv.visitTypeInsn(Opcodes.NEW, "net/minecraft/server/" + version + "/BlockPosition"); - mv.visitInsn(Opcodes.DUP); - mv.visitInsn(Opcodes.ICONST_0); - mv.visitInsn(Opcodes.ICONST_0); - mv.visitInsn(Opcodes.ICONST_0); - mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "net/minecraft/server/" + version + "/BlockPosition", "", "(III)V", false); - mv.visitVarInsn(Opcodes.ALOAD, 1); - mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "net/minecraft/server/" + version + "/ContainerAnvil", "", "(Lnet/minecraft/server/" + version + "/PlayerInventory;Lnet/minecraft/server/" + version + "/World;Lnet/minecraft/server/" + version + "/BlockPosition;Lnet/minecraft/server/" + version + "/EntityHuman;)V", false); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLineNumber(13, l1); - mv.visitInsn(Opcodes.RETURN); - Label l2 = new Label(); - mv.visitLabel(l2); - mv.visitLocalVariable("this", "Lme/skymc/taboolib/anvil/AnvilContainer;", null, l0, l2, 0); - mv.visitLocalVariable("player", "Lnet/minecraft/server/" + version + "/EntityHuman;", null, l0, l2, 1); - mv.visitMaxs(8, 2); - mv.visitEnd(); - } - { - mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "a", "(Lnet/minecraft/server/" + version + "/EntityHuman;)Z", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(17, l0); - mv.visitInsn(Opcodes.ICONST_1); - mv.visitInsn(Opcodes.IRETURN); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLocalVariable("this", "Lme/skymc/taboolib/anvil/AnvilContainer;", null, l0, l1, 0); - mv.visitLocalVariable("player", "Lnet/minecraft/server/" + version + "/EntityHuman;", null, l0, l1, 1); - mv.visitMaxs(1, 2); - mv.visitEnd(); - } - { - mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "openAnvil", "(Lorg/bukkit/entity/Player;)V", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(21, l0); - mv.visitVarInsn(Opcodes.ALOAD, 0); - mv.visitTypeInsn(Opcodes.CHECKCAST, "org/bukkit/craftbukkit/" + version + "/entity/CraftPlayer"); - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/bukkit/craftbukkit/" + version + "/entity/CraftPlayer", "getHandle", "()Lnet/minecraft/server/" + version + "/EntityPlayer;", false); - mv.visitVarInsn(Opcodes.ASTORE, 1); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLineNumber(22, l1); - mv.visitTypeInsn(Opcodes.NEW, "me/skymc/taboolib/anvil/AnvilContainer"); - mv.visitInsn(Opcodes.DUP); - mv.visitVarInsn(Opcodes.ALOAD, 1); - mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "me/skymc/taboolib/anvil/AnvilContainer", "", "(Lnet/minecraft/server/" + version + "/EntityHuman;)V", false); - mv.visitVarInsn(Opcodes.ASTORE, 2); - Label l2 = new Label(); - mv.visitLabel(l2); - mv.visitLineNumber(23, l2); - mv.visitVarInsn(Opcodes.ALOAD, 1); - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "net/minecraft/server/" + version + "/EntityPlayer", "nextContainerCounter", "()I", false); - mv.visitVarInsn(Opcodes.ISTORE, 3); - Label l3 = new Label(); - mv.visitLabel(l3); - mv.visitLineNumber(24, l3); - mv.visitVarInsn(Opcodes.ALOAD, 1); - mv.visitFieldInsn(Opcodes.GETFIELD, "net/minecraft/server/" + version + "/EntityPlayer", "playerConnection", "Lnet/minecraft/server/" + version + "/PlayerConnection;"); - mv.visitTypeInsn(Opcodes.NEW, "net/minecraft/server/" + version + "/PacketPlayOutOpenWindow"); - mv.visitInsn(Opcodes.DUP); - mv.visitVarInsn(Opcodes.ILOAD, 3); - mv.visitLdcInsn("minecraft:anvil"); - mv.visitTypeInsn(Opcodes.NEW, "net/minecraft/server/" + version + "/ChatMessage"); - mv.visitInsn(Opcodes.DUP); - mv.visitLdcInsn("Repairing"); - mv.visitInsn(Opcodes.ICONST_0); - mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); - mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "net/minecraft/server/" + version + "/ChatMessage", "", "(Ljava/lang/String;[Ljava/lang/Object;)V", false); - mv.visitInsn(Opcodes.ICONST_0); - mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "net/minecraft/server/" + version + "/PacketPlayOutOpenWindow", "", "(ILjava/lang/String;Lnet/minecraft/server/" + version + "/IChatBaseComponent;I)V", false); - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "net/minecraft/server/" + version + "/PlayerConnection", "sendPacket", "(Lnet/minecraft/server/" + version + "/Packet;)V", false); - Label l4 = new Label(); - mv.visitLabel(l4); - mv.visitLineNumber(25, l4); - mv.visitVarInsn(Opcodes.ALOAD, 1); - mv.visitVarInsn(Opcodes.ALOAD, 2); - mv.visitFieldInsn(Opcodes.PUTFIELD, "net/minecraft/server/" + version + "/EntityPlayer", "activeContainer", "Lnet/minecraft/server/" + version + "/Container;"); - Label l5 = new Label(); - mv.visitLabel(l5); - mv.visitLineNumber(26, l5); - mv.visitVarInsn(Opcodes.ALOAD, 1); - mv.visitFieldInsn(Opcodes.GETFIELD, "net/minecraft/server/" + version + "/EntityPlayer", "activeContainer", "Lnet/minecraft/server/" + version + "/Container;"); - mv.visitVarInsn(Opcodes.ILOAD, 3); - mv.visitFieldInsn(Opcodes.PUTFIELD, "net/minecraft/server/" + version + "/Container", "windowId", "I"); - Label l6 = new Label(); - mv.visitLabel(l6); - mv.visitLineNumber(27, l6); - mv.visitVarInsn(Opcodes.ALOAD, 1); - mv.visitFieldInsn(Opcodes.GETFIELD, "net/minecraft/server/" + version + "/EntityPlayer", "activeContainer", "Lnet/minecraft/server/" + version + "/Container;"); - mv.visitVarInsn(Opcodes.ALOAD, 1); - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "net/minecraft/server/" + version + "/Container", "addSlotListener", "(Lnet/minecraft/server/" + version + "/ICrafting;)V", false); - Label l7 = new Label(); - mv.visitLabel(l7); - mv.visitLineNumber(28, l7); - mv.visitInsn(Opcodes.RETURN); - Label l8 = new Label(); - mv.visitLabel(l8); - mv.visitLocalVariable("p", "Lorg/bukkit/entity/Player;", null, l0, l8, 0); - mv.visitLocalVariable("player", "Lnet/minecraft/server/" + version + "/EntityPlayer;", null, l1, l8, 1); - mv.visitLocalVariable("container", "Lme/skymc/taboolib/anvil/AnvilContainer;", null, l2, l8, 2); - mv.visitLocalVariable("c", "I", null, l3, l8, 3); - mv.visitMaxs(9, 4); - mv.visitEnd(); - } - cw.visitEnd(); - return cw.toByteArray(); - } -} diff --git a/src/main/scala/me/skymc/taboolib/bungee/TabooLibBungee.java b/src/main/scala/me/skymc/taboolib/bungee/TabooLibBungee.java deleted file mode 100644 index 1709569..0000000 --- a/src/main/scala/me/skymc/taboolib/bungee/TabooLibBungee.java +++ /dev/null @@ -1,11 +0,0 @@ -package me.skymc.taboolib.bungee; - -import net.md_5.bungee.api.plugin.Plugin; - -/** - * @Author sky - * @Since 2018-08-09 11:47 - */ -public class TabooLibBungee extends Plugin { - -} diff --git a/src/main/scala/me/skymc/taboolib/cloud/TCloudCommand.java b/src/main/scala/me/skymc/taboolib/cloud/TCloudCommand.java deleted file mode 100644 index dd6a2cf..0000000 --- a/src/main/scala/me/skymc/taboolib/cloud/TCloudCommand.java +++ /dev/null @@ -1,250 +0,0 @@ -package me.skymc.taboolib.cloud; - -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.cloud.expansion.Expansion; -import me.skymc.taboolib.cloud.expansion.ExpansionType; -import me.skymc.taboolib.commands.internal.BaseMainCommand; -import me.skymc.taboolib.commands.internal.BaseSubCommand; -import me.skymc.taboolib.commands.internal.TCommand; -import me.skymc.taboolib.commands.internal.plugin.TLibLocale; -import me.skymc.taboolib.commands.internal.type.CommandArgument; -import me.skymc.taboolib.commands.internal.type.CommandRegister; -import me.skymc.taboolib.common.util.SimpleIterator; -import me.skymc.taboolib.fileutils.FileUtils; -import me.skymc.taboolib.plugin.PluginUtils; -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.util.NumberConversions; - -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * @Author sky - * @Since 2018-09-30 19:17 - */ -@TCommand( - name = "taboolibcloud", - permission = "taboolib.admin", - aliases = "tcloud" -) -public class TCloudCommand extends BaseMainCommand { - - @CommandRegister - BaseSubCommand refresh = new BaseSubCommand() { - @Override - public String getLabel() { - return "refresh"; - } - - @Override - public String getDescription() { - return TLibLocale.description("TCLOUD", "REFRESH"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.REFRESH.SUCCESS"); - TCloudLoader.refresh(); - } - }; - @CommandRegister(priority = 1) - BaseSubCommand status = new BaseSubCommand() { - @Override - public String getLabel() { - return "status"; - } - - @Override - public String getDescription() { - return TLibLocale.description("TCLOUD", "STATUS"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - if (!TCloudLoader.isConnected()) { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.STATUS.CONNECT-FAILED"); - } else { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.STATUS.STATUS", String.valueOf(TCloudLoader.getExpansionInternal().size() + TCloudLoader.getExpansionPlugins().size()), String.valueOf(TCloudLoader.getExpansionInternal().size()), String.valueOf(TCloudLoader.getExpansionPlugins().size())); - } - } - }; - @CommandRegister(priority = 2) - BaseSubCommand info = new BaseSubCommand() { - @Override - public String getLabel() { - return "info"; - } - - @Override - public String getDescription() { - return TLibLocale.description("TCLOUD", "INFO"); - } - - @Override - public CommandArgument[] getArguments() { - return TLibLocale.arguments("TCLOUD", "INFO", 1); - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - Expansion expansion = TCloudLoader.getExpansion(args[0]); - if (expansion == null) { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.INFO.EXPANSION-NOT-FOUND", args[0]); - } else { - String builder = Arrays.stream(expansion.getAuthor()).map(author -> author + ", ").collect(Collectors.joining()); - TLocale.sendTo(sender, "COMMANDS.TCLOUD.INFO.EXPANSION-INFO", expansion.getName(), builder.substring(0, builder.length() - 2), expansion.getVersion(), expansion.getDescription(), expansion.getLastUpdate(), expansion.getLastUpdateNote()); - TLocale.sendTo(sender, "COMMANDS.TCLOUD.INFO.EXPANSION-INFO-DETAIL.0"); - Arrays.stream(expansion.getDetail()).forEach(detail -> TLocale.sendTo(sender, "COMMANDS.TCLOUD.INFO.EXPANSION-INFO-DETAIL.1", detail)); - } - } - }; - - @CommandRegister(priority = 3) - BaseSubCommand download = new BaseSubCommand() { - @Override - public String getLabel() { - return "download"; - } - - @Override - public String getDescription() { - return TLibLocale.description("TCLOUD", "DOWNLOAD"); - } - - @Override - public CommandArgument[] getArguments() { - return TLibLocale.arguments("TCLOUD", "DOWNLOAD", 1); - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - Expansion expansion = TCloudLoader.getExpansion(args[0]); - if (expansion == null) { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.DOWNLOAD.EXPANSION-NOT-FOUND", args[0]); - } else if (!expansion.canUse()) { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.DOWNLOAD.EXPANSION-VERSION", args[0], String.valueOf(expansion.getDependVersion())); - } else if (TCloudLoader.isExpansionExists(expansion)) { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.DOWNLOAD.EXPANSION-EXISTS", args[0]); - } else { - Bukkit.getScheduler().runTaskAsynchronously(TabooLib.instance(), () -> { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.DOWNLOAD.DOWNLOAD-START", args[0], expansion.getLink()); - FileUtils.download(expansion.getLink(), expansion.getFile()); - TLocale.sendTo(sender, "COMMANDS.TCLOUD.DOWNLOAD.DOWNLOAD-SUCCESS", args[0]); - }); - } - } - }; - - @CommandRegister(priority = 4) - BaseSubCommand update = new BaseSubCommand() { - @Override - public String getLabel() { - return "update"; - } - - @Override - public String getDescription() { - return TLibLocale.description("TCLOUD", "UPDATE"); - } - - @Override - public CommandArgument[] getArguments() { - return TLibLocale.arguments("TCLOUD", "UPDATE", 1); - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - Expansion expansion = TCloudLoader.getExpansion(args[0]); - if (expansion == null) { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.UPDATE.EXPANSION-NOT-FOUND", args[0]); - } else if (!TCloudLoader.isExpansionExists(expansion)) { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.UPDATE.EXPANSION-NOT-EXISTS", args[0]); - } else if (!expansion.canUpdate()) { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.UPDATE.EXPANSION-NO-UPDATE", args[0]); - } else if (!expansion.canUse()) { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.UPDATE.EXPANSION-VERSION", args[0], String.valueOf(expansion.getDependVersion())); - } else { - Bukkit.getScheduler().runTaskAsynchronously(TabooLib.instance(), () -> { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.UPDATE.UPDATE-START", args[0], expansion.getVersion(), expansion.getLink()); - FileUtils.download(expansion.getLink(), PluginUtils.getPluginFile(expansion.getName())); - TLocale.sendTo(sender, "COMMANDS.TCLOUD.UPDATE.UPDATE-SUCCESS", args[0]); - }); - } - } - }; - - @CommandRegister(priority = 5) - BaseSubCommand list = new BaseSubCommand() { - @Override - public String getLabel() { - return "list"; - } - - @Override - public String getDescription() { - return TLibLocale.description("TCLOUD", "LIST"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[] { - TLibLocale.argument("TCLOUD", "LIST", 0), - TLibLocale.argument("TCLOUD", "LIST", 1, false) - }; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - ExpansionType type; - switch (args[0].toLowerCase()) { - case "plugins": - type = ExpansionType.PLUGIN; - break; - case "internal": - type = ExpansionType.INTERNAL; - break; - default: - TLocale.sendTo(sender, "COMMANDS.TCLOUD.LIST.INVALID-TYPE.0"); - return; - } - Map expansions = type == ExpansionType.PLUGIN ? TCloudLoader.getExpansionPlugins() : TCloudLoader.getExpansionInternal(); - int page = args.length < 2 ? 1 : NumberConversions.toInt(args[1]); - int pageMax = (expansions.size() / 5) + ((expansions.size() % 5) == 0 ? 0 : 1); - if (page < 1 || page > pageMax) { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.LIST.INVALID-TYPE.1"); - return; - } - TLocale.sendTo(sender, "COMMANDS.TCLOUD.LIST.LIST-HEAD", type.name(), String.valueOf(page), String.valueOf(pageMax)); - int i = (page - 1) * 5; - for (Map.Entry entry : new SimpleIterator(expansions).mapIterator((page - 1) * 5, page * 5)) { - if (!TCloudLoader.isExpansionExists(entry.getValue())) { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.LIST.LIST-EXPANSION.0", String.valueOf(++i), entry.getValue().getName(), Arrays.toString(entry.getValue().getAuthor())); - } else if (entry.getValue().canUpdate()) { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.LIST.LIST-EXPANSION.1", String.valueOf(++i), entry.getValue().getName(), Arrays.toString(entry.getValue().getAuthor())); - } else { - TLocale.sendTo(sender, "COMMANDS.TCLOUD.LIST.LIST-EXPANSION.2", String.valueOf(++i), entry.getValue().getName(), Arrays.toString(entry.getValue().getAuthor())); - } - } - TLocale.sendTo(sender, "COMMANDS.TCLOUD.LIST.LIST-BOTTOM"); - } - }; - - @Override - public String getCommandTitle() { - return TLocale.asString("COMMANDS.TCLOUD.COMMAND-TITLE"); - } -} diff --git a/src/main/scala/me/skymc/taboolib/cloud/TCloudLoader.java b/src/main/scala/me/skymc/taboolib/cloud/TCloudLoader.java deleted file mode 100644 index c498e7f..0000000 --- a/src/main/scala/me/skymc/taboolib/cloud/TCloudLoader.java +++ /dev/null @@ -1,133 +0,0 @@ -package me.skymc.taboolib.cloud; - -import com.google.common.collect.Maps; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.cloud.expansion.Expansion; -import me.skymc.taboolib.cloud.expansion.ExpansionType; -import me.skymc.taboolib.common.function.TFunction; -import me.skymc.taboolib.common.schedule.TSchedule; -import me.skymc.taboolib.fileutils.FileUtils; -import me.skymc.taboolib.plugin.PluginUtils; -import org.bukkit.Bukkit; - -import java.io.File; -import java.util.Map; - -/** - * @Author sky - * @Since 2018-09-30 17:30 - */ -@TFunction(enable = "init") -public class TCloudLoader { - - private static String url = "https://gitee.com/bkm016/TabooLibCloud/raw/master/cloud.json"; - private static String latestJsonOrigin; - private static JsonObject latestJsonObject; - private static Map expansionPlugins = Maps.newTreeMap(); - private static Map expansionInternal = Maps.newTreeMap(); - private static File expansionInternalFolder; - - static void init() { - createFolder(); - refresh(); - } - - public static void createFolder() { - if (!(expansionInternalFolder = new File(TabooLib.instance().getDataFolder(), "TCloud")).exists()) { - expansionInternalFolder.mkdirs(); - } - } - - @TSchedule(async = true, period = 20 * 60 * 60) - public static void refresh() { - Bukkit.getScheduler().runTaskAsynchronously(TabooLib.instance(), () -> { - long time = System.currentTimeMillis(); - latestJsonOrigin = FileUtils.getStringFromURL(url, 1024); - if (latestJsonOrigin == null) { - if (!TabooLib.isSilent()) { - TLocale.Logger.error("TCLOUD.LIST-CONNECT-FAILED"); - } - return; - } - try { - latestJsonObject = new JsonParser().parse(latestJsonOrigin).getAsJsonObject(); - } catch (Exception e) { - if (!TabooLib.isSilent()) { - TLocale.Logger.info("TCLOUD.LIST-PARSE-FAILED", e.getMessage()); - } - return; - } - if (latestJsonObject.has("plugins")) { - for (Map.Entry pluginEntry : latestJsonObject.getAsJsonObject("plugins").entrySet()) { - try { - expansionPlugins.put(pluginEntry.getKey(), Expansion.unSerialize(ExpansionType.PLUGIN, pluginEntry.getKey(), pluginEntry.getValue().getAsJsonObject())); - } catch (Exception e) { - if (!TabooLib.isSilent()) { - TLocale.Logger.info("TCLOUD.LIST-LOAD-FAILED", pluginEntry.getKey(), e.getMessage()); - } - } - } - } - if (latestJsonObject.has("internal")) { - for (Map.Entry pluginEntry : latestJsonObject.getAsJsonObject("internal").entrySet()) { - try { - expansionInternal.put(pluginEntry.getKey(), Expansion.unSerialize(ExpansionType.INTERNAL, pluginEntry.getKey(), pluginEntry.getValue().getAsJsonObject())); - } catch (Exception e) { - if (!TabooLib.isSilent()) { - TLocale.Logger.info("TCLOUD.LIST-LOAD-FAILED", pluginEntry.getKey(), e.getMessage()); - } - } - } - } - if (!TabooLib.isSilent()) { - TLocale.Logger.info("TCLOUD.LIST-LOAD-SUCCESS", String.valueOf(System.currentTimeMillis() - time)); - } - }); - } - - public static boolean isConnected() { - return latestJsonOrigin != null; - } - - public static String getLatestJsonOrigin() { - return latestJsonOrigin; - } - - public static JsonObject getLatestJsonObject() { - return latestJsonObject; - } - - public static Map getExpansionPlugins() { - return expansionPlugins; - } - - public static Map getExpansionInternal() { - return expansionInternal; - } - - public static File getExpansionInternalFolder() { - return expansionInternalFolder; - } - - public static boolean isExpansionExists(Expansion expansion) { - return expansion.getType() == ExpansionType.PLUGIN && PluginUtils.isPluginExists(expansion.getName()); - } - - public static Expansion getExpansion(String name) { - for (Map.Entry stringExpansionEntry : expansionPlugins.entrySet()) { - if (stringExpansionEntry.getKey().equalsIgnoreCase(name)) { - return stringExpansionEntry.getValue(); - } - } - for (Map.Entry stringExpansionEntry : expansionInternal.entrySet()) { - if (stringExpansionEntry.getKey().equalsIgnoreCase(name)) { - return stringExpansionEntry.getValue(); - } - } - return null; - } -} diff --git a/src/main/scala/me/skymc/taboolib/cloud/expansion/Expansion.java b/src/main/scala/me/skymc/taboolib/cloud/expansion/Expansion.java deleted file mode 100644 index 47b327f..0000000 --- a/src/main/scala/me/skymc/taboolib/cloud/expansion/Expansion.java +++ /dev/null @@ -1,118 +0,0 @@ -package me.skymc.taboolib.cloud.expansion; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.ilummc.eagletdl.EagletTask; -import com.ilummc.eagletdl.ProgressEvent; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.cloud.TCloudLoader; -import me.skymc.taboolib.fileutils.FileUtils; -import me.skymc.taboolib.string.ArrayUtils; -import org.bukkit.Bukkit; -import org.bukkit.util.NumberConversions; - -import java.io.File; -import java.util.stream.IntStream; - -/** - * @Author sky - * @Since 2018-09-30 16:39 - */ -public class Expansion { - - private final String name; - private final String[] author; - private final String description; - private final String[] detail; - private final String version; - private final String lastUpdate; - private final String lastUpdateNote; - private final String link; - private final double dependVersion; - private final ExpansionType type; - - public Expansion(String name, String[] author, String description, String[] detail, String version, String lastUpdate, String lastUpdateNote, String link, double dependVersion, ExpansionType type) { - this.name = name; - this.author = author; - this.description = description; - this.detail = detail; - this.version = version; - this.lastUpdate = lastUpdate; - this.lastUpdateNote = lastUpdateNote; - this.link = link; - this.dependVersion = dependVersion; - this.type = type; - } - - public static Expansion unSerialize(ExpansionType type, String name, JsonObject object) { - String[] author = object.get("author").isJsonArray() ? toArray(object.get("author").getAsJsonArray()) : ArrayUtils.asArray(object.get("author").getAsString()); - String description = object.get("description").getAsString(); - String[] detail = object.get("detail").isJsonArray() ? toArray(object.get("detail").getAsJsonArray()) : ArrayUtils.asArray(object.get("detail").getAsString()); - String version = object.get("version").getAsString(); - String lastUpdate = object.get("last_update").getAsString(); - String lastUpdateNote = object.get("last_update_note").getAsString(); - String link = object.get("link").getAsString(); - double dependVersion = object.has("depend-version") ? object.get("depend-version").getAsDouble() : 0D; - return new Expansion(name, author, description, detail, version, lastUpdate, lastUpdateNote, link, dependVersion, type); - } - - public static String[] toArray(JsonArray json) { - return IntStream.range(0, json.size()).mapToObj(i -> json.get(i).getAsString()).toArray(String[]::new); - } - - public String getName() { - return name; - } - - public String[] getAuthor() { - return author; - } - - public String getDescription() { - return description; - } - - public String[] getDetail() { - return detail; - } - - public String getVersion() { - return version; - } - - public String getLastUpdate() { - return lastUpdate; - } - - public String getLastUpdateNote() { - return lastUpdateNote; - } - - public String getLink() { - return link; - } - - public double getDependVersion() { - return dependVersion; - } - - public ExpansionType getType() { - return type; - } - - public File getFile() { - return type == ExpansionType.INTERNAL ? new File(TCloudLoader.getExpansionInternalFolder(), "[TCLOUD] " + name + ".jar") : new File("plugins/[TCLOUD] " + name + ".jar"); - } - - public boolean canUse() { - return TabooLib.getPluginVersion() >= dependVersion; - } - - public boolean canUpdate() { - if (!TCloudLoader.isExpansionExists(this)) { - return false; - } - return type == ExpansionType.PLUGIN && NumberConversions.toDouble(Bukkit.getPluginManager().getPlugin(name).getDescription().getVersion()) < NumberConversions.toDouble(version); - } -} diff --git a/src/main/scala/me/skymc/taboolib/cloud/expansion/ExpansionType.java b/src/main/scala/me/skymc/taboolib/cloud/expansion/ExpansionType.java deleted file mode 100644 index a59b388..0000000 --- a/src/main/scala/me/skymc/taboolib/cloud/expansion/ExpansionType.java +++ /dev/null @@ -1,10 +0,0 @@ -package me.skymc.taboolib.cloud.expansion; - -/** - * @Author sky - * @Since 2018-09-30 16:39 - */ -public enum ExpansionType { - - INTERNAL, PLUGIN -} \ No newline at end of file diff --git a/src/main/scala/me/skymc/taboolib/commands/TabooLibExecuteCommand.java b/src/main/scala/me/skymc/taboolib/commands/TabooLibExecuteCommand.java deleted file mode 100644 index e380cde..0000000 --- a/src/main/scala/me/skymc/taboolib/commands/TabooLibExecuteCommand.java +++ /dev/null @@ -1,163 +0,0 @@ -package me.skymc.taboolib.commands; - -import com.ilummc.tlib.resources.TLocale; -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.commands.internal.BaseMainCommand; -import me.skymc.taboolib.commands.internal.BaseSubCommand; -import me.skymc.taboolib.commands.internal.TCommand; -import me.skymc.taboolib.commands.internal.type.CommandArgument; -import me.skymc.taboolib.commands.internal.type.CommandRegister; -import me.skymc.taboolib.string.ArrayUtils; -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.server.ServerCommandEvent; - -/** - * @Author sky - * @Since 2018-07-04 21:32 - */ -@TCommand( - name = "taboolibexecute", - aliases = {"texecute"}, - permission = "taboolib.admin" -) -public class TabooLibExecuteCommand extends BaseMainCommand { - - @Override - public String getCommandTitle() { - return TLocale.asString("COMMANDS.TEXECUTE.COMMAND-TITLE"); - } - - @CommandRegister(priority = 1) - BaseSubCommand chat = new BaseSubCommand() { - @Override - public String getLabel() { - return "chat"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TEXECUTE.CHAT.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[] { - new CommandArgument(TLocale.asString("COMMANDS.TEXECUTE.CHAT.ARGUMENTS.0")), - new CommandArgument(TLocale.asString("COMMANDS.TEXECUTE.CHAT.ARGUMENTS.1")) - }; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - Player player = Bukkit.getPlayerExact(args[0]); - if (player == null) { - TLocale.sendTo(sender, "INVALID-PLAYER-OFFLINE", args[0]); - return; - } - player.chat(ArrayUtils.arrayJoin(args, 1)); - } - }; - - @CommandRegister(priority = 1) - BaseSubCommand command = new BaseSubCommand() { - @Override - public String getLabel() { - return "command"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TEXECUTE.COMMAND.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[] { - new CommandArgument(TLocale.asString("COMMANDS.TEXECUTE.COMMAND.ARGUMENTS.0")), - new CommandArgument(TLocale.asString("COMMANDS.TEXECUTE.COMMAND.ARGUMENTS.1")) - }; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - if (args[0].equalsIgnoreCase("console")) { - dispatchCommand(Bukkit.getConsoleSender(), ArrayUtils.arrayJoin(args, 1)); - return; - } - Player player = Bukkit.getPlayerExact(args[0]); - if (player == null) { - TLocale.sendTo(sender, "INVALID-TARGET-NOT-FOUND", args[0]); - return; - } - dispatchCommand(player, ArrayUtils.arrayJoin(args, 1)); - } - }; - - @CommandRegister(priority = 2) - BaseSubCommand commandAsOp = new BaseSubCommand() { - @Override - public String getLabel() { - return "commandAsOp"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TEXECUTE.COMMAND-AS-OP.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[] { - new CommandArgument(TLocale.asString("COMMANDS.TEXECUTE.COMMAND-AS-OP.ARGUMENTS.0")), - new CommandArgument(TLocale.asString("COMMANDS.TEXECUTE.COMMAND-AS-OP.ARGUMENTS.1")) - }; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - if (args[0].equalsIgnoreCase("console")) { - dispatchCommand(Bukkit.getConsoleSender(), ArrayUtils.arrayJoin(args, 1)); - return; - } - Player player = Bukkit.getPlayerExact(args[0]); - if (player == null) { - TLocale.sendTo(sender, "INVALID-TARGET-NOT-FOUND", args[0]); - return; - } - boolean isOp = player.isOp(); - player.setOp(true); - try { - dispatchCommand(player, ArrayUtils.arrayJoin(args, 1)); - } catch (Exception ignored) { - } - player.setOp(isOp); - } - }; - - public static boolean dispatchCommand(CommandSender sender, String command) { - try { - if ((sender instanceof Player)) { - PlayerCommandPreprocessEvent e = new PlayerCommandPreprocessEvent((Player) sender, "/" + command); - Bukkit.getPluginManager().callEvent(e); - if (e.isCancelled() || Strings.isBlank(e.getMessage()) || !e.getMessage().startsWith("/")) { - return false; - } - return Bukkit.dispatchCommand(e.getPlayer(), e.getMessage().substring(1)); - } else { - ServerCommandEvent e = new ServerCommandEvent(sender, command); - Bukkit.getPluginManager().callEvent(e); - if (e.isCancelled() || Strings.isBlank(e.getCommand())) { - return false; - } - return Bukkit.dispatchCommand(e.getSender(), e.getCommand()); - } - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } -} diff --git a/src/main/scala/me/skymc/taboolib/commands/TabooLibMainCommand.java b/src/main/scala/me/skymc/taboolib/commands/TabooLibMainCommand.java deleted file mode 100644 index 61e6f8c..0000000 --- a/src/main/scala/me/skymc/taboolib/commands/TabooLibMainCommand.java +++ /dev/null @@ -1,820 +0,0 @@ -package me.skymc.taboolib.commands; - -import com.ilummc.tlib.resources.TLocale; -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.TCommand; -import me.skymc.taboolib.commands.internal.type.CommandArgument; -import me.skymc.taboolib.commands.internal.type.CommandRegister; -import me.skymc.taboolib.commands.taboolib.*; -import me.skymc.taboolib.database.GlobalDataManager; -import me.skymc.taboolib.inventory.ItemUtils; -import me.skymc.taboolib.other.DateUtils; -import me.skymc.taboolib.other.NumberUtils; -import me.skymc.taboolib.timecycle.TimeCycle; -import me.skymc.taboolib.timecycle.TimeCycleEvent; -import me.skymc.taboolib.timecycle.TimeCycleInitializeEvent; -import me.skymc.taboolib.timecycle.TimeCycleManager; -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.concurrent.TimeUnit; - -/** - * @Author sky - * @Since 2018-05-09 21:38 - */ -@TCommand( - name = "taboolib", - permission = "taboolib.admin", - aliases = "tlib" -) -public class TabooLibMainCommand extends BaseMainCommand { - - @Override - public String getCommandTitle() { - return TLocale.asString("COMMANDS.TABOOLIB.COMMAND-TITLE"); - } - - @CommandRegister(priority = 1) - BaseSubCommand save = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "save"; - } - - @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 void onCommand(CommandSender sender, Command command, String label, String[] args) { - new SaveCommand(sender, args); - } - - @Override - public boolean ignoredLabel() { - return false; - } - }; - - @CommandRegister(priority = 2) - BaseSubCommand item = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "item"; - } - - @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 void onCommand(CommandSender sender, Command command, String label, String[] args) { - new ItemCommand(sender, args); - } - - @Override - public boolean ignoredLabel() { - return false; - } - }; - - @CommandRegister(priority = 3) - BaseSubCommand itemInfo = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "itemInfo"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.INFO.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new InfoCommand(sender, args); - } - }; - - @CommandRegister(priority = 3.1) - BaseSubCommand infoList = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "itemList"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.ITEMLIST.DESCRIPTION"); - } - - @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 boolean ignoredLabel() { - return false; - } - }; - - @CommandRegister(priority = 4) - BaseSubCommand itemReload = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "itemReload"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.ITEMRELOAD.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - ItemUtils.reloadItemCache(); - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.ITEMRELOAD.SUCCESS-RELOAD"); - } - }; - - @CommandRegister(priority = 6) - BaseSubCommand attributes = new BaseSubCommand() { - - @Override - public String getLabel() { - return "attributes"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.ATTRIBUTES.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new AttributesCommand(sender, args); - } - }; - - @CommandRegister(priority = 7) - BaseSubCommand enchants = new BaseSubCommand() { - - @Override - public String getLabel() { - return "enchants"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.ENCHANTS.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new EnchantCommand(sender, args); - } - }; - - @CommandRegister(priority = 8) - BaseSubCommand potions = new BaseSubCommand() { - - @Override - public String getLabel() { - return "potions"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.POTIONS.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new PotionCommand(sender, args); - } - }; - - @CommandRegister(priority = 9) - BaseSubCommand flags = new BaseSubCommand() { - - @Override - public String getLabel() { - return "flags"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.FLAGS.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new FlagCommand(sender, args); - } - }; - - @CommandRegister(priority = 10) - BaseSubCommand slots = new BaseSubCommand() { - - @Override - public String getLabel() { - return "slots"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.SLOTS.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new AttributesCommand(sender, args); - } - }; - - @CommandRegister(priority = 11) - BaseSubCommand sounds = new BaseSubCommand() { - - @Override - public String getLabel() { - return "sounds"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.SOUNDS.DESCRIPTION"); - } - - @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 boolean ignoredLabel() { - return false; - } - }; - - @CommandRegister(priority = 13) - BaseSubCommand getVariable = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "getVariable"; - } - - @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 void onCommand(CommandSender sender, Command command, String label, String[] args) { - new VariableGetCommand(sender, args); - } - - @Override - public boolean ignoredLabel() { - return false; - } - }; - - @CommandRegister(priority = 13.1) - BaseSubCommand setVariable = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "setVariable"; - } - - @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 void onCommand(CommandSender sender, Command command, String label, String[] args) { - new VariableSetCommand(sender, args); - } - - @Override - public boolean ignoredLabel() { - return false; - } - }; - - @CommandRegister(priority = 13.3) - BaseSubCommand cycleList = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "cycleList"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.TIMECYCLE.DESCRIPTION.LIST"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.LIST.HEAD"); - TimeCycleManager.getTimeCycles().forEach(cycle -> TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.LIST.BODY", cycle.getName())); - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.LIST.FOOT"); - } - }; - - @CommandRegister(priority = 14) - BaseSubCommand cycleInfo = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "cycleInfo"; - } - - @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 void onCommand(CommandSender sender, Command command, String label, String[] args) { - TimeCycle cycle = TimeCycleManager.getTimeCycle(args[0]); - if (cycle == null) { - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.INVALID-CYCLE", args[0]); - } else { - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.CYCLE-INFO", - asString(cycle.getCycle() / 1000L), - cycle.getPlugin().getName(), - DateUtils.CH_ALL.format(TimeCycleManager.getBeforeTimeline(cycle.getName())), - DateUtils.CH_ALL.format(TimeCycleManager.getAfterTimeline(cycle.getName()))); - } - } - - private String asString(long seconds) { - long day = TimeUnit.SECONDS.toDays(seconds); - long hours = TimeUnit.SECONDS.toHours(seconds) - day * 24; - long minute = TimeUnit.SECONDS.toMinutes(seconds) - TimeUnit.SECONDS.toHours(seconds) * 60L; - long second = TimeUnit.SECONDS.toSeconds(seconds) - TimeUnit.SECONDS.toMinutes(seconds) * 60L; - return "§f" + day + "§7 天, §f" + hours + "§7 小时, §f" + minute + "§7 分钟, §f" + second + "§7 秒"; - } - }; - - @CommandRegister(priority = 15) - BaseSubCommand cycleReset = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "cycleReset"; - } - - @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 void onCommand(CommandSender sender, Command command, String label, String[] args) { - TimeCycle cycle = TimeCycleManager.getTimeCycle(args[0]); - if (cycle == null) { - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.INVALID-CYCLE", args[0]); - return; - } - new BukkitRunnable() { - - @Override - public void run() { - long time = new TimeCycleInitializeEvent(cycle, System.currentTimeMillis()).call().getTimeline(); - // 初始化 - GlobalDataManager.setVariable("timecycle:" + cycle.getName(), String.valueOf(time)); - // 触发器 - Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle)); - // 提示 - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.CYCLE-RESET", args[0]); - } - }.runTaskAsynchronously(Main.getInst()); - } - }; - - @CommandRegister(priority = 16) - BaseSubCommand cycleUpdate = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "cycleUpdate"; - } - - @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 void onCommand(CommandSender sender, Command command, String label, String[] args) { - TimeCycle cycle = TimeCycleManager.getTimeCycle(args[0]); - if (cycle == null) { - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.INVALID-CYCLE", args[0]); - return; - } - new BukkitRunnable() { - - @Override - public void run() { - // 重置 - GlobalDataManager.setVariable("timecycle:" + cycle.getName(), String.valueOf(System.currentTimeMillis())); - // 触发器 - Bukkit.getPluginManager().callEvent(new TimeCycleEvent(cycle)); - // 提示 - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.TIMECYCLE.CYCLE-UPDATE", args[0]); - } - }.runTaskAsynchronously(Main.getInst()); - } - }; - - @CommandRegister(priority = 20) - BaseSubCommand tagDisplay = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "tagDisplay"; - } - - @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 void onCommand(CommandSender sender, Command command, String label, String[] args) { - new TagDisplayCommand(sender, args); - } - - @Override - public boolean ignoredLabel() { - return false; - } - }; - - @CommandRegister(priority = 21) - BaseSubCommand tagPrefix = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "tagPrefix"; - } - - @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 void onCommand(CommandSender sender, Command command, String label, String[] args) { - new TagPrefixCommand(sender, args); - } - - @Override - public boolean ignoredLabel() { - return false; - } - }; - - @CommandRegister(priority = 22) - BaseSubCommand tagSuffix = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "tagSuffix"; - } - - @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 void onCommand(CommandSender sender, Command command, String label, String[] args) { - new TagSuffixCommand(sender, args); - } - - @Override - public boolean ignoredLabel() { - return false; - } - }; - - @CommandRegister(priority = 23) - BaseSubCommand tagDelete = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "tagDelete"; - } - - @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 void onCommand(CommandSender sender, Command command, String label, String[] args) { - new TagDeleteCommand(sender, args); - } - - @Override - public boolean ignoredLabel() { - return false; - } - }; - - @CommandRegister(priority = 24.1) - BaseSubCommand lagServer = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "lagServer"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.LAGSERVER.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[] { - new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.LAGSERVER.ARGUMENTS.0")) - }; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - if (NumberUtils.getInteger(args[0]) > 300000) { - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.LAGSERVER.INVALID-TIME"); - } else { - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.LAGSERVER.START"); - try { - Thread.sleep(NumberUtils.getInteger(args[0])); - } catch (Exception ignored) { - } - TLocale.sendTo(sender, "COMMANDS.TABOOLIB.LAGSERVER.STOP"); - } - } - }; - - @CommandRegister(priority = 27) - BaseSubCommand importData = new BaseSubCommand() { - - @Override - public boolean hideInHelp() { - return true; - } - - @Override - public String getLabel() { - return "importData"; - } - - @Override - public String getDescription() { - return TLocale.asString("COMMANDS.TABOOLIB.IMPORTDATA.DESCRIPTION"); - } - - @Override - public CommandArgument[] getArguments() { - return new CommandArgument[0]; - } - - @Override - public void onCommand(CommandSender sender, Command command, String label, String[] args) { - new ImportCommand(sender, args); - } - }; -} diff --git a/src/main/scala/me/skymc/taboolib/commands/internal/TBaseCommand.java b/src/main/scala/me/skymc/taboolib/commands/internal/TBaseCommand.java deleted file mode 100644 index c107ed6..0000000 --- a/src/main/scala/me/skymc/taboolib/commands/internal/TBaseCommand.java +++ /dev/null @@ -1,20 +0,0 @@ -package me.skymc.taboolib.commands.internal; - -/** - * 歪日删错了 - * - * @author sky - */ -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); - } -} \ No newline at end of file diff --git a/src/main/scala/me/skymc/taboolib/commands/internal/plugin/TLibLocale.java b/src/main/scala/me/skymc/taboolib/commands/internal/plugin/TLibLocale.java deleted file mode 100644 index a8b9623..0000000 --- a/src/main/scala/me/skymc/taboolib/commands/internal/plugin/TLibLocale.java +++ /dev/null @@ -1,33 +0,0 @@ -package me.skymc.taboolib.commands.internal.plugin; - -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.commands.internal.type.CommandArgument; - -import java.util.stream.IntStream; - -/** - * @Author sky - * @Since 2018-09-30 19:26 - */ -public class TLibLocale { - - public static String title(String name) { - return TLocale.asString("COMMANDS." + name + ".COMMAND-TITLE"); - } - - public static String description(String name, String label) { - return TLocale.asString("COMMANDS." + name + "." + label + ".DESCRIPTION"); - } - - public static CommandArgument[] arguments(String name, String label, int size) { - return IntStream.range(0, size).mapToObj(i -> new CommandArgument(TLocale.asString("COMMANDS." + name + "." + label + ".ARGUMENTS." + i))).toArray(CommandArgument[]::new); - } - - public static CommandArgument argument(String name, String label, int index) { - return new CommandArgument(TLocale.asString("COMMANDS." + name + "." + label + ".ARGUMENTS." + index)); - } - - public static CommandArgument argument(String name, String label, int index, boolean required) { - return new CommandArgument(TLocale.asString("COMMANDS." + name + "." + label + ".ARGUMENTS." + index), required); - } -} diff --git a/src/main/scala/me/skymc/taboolib/common/json/TJsonArray.java b/src/main/scala/me/skymc/taboolib/common/json/TJsonArray.java deleted file mode 100644 index f23a63e..0000000 --- a/src/main/scala/me/skymc/taboolib/common/json/TJsonArray.java +++ /dev/null @@ -1,350 +0,0 @@ -package me.skymc.taboolib.common.json; - -import com.google.gson.*; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Spliterator; -import java.util.function.Consumer; - -/** - * 让 JsonObject 有更加人性化的操作,目前版本只能获取数据。 - * - * @Author 坏黑 - * @Since 2018-10-27 23:46 - */ -public class TJsonArray implements Iterable { - - private JsonArray jsonArray; - - TJsonArray(JsonArray jsonArray) { - this.jsonArray = jsonArray; - } - - /** - * 从 Json 原代码中获取 - * - * @param json 源代码 - * @return {@link TJsonArray} - * @throws JsonParseException if the specified text is not valid JSON - * @throws IllegalStateException This is not a JSON Array. - */ - public static TJsonArray fromJson(String json) throws JsonParseException, IllegalStateException { - return new TJsonArray(new JsonParser().parse(json).getAsJsonArray()); - } - - /** - * 从 JsonArray 创建 - * - * @param jsonArray JsonArray 对象 - * @return {@link TJsonObject} - */ - public static TJsonArray fromJsonArray(JsonArray jsonArray) { - return new TJsonArray(jsonArray); - } - - /** - * 添加成员 - * - * @param obj 成员 - */ - public void add(TJsonObject obj) { - jsonArray.add(obj.asOriginJsonElement()); - } - - /** - * 添加成员 - * - * @param obj 成员 - */ - public void add(Boolean obj) { - jsonArray.add(new JsonPrimitive(obj)); - } - - /** - * 添加成员 - * - * @param obj 成员 - */ - public void add(Character obj) { - jsonArray.add(new JsonPrimitive(obj)); - } - - /** - * 添加成员 - * - * @param obj 成员 - */ - public void add(Number obj) { - jsonArray.add(new JsonPrimitive(obj)); - } - - /** - * 添加成员 - * - * @param obj 成员 - */ - public void add(String obj) { - jsonArray.add(new JsonPrimitive(obj)); - } - - /** - * 添加所有成员 - * - * @param array 成员集合 - */ - public void addAll(TJsonArray array) { - jsonArray.add(array.asOriginJsonArray()); - } - - /** - * 设置成员 - * - * @param index 位置 - * @param obj 成员 - */ - public void set(int index, TJsonObject obj) { - jsonArray.set(index, obj.asOriginJsonElement()); - } - - /** - * 设置成员 - * - * @param index 位置 - * @param obj 成员 - */ - public void set(int index, Boolean obj) { - jsonArray.set(index, new JsonPrimitive(obj)); - } - - /** - * 设置成员 - * - * @param index 位置 - * @param obj 成员 - */ - public void set(int index, Number obj) { - jsonArray.set(index, new JsonPrimitive(obj)); - } - - /** - * 设置成员 - * - * @param index 位置 - * @param obj 成员 - */ - public void set(int index, String obj) { - jsonArray.set(index, new JsonPrimitive(obj)); - } - - /** - * 移除成员 - * - * @param obj 成员 - */ - public void remove(JsonElement obj) { - jsonArray.remove(obj); - } - - /** - * 移除成员 - * - * @param obj 成员 - */ - public void remove(Boolean obj) { - jsonArray.remove(new JsonPrimitive(obj)); - } - - /** - * 移除成员 - * - * @param obj 成员 - */ - public void remove(Number obj) { - jsonArray.remove(new JsonPrimitive(obj)); - } - - /** - * 移除成员 - * - * @param obj 成员 - */ - public void remove(String obj) { - jsonArray.remove(new JsonPrimitive(obj)); - } - - /** - * 含有成员 - * - * @param obj 成员 - * @return boolean - */ - public boolean contains(JsonElement obj) { - return jsonArray.contains(obj); - } - - /** - * 含有成员 - * - * @param obj 成员 - * @return boolean - */ - public boolean contains(Boolean obj) { - return jsonArray.contains(new JsonPrimitive(obj)); - } - - /** - * 含有成员 - * - * @param obj 成员 - * @return boolean - */ - public boolean contains(Number obj) { - return jsonArray.contains(new JsonPrimitive(obj)); - } - - /** - * 含有成员 - * - * @param obj 成员 - * @return boolean - */ - public boolean contains(String obj) { - return jsonArray.contains(new JsonPrimitive(obj)); - } - - /** - * 获取成员,默认值:null - * - * @param index 序号 - * @return {@link TJsonObject} - */ - public TJsonObject getJsonObject(int index) { - return jsonArray.get(index).isJsonObject() ? TJsonObject.fromJsonObject(jsonArray.get(index).getAsJsonObject()) : null; - } - - /** - * 获取成员,默认值:null - * - * @param index 序号 - * @return {@link TJsonArray} - */ - public TJsonArray getJsonArray(int index) { - return jsonArray.get(index).isJsonArray() ? TJsonArray.fromJsonArray(jsonArray.get(index).getAsJsonArray()) : null; - } - - /** - * 获取成员,默认值:false - * - * @param index 序号 - * @return boolean - */ - public Boolean getBoolean(int index) { - return jsonArray.get(index).isJsonPrimitive() && jsonArray.get(index).getAsBoolean(); - } - - /** - * 获取成员 - * - * @param index 序号 - * @param def 默认值 - * @return boolean - */ - public Boolean getBoolean(int index, boolean def) { - return jsonArray.get(index).isJsonPrimitive() ? jsonArray.get(index).getAsBoolean() : def; - } - - /** - * 获取成员,默认值:0 - * - * @param index 序号 - * @return number - */ - public Number getNumber(int index) { - return jsonArray.get(index).isJsonPrimitive() ? jsonArray.get(index).getAsNumber() : 0; - } - - /** - * 获取成员 - * - * @param index 序号 - * @param def 默认值 - * @return number - */ - public Number getNumber(int index, Number def) { - return jsonArray.get(index).isJsonPrimitive() ? jsonArray.get(index).getAsNumber() : def; - } - - /** - * 获取成员,默认值:null - * - * @param index 序号 - * @return string - */ - public String getString(int index) { - return jsonArray.get(index).isJsonPrimitive() ? jsonArray.get(index).getAsString() : null; - } - - /** - * 获取成员 - * - * @param index 序号 - * @param def 默认值 - * @return string - */ - public String getString(int index, String def) { - return jsonArray.get(index).isJsonPrimitive() ? jsonArray.get(index).getAsString() : def; - } - - /** - * 成员数量 - * - * @return int - */ - public int size() { - return jsonArray.size(); - } - - /** - * 转换为 JsonArray 类型 - * - * @return {@link JsonArray} - */ - public JsonArray asOriginJsonArray() { - return jsonArray; - } - - @Override - public Iterator iterator() { - List jsonObjectList = new ArrayList<>(); - for (JsonElement jsonElement : jsonArray) { - jsonObjectList.add(TJsonObject.fromJsonObject(jsonElement)); - } - return jsonObjectList.iterator(); - } - - @Override - public void forEach(Consumer action) { - List jsonObjectList = new ArrayList<>(); - for (JsonElement jsonElement : jsonArray) { - jsonObjectList.add(TJsonObject.fromJsonObject(jsonElement)); - } - jsonObjectList.forEach(action); - } - - @Override - public Spliterator spliterator() { - List jsonObjectList = new ArrayList<>(); - for (JsonElement jsonElement : jsonArray) { - jsonObjectList.add(TJsonObject.fromJsonObject(jsonElement)); - } - return jsonObjectList.spliterator(); - } - - @Override - public String toString() { - return jsonArray.toString(); - } - -} diff --git a/src/main/scala/me/skymc/taboolib/common/json/TJsonObject.java b/src/main/scala/me/skymc/taboolib/common/json/TJsonObject.java deleted file mode 100644 index fb24546..0000000 --- a/src/main/scala/me/skymc/taboolib/common/json/TJsonObject.java +++ /dev/null @@ -1,253 +0,0 @@ -package me.skymc.taboolib.common.json; - -import com.google.gson.*; - -import java.util.*; -import java.util.stream.Collectors; - -/** - * 让 JsonObject 有更加人性化的操作,目前版本只能获取数据。 - * - * @Author 坏黑 - * @Since 2018-10-27 23:06 - */ -public class TJsonObject { - - private JsonElement jsonObject; - - TJsonObject(JsonElement jsonObject) { - this.jsonObject = jsonObject; - } - - /** - * 从 Json 原代码中获取 - * - * @param json 源代码 - * @return {@link TJsonObject} - * @throws JsonParseException if the specified text is not valid JSON - */ - public static TJsonObject fromJson(String json) throws JsonParseException { - return new TJsonObject(new JsonParser().parse(json)); - } - - /** - * 从 JsonElement 创建 - * - * @param jsonElement JsonElement 对象 - * @return {@link TJsonObject} - */ - public static TJsonObject fromJsonObject(JsonElement jsonElement) { - return new TJsonObject(jsonElement); - } - - /** - * 是否含有该节点 - * - * @param path 地址 - * @return boolean - */ - public boolean contains(String path) { - return get(path) != null; - } - - /** - * 获取文本,默认值:空 - * - * @param path 地址 - * @return String - */ - public String getString(String path) { - return getString(path, ""); - } - - /** - * 获取文本 - * - * @param path 地址 - * @param def 默认值 - * @return String - */ - public String getString(String path, String def) { - JsonElement jsonElement = get(path); - return !(jsonElement instanceof JsonPrimitive) || jsonElement == null ? def : jsonElement.getAsString(); - } - - /** - * 获取数字,默认值:0 - * - * @param path 地址 - * @return Number - */ - public Number getNumber(String path) { - return getNumber(path, 0); - } - - /** - * 获取数字 - * - * @param path 地址 - * @param def 默认值 - * @return Number - */ - public Number getNumber(String path, Number def) { - JsonElement jsonElement = get(path); - return !(jsonElement instanceof JsonPrimitive) || jsonElement == null ? def : jsonElement.getAsNumber(); - } - - /** - * 获取布尔值,默认值:false - * - * @param path 地址 - * @return boolean - */ - public boolean getBoolean(String path) { - return getBoolean(path, false); - } - - /** - * 获取布尔值 - * - * @param path 地址 - * @param def 默认值 - * @return boolean - */ - public boolean getBoolean(String path, boolean def) { - JsonElement jsonElement = get(path); - return !(jsonElement instanceof JsonPrimitive) || jsonElement == null ? def : jsonElement.getAsBoolean(); - } - - /** - * 获取 TJsonObject 对象,默认值:null - * - * @param path 地址 - * @return {@link TJsonObject} - */ - public TJsonObject getJsonObject(String path) { - JsonElement jsonElement = get(path); - return !(jsonElement instanceof JsonObject) || jsonElement == null ? null : TJsonObject.fromJsonObject(jsonElement); - } - - /** - * 获取 TJsonArray 对象,默认值:null - * - * @param path 地址 - * @return {@link TJsonArray} - */ - public TJsonArray getJsonArray(String path) { - JsonElement jsonElement = get(path); - return !(jsonElement instanceof JsonArray) || jsonElement == null ? null : TJsonArray.fromJsonArray((JsonArray) jsonElement); - } - - /** - * 获取所有成员 - * - * @return {@link Map.Entry} - */ - public Set> entrySet() { - return !(jsonObject instanceof JsonObject) ? new HashSet<>() : ((JsonObject) jsonObject).entrySet().stream().map(jsonElementEntry -> new HashMap.SimpleEntry<>(jsonElementEntry.getKey(), fromJsonObject(jsonElementEntry.getValue()))).collect(Collectors.toCollection(HashSet::new)); - } - - /** - * 获取所有键 - * - * @return {@link Set} - */ - public Set keySet() { - return !(jsonObject instanceof JsonObject) ? new HashSet<>() : ((JsonObject) jsonObject).entrySet().stream().map(Map.Entry::getKey).collect(Collectors.toCollection(HashSet::new)); - } - - /** - * 获取所有值 - * - * @return {@link Collection} - */ - public Collection values() { - return !(jsonObject instanceof JsonObject) ? new ArrayList<>() : ((JsonObject) jsonObject).entrySet().stream().map(jsonElementEntry -> new TJsonObject(jsonElementEntry.getValue())).collect(Collectors.toList()); - } - - /** - * 是否为 JsonObject 类型 - * - * @return boolean - */ - public boolean isJsonObject() { - return jsonObject instanceof JsonObject; - } - - /** - * 是否为 JsonArray 类型 - * - * @return boolean - */ - public boolean isJsonArray() { - return jsonObject instanceof JsonArray; - } - - /** - * 是否为 JsonPrimitive 类型 - * - * @return boolean - */ - public boolean isJsonPrimitive() { - return jsonObject instanceof JsonPrimitive; - } - - /** - * 转换为 JsonObject 类型 - * - * @return {@link JsonObject} - */ - public JsonObject asOriginJsonObject() { - return (JsonObject) jsonObject; - } - - /** - * 转换为 JsonArray 类型 - * - * @return {@link JsonArray} - */ - public JsonArray asOriginJsonArray() { - return (JsonArray) jsonObject; - } - - /** - * 转换为 JsonElement 类型 - * - * @return {@link JsonElement} - */ - public JsonElement asOriginJsonElement() { - return jsonObject; - } - - /** - * 转换为 JsonPrimitive 类型 - * - * @return {@link JsonPrimitive} - */ - public JsonPrimitive asOriginJsonPrimitive() { - return (JsonPrimitive) jsonObject; - } - - @Override - public String toString() { - return jsonObject.toString(); - } - - // ********************************* - // - // Private Methods - // - // ********************************* - - private JsonElement get(String path) { - JsonElement subElement = jsonObject; - for (String p : path.split("/")) { - if (subElement instanceof JsonObject && ((JsonObject) subElement).has(p)) { - subElement = ((JsonObject) subElement).get(p); - } else { - return null; - } - } - return subElement; - } -} diff --git a/src/main/scala/me/skymc/taboolib/common/loader/Instantiable.java b/src/main/scala/me/skymc/taboolib/common/loader/Instantiable.java deleted file mode 100644 index 9ffadc4..0000000 --- a/src/main/scala/me/skymc/taboolib/common/loader/Instantiable.java +++ /dev/null @@ -1,18 +0,0 @@ -package me.skymc.taboolib.common.loader; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * @Author sky - * @Since 2018-08-27 10:04 - */ -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -public @interface Instantiable { - - String value(); - -} diff --git a/src/main/scala/me/skymc/taboolib/common/loader/InstantiableLoader.java b/src/main/scala/me/skymc/taboolib/common/loader/InstantiableLoader.java deleted file mode 100644 index 7ab178e..0000000 --- a/src/main/scala/me/skymc/taboolib/common/loader/InstantiableLoader.java +++ /dev/null @@ -1,86 +0,0 @@ -package me.skymc.taboolib.common.loader; - -import com.ilummc.tlib.logger.TLogger; -import com.ilummc.tlib.util.Ref; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.TabooLibLoader; -import me.skymc.taboolib.listener.TListener; -import me.skymc.taboolib.methods.ReflectionUtils; -import org.bukkit.Bukkit; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.server.PluginDisableEvent; -import org.bukkit.event.server.PluginEnableEvent; -import org.bukkit.plugin.Plugin; - -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @Author sky - * @Since 2018-08-27 10:04 - */ -@TListener -public class InstantiableLoader implements Listener { - - private static ConcurrentHashMap instance = new ConcurrentHashMap<>(); - - public InstantiableLoader() { - loadInstantiable(); - } - - @EventHandler - public void onEnable(PluginEnableEvent e) { - loadInstantiable(e.getPlugin()); - } - - @EventHandler - public void onDisable(PluginDisableEvent e) { - clear(e.getPlugin()); - } - - public static void clear(Plugin plugin) { - instance.entrySet().stream().filter(entry -> Ref.getCallerPlugin(entry.getValue().getClass()).equals(plugin)).forEach(entry -> instance.remove(entry.getKey())); - } - - public static void loadInstantiable() { - for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - try { - loadInstantiable(plugin); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public static void loadInstantiable(Plugin plugin) { - TabooLibLoader.getPluginClasses(plugin).ifPresent(classes -> { - for (Class pluginClass : classes) { - if (pluginClass.isAnnotationPresent(Instantiable.class)) { - Instantiable instantiable = (Instantiable) pluginClass.getAnnotation(Instantiable.class); - try { - instance.put(instantiable.value(), ReflectionUtils.instantiateObject(pluginClass)); - TabooLib.debug("Instantiable " + pluginClass.getSimpleName() + " instanced. (" + plugin.getName() + ")"); - } catch (Exception e) { - TLogger.getGlobalLogger().warn("Instance Failed: " + pluginClass.getName()); - e.printStackTrace(); - } - } - } - }); - } - - // ********************************* - // - // Getter and Setter - // - // ********************************* - - public static ConcurrentHashMap getInstance() { - return instance; - } - - public static Optional getInstance(String name) { - return Optional.ofNullable(instance.get(name)); - } -} diff --git a/src/main/scala/me/skymc/taboolib/database/GlobalDataManager.java b/src/main/scala/me/skymc/taboolib/database/GlobalDataManager.java deleted file mode 100644 index 1fffb19..0000000 --- a/src/main/scala/me/skymc/taboolib/database/GlobalDataManager.java +++ /dev/null @@ -1,415 +0,0 @@ -package me.skymc.taboolib.database; - -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.Main.StorageType; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.playerdata.DataUtils; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.concurrent.ConcurrentHashMap; - -public class GlobalDataManager { - - public static FileConfiguration data = DataUtils.addPluginData("TabooLibrary-Variable.yml", null); - - /** - * 获取变量 - * - * @param name 名称 - * @param defaultVariable 默认值 - * @return - */ - public static String getVariable(String name, String defaultVariable) { - if (Main.getStorageType() == StorageType.SQL) { - Object obj = Main.getConnection().getValueLast(Main.getTablePrefix() + "_plugindata", "name", name, "variable"); - return obj != null ? "null".equals(obj.toString()) ? defaultVariable : obj.toString() : defaultVariable; - } else { - return data.contains(name) ? data.getString(name) : defaultVariable; - } - } - - /** - * 获取缓存变量(该方法仅限数据库储存方式) - * - * @param name 名称 - * @param defaultVariable 默认值 - * @return - */ - public static String getVariableAsynchronous(String name, String defaultVariable) { - if (Main.getStorageType() == StorageType.SQL) { - SQLVariable variable = SQLMethod.getSQLVariable(name); - return variable == null ? defaultVariable : "null".equals(variable.getVariable()) ? defaultVariable : variable.getVariable(); - } else { - return getVariable(name, defaultVariable); - } - } - - /** - * 设置变量 - * - * @param name 名称 - * @param variable 变量 - */ - public static void setVariable(String name, String variable) { - if (Main.getStorageType() == StorageType.SQL) { - Main.getConnection().intoValue(Main.getTablePrefix() + "_plugindata", name, variable == null ? "null" : variable, TabooLib.getServerUID()); - } else { - data.set(name, variable); - } - } - - /** - * 设置缓存变量(该方法仅限数据库储存方式) - * - * @param name - * @param variable - */ - public static void setVariableAsynchronous(String name, String variable) { - if (Main.getStorageType() == StorageType.SQL) { - SQLVariable _variable = SQLMethod.contains(name) ? SQLMethod.getSQLVariable(name).setVariable(variable == null ? "null" : variable) : SQLMethod.addSQLVariable(name, variable == null ? "null" : variable); - // 更新数据 - SQLMethod.uploadVariable(_variable, true); - } else { - setVariable(name, variable); - } - } - - /** - * 检查变量是否存在 - * - * @param name 名称 - */ - public static boolean contains(String name) { - if (Main.getStorageType() == StorageType.SQL) { - return getVariable(name, null) != null; - } else { - return data.contains(name); - } - } - - /** - * 检查变量是否被缓存(该方法仅限数据库储存方式) - * - * @param name 名称 - * @return - */ - public static boolean containsAsynchronous(String name) { - if (Main.getStorageType() == StorageType.SQL) { - return getVariableAsynchronous(name, null) != null; - } else { - return contains(name); - } - } - - /** - * 清理所有失效的变量 - * 该方法仅限数据库储存时有效 - */ - public static void clearInvalidVariables() { - if (Main.getStorageType() == StorageType.SQL) { - HashMap map = getVariables(); - Main.getConnection().truncateTable(Main.getTablePrefix() + "_plugindata"); - for (String name : map.keySet()) { - Main.getConnection().intoValue(Main.getTablePrefix() + "_plugindata", name, map.get(name), TabooLib.getServerUID()); - } - } - } - - /** - * 获取所有有效变量 - * - * @return - */ - public static HashMap getVariables() { - HashMap map = new HashMap<>(); - if (Main.getStorageType() == StorageType.SQL) { - LinkedList> list = Main.getConnection().getValues(Main.getTablePrefix() + "_plugindata", "id", -1, false, "name", "variable"); - for (HashMap _map : list) { - if (!"null".equals(_map.get("variable").toString())) { - map.put(_map.get("name").toString(), _map.get("variable").toString()); - } - } - } else { - for (String name : data.getConfigurationSection("").getKeys(false)) { - map.put(name, data.getString(name)); - } - } - return map; - } - - /** - * 获取缓存变量(该方法仅限数据库储存方式) - * - * @return - */ - public static HashMap getVariablesAsynchronous() { - if (Main.getStorageType() == StorageType.SQL) { - HashMap map = new HashMap<>(); - for (SQLVariable variable : SQLMethod.getSQLVariables()) { - if (!"null".equals(variable.getVariable())) { - map.put(variable.getName(), variable.getVariable()); - } - } - return map; - } else { - return getVariables(); - } - } - - /** - * 数据库变量 - * - * @author sky - */ - public static class SQLVariable { - - public String name = ""; - public String variable = ""; - public String upgradeUID = ""; - - public SQLVariable(String name, String variable, String upgradeUID) { - this.name = name; - this.variable = variable; - this.upgradeUID = upgradeUID; - } - - public String getName() { - return name; - } - - public String getVariable() { - return variable; - } - - public SQLVariable setVariable(String args) { - this.variable = args; - return this; - } - - public String getUpgradeUID() { - return upgradeUID; - } - } - - /** - * 数据库方法 - * - * @author sky - */ - public static class SQLMethod { - - private static ConcurrentHashMap variables = new ConcurrentHashMap<>(); - - /** - * 获取数据 - * - * @param name 名字 - */ - public static SQLVariable getSQLVariable(String name) { - return variables.get(name); - } - - /** - * 获取所有变量 - * - * @return - */ - public static Collection getSQLVariables() { - return variables.values(); - } - - /** - * 添加一个变量 - * - * @param name 名字 - * @param value 值 - * @return - */ - public static SQLVariable addSQLVariable(String name, String value) { - SQLVariable variable = new SQLVariable(name, value, TabooLib.getServerUID()); - variables.put(name, variable); - return variable; - } - - /** - * 移除一个变量 - * - * @param name 名字 - * @return - */ - public static SQLVariable removeSQLVariable(String name) { - if (variables.contains(name)) { - variables.get(name).setVariable("null"); - } - return variables.get(name); - } - - /** - * 是否包含变量 - * - * @param name 名字 - * @return - */ - public static boolean contains(String name) { - return variables.containsKey(name); - } - - /** - * 载入数据库中的所有变量缓存 - * - * @param sync 是否异步 - */ - public static void loadVariables(boolean sync) { - if (Main.getStorageType() == StorageType.LOCAL) { - return; - } - - BukkitRunnable runnable = new BukkitRunnable() { - - @Override - public void run() { - LinkedList> list = Main.getConnection().getValues(Main.getTablePrefix() + "_plugindata", "id", -1, false, "name", "variable", "upgrade"); - for (HashMap _map : list) { - if (!"null".equals(_map.get("variable").toString())) { - variables.put(_map.get("name").toString(), new SQLVariable(_map.get("name").toString(), _map.get("variable").toString(), _map.get("upgrade").toString())); - } - } - } - }; - - if (sync) { - runnable.runTaskAsynchronously(Main.getInst()); - } else { - runnable.run(); - } - } - - /** - * 检查当前变量是否被其他服务器更新 - * - * @param sync 是否异步 - */ - public static void checkVariable(boolean sync) { - if (Main.getStorageType() == StorageType.LOCAL) { - return; - } - - BukkitRunnable runnable = new BukkitRunnable() { - - @Override - public void run() { - LinkedList> list = Main.getConnection().getValues(Main.getTablePrefix() + "_plugindata", "id", -1, false, "name", "variable", "upgrade"); - // 循环变量 - for (HashMap value : list) { - Object name = value.get("name"); - try { - // 如果变量存在 - if (variables.containsKey(name)) { - // 如果变量不是由本服更新 - if (!value.get("upgrade").equals(variables.get(name).getUpgradeUID())) { - // 如果变量是空 - if ("null".equals(value.get("variable"))) { - // 删除变量 - variables.remove(name); - } else { - // 更新变量 - variables.get(name).setVariable(value.get("variable").toString()); - } - } - } - // 如果变量存在则下载到本地 - else if (!"null".equals(value.get("variable"))) { - variables.put(value.get("name").toString(), new SQLVariable(value.get("name").toString(), value.get("variable").toString(), value.get("upgrade").toString())); - } - } catch (Exception e) { - // 移除 - variables.remove(name); - // 提示 - TLocale.Logger.error("GLOBAL-DATAMANAGER.ERROR-CHECK-VARIABLE", String.valueOf(name), e.toString()); - } - } - } - }; - - if (sync) { - runnable.runTaskAsynchronously(Main.getInst()); - } else { - runnable.run(); - } - } - - /** - * 向数据库上传所有数据 - * - * @param sync 是否异步 - */ - public static void uploadVariables(boolean sync) { - if (Main.getStorageType() == StorageType.LOCAL) { - return; - } - - for (SQLVariable variable : variables.values()) { - uploadVariable(variable, sync); - } - } - - /** - * 向数据库上传当前数据 - * - * @param variable 数据 - * @param sync 是否异步 - */ - public static void uploadVariable(SQLVariable variable, boolean sync) { - if (Main.getStorageType() == StorageType.LOCAL) { - return; - } - - BukkitRunnable runnable = new BukkitRunnable() { - - @Override - public void run() { - Main.getConnection().intoValue(Main.getTablePrefix() + "_plugindata", variable.getName(), variable.getVariable() == null ? "null" : variable.getVariable(), TabooLib.getServerUID()); - } - }; - - if (sync) { - runnable.runTaskAsynchronously(Main.getInst()); - } else { - runnable.run(); - } - } - - /** - * 启动数据库储存方法 - */ - public static void startSQLMethod() { - long time = System.currentTimeMillis(); - // 载入数据 - loadVariables(false); - // 提示信息 - TLocale.Logger.info("GLOBAL-DATAMANAGER.SUCCESS-LOADED-VARIABLE", String.valueOf(variables.size()), String.valueOf(System.currentTimeMillis() - time)); - - // 检查更新 - new BukkitRunnable() { - - @Override - public void run() { - checkVariable(true); - } - }.runTaskTimerAsynchronously(Main.getInst(), Main.getInst().getConfig().getInt("PluginData.CHECK-DELAY") * 20, Main.getInst().getConfig().getInt("PluginData.CHECK-DELAY") * 20); - } - - /** - * 结束数据库储存方法 - */ - public static void cancelSQLMethod() { - // 上传数据 - uploadVariables(false); - } - } -} diff --git a/src/main/scala/me/skymc/taboolib/database/PlayerDataManager.java b/src/main/scala/me/skymc/taboolib/database/PlayerDataManager.java deleted file mode 100644 index 217bfd3..0000000 --- a/src/main/scala/me/skymc/taboolib/database/PlayerDataManager.java +++ /dev/null @@ -1,255 +0,0 @@ -package me.skymc.taboolib.database; - -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.Main.StorageType; -import me.skymc.taboolib.events.PlayerLoadedEvent; -import me.skymc.taboolib.exception.PlayerOfflineException; -import me.skymc.taboolib.fileutils.ConfigUtils; -import me.skymc.taboolib.fileutils.FileUtils; -import me.skymc.taboolib.listener.TListener; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -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 org.bukkit.scheduler.BukkitRunnable; - -import java.io.File; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - -@TListener -public class PlayerDataManager implements Listener { - - private static final ConcurrentHashMap PLAYER_DATA = new ConcurrentHashMap<>(); - - /** - * 获取用户储存方式 - * - * @return - */ - public static UsernameType getUsernameType() { - return Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? UsernameType.UUID : UsernameType.USERNAME; - } - - /** - * 获取玩家数据 - * - * @param player 玩家 - * @return - * @throws PlayerOfflineException - */ - public static FileConfiguration getPlayerData(Player player) { - if (getUsernameType() == UsernameType.UUID) { - return getPlayerData(player.getUniqueId().toString(), false); - } else { - return getPlayerData(player.getName(), false); - } - } - - /** - * 获取玩家数据 - * - * @param player - * @return - */ - public static FileConfiguration getPlayerData(OfflinePlayer player) { - if (!player.isOnline()) { - return null; - } - if (getUsernameType() == UsernameType.UUID) { - return getPlayerData(player.getUniqueId().toString(), false); - } else { - return getPlayerData(player.getName(), false); - } - } - - /** - * 读取玩家数据 - * - * @param username 玩家 - * @return - * @throws PlayerOfflineException - */ - public static FileConfiguration getPlayerData(String username, boolean offline) { - if (PLAYER_DATA.containsKey(username)) { - return PLAYER_DATA.get(username); - } else if (offline) { - if (Main.getStorageType() == StorageType.SQL) { - throw new PlayerOfflineException(TLocale.asString("PLAYER-DATAMANAGER.ERROR-STORAGE-SQL")); - } - return loadPlayerData(username); - } - return null; - } - - /** - * 载入玩家数据 - * - * @param username 玩家 - * @return - */ - public static FileConfiguration loadPlayerData(String username) { - // 本地储存 - if (Main.getStorageType() == StorageType.LOCAL) { - // 读取文件 - File file = FileUtils.file(Main.getPlayerDataFolder(), username + ".yml"); - // 载入配置 - PLAYER_DATA.put(username, YamlConfiguration.loadConfiguration(file)); - } else { - // 数据是否存在 - if (Main.getConnection().isExists(Main.getTablePrefix() + "_playerdata", "username", username)) { - // 获取数据 - String code = Main.getConnection().getValue(Main.getTablePrefix() + "_playerdata", "username", username, "configuration").toString(); - try { - // 载入配置 - PLAYER_DATA.put(username, ConfigUtils.decodeYAML(code)); - } catch (Exception e) { - // 创建空数据 - PLAYER_DATA.put(username, new YamlConfiguration()); - // 反馈信息 - TLocale.Logger.error("PLAYER-DATAMANAGER.ERROR-PLAYER-DATA", username, e.toString()); - } - } else { - // 创建空数据 - PLAYER_DATA.put(username, new YamlConfiguration()); - } - } - return PLAYER_DATA.get(username); - } - - /** - * 保存玩家数据 - * - * @param username 玩家 - * @param remove 是否移除缓存 - */ - public static void savePlayerData(String username, boolean remove) { - // 没有数据 - if (!PLAYER_DATA.containsKey(username)) { - return; - } - // 本地储存 - if (Main.getStorageType() == StorageType.LOCAL) { - // 读取文件 - File file = FileUtils.file(Main.getPlayerDataFolder(), username + ".yml"); - // 保存配置 - try { - PLAYER_DATA.get(username).save(file); - } catch (Exception e) { - // TODO: handle exception - } - } - // 如果是数据库储存且有数据 - else if (PLAYER_DATA.get(username).getConfigurationSection("").getKeys(false).size() > 0) { - // 数据是否存在 - if (Main.getConnection().isExists(Main.getTablePrefix() + "_playerdata", "username", username)) { - // 写入数据 - Main.getConnection().setValue(Main.getTablePrefix() + "_playerdata", "username", username, "configuration", ConfigUtils.encodeYAML(PLAYER_DATA.get(username))); - } else { - // 插入数据 - Main.getConnection().intoValue(Main.getTablePrefix() + "_playerdata", username, ConfigUtils.encodeYAML(PLAYER_DATA.get(username))); - } - } - // 获取这个属性对应的玩家 - Player player; - if (getUsernameType() == UsernameType.UUID) { - player = Bukkit.getPlayer(UUID.fromString(username)); - } else { - player = Bukkit.getPlayerExact(username); - } - // 如果移除数据 或 玩家不在线 - if (remove || player == null) { - PLAYER_DATA.remove(username); - } - } - - /** - * 保存所有玩家的缓存 - * - * @param sync 是否异步进行 - * @param remove 是否移除数据 - */ - public static void saveAllCaches(boolean sync, boolean remove) { - BukkitRunnable runnable = new BukkitRunnable() { - - @Override - public void run() { - // 保存 - PLAYER_DATA.keySet().forEach(name -> savePlayerData(name, false)); - } - }; - // 如果异步 - if (sync) { - runnable.runTaskAsynchronously(Main.getInst()); - } - // 如果同步 - else { - runnable.run(); - } - } - - /** - * 保存所有玩家的数据 - * - * @param sync 是否异步进行 - * @param remove 是否移除数据 - */ - public static void saveAllPlayers(boolean sync, boolean remove) { - // 创建任务 - BukkitRunnable runnable = new BukkitRunnable() { - - @Override - public void run() { - for (Player player : Bukkit.getOnlinePlayers()) { - savePlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? player.getUniqueId().toString() : player.getName(), remove); - } - } - }; - // 如果异步 - if (sync) { - runnable.runTaskAsynchronously(Main.getInst()); - } - // 如果同步 - else { - runnable.run(); - } - } - - @EventHandler - public void join(PlayerJoinEvent e) { - new BukkitRunnable() { - - @Override - public void run() { - // 载入数据 - loadPlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? e.getPlayer().getUniqueId().toString() : e.getPlayer().getName()); - // 载入完成 - Bukkit.getPluginManager().callEvent(new PlayerLoadedEvent(e.getPlayer())); - } - }.runTaskAsynchronously(Main.getInst()); - } - - @EventHandler - public void quit(PlayerQuitEvent e) { - if (!Main.isDisable()) { - new BukkitRunnable() { - - @Override - public void run() { - // 保存数据 - savePlayerData(Main.getInst().getConfig().getBoolean("ENABLE-UUID") ? e.getPlayer().getUniqueId().toString() : e.getPlayer().getName(), true); - } - }.runTaskAsynchronously(Main.getInst()); - } - } - - public enum UsernameType { - UUID, USERNAME - } -} diff --git a/src/main/scala/me/skymc/taboolib/events/CustomBookOpenEvent.java b/src/main/scala/me/skymc/taboolib/events/CustomBookOpenEvent.java deleted file mode 100644 index ac8ad24..0000000 --- a/src/main/scala/me/skymc/taboolib/events/CustomBookOpenEvent.java +++ /dev/null @@ -1,81 +0,0 @@ -package me.skymc.taboolib.events; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.bukkit.inventory.ItemStack; - -/** - * The event called when a book is opened trough this Util - */ -public class CustomBookOpenEvent extends Event implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - - private boolean cancelled; - - /** - * The player - */ - private final Player player; - - /** - * The hand used to open the book (the previous item will be restored after the opening) - */ - private Hand hand; - - /** - * The actual book to be opened - */ - private ItemStack book; - - public Player getPlayer() { - return player; - } - - public Hand getHand() { - return hand; - } - - public void setHand(Hand hand) { - this.hand = hand; - } - - public ItemStack getBook() { - return book; - } - - public void setBook(ItemStack book) { - this.book = book; - } - - public CustomBookOpenEvent(Player player, ItemStack book, boolean offHand) { - this.player = player; - this.book = book; - this.hand = offHand ? Hand.OFF_HAND : Hand.MAIN_HAND; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - public enum Hand { - MAIN_HAND, OFF_HAND - } -} diff --git a/src/main/scala/me/skymc/taboolib/events/TPluginEnableEvent.java b/src/main/scala/me/skymc/taboolib/events/TPluginEnableEvent.java deleted file mode 100644 index 3efff37..0000000 --- a/src/main/scala/me/skymc/taboolib/events/TPluginEnableEvent.java +++ /dev/null @@ -1,28 +0,0 @@ -package me.skymc.taboolib.events; - -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.bukkit.plugin.Plugin; - -public class TPluginEnableEvent extends Event { - - private static final HandlerList handlers = new HandlerList(); - private Plugin plugin; - - public TPluginEnableEvent(Plugin plugin) { - this.plugin = plugin; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - public Plugin getPlugin() { - return this.plugin; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } -} diff --git a/src/main/scala/me/skymc/taboolib/events/TPluginLoadEvent.java b/src/main/scala/me/skymc/taboolib/events/TPluginLoadEvent.java deleted file mode 100644 index 8e2a07e..0000000 --- a/src/main/scala/me/skymc/taboolib/events/TPluginLoadEvent.java +++ /dev/null @@ -1,28 +0,0 @@ -package me.skymc.taboolib.events; - -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.bukkit.plugin.Plugin; - -public class TPluginLoadEvent extends Event { - - private static final HandlerList handlers = new HandlerList(); - private Plugin plugin; - - public TPluginLoadEvent(Plugin plugin) { - this.plugin = plugin; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - public Plugin getPlugin() { - return this.plugin; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } -} diff --git a/src/main/scala/me/skymc/taboolib/events/itag/AsyncPlayerReceiveNameTagEvent.java b/src/main/scala/me/skymc/taboolib/events/itag/AsyncPlayerReceiveNameTagEvent.java deleted file mode 100644 index 6d765de..0000000 --- a/src/main/scala/me/skymc/taboolib/events/itag/AsyncPlayerReceiveNameTagEvent.java +++ /dev/null @@ -1,85 +0,0 @@ -package me.skymc.taboolib.events.itag; - -import com.google.common.base.Preconditions; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import java.util.UUID; - -/** - * @author md_5 - */ -public class AsyncPlayerReceiveNameTagEvent extends Event { - - private static final HandlerList handlers = new HandlerList(); - - private final Player player; - private final Player namedPlayer; - private String tag; - private UUID UUID; - private boolean tagModified; - private boolean UUIDModified; - - public Player getPlayer() { - return player; - } - - public Player getNamedPlayer() { - return namedPlayer; - } - - public String getTag() { - return tag; - } - - public java.util.UUID getUUID() { - return UUID; - } - - public boolean isTagModified() { - return tagModified; - } - - public boolean isUUIDModified() { - return UUIDModified; - } - - public AsyncPlayerReceiveNameTagEvent(Player who, Player namedPlayer, String initialName, UUID uuid) { - Preconditions.checkNotNull(who, "who"); - Preconditions.checkNotNull(namedPlayer, "namedPlayer"); - Preconditions.checkNotNull(initialName, "initialName"); - Preconditions.checkNotNull(uuid, "uuid"); - - this.player = who; - this.namedPlayer = namedPlayer; - this.tag = initialName; - this.tagModified = namedPlayer.getName().equals(initialName); - this.UUID = uuid; - } - - public boolean setTag(String tag) { - Preconditions.checkNotNull(tag, "tag"); - - this.tag = tag; - this.tagModified = true; - - return tag.length() < 16; - } - - public void setUUID(UUID uuid) { - Preconditions.checkNotNull(uuid, "uuid"); - - this.UUID = uuid; - this.UUIDModified = true; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/main/scala/me/skymc/taboolib/events/itag/PlayerReceiveNameTagEvent.java b/src/main/scala/me/skymc/taboolib/events/itag/PlayerReceiveNameTagEvent.java deleted file mode 100644 index 7ea835e..0000000 --- a/src/main/scala/me/skymc/taboolib/events/itag/PlayerReceiveNameTagEvent.java +++ /dev/null @@ -1,57 +0,0 @@ -package me.skymc.taboolib.events.itag; - -import com.google.common.base.Preconditions; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; - -/** - * @author md_5 - */ -public class PlayerReceiveNameTagEvent extends PlayerEvent { - - private static final HandlerList handlers = new HandlerList(); - private final Player namedPlayer; - private String tag; - private boolean modified; - - public Player getNamedPlayer() { - return namedPlayer; - } - - public String getTag() { - return tag; - } - - public boolean isModified() { - return modified; - } - - public PlayerReceiveNameTagEvent(Player who, Player namedPlayer, String initialName) { - super(who); - Preconditions.checkNotNull(who, "who"); - Preconditions.checkNotNull(namedPlayer, "namedPlayer"); - Preconditions.checkNotNull(initialName, "initialName"); - - this.namedPlayer = namedPlayer; - this.tag = initialName; - } - - public boolean setTag(String tag) { - Preconditions.checkNotNull(tag, "tag"); - - this.tag = tag; - this.modified = true; - - return tag.length() < 16; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/main/scala/me/skymc/taboolib/exception/PlayerOfflineException.java b/src/main/scala/me/skymc/taboolib/exception/PlayerOfflineException.java deleted file mode 100644 index 1dd431e..0000000 --- a/src/main/scala/me/skymc/taboolib/exception/PlayerOfflineException.java +++ /dev/null @@ -1,10 +0,0 @@ -package me.skymc.taboolib.exception; - -public class PlayerOfflineException extends Error { - - private static final long serialVersionUID = 4129402767538548807L; - - public PlayerOfflineException(String message) { - super(message); - } -} diff --git a/src/main/scala/me/skymc/taboolib/exception/PluginNotFoundException.java b/src/main/scala/me/skymc/taboolib/exception/PluginNotFoundException.java deleted file mode 100644 index 0fec22b..0000000 --- a/src/main/scala/me/skymc/taboolib/exception/PluginNotFoundException.java +++ /dev/null @@ -1,10 +0,0 @@ -package me.skymc.taboolib.exception; - -public class PluginNotFoundException extends Error { - - private static final long serialVersionUID = -475540326950009346L; - - public PluginNotFoundException(String message) { - super(message); - } -} diff --git a/src/main/scala/me/skymc/taboolib/fileutils/ConfigUtils.java b/src/main/scala/me/skymc/taboolib/fileutils/ConfigUtils.java deleted file mode 100644 index d31635b..0000000 --- a/src/main/scala/me/skymc/taboolib/fileutils/ConfigUtils.java +++ /dev/null @@ -1,212 +0,0 @@ -package me.skymc.taboolib.fileutils; - -import com.google.common.collect.Maps; -import com.google.common.io.Files; -import com.ilummc.tlib.bean.Property; -import com.ilummc.tlib.resources.TLocale; -import com.ilummc.tlib.util.Ref; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.MemoryConfiguration; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; - -import java.io.File; -import java.io.StringReader; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.nio.charset.Charset; -import java.util.Map; - -public class ConfigUtils { - - private static final Yaml YAML; - - static { - DumperOptions options = new DumperOptions(); - options.setAllowUnicode(false); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - YAML = new Yaml(options); - } - - @SuppressWarnings("unchecked") - public static Map yamlToMap(String yamlText) { - return (Map) YAML.load(yamlText); - } - - public static MemoryConfiguration objToConf(Object object) { - return mapToConf(objToMap(object)); - } - - public static MemoryConfiguration objToConf(Object object, int excludedModifiers) { - return mapToConf(objToMap(object, excludedModifiers)); - } - - public static Object confToObj(MemoryConfiguration configuration, Class clazz) { - try { - return mapToObj(configuration.getValues(false), clazz.newInstance()); - } catch (InstantiationException | IllegalAccessException e) { - return null; - } - } - - public static Object confToObj(MemoryConfiguration configuration, T obj) { - return mapToObj(configuration.getValues(false), obj); - } - - public static String mapToYaml(Map map) { - String dump = YAML.dump(map); - if ("{}\n".equals(dump)) { - dump = ""; - } - return dump; - } - - public static MemoryConfiguration mapToConf(Map map) { - YamlConfiguration configuration = new YamlConfiguration(); - convertMapsToSections(map, configuration); - return configuration; - } - - public static Map confToMap(MemoryConfiguration configuration) { - return configuration.getValues(false); - } - - /** - * 将会在该类无默认构造方法时返回 null - */ - public static T mapToObj(Map map, Class clazz) { - try { - return mapToObj(map, clazz.newInstance()); - } catch (InstantiationException | IllegalAccessException e) { - return null; - } - } - - @SuppressWarnings("unchecked") - public static T mapToObj(Map map, T obj) { - Class clazz = obj.getClass(); - map.forEach((string, value) -> Ref.getFieldBySerializedName(clazz, string).ifPresent(field -> { - if (!field.isAccessible()) { - field.setAccessible(true); - } - try { - if (Property.class.isAssignableFrom(field.getType())) { - Property property = (Property) field.get(obj); - if (property != null) { - property.set(value); - } else { - field.set(obj, Property.of(value)); - } - } else { - field.set(obj, value); - } - } catch (IllegalAccessException ignored) { - } - })); - return obj; - } - - public static Map objToMap(Object object) { - return objToMap(object, Modifier.TRANSIENT & Modifier.STATIC & Ref.ACC_SYNTHETIC); - } - - @SuppressWarnings("unchecked") - public static Map objToMap(Object object, int excludedModifiers) { - Map map = Maps.newHashMap(); - if (object instanceof Map) { - ((Map) object).forEach((k, v) -> map.put(k, objToMap(v, excludedModifiers))); - return map; - } - if (object instanceof ConfigurationSection) { - map.putAll(objToMap(((ConfigurationSection) object).getValues(false), excludedModifiers)); - return map; - } - for (Field field : Ref.getDeclaredFields(object.getClass(), excludedModifiers, false)) { - try { - if (!field.isAccessible()) { - field.setAccessible(true); - } - Object obj = field.get(object); - if (obj instanceof Property) { - obj = ((Property) obj).get(); - } - if (obj instanceof ConfigurationSection) { - obj = objToMap(((ConfigurationSection) obj).getValues(false), excludedModifiers); - } - map.put(Ref.getSerializedName(field), obj); - } catch (IllegalAccessException ignored) { - } - } - return map; - } - - private static void convertMapsToSections(Map input, ConfigurationSection section) { - for (Object o : input.entrySet()) { - Map.Entry entry = (Map.Entry) o; - String key = entry.getKey().toString(); - Object value = entry.getValue(); - if (value instanceof Map) { - convertMapsToSections((Map) value, section.createSection(key)); - } else { - section.set(key, value); - } - } - } - - public static FileConfiguration decodeYAML(String args) { - return YamlConfiguration.loadConfiguration(new StringReader(Base64Coder.decodeString(args))); - } - - public static String encodeYAML(FileConfiguration file) { - return Base64Coder.encodeLines(file.saveToString().getBytes()).replaceAll("\\s+", ""); - } - - /** - * 以 UTF-8 的格式释放配置文件并载入 - *

- * 录入时间:2018年2月10日21:28:30 - * 录入版本:3.49 - * - * @param plugin - * @return - */ - public static FileConfiguration saveDefaultConfig(Plugin plugin, String name) { - File file = new File(plugin.getDataFolder(), name); - if (!file.exists()) { - plugin.saveResource(name, true); - } - return load(plugin, file); - } - - /** - * 以 UTF-8 的格式载入配置文件 - * - * @return - */ - public static FileConfiguration load(Plugin plugin, File file) { - return loadYaml(plugin, file); - } - - public static YamlConfiguration loadYaml(Plugin plugin, File file) { - YamlConfiguration configuration = new YamlConfiguration(); - try { - String yaml = Files.toString(file, Charset.forName("utf-8")); - configuration.loadFromString(yaml); - return configuration; - } catch (Exception e) { - TLocale.Logger.error("FILE-UTILS.FAIL-LOAD-CONFIGURATION", plugin.getName(), file.getPath()); - e.printStackTrace(); - } - return configuration; - } - - - @Deprecated - public static FileConfiguration load(Plugin plugin, String file) { - return load(plugin, FileUtils.file(file)); - } -} diff --git a/src/main/scala/me/skymc/taboolib/fileutils/FileUtils.java b/src/main/scala/me/skymc/taboolib/fileutils/FileUtils.java deleted file mode 100644 index c16ab30..0000000 --- a/src/main/scala/me/skymc/taboolib/fileutils/FileUtils.java +++ /dev/null @@ -1,481 +0,0 @@ -package me.skymc.taboolib.fileutils; - -import ch.njol.util.Closeable; -import com.ilummc.eagletdl.EagletTask; -import com.ilummc.eagletdl.ProgressEvent; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.common.io.IOUtils; -import org.bukkit.plugin.Plugin; - -import java.io.*; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; -import java.nio.channels.FileChannel; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.jar.JarFile; - -/** - * @author sky - */ -public class FileUtils { - - /** - * 获取本地 IP 地址 - * - * @return {@link String} - */ - public static String ip() { - URL url; - URLConnection con; - try { - url = new URL("http://1212.ip138.com/ic.asp"); - con = url.openConnection(); - } catch (Exception ignored) { - return "[IP ERROR]"; - } - InputStream ins = null; - InputStreamReader inputStreamReader = null; - BufferedReader bufferedReader = null; - try { - ins = con.getInputStream(); - inputStreamReader = new InputStreamReader(ins, "GB2312"); - bufferedReader = new BufferedReader(inputStreamReader); - StringBuilder webContent = new StringBuilder(); - bufferedReader.lines().forEach(webContent::append); - int start = webContent.indexOf("[") + 1; - int end = webContent.indexOf("]"); - return webContent.substring(start, end); - } catch (Exception ignored) { - return "[IP ERROR]"; - } finally { - IOUtils.close(con); - IOUtils.closeQuietly(bufferedReader); - IOUtils.closeQuietly(inputStreamReader); - IOUtils.closeQuietly(ins); - } - } - - /** - * 获取插件所有类 - * - * @return {@link List} - */ - public static List getClasses(Class obj) { - List classes = new ArrayList<>(); - URL url = getCaller(obj).getProtectionDomain().getCodeSource().getLocation(); - try { - File src; - try { - src = new File(url.toURI()); - } catch (URISyntaxException e) { - src = new File(url.getPath()); - } - new JarFile(src).stream().filter(entry -> entry.getName().endsWith(".class")).forEach(entry -> { - String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6); - try { - classes.add(Class.forName(className, false, obj.getClassLoader())); - } catch (Throwable ignored) { - } - }); - } catch (Throwable ignored) { - } - return classes; - } - - /** - * 获取插件所有类 - * - * @param plugin 插件 - */ - public static List getClasses(Plugin plugin) { - return getClasses(plugin, new String[0]); - } - - /** - * 获取插件所有类 - * - * @param plugin 插件 - * @param ignore 忽略包名 - */ - public static List getClasses(Plugin plugin, String[] ignore) { - List classes = new CopyOnWriteArrayList<>(); - URL url = plugin.getClass().getProtectionDomain().getCodeSource().getLocation(); - try { - File src; - try { - src = new File(url.toURI()); - } catch (URISyntaxException e) { - src = new File(url.getPath()); - } - new JarFile(src).stream().filter(entry -> entry.getName().endsWith(".class")).forEach(entry -> { - String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6); - try { - if (Arrays.stream(ignore).noneMatch(className::startsWith)) { - classes.add(Class.forName(className, false, plugin.getClass().getClassLoader())); - } - } catch (Throwable ignored) { - } - }); - } catch (Throwable ignored) { - } - return classes; - } - - /** - * 获取资源文件 - * - * @param filename 文件名 - * @return {@link InputStream} - */ - public static InputStream getResource(String filename) { - return getResource(Main.getInst(), filename); - } - - /** - * 获取插件资源文件 - * - * @param plugin 插件 - * @param filename 文件名 - * @return {@link InputStream} - */ - public static InputStream getResource(Plugin plugin, String filename) { - return plugin.getClass().getClassLoader().getResourceAsStream(filename); - } - - /** - * 写入文件 - * - * @param inputStream 输入流 - * @param file 文件 - */ - public static void inputStreamToFile(InputStream inputStream, File file) { - try (FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos)) { - byte[] buf = new byte[1024]; - int len; - while ((len = inputStream.read(buf)) > 0) { - bos.write(buf, 0, len); - } - bos.flush(); - } catch (Exception ignored) { - } - } - - /** - * 释放资源文件 - * - * @param plugin 所属插件 - * @param path 地址 - * @param replace 是否替换 - */ - public static void releaseResource(Plugin plugin, String path, boolean replace) { - File file = new File(plugin.getDataFolder(), path); - if (!file.exists() || replace) { - inputStreamToFile(getResource(plugin, path), file); - } - } - - /** - * 检测文件并创建 - * - * @param file 文件 - */ - public static File createNewFile(File file) { - if (file != null && !file.exists()) { - try { - file.createNewFile(); - } catch (Exception ignored) { - } - } - return file; - } - - /** - * 检测文件并创建(目录) - * - * @param file 文件 - */ - public static void createNewFileAndPath(File file) { - if (!file.exists()) { - String filePath = file.getPath(); - int index = filePath.lastIndexOf(File.separator); - String folderPath; - File folder; - if ((index >= 0) && (!(folder = new File(filePath.substring(0, index))).exists())) { - folder.mkdirs(); - } - try { - file.createNewFile(); - } catch (IOException ignored) { - } - } - } - - /** - * 创建并获取目录 - * - * @param path 目录文件 - * @return - */ - public static File folder(File path) { - if (!path.exists()) { - path.mkdirs(); - } - return path; - } - - /** - * 创建并获取目录 - * - * @param path 目录地址 - * @return - */ - public static File folder(String path) { - return folder(new File(path)); - } - - /** - * 创建并获取文件 - * - * @param path 目录 - * @param filePath 地址 - * @return - */ - public static File file(File path, String filePath) { - return createNewFile(new File(path, filePath)); - } - - /** - * 创建并获取文件 - * - * @param filePath 地址 - * @return {@link File} - */ - public static File file(String filePath) { - return createNewFile(new File(filePath)); - } - - /** - * 删除文件夹 - * - * @param file 文件夹 - */ - public static void deleteAllFile(File file) { - if (!file.exists()) { - return; - } - if (file.isFile()) { - file.delete(); - return; - } - for (File file1 : Objects.requireNonNull(file.listFiles())) { - deleteAllFile(file1); - } - file.delete(); - } - - /** - * 复制文件夹 - * - * @param originFileName 文件1 - * @param targetFileName 文件2 - */ - public static void copyAllFile(String originFileName, String targetFileName) { - File originFile = new File(originFileName); - File targetFile = new File(targetFileName); - if (!targetFile.exists()) { - if (!originFile.isDirectory()) { - createNewFile(targetFile); - } else { - targetFile.mkdirs(); - } - } - if (originFile.isDirectory()) { - for (File file : Objects.requireNonNull(originFile.listFiles())) { - if (file.isDirectory()) { - copyAllFile(file.getAbsolutePath(), targetFileName + "/" + file.getName()); - } else { - fileChannelCopy(file, new File(targetFileName + "/" + file.getName())); - } - } - } else { - fileChannelCopy(originFile, targetFile); - } - } - - /** - * 复制文件(通道) - * - * @param file1 文件1 - * @param file2 文件2 - */ - public static void fileChannelCopy(File file1, File file2) { - try (FileInputStream fileIn = new FileInputStream(file1); - FileOutputStream fileOut = new FileOutputStream(file2); - FileChannel channelIn = fileIn.getChannel(); - FileChannel channelOut = fileOut.getChannel()) { - channelIn.transferTo(0, channelIn.size(), channelOut); - } catch (IOException ignored) { - } - } - - /** - * 通过 URL 读取文本 - * - * @param url 地址 - * @param def 默认值 - * @return 文本 - */ - public static String getStringFromURL(String url, String def) { - String s = getStringFromURL(url, 1024); - return s == null ? def : s; - } - - /** - * 通过 URL 读取文本 - * - * @param url 地址 - * @param size 大小 - * @return 文本 - */ - public static String getStringFromURL(String url, int size) { - URLConnection conn = null; - BufferedInputStream bin = null; - try { - conn = new URL(url).openConnection(); - bin = new BufferedInputStream(conn.getInputStream()); - return getStringFromInputStream(bin, size, conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding()); - } catch (IOException e) { - e.printStackTrace(); - } finally { - IOUtils.close(conn); - IOUtils.closeQuietly(bin); - } - return null; - } - - /** - * 通过文件读取文本 - * - * @param file 文件 - * @param size 大小 - * @param encode 编码 - * @return 文本 - */ - public static String getStringFromFile(File file, int size, String encode) { - try (FileInputStream fin = new FileInputStream(file); BufferedInputStream bin = new BufferedInputStream(fin)) { - return getStringFromInputStream(fin, size, encode); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * 通过输入流读取文本 - * - * @param in 输入流 - * @param size 大小 - * @param encode 编码 - * @return 文本 - */ - public static String getStringFromInputStream(InputStream in, int size, String encode) { - try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { - byte[] b = new byte[size]; - int i; - while ((i = in.read(b)) > 0) { - bos.write(b, 0, i); - } - return new String(bos.toByteArray(), encode); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - /** - * 下载文件 - * - * @param url 下载地址 - * @param file 下载位置 - */ - public static void download(String url, File file) { - download(url, file, false); - } - - /** - * 下载文件 - * - * @param url 下载地址 - * @param file 下载位置 - * @param async 是否异步 - */ - public static void download(String url, File file, boolean async) { - EagletTask eagletTask = new EagletTask() - .url(url) - .file(file) - .setThreads(8) - .setOnError(event -> { - }) - .setOnConnected(event -> TLocale.Logger.info("UTIL.DOWNLOAD-CONNECTED", file.getName(), ProgressEvent.format(event.getContentLength()))) - .setOnProgress(event -> TLocale.Logger.info("UTIL.DOWNLOAD-PROGRESS", event.getSpeedFormatted(), event.getPercentageFormatted())) - .setOnComplete(event -> { - if (event.isSuccess()) { - TLocale.Logger.info("UTIL.DOWNLOAD-SUCCESS", file.getName()); - } else { - TLocale.Logger.error("UTIL.DOWNLOAD-FAILED", file.getName()); - } - }).start(); - if (!async) { - eagletTask.waitUntil(); - } - } - - @Deprecated - public static void download(String url, String filename, File saveDir) { - download(url, new File(saveDir, filename)); - } - - @Deprecated - public static void close(Closeable closeable) { - try { - if (closeable != null) { - closeable.close(); - } - } catch (Exception ignored) { - } - } - - @Deprecated - public static byte[] read(InputStream in) { - byte[] buffer = new byte[1024]; - int len; - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - while ((len = in.read(buffer)) != -1) { - bos.write(buffer, 0, len); - } - } catch (Exception ignored) { - } - return bos.toByteArray(); - } - - // ********************************* - // - // Private Methods - // - // ********************************* - - private static Class getCaller(Class obj) { - try { - return Class.forName(Thread.currentThread().getStackTrace()[3].getClassName(), false, obj.getClassLoader()); - } catch (ClassNotFoundException ignored) { - } - return null; - } -} diff --git a/src/main/scala/me/skymc/taboolib/inventory/ItemUtils.java b/src/main/scala/me/skymc/taboolib/inventory/ItemUtils.java deleted file mode 100644 index 4e2e131..0000000 --- a/src/main/scala/me/skymc/taboolib/inventory/ItemUtils.java +++ /dev/null @@ -1,493 +0,0 @@ -package me.skymc.taboolib.inventory; - -import com.ilummc.tlib.resources.TLocale; -import me.clip.placeholderapi.PlaceholderAPI; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.common.function.TFunction; -import me.skymc.taboolib.common.nms.NMSHandler; -import me.skymc.taboolib.common.nms.nbt.NBTBase; -import me.skymc.taboolib.common.nms.nbt.NBTCompound; -import me.skymc.taboolib.common.nms.nbt.NBTList; -import me.skymc.taboolib.common.util.SimpleI18n; -import me.skymc.taboolib.fileutils.ConfigUtils; -import me.skymc.taboolib.itemnbtapi.NBTItem; -import me.skymc.taboolib.other.NumberUtils; -import org.bukkit.Color; -import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.LeatherArmorMeta; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.util.NumberConversions; - -import java.io.File; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.stream.IntStream; - -/** - * @author sky - */ -@TFunction(enable = "init") -public class ItemUtils { - - private static File finalItemsFolder; - private static FileConfiguration itemDir; - private static FileConfiguration itemCache; - private static LinkedHashMap itemLib = new LinkedHashMap<>(); - private static LinkedHashMap itemCaches = new LinkedHashMap<>(); - private static LinkedHashMap itemCachesFinal = new LinkedHashMap<>(); - - public static void init() { - try { - reloadItemDir(); - reloadItemCache(); - } catch (Exception e) { - TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-ITEMS", e.toString()); - } - } - - public static void reloadItemDir() { - File file = new File(Main.getInst().getConfig().getString("DATAURL.ITEMDIR")); - if (file.exists()) { - itemDir = YamlConfiguration.loadConfiguration(file); - } - } - - 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)); - TabooLib.debug("Loaded " + (itemCaches.size() + itemCachesFinal.size()) + " items."); -// TLocale.Logger.info("ITEM-UTILS.SUCCESS-LOAD-CACHES", String.valueOf(itemCaches.size() + itemCachesFinal.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 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)); - } - } - } - - // ********************************* - // - // API - // - // ********************************* - - public static boolean isExists(String name) { - return itemCachesFinal.containsKey(name) || itemCaches.containsKey(name); - } - - public static ItemStack getCacheItem(String name) { - return itemCachesFinal.containsKey(name) ? itemCachesFinal.get(name) : itemCaches.get(name); - } - - public static ItemStack getItemFromDir(String name) { - return itemDir != null ? itemDir.getItemStack("item." + name) : null; - } - - public static String getCustomName(ItemStack item) { - return SimpleI18n.getCustomName(item); - } - - 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); - } - - 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) { - return placeholderPlayer == null ? args.replace("&", "§") : 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; - } - - public static ItemFlag asItemFlag(String flag) { - try { - return ItemFlag.valueOf(flag); - } catch (Exception e) { - return null; - } - } - - @SuppressWarnings("deprecation") - public static Material asMaterial(String args) { - try { - Material material = Material.getMaterial(args.toUpperCase()); - 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 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); - } - } - - public static String asAttribute(String name) { - switch (name.toLowerCase()) { - case "damage": - return "generic.attackDamage"; - case "attackspeed": - return "generic.attackSpeed"; - case "health": - return "generic.maxHealth"; - case "speed": - return "generic.movementSpeed"; - case "knockback": - return "generic.knockbackResistance"; - case "armor": - return "generic.armor"; - case "luck": - return "generic.luck"; - default: - return null; - } - } - - 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; - } - - public static boolean hasLore(ItemStack i, String a) { - return isLored(i) && i.getItemMeta().getLore().toString().contains(a); - } - - public static boolean isLored(ItemStack i) { - return i != null && i.getItemMeta() != null && i.getItemMeta().getLore() != null; - } - - public static boolean isNamed(ItemStack i) { - return i != null && i.getItemMeta() != null && i.getItemMeta().getDisplayName() != null; - } - - public static ItemStack addLore(ItemStack is, String line) { - ItemMeta meta = is.getItemMeta(); - List lore = meta.hasLore() ? meta.getLore() : Collections.emptyList(); - lore.add(TLocale.Translate.setColored(line)); - is.setItemMeta(meta); - return is; - } - - public static ItemStack delLore(ItemStack is, int line) { - ItemMeta meta = is.getItemMeta(); - if (meta.hasLore()) { - List l = meta.getLore(); - if (l.size() >= line) { - l.remove(line); - meta.setLore(l); - is.setItemMeta(meta); - } - } - return is; - } - - public static ItemStack replaceLore(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; - } - - 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; - } - - public static ItemStack loadItem(FileConfiguration f, String s) { - return loadItem(f, s, null); - } - - public static ItemStack loadItem(FileConfiguration f, String s, Player 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.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("enchant")) { - for (String preEnchant : section.getConfigurationSection("enchant").getKeys(false)) { - Enchantment enchant = asEnchantment(preEnchant); - if (enchant != null) { - meta.addEnchant(enchant, section.getInt("enchant." + 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); - // 数据 - NBTCompound nbt = NMSHandler.getHandler().loadNBT(item); - // 物品标签 - if (section.contains("nbt")) { - for (String name : section.getConfigurationSection("nbt").getKeys(false)) { - Object obj = section.get("nbt." + name); - if (obj instanceof String) { - nbt.put(name, new NBTBase(obj.toString())); - } else if (obj instanceof Double) { - nbt.put(name, new NBTBase(NumberConversions.toDouble(obj))); - } else if (obj instanceof Integer) { - nbt.put(name, new NBTBase(NumberConversions.toInt(obj))); - } else if (obj instanceof Long) { - nbt.put(name, new NBTBase(NumberConversions.toLong(obj))); - } - } - } - // 物品属性 - if (section.contains("attributes")) { - NBTList attr = new NBTList(); - for (String hand : section.getConfigurationSection("attributes").getKeys(false)) { - for (String name : section.getConfigurationSection("attributes." + hand).getKeys(false)) { - if (asAttribute(name) != null) { - try { - NBTCompound a = new NBTCompound(); - String num = section.getString("attributes." + hand + "." + name); - if (num.endsWith("%")) { - a.put("Amount", new NBTBase(NumberConversions.toDouble(num.substring(0, num.length() - 1)) / 100D)); - a.put("Operation", new NBTBase(1)); - } else { - a.put("Amount", new NBTBase(NumberConversions.toDouble(num))); - a.put("Operation", new NBTBase(0)); - } - a.put("AttributeName", new NBTBase(asAttribute(name))); - a.put("UUIDMost", new NBTBase(NumberUtils.getRandom().nextInt(Integer.MAX_VALUE))); - a.put("UUIDLeast", new NBTBase(NumberUtils.getRandom().nextInt(Integer.MAX_VALUE))); - a.put("Name", new NBTBase(asAttribute(name))); - if (!hand.equals("all")) { - a.put("Slot", new NBTBase(hand)); - } - attr.add(a); - } catch (Exception ignored) { - } - } else { - TLocale.Logger.error("ITEM-UTILS.FAIL-LOAD-POTION", name); - } - } - } - nbt.put("AttributeModifiers", attr); - } - return NMSHandler.getHandler().saveNBT(item, nbt); - } - - // ********************************* - // - // Getter and Setter - // - // ********************************* - - public static FileConfiguration getItemDir() { - return itemDir; - } - - public static LinkedHashMap getItemLib() { - return itemLib; - } - - public static FileConfiguration getItemCache() { - return itemCache; - } - - public static File getFinalItemsFolder() { - return finalItemsFolder; - } - - public static LinkedHashMap getItemCaches() { - return itemCaches; - } - - public static LinkedHashMap getItemCachesFinal() { - return itemCachesFinal; - } - - // ********************************* - // - // Deprecated - // - // ********************************* - - @Deprecated - public static NBTItem setAttribute(NBTItem nbt, String name, Object num, String hand) { - return nbt; - } - - @Deprecated - public static FileConfiguration getItemdir() { - return itemDir; - } - - @Deprecated - public static LinkedHashMap getItemlib() { - return itemLib; - } - - @Deprecated - public static ItemStack item(int n, int a, int d) { - return new ItemStack(n, a, (short) d); - } - - @Deprecated - public static ItemStack repalceLore(ItemStack i, String l1, String l2) { - return replaceLore(i, l1, l2); - } - - @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); - } -} diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/MenuBuilder.java b/src/main/scala/me/skymc/taboolib/inventory/builder/MenuBuilder.java deleted file mode 100644 index f064bc9..0000000 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/MenuBuilder.java +++ /dev/null @@ -1,71 +0,0 @@ -package me.skymc.taboolib.inventory.builder; - -import me.skymc.taboolib.inventory.builder.menu.MenuBuilderCallable; -import me.skymc.taboolib.inventory.builder.menu.MenuBuilderHolder; -import me.skymc.taboolib.inventory.builder.menu.MenuBuilderItem; -import org.bukkit.Bukkit; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import java.util.Arrays; -import java.util.HashMap; - -/** - * @Author sky - * @Since 2018-08-22 13:40 - * @BuilderVersion 1.0 - */ -@Deprecated -public class MenuBuilder { - - private boolean lock; - private String name; - private int rows = 9; - private Inventory parent; - - private HashMap items = new HashMap<>(); - - public MenuBuilder() { - this(true); - } - - public MenuBuilder(boolean lock) { - this.lock = lock; - } - - public MenuBuilder lock(boolean lock) { - this.lock = lock; - return this; - } - - public MenuBuilder name(String name) { - this.name = name; - return this; - } - - public MenuBuilder rows(int rows) { - this.rows = rows * 9; - return this; - } - - public MenuBuilder item(ItemStack itemStack, int... slots) { - Arrays.stream(slots).forEach(slot -> items.put(slot, new MenuBuilderItem(itemStack, null))); - return this; - } - - public MenuBuilder item(ItemStack itemStack, MenuBuilderCallable callable, int... slots) { - Arrays.stream(slots).forEach(slot -> items.put(slot, new MenuBuilderItem(itemStack, callable))); - return this; - } - - public MenuBuilder parent(Inventory parent) { - this.parent = parent; - return this; - } - - public Inventory build() { - Inventory inventory = Bukkit.createInventory(new MenuBuilderHolder(lock, items, parent), rows, name); - items.forEach((key, value) -> inventory.setItem(key, value.getItemStack())); - return inventory; - } -} diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderCallable.java b/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderCallable.java deleted file mode 100644 index 8a0beb6..0000000 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderCallable.java +++ /dev/null @@ -1,10 +0,0 @@ -package me.skymc.taboolib.inventory.builder.menu; - -/** - * @Author sky - * @Since 2018-08-22 15:41 - */ -public interface MenuBuilderCallable { - - void call(MenuBuilderEvent event); -} diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderEvent.java b/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderEvent.java deleted file mode 100644 index 692896c..0000000 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderEvent.java +++ /dev/null @@ -1,48 +0,0 @@ -package me.skymc.taboolib.inventory.builder.menu; - -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.ItemStack; - -/** - * @Author sky - * @Since 2018-08-22 15:44 - */ -public class MenuBuilderEvent { - - private final InventoryClickEvent parentEvent; - private final Player player; - private final ItemStack clickItem; - private final int clickSlot; - - public MenuBuilderEvent(InventoryClickEvent parentEvent, Player player, ItemStack clickItem, int clickSlot) { - this.parentEvent = parentEvent; - this.player = player; - this.clickItem = clickItem; - this.clickSlot = clickSlot; - } - - public InventoryClickEvent getParentEvent() { - return parentEvent; - } - - public Player getPlayer() { - return player; - } - - public ItemStack getClickItem() { - return clickItem; - } - - public int getClickSlot() { - return clickSlot; - } - - public void setCancelled(boolean canceled) { - parentEvent.setCancelled(canceled); - } - - public boolean isCancelled() { - return parentEvent.isCancelled(); - } -} diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderHolder.java b/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderHolder.java deleted file mode 100644 index b54684d..0000000 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderHolder.java +++ /dev/null @@ -1,50 +0,0 @@ -package me.skymc.taboolib.inventory.builder.menu; - -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; - -import java.util.HashMap; - -/** - * @author sky - * @Since 2018-08-22 13:40 - */ -public class MenuBuilderHolder implements InventoryHolder { - - private final boolean lock; - private final HashMap items; - private final Inventory parent; - - public MenuBuilderHolder(boolean lock, HashMap items, Inventory parent) { - this.lock = lock; - this.items = items; - this.parent = parent; - } - - public MenuBuilderHolder(boolean lock, HashMap items) { - this(lock, items, null); - } - - @Override - public Inventory getInventory() { - return null; - } - - // ********************************* - // - // Getter and Setter - // - // ********************************* - - public boolean isLock() { - return lock; - } - - public HashMap getItems() { - return items; - } - - public Inventory getParent() { - return parent; - } -} \ No newline at end of file diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderItem.java b/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderItem.java deleted file mode 100644 index 17e0cce..0000000 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderItem.java +++ /dev/null @@ -1,26 +0,0 @@ -package me.skymc.taboolib.inventory.builder.menu; - -import org.bukkit.inventory.ItemStack; - -/** - * @Author sky - * @Since 2018-08-22 15:36 - */ -public class MenuBuilderItem { - - private final ItemStack itemStack; - private final MenuBuilderCallable callable; - - public MenuBuilderItem(ItemStack itemStack, MenuBuilderCallable callable) { - this.itemStack = itemStack; - this.callable = callable; - } - - public ItemStack getItemStack() { - return itemStack; - } - - public MenuBuilderCallable getCallable() { - return callable; - } -} diff --git a/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderListener.java b/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderListener.java deleted file mode 100644 index 3eba630..0000000 --- a/src/main/scala/me/skymc/taboolib/inventory/builder/menu/MenuBuilderListener.java +++ /dev/null @@ -1,49 +0,0 @@ -package me.skymc.taboolib.inventory.builder.menu; - -import me.skymc.taboolib.Main; -import me.skymc.taboolib.listener.TListener; -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.inventory.InventoryAction; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; - -import java.util.Optional; - -/** - * @Author sky - * @Since 2018-08-22 13:40 - */ -@TListener -public class MenuBuilderListener implements Listener { - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onClick(InventoryClickEvent e) { - if (!(e.getInventory().getHolder() instanceof MenuBuilderHolder)) { - return; - } - MenuBuilderHolder holder = (MenuBuilderHolder) e.getInventory().getHolder(); - if (holder.isLock() || e.getAction() == InventoryAction.COLLECT_TO_CURSOR) { - e.setCancelled(true); - } - Optional.ofNullable(holder.getItems().get(e.getRawSlot())).ifPresent(item -> { - if (item.getCallable() != null) { - item.getCallable().call(new MenuBuilderEvent(e, (Player) e.getWhoClicked(), e.getCurrentItem(), e.getRawSlot())); - } - }); - } - - @EventHandler - public void onClose(InventoryCloseEvent event) { - if (event.getInventory().getHolder() instanceof MenuBuilderHolder) { - MenuBuilderHolder holder = (MenuBuilderHolder) event.getInventory().getHolder(); - if (holder.getParent() != null) { - Bukkit.getScheduler().runTask(Main.getInst(), () -> event.getPlayer().openInventory(holder.getParent())); - } - } - } - -} diff --git a/src/main/scala/me/skymc/taboolib/itagapi/TagPacket.java b/src/main/scala/me/skymc/taboolib/itagapi/TagPacket.java deleted file mode 100644 index ca76c61..0000000 --- a/src/main/scala/me/skymc/taboolib/itagapi/TagPacket.java +++ /dev/null @@ -1,134 +0,0 @@ -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.EventPriority; -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() { - Preconditions.checkArgument(!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/scala/me/skymc/taboolib/listener/ListenerPlayerCommand.java b/src/main/scala/me/skymc/taboolib/listener/ListenerPlayerCommand.java deleted file mode 100644 index 0b0f990..0000000 --- a/src/main/scala/me/skymc/taboolib/listener/ListenerPlayerCommand.java +++ /dev/null @@ -1,104 +0,0 @@ -package me.skymc.taboolib.listener; - -import com.ilummc.tlib.filter.TLoggerFilter; -import com.ilummc.tlib.logger.TLogger; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.commands.builder.SimpleCommandBuilder; -import me.skymc.taboolib.common.inject.TInject; -import me.skymc.taboolib.database.PlayerDataManager; -import me.skymc.taboolib.inventory.ItemUtils; -import me.skymc.taboolib.itemnbtapi.NBTItem; -import me.skymc.taboolib.json.tellraw.TellrawJson; -import me.skymc.taboolib.message.MsgUtils; -import me.skymc.taboolib.permission.PermissionUtils; -import me.skymc.taboolib.playerdata.DataUtils; -import org.bukkit.Bukkit; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.server.ServerCommandEvent; - -/** - * @author sky - */ -@TListener -public class ListenerPlayerCommand implements Listener { - - private static boolean nextException; - - public ListenerPlayerCommand() { - Bukkit.getScheduler().runTaskTimer(TabooLib.instance(), () -> { - if (nextException) { - nextException = false; - throw new IllegalStateException("TabooLib Example Exception"); - } - }, 0, 20); - } - - @TInject - static SimpleCommandBuilder tExceptionCommand = SimpleCommandBuilder.create("tExceptionCommand", TabooLib.instance()) - .execute((sender, args) -> { - throw new IllegalStateException("TabooLib Example Exception"); - }); - - @TInject - static SimpleCommandBuilder tExceptionSchedule = SimpleCommandBuilder.create("tExceptionSchedule", TabooLib.instance()) - .execute((sender, args) -> { - nextException = true; - return true; - }); - - @EventHandler - public void cmd(ServerCommandEvent e) { - if (e.getCommand().equalsIgnoreCase("saveFiles")) { - if (TabooLib.getVerint() > 10700) { - e.setCancelled(true); - } - Bukkit.getScheduler().runTask(Main.getInst(), () -> { - DataUtils.saveAllCaches(); - PlayerDataManager.saveAllCaches(true, false); - }); - TLogger.getGlobalLogger().info("Successfully."); - } else if (e.getCommand().equalsIgnoreCase("tDebug")) { - if (TabooLib.getVerint() > 10700) { - e.setCancelled(true); - } - if (TabooLib.isDebug()) { - TabooLib.setDebug(false); - TLogger.getGlobalLogger().info("&cDisabled."); - } else { - TabooLib.setDebug(true); - TLogger.getGlobalLogger().info("&aEnabled."); - } - } else if (e.getCommand().equalsIgnoreCase("tExceptionEvent")) { - e.setCancelled(true); - throw new IllegalStateException("TabooLib Example Exception"); - } - } - - @SuppressWarnings("deprecation") - @EventHandler - public void cmd(PlayerCommandPreprocessEvent e) { - // 注入异常拦截器 - TLoggerFilter.inject0(); - // 其他指令 - if (e.getMessage().equals("/unbreakable") && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.unbreakable")) { - e.setCancelled(true); - NBTItem nbt = new NBTItem(e.getPlayer().getItemInHand()); - nbt.setInteger("Unbreakable", 1); - e.getPlayer().setItemInHand(nbt.getItem()); - MsgUtils.send(e.getPlayer(), "Success!"); - } else if (e.getMessage().equals("/tellrawTest") && PermissionUtils.hasPermission(e.getPlayer(), "taboolib.tellraw")) { - e.setCancelled(true); - TellrawJson.create() - .append("§8[§3§lTabooLib§8] §7TellrawJson Test: §f[") - .append(ItemUtils.getCustomName(e.getPlayer().getItemInHand())).hoverItem(e.getPlayer().getItemInHand()) - .append("§f]") - .send(e.getPlayer()); - } else if (e.getMessage().equalsIgnoreCase("/tExceptionEvent")) { - e.setCancelled(true); - throw new IllegalStateException("TabooLib Example Exception"); - } - } -} diff --git a/src/main/scala/me/skymc/taboolib/listener/ListenerPlayerJoinAndQuit.java b/src/main/scala/me/skymc/taboolib/listener/ListenerPlayerJoinAndQuit.java deleted file mode 100644 index 58ecb1b..0000000 --- a/src/main/scala/me/skymc/taboolib/listener/ListenerPlayerJoinAndQuit.java +++ /dev/null @@ -1,27 +0,0 @@ -package me.skymc.taboolib.listener; - -import me.skymc.taboolib.Main; -import me.skymc.taboolib.playerdata.DataUtils; -import me.skymc.taboolib.translateuuid.TranslateUUID; -import org.bukkit.Bukkit; -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; - -@TListener -public class ListenerPlayerJoinAndQuit implements Listener { - - @EventHandler - public void onJoin(PlayerJoinEvent e) { - if (TranslateUUID.isEnabled()) { - Bukkit.getScheduler().runTaskAsynchronously(Main.getInst(), () -> TranslateUUID.updateUsername(e.getPlayer().getUniqueId(), e.getPlayer().getName())); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onQuit(PlayerQuitEvent e) { - DataUtils.saveOnline(e.getPlayer().getName()); - } -} diff --git a/src/main/scala/me/skymc/taboolib/listener/ListenerPlugin.java b/src/main/scala/me/skymc/taboolib/listener/ListenerPlugin.java deleted file mode 100644 index 61a017d..0000000 --- a/src/main/scala/me/skymc/taboolib/listener/ListenerPlugin.java +++ /dev/null @@ -1,106 +0,0 @@ -package me.skymc.taboolib.listener; - -import com.ilummc.tlib.TLib; -import com.ilummc.tlib.filter.TLoggerFilter; -import com.ilummc.tlib.inject.TConfigWatcher; -import com.ilummc.tlib.inject.TDependencyInjector; -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.common.configuration.TConfiguration; -import me.skymc.taboolib.events.TPluginEnableEvent; -import me.skymc.taboolib.events.TPluginLoadEvent; -import me.skymc.taboolib.mysql.MysqlUtils; -import me.skymc.taboolib.mysql.hikari.HikariHandler; -import me.skymc.taboolib.mysql.protect.MySQLConnection; -import me.skymc.taboolib.timecycle.TimeCycleManager; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.server.PluginDisableEvent; -import org.bukkit.scheduler.BukkitRunnable; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; - -/** - * @author sky - */ -@TListener -public class ListenerPlugin implements Listener { - - @EventHandler - public void load(TPluginLoadEvent e) { - if (TabooLib.isDependTabooLib(e.getPlugin())) { - TLoggerFilter.inject(new TLoggerFilter(), e.getPlugin().getLogger()); - } - } - - @EventHandler (priority = EventPriority.LOWEST) - public void enable(TPluginEnableEvent e) { - if (!TLib.getTLib().isInjectEnabled() || !TLib.getTLib().isBlackListPluginExists()) { - try { - TDependencyInjector.inject(e.getPlugin(), e.getPlugin()); - } catch (Exception err) { - err.printStackTrace(); - } - } - } - - @EventHandler - public void disable(PluginDisableEvent e) { - TabooLib.debug("Plugin \"" + e.getPlugin().getName() + "\" was disabled."); - // 注销插件注入 - if (!TLib.getTLib().isInjectEnabled() || !TLib.getTLib().isBlackListPluginExists()) { - TDependencyInjector.eject(e.getPlugin(), e.getPlugin()); - } - // 注销时间周期 - TimeCycleManager.cancel(e.getPlugin()); - // 注销插件配置 - Optional.ofNullable(TConfiguration.getFiles().get(e.getPlugin().getName())).ifPresent(files -> { - TConfigWatcher tConfigWatcher = TLib.getTLib().getConfigWatcher(); - for (File file : files) { - tConfigWatcher.removeListener(file); - TabooLib.debug("Remove TConfiguration \"" + file.getName() + "\" from Plugin \"" + e.getPlugin().getName() + "\""); - } - }); - // 注销数据库连接 - new HashSet<>(HikariHandler.getDataSource().keySet()).stream().filter(host -> e.getPlugin().equals(host.getPlugin()) && host.isAutoClose()).forEach(HikariHandler::closeDataSource); - // 获取连接 - List connection = new ArrayList<>(); - for (MySQLConnection conn : MysqlUtils.CONNECTIONS) { - if (conn.getPlugin().equals(e.getPlugin())) { - connection.add(conn); - MysqlUtils.CONNECTIONS.remove(conn); - } - } - // 异步注销 - BukkitRunnable runnable = new BukkitRunnable() { - - @Override - public void run() { - int i = 0; - for (MySQLConnection conn : connection) { - conn.setFallReconnection(false); - conn.closeConnection(); - i++; - } - if (i > 0) { - TLocale.Logger.info("MYSQL-CONNECTION.SUCCESS-CONNECTION-CANCEL", e.getPlugin().getName(), String.valueOf(i)); - } - } - }; - // 如果插件关闭 - try { - runnable.runTaskLater(Main.getInst(), 40); - } catch (Exception err) { - TLocale.Logger.error("MYSQL-CONNECTION.FAIL-EXECUTE-TASK"); - runnable.run(); - } - // 注销异常拦截 - TLoggerFilter.eject(e.getPlugin()); - } -} diff --git a/src/main/scala/me/skymc/taboolib/listener/TListenerCommand.java b/src/main/scala/me/skymc/taboolib/listener/TListenerCommand.java deleted file mode 100644 index 32317bc..0000000 --- a/src/main/scala/me/skymc/taboolib/listener/TListenerCommand.java +++ /dev/null @@ -1,9 +0,0 @@ -package me.skymc.taboolib.listener; - -/** - * @Author sky - * @Since 2018-08-25 10:16 - */ -public class TListenerCommand { - -} diff --git a/src/main/scala/me/skymc/taboolib/particle/EffLib.java b/src/main/scala/me/skymc/taboolib/particle/EffLib.java deleted file mode 100644 index 18e0cef..0000000 --- a/src/main/scala/me/skymc/taboolib/particle/EffLib.java +++ /dev/null @@ -1,1677 +0,0 @@ -package me.skymc.taboolib.particle; - -import me.skymc.taboolib.methods.ReflectionUtils; -import me.skymc.taboolib.methods.ReflectionUtils.PackageType; -import org.bukkit.*; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -/** - * ParticleEffect Library - *

- * This library was created by @DarkBlade12 and allows you to display all Minecraft particle effects on a Bukkit server - *

- * You are welcome to use it, modify it and redistribute it under the following conditions: - *

    - *
  • Don't claim this class as your own - *
  • Don't remove this disclaimer - *
- *

- * Special thanks: - *

    - *
  • @microgeek (original idea, names and packet parameters) - *
  • @ShadyPotato (1.8 names, ids and packet parameters) - *
  • @RingOfStorms (particle behavior) - *
  • @Cybermaxke (particle behavior) - *
  • @JamieSinn (hosting a jenkins server and documentation for particleeffect) - *
- *

- * It would be nice if you provide credit to me if you use this class in a published project - * - * @author DarkBlade12 - * @version 1.7 - */ -public enum EffLib { - - /** - * A particle effect which is displayed by exploding tnt and creepers: - *

    - *
  • It looks like a white cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - EXPLOSION_NORMAL("explode", 0, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by exploding ghast fireballs and wither skulls: - *
    - *
  • It looks like a gray ball which is fading away - *
  • The speed value slightly influences the size of this particle effect - *
- */ - EXPLOSION_LARGE("largeexplode", 1, -1), - /** - * A particle effect which is displayed by exploding tnt and creepers: - *
    - *
  • It looks like a crowd of gray balls which are fading away - *
  • The speed value has no influence on this particle effect - *
- */ - EXPLOSION_HUGE("hugeexplosion", 2, -1), - /** - * A particle effect which is displayed by launching fireworks: - *
    - *
  • It looks like a white star which is sparkling - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - FIREWORKS_SPARK("fireworksSpark", 3, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by swimming entities and arrows in water: - *
    - *
  • It looks like a bubble - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - WATER_BUBBLE("bubble", 4, -1, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_WATER), - /** - * A particle effect which is displayed by swimming entities and shaking wolves: - *
    - *
  • It looks like a blue drop - *
  • The speed value has no influence on this particle effect - *
- */ - WATER_SPLASH("splash", 5, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed on water when fishing: - *
    - *
  • It looks like a blue droplet - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - WATER_WAKE("wake", 6, 7, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by water: - *
    - *
  • It looks like a tiny blue square - *
  • The speed value has no influence on this particle effect - *
- */ - SUSPENDED("suspended", 7, -1, ParticleProperty.REQUIRES_WATER), - /** - * A particle effect which is displayed by air when close to bedrock and the in the void: - *
    - *
  • It looks like a tiny gray square - *
  • The speed value has no influence on this particle effect - *
- */ - SUSPENDED_DEPTH("depthSuspend", 8, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed when landing a critical hit and by arrows: - *
    - *
  • It looks like a light brown cross - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - CRIT("crit", 9, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed when landing a hit with an enchanted weapon: - *
    - *
  • It looks like a cyan star - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - CRIT_MAGIC("magicCrit", 10, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by primed tnt, torches, droppers, dispensers, end portals, brewing stands and monster spawners: - *
    - *
  • It looks like a little gray cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - SMOKE_NORMAL("smoke", 11, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by fire, minecarts with furnace and blazes: - *
    - *
  • It looks like a large gray cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - SMOKE_LARGE("largesmoke", 12, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed when splash potions or bottles o' enchanting hit something: - *
    - *
  • It looks like a white swirl - *
  • The speed value causes the particle to only move upwards when set to 0 - *
  • Only the motion on the y-axis can be controlled, the motion on the x- and z-axis are multiplied by 0.1 when setting the values to 0 - *
- */ - SPELL("spell", 13, -1), - /** - * A particle effect which is displayed when instant splash potions hit something: - *
    - *
  • It looks like a white cross - *
  • The speed value causes the particle to only move upwards when set to 0 - *
  • Only the motion on the y-axis can be controlled, the motion on the x- and z-axis are multiplied by 0.1 when setting the values to 0 - *
- */ - SPELL_INSTANT("instantSpell", 14, -1), - /** - * A particle effect which is displayed by entities with active potion effects: - *
    - *
  • It looks like a colored swirl - *
  • The speed value causes the particle to be colored black when set to 0 - *
  • The particle color gets lighter when increasing the speed and darker when decreasing the speed - *
- */ - SPELL_MOB("mobSpell", 15, -1, ParticleProperty.COLORABLE), - /** - * A particle effect which is displayed by entities with active potion effects applied through a beacon: - *
    - *
  • It looks like a transparent colored swirl - *
  • The speed value causes the particle to be always colored black when set to 0 - *
  • The particle color gets lighter when increasing the speed and darker when decreasing the speed - *
- */ - SPELL_MOB_AMBIENT("mobSpellAmbient", 16, -1, ParticleProperty.COLORABLE), - /** - * A particle effect which is displayed by witches: - *
    - *
  • It looks like a purple cross - *
  • The speed value causes the particle to only move upwards when set to 0 - *
  • Only the motion on the y-axis can be controlled, the motion on the x- and z-axis are multiplied by 0.1 when setting the values to 0 - *
- */ - SPELL_WITCH("witchMagic", 17, -1), - /** - * A particle effect which is displayed by blocks beneath a water source: - *
    - *
  • It looks like a blue drip - *
  • The speed value has no influence on this particle effect - *
- */ - DRIP_WATER("dripWater", 18, -1), - /** - * A particle effect which is displayed by blocks beneath a lava source: - *
    - *
  • It looks like an orange drip - *
  • The speed value has no influence on this particle effect - *
- */ - DRIP_LAVA("dripLava", 19, -1), - /** - * A particle effect which is displayed when attacking a villager in a village: - *
    - *
  • It looks like a cracked gray heart - *
  • The speed value has no influence on this particle effect - *
- */ - VILLAGER_ANGRY("angryVillager", 20, -1), - /** - * A particle effect which is displayed when using bone meal and trading with a villager in a village: - *
    - *
  • It looks like a green star - *
  • The speed value has no influence on this particle effect - *
- */ - VILLAGER_HAPPY("happyVillager", 21, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by mycelium: - *
    - *
  • It looks like a tiny gray square - *
  • The speed value has no influence on this particle effect - *
- */ - TOWN_AURA("townaura", 22, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by note blocks: - *
    - *
  • It looks like a colored note - *
  • The speed value causes the particle to be colored green when set to 0 - *
- */ - NOTE("note", 23, -1, ParticleProperty.COLORABLE), - /** - * A particle effect which is displayed by nether portals, endermen, ender pearls, eyes of ender, ender chests and dragon eggs: - *
    - *
  • It looks like a purple cloud - *
  • The speed value influences the spread of this particle effect - *
- */ - PORTAL("portal", 24, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by enchantment tables which are nearby bookshelves: - *
    - *
  • It looks like a cryptic white letter - *
  • The speed value influences the spread of this particle effect - *
- */ - ENCHANTMENT_TABLE("enchantmenttable", 25, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by torches, active furnaces, magma cubes and monster spawners: - *
    - *
  • It looks like a tiny flame - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - FLAME("flame", 26, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by lava: - *
    - *
  • It looks like a spark - *
  • The speed value has no influence on this particle effect - *
- */ - LAVA("lava", 27, -1), - /** - * A particle effect which is currently unused: - *
    - *
  • It looks like a transparent gray square - *
  • The speed value has no influence on this particle effect - *
- */ - FOOTSTEP("footstep", 28, -1), - /** - * A particle effect which is displayed when a mob dies: - *
    - *
  • It looks like a large white cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - CLOUD("cloud", 29, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by redstone ore, powered redstone, redstone torches and redstone repeaters: - *
    - *
  • It looks like a tiny colored cloud - *
  • The speed value causes the particle to be colored red when set to 0 - *
- */ - REDSTONE("reddust", 30, -1, ParticleProperty.COLORABLE), - /** - * A particle effect which is displayed when snowballs hit a block: - *
    - *
  • It looks like a little piece with the snowball texture - *
  • The speed value has no influence on this particle effect - *
- */ - SNOWBALL("snowballpoof", 31, -1), - /** - * A particle effect which is currently unused: - *
    - *
  • It looks like a tiny white cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - SNOW_SHOVEL("snowshovel", 32, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by slimes: - *
    - *
  • It looks like a tiny part of the slimeball icon - *
  • The speed value has no influence on this particle effect - *
- */ - SLIME("slime", 33, -1), - /** - * A particle effect which is displayed when breeding and taming animals: - *
    - *
  • It looks like a red heart - *
  • The speed value has no influence on this particle effect - *
- */ - HEART("heart", 34, -1), - /** - * A particle effect which is displayed by barriers: - *
    - *
  • It looks like a red box with a slash through it - *
  • The speed value has no influence on this particle effect - *
- */ - BARRIER("barrier", 35, 8), - /** - * A particle effect which is displayed when breaking a tool or eggs hit a block: - *
    - *
  • It looks like a little piece with an item texture - *
- */ - ITEM_CRACK("iconcrack", 36, -1, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_DATA), - /** - * A particle effect which is displayed when breaking blocks or sprinting: - *
    - *
  • It looks like a little piece with a block texture - *
  • The speed value has no influence on this particle effect - *
- */ - BLOCK_CRACK("blockcrack", 37, -1, ParticleProperty.REQUIRES_DATA), - /** - * A particle effect which is displayed when falling: - *
    - *
  • It looks like a little piece with a block texture - *
- */ - BLOCK_DUST("blockdust", 38, 7, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_DATA), - /** - * A particle effect which is displayed when rain hits the ground: - *
    - *
  • It looks like a blue droplet - *
  • The speed value has no influence on this particle effect - *
- */ - WATER_DROP("droplet", 39, 8), - /** - * A particle effect which is currently unused: - *
    - *
  • It has no visual effect - *
- */ - ITEM_TAKE("take", 40, 8), - /** - * A particle effect which is displayed by elder guardians: - *
    - *
  • It looks like the shape of the elder guardian - *
  • The speed value has no influence on this particle effect - *
  • The offset values have no influence on this particle effect - *
- */ - MOB_APPEARANCE("mobappearance", 41, 8), - - /** - * 龙息 - */ - DRAGON_BREATH("dragonbreath", 42, 9), - - /** - * 末地烛 - */ - END_ROD("endrod", 43, 9), - - /** - * 伤害 - */ - DAMAGE_INDICATOR("damageIndicator", 44, 9), - - /** - * 挥砍 - */ - SWEEP_ATTACK("sweepAttack", 45, 9), - - /** - * 掉落方块 - */ - FALLING_DUST("fallingdust", 46, 11, ParticleProperty.REQUIRES_DATA), - - /** - * 不死图腾 - */ - TOTEM("totem", 47, 11); - - private static final Map NAME_MAP = new HashMap<>(); - private static final Map ID_MAP = new HashMap<>(); - private final String name; - private final int id; - private final int requiredVersion; - private final List properties; - - // Initialize map for quick name and id lookup - static { - for (EffLib effect : values()) { - NAME_MAP.put(effect.name, effect); - ID_MAP.put(effect.id, effect); - } - } - - /** - * Construct a new particle effect - * - * @param name Name of this particle effect - * @param id Id of this particle effect - * @param requiredVersion Version which is required (1.x) - * @param properties Properties of this particle effect - */ - EffLib(String name, int id, int requiredVersion, ParticleProperty... properties) { - this.name = name; - this.id = id; - this.requiredVersion = requiredVersion; - this.properties = Arrays.asList(properties); - } - - /** - * Returns the name of this particle effect - * - * @return The name - */ - public String getName() { - return name; - } - - /** - * Returns the id of this particle effect - * - * @return The id - */ - public int getId() { - return id; - } - - /** - * Returns the required version for this particle effect (1.x) - * - * @return The required version - */ - public int getRequiredVersion() { - return requiredVersion; - } - - /** - * Determine if this particle effect has a specific property - * - * @return Whether it has the property or not - */ - public boolean hasProperty(ParticleProperty property) { - return properties.contains(property); - } - - /** - * Determine if this particle effect is supported by your current server version - * - * @return Whether the particle effect is supported or not - */ - public boolean isSupported() { - return requiredVersion == -1 || ParticlePacket.getVersion() >= requiredVersion; - } - - /** - * Returns the particle effect with the given name - * - * @param name Name of the particle effect - * @return The particle effect - */ - public static EffLib fromName(String name) { - for (Entry entry : NAME_MAP.entrySet()) { - if (!entry.getKey().equalsIgnoreCase(name)) { - continue; - } - return entry.getValue(); - } - return null; - } - - /** - * Returns the particle effect with the given id - * - * @param id Id of the particle effect - * @return The particle effect - */ - public static EffLib fromId(int id) { - for (Entry entry : ID_MAP.entrySet()) { - if (entry.getKey() != id) { - continue; - } - return entry.getValue(); - } - return null; - } - - /** - * Determine if water is at a certain location - * - * @param location Location to check - * @return Whether water is at this location or not - */ - private static boolean isWater(Location location) { - Material material = location.getBlock().getType(); - return material == Material.WATER || material == Material.STATIONARY_WATER; - } - - /** - * Determine if the distance between @param location and one of the players exceeds 256 - * - * @param location Location to check - * @return Whether the distance exceeds 256 or not - */ - private static boolean isLongDistance(Location location, List players) { - String world = location.getWorld().getName(); - for (Player player : players) { - Location playerLocation = player.getLocation(); - if (!world.equals(playerLocation.getWorld().getName()) || playerLocation.distanceSquared(location) < 65536) { - continue; - } - return true; - } - return false; - } - - /** - * Determine if the data type for a particle effect is correct - * - * @param effect Particle effect - * @param data Particle data - * @return Whether the data type is correct or not - */ - private static boolean isDataCorrect(EffLib effect, ParticleData data) { - return ((effect == BLOCK_CRACK || effect == BLOCK_DUST || effect == FALLING_DUST) && data instanceof BlockData) || ((effect == ITEM_CRACK) && data instanceof ItemData); - } - - /** - * Determine if the color type for a particle effect is correct - * - * @param effect Particle effect - * @param color Particle color - * @return Whether the color type is correct or not - */ - private static boolean isColorCorrect(EffLib effect, ParticleColor color) { - return ((effect == SPELL_MOB || effect == SPELL_MOB_AMBIENT || effect == REDSTONE) && color instanceof OrdinaryColor) || (effect == NOTE && color instanceof NoteColor); - } - - /** - * Displays a particle effect which is only visible for all players within a certain range in the world of @param center - * - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param center Center location of the effect - * @param range Range of the visibility - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect requires additional data - * @throws IllegalArgumentException If the particle effect requires water and none is at the center location - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect requires additional data"); - } - if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { - throw new IllegalArgumentException("There is no water at the center location"); - } - new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256, null).sendTo(center, range); - } - - /** - * Displays a particle effect which is only visible for the specified players - * - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect requires additional data - * @throws IllegalArgumentException If the particle effect requires water and none is at the center location - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect requires additional data"); - } - if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { - throw new IllegalArgumentException("There is no water at the center location"); - } - new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), null).sendTo(center, players); - } - - /** - * Displays a particle effect which is only visible for the specified players - * - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect requires additional data - * @throws IllegalArgumentException If the particle effect requires water and none is at the center location - * @see #display(float, float, float, float, int, Location, List) - */ - public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, Player... players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - display(offsetX, offsetY, offsetZ, speed, amount, center, Arrays.asList(players)); - } - - /** - * Displays a single particle which flies into a determined direction and is only visible for all players within a certain range in the world of @param center - * - * @param direction Direction of the particle - * @param speed Display speed of the particle - * @param center Center location of the effect - * @param range Range of the visibility - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect requires additional data - * @throws IllegalArgumentException If the particle effect is not directional or if it requires water and none is at the center location - * @see ParticlePacket#ParticlePacket(EffLib, Vector, float, boolean, ParticleData) - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect requires additional data"); - } - if (!hasProperty(ParticleProperty.DIRECTIONAL)) { - throw new IllegalArgumentException("This particle effect is not directional"); - } - if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { - throw new IllegalArgumentException("There is no water at the center location"); - } - new ParticlePacket(this, direction, speed, range > 256, null).sendTo(center, range); - } - - /** - * Displays a single particle which flies into a determined direction and is only visible for the specified players - * - * @param direction Direction of the particle - * @param speed Display speed of the particle - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect requires additional data - * @throws IllegalArgumentException If the particle effect is not directional or if it requires water and none is at the center location - * @see ParticlePacket#ParticlePacket(EffLib, Vector, float, boolean, ParticleData) - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect requires additional data"); - } - if (!hasProperty(ParticleProperty.DIRECTIONAL)) { - throw new IllegalArgumentException("This particle effect is not directional"); - } - if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { - throw new IllegalArgumentException("There is no water at the center location"); - } - new ParticlePacket(this, direction, speed, isLongDistance(center, players), null).sendTo(center, players); - } - - /** - * Displays a single particle which flies into a determined direction and is only visible for the specified players - * - * @param direction Direction of the particle - * @param speed Display speed of the particle - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect requires additional data - * @throws IllegalArgumentException If the particle effect is not directional or if it requires water and none is at the center location - * @see #display(Vector, float, Location, List) - */ - public void display(Vector direction, float speed, Location center, Player... players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - display(direction, speed, center, Arrays.asList(players)); - } - - /** - * Displays a single particle which is colored and only visible for all players within a certain range in the world of @param center - * - * @param color Color of the particle - * @param center Center location of the effect - * @param speed Display speed of the particle - * @param amount Amount of particles - * @param range Range of the visibility - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleColorException If the particle effect is not colorable or the color type is incorrect - * @see ParticlePacket#ParticlePacket(EffLib, ParticleColor, boolean) - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(ParticleColor color, Location center, float speed, int amount, double range) throws ParticleVersionException, ParticleColorException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (!hasProperty(ParticleProperty.COLORABLE)) { - throw new ParticleColorException("This particle effect is not colorable"); - } - if (!isColorCorrect(this, color)) { - throw new ParticleColorException("The particle color type is incorrect"); - } - new ParticlePacket(this, color, speed, amount, range > 256).sendTo(center, range); - } - - /** - * Displays a single particle which is colored and only visible for the specified players - * - * @param color Color of the particle - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleColorException If the particle effect is not colorable or the color type is incorrect - * @see ParticlePacket#ParticlePacket(EffLib, ParticleColor, boolean) - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(ParticleColor color, Location center, List players) throws ParticleVersionException, ParticleColorException { - display(color, center, 1, 0, players); - } - - /** - * Displays a single particle which is colored and only visible for the specified players - * - * @param color Color of the particle - * @param center Center location of the effect - * @param speed Display speed of the particle - * @param amount Amount of particles - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleColorException If the particle effect is not colorable or the color type is incorrect - * @see ParticlePacket#ParticlePacket(EffLib, ParticleColor, boolean) - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(ParticleColor color, Location center, float speed, int amount, List players) throws ParticleVersionException, ParticleColorException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (!hasProperty(ParticleProperty.COLORABLE)) { - throw new ParticleColorException("This particle effect is not colorable"); - } - if (!isColorCorrect(this, color)) { - throw new ParticleColorException("The particle color type is incorrect"); - } - new ParticlePacket(this, color, isLongDistance(center, players)).sendTo(center, players); - } - - /** - * Displays a single particle which is colored and only visible for the specified players - * - * @param color Color of the particle - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleColorException If the particle effect is not colorable or the color type is incorrect - * @see #display(ParticleColor, Location, List) - */ - public void display(ParticleColor color, Location center, Player... players) throws ParticleVersionException, ParticleColorException { - display(color, center, Arrays.asList(players)); - } - - /** - * Displays a single particle which is colored and only visible for the specified players - * - * @param color Color of the particle - * @param center Center location of the effect - * @param speed Display speed of the particle - * @param amount Amount of particles - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleColorException If the particle effect is not colorable or the color type is incorrect - * @see #display(ParticleColor, Location, List) - */ - public void display(ParticleColor color, Location center, float speed, int amount, Player... players) throws ParticleVersionException, ParticleColorException { - display(color, center, speed, amount, Arrays.asList(players)); - } - - /** - * Displays a particle effect which requires additional data and is only visible for all players within a certain range in the world of @param center - * - * @param data Data of the effect - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param center Center location of the effect - * @param range Range of the visibility - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect does not require additional data"); - } - if (!isDataCorrect(this, data)) { - throw new ParticleDataException("The particle data type is incorrect"); - } - new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256, data).sendTo(center, range); - } - - /** - * Displays a particle effect which requires additional data and is only visible for the specified players - * - * @param data Data of the effect - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect does not require additional data"); - } - if (!isDataCorrect(this, data)) { - throw new ParticleDataException("The particle data type is incorrect"); - } - new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), data).sendTo(center, players); - } - - /** - * Displays a particle effect which requires additional data and is only visible for the specified players - * - * @param data Data of the effect - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect - * @see #display(ParticleData, float, float, float, float, int, Location, List) - */ - public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, Player... players) throws ParticleVersionException, ParticleDataException { - display(data, offsetX, offsetY, offsetZ, speed, amount, center, Arrays.asList(players)); - } - - /** - * Displays a single particle which requires additional data that flies into a determined direction and is only visible for all players within a certain range in the world of @param center - * - * @param data Data of the effect - * @param direction Direction of the particle - * @param speed Display speed of the particles - * @param center Center location of the effect - * @param range Range of the visibility - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(ParticleData data, Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect does not require additional data"); - } - if (!isDataCorrect(this, data)) { - throw new ParticleDataException("The particle data type is incorrect"); - } - new ParticlePacket(this, direction, speed, range > 256, data).sendTo(center, range); - } - - /** - * Displays a single particle which requires additional data that flies into a determined direction and is only visible for the specified players - * - * @param data Data of the effect - * @param direction Direction of the particle - * @param speed Display speed of the particles - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(ParticleData data, Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect does not require additional data"); - } - if (!isDataCorrect(this, data)) { - throw new ParticleDataException("The particle data type is incorrect"); - } - new ParticlePacket(this, direction, speed, isLongDistance(center, players), data).sendTo(center, players); - } - - /** - * Displays a single particle which requires additional data that flies into a determined direction and is only visible for the specified players - * - * @param data Data of the effect - * @param direction Direction of the particle - * @param speed Display speed of the particles - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect - * @see #display(ParticleData, Vector, float, Location, List) - */ - public void display(ParticleData data, Vector direction, float speed, Location center, Player... players) throws ParticleVersionException, ParticleDataException { - display(data, direction, speed, center, Arrays.asList(players)); - } - - /** - * Represents the property of a particle effect - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - public enum ParticleProperty { - /** - * The particle effect requires water to be displayed - */ - REQUIRES_WATER, - /** - * The particle effect requires block or item data to be displayed - */ - REQUIRES_DATA, - /** - * The particle effect uses the offsets as direction values - */ - DIRECTIONAL, - /** - * The particle effect uses the offsets as color values - */ - COLORABLE - } - - /** - * Represents the particle data for effects like {@link EffLib#ITEM_CRACK}, {@link EffLib#BLOCK_CRACK} and {@link EffLib#BLOCK_DUST} - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - public static abstract class ParticleData { - private final Material material; - private final byte data; - private final int[] packetData; - - /** - * Construct a new particle data - * - * @param material Material of the item/block - * @param data Data value of the item/block - */ - @SuppressWarnings("deprecation") - public ParticleData(Material material, byte data) { - this.material = material; - this.data = data; - this.packetData = new int[] {material.getId(), data}; - } - - /** - * Returns the material of this data - * - * @return The material - */ - public Material getMaterial() { - return material; - } - - /** - * Returns the data value of this data - * - * @return The data value - */ - public byte getData() { - return data; - } - - /** - * Returns the data as an int array for packet construction - * - * @return The data for the packet - */ - public int[] getPacketData() { - return packetData; - } - - /** - * Returns the data as a string for pre 1.8 versions - * - * @return The data string for the packet - */ - public String getPacketDataString() { - return "_" + packetData[0] + "_" + packetData[1]; - } - } - - /** - * Represents the item data for the {@link EffLib#ITEM_CRACK} effect - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - public static final class ItemData extends ParticleData { - /** - * Construct a new item data - * - * @param material Material of the item - * @param data Data value of the item - * @see ParticleData#ParticleData(Material, byte) - */ - public ItemData(Material material, byte data) { - super(material, data); - } - } - - /** - * Represents the block data for the {@link EffLib#BLOCK_CRACK} and {@link EffLib#BLOCK_DUST} effects - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - public static final class BlockData extends ParticleData { - /** - * Construct a new block data - * - * @param material Material of the block - * @param data Data value of the block - * @throws IllegalArgumentException If the material is not a block - * @see ParticleData#ParticleData(Material, byte) - */ - public BlockData(Material material, byte data) throws IllegalArgumentException { - super(material, data); - if (!material.isBlock()) { - throw new IllegalArgumentException("The material is not a block"); - } - } - } - - /** - * Represents the color for effects like {@link EffLib#SPELL_MOB}, {@link EffLib#SPELL_MOB_AMBIENT}, {@link EffLib#REDSTONE} and {@link EffLib#NOTE} - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - public static abstract class ParticleColor { - /** - * Returns the value for the offsetX field - * - * @return The offsetX value - */ - public abstract float getValueX(); - - /** - * Returns the value for the offsetY field - * - * @return The offsetY value - */ - public abstract float getValueY(); - - /** - * Returns the value for the offsetZ field - * - * @return The offsetZ value - */ - public abstract float getValueZ(); - } - - /** - * Represents the color for effects like {@link EffLib#SPELL_MOB}, {@link EffLib#SPELL_MOB_AMBIENT} and {@link EffLib#NOTE} - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - public static final class OrdinaryColor extends ParticleColor { - private final int red; - private final int green; - private final int blue; - - /** - * Construct a new ordinary color - * - * @param red Red value of the RGB format - * @param green Green value of the RGB format - * @param blue Blue value of the RGB format - * @throws IllegalArgumentException If one of the values is lower than 0 or higher than 255 - */ - public OrdinaryColor(int red, int green, int blue) throws IllegalArgumentException { - if (red < 0) { - throw new IllegalArgumentException("The red value is lower than 0"); - } - if (red > 255) { - throw new IllegalArgumentException("The red value is higher than 255"); - } - this.red = red; - if (green < 0) { - throw new IllegalArgumentException("The green value is lower than 0"); - } - if (green > 255) { - throw new IllegalArgumentException("The green value is higher than 255"); - } - this.green = green; - if (blue < 0) { - throw new IllegalArgumentException("The blue value is lower than 0"); - } - if (blue > 255) { - throw new IllegalArgumentException("The blue value is higher than 255"); - } - this.blue = blue; - } - - /** - * Construct a new ordinary color - * - * @param color Bukkit color - */ - public OrdinaryColor(Color color) { - this(color.getRed(), color.getGreen(), color.getBlue()); - } - - /** - * Returns the red value of the RGB format - * - * @return The red value - */ - public int getRed() { - return red; - } - - /** - * Returns the green value of the RGB format - * - * @return The green value - */ - public int getGreen() { - return green; - } - - /** - * Returns the blue value of the RGB format - * - * @return The blue value - */ - public int getBlue() { - return blue; - } - - /** - * Returns the red value divided by 255 - * - * @return The offsetX value - */ - @Override - public float getValueX() { - return red / 255F; - } - - /** - * Returns the green value divided by 255 - * - * @return The offsetY value - */ - @Override - public float getValueY() { - return green / 255F; - } - - /** - * Returns the blue value divided by 255 - * - * @return The offsetZ value - */ - @Override - public float getValueZ() { - return blue / 255F; - } - } - - /** - * Represents the color for the {@link EffLib#NOTE} effect - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - public static final class NoteColor extends ParticleColor { - private final int note; - - /** - * Construct a new note color - * - * @param note Note id which determines color - * @throws IllegalArgumentException If the note value is lower than 0 or higher than 24 - */ - public NoteColor(int note) throws IllegalArgumentException { - if (note < 0) { - throw new IllegalArgumentException("The note value is lower than 0"); - } - if (note > 24) { - throw new IllegalArgumentException("The note value is higher than 24"); - } - this.note = note; - } - - /** - * Returns the note value divided by 24 - * - * @return The offsetX value - */ - @Override - public float getValueX() { - return note / 24F; - } - - /** - * Returns zero because the offsetY value is unused - * - * @return zero - */ - @Override - public float getValueY() { - return 0; - } - - /** - * Returns zero because the offsetZ value is unused - * - * @return zero - */ - @Override - public float getValueZ() { - return 0; - } - - } - - /** - * Represents a runtime exception that is thrown either if the displayed particle effect requires data and has none or vice-versa or if the data type is incorrect - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - private static final class ParticleDataException extends RuntimeException { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new particle data exception - * - * @param message Message that will be logged - */ - public ParticleDataException(String message) { - super(message); - } - } - - /** - * Represents a runtime exception that is thrown either if the displayed particle effect is not colorable or if the particle color type is incorrect - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - private static final class ParticleColorException extends RuntimeException { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new particle color exception - * - * @param message Message that will be logged - */ - public ParticleColorException(String message) { - super(message); - } - } - - /** - * Represents a runtime exception that is thrown if the displayed particle effect requires a newer version - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - private static final class ParticleVersionException extends RuntimeException { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new particle version exception - * - * @param message Message that will be logged - */ - public ParticleVersionException(String message) { - super(message); - } - } - - /** - * Represents a particle effect packet with all attributes which is used for sending packets to the players - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.5 - */ - public static final class ParticlePacket { - private static int version; - private static Class enumParticle; - private static Constructor packetConstructor; - private static Method getHandle; - private static Field playerConnection; - private static Method sendPacket; - private static boolean initialized; - private final EffLib effect; - private float offsetX; - private final float offsetY; - private final float offsetZ; - private final float speed; - private final int amount; - private final boolean longDistance; - private final ParticleData data; - private Object packet; - - /** - * Construct a new particle packet - * - * @param effect Particle effect - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 - * @param data Data of the effect - * @throws IllegalArgumentException If the speed or amount is lower than 0 - * @see #initialize() - */ - public ParticlePacket(EffLib effect, float offsetX, float offsetY, float offsetZ, float speed, int amount, boolean longDistance, ParticleData data) throws IllegalArgumentException { - initialize(); - if (speed < 0) { - throw new IllegalArgumentException("The speed is lower than 0"); - } - if (amount < 0) { - throw new IllegalArgumentException("The amount is lower than 0"); - } - this.effect = effect; - this.offsetX = offsetX; - this.offsetY = offsetY; - this.offsetZ = offsetZ; - this.speed = speed; - this.amount = amount; - this.longDistance = longDistance; - this.data = data; - } - - /** - * Construct a new particle packet of a single particle flying into a determined direction - * - * @param effect Particle effect - * @param direction Direction of the particle - * @param speed Display speed of the particle - * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 - * @param data Data of the effect - * @throws IllegalArgumentException If the speed is lower than 0 - */ - public ParticlePacket(EffLib effect, Vector direction, float speed, boolean longDistance, ParticleData data) throws IllegalArgumentException { - this(effect, (float) direction.getX(), (float) direction.getY(), (float) direction.getZ(), speed, 0, longDistance, data); - } - - /** - * Construct a new particle packet of a single colored particle - * - * @param effect Particle effect - * @param color Color of the particle - * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 - */ - public ParticlePacket(EffLib effect, ParticleColor color, boolean longDistance) { - this(effect, color, 1, 0, longDistance); - } - - /** - * Construct a new particle packet of a single colored particle - * - * @param effect Particle effect - * @param color Color of the particle - * @param speed Display speed of the particle - * @param amount Amount of particles - * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 - */ - public ParticlePacket(EffLib effect, ParticleColor color, float speed, int amount, boolean longDistance) { - this(effect, color.getValueX(), color.getValueY(), color.getValueZ(), speed, amount, longDistance, null); - if (effect == EffLib.REDSTONE && color instanceof OrdinaryColor && ((OrdinaryColor) color).getRed() == 0) { - offsetX = Float.MIN_NORMAL; - } - } - - /** - * Initializes {@link #packetConstructor}, {@link #getHandle}, {@link #playerConnection} and {@link #sendPacket} and sets {@link #initialized} to true if it succeeds - *

- * Note: These fields only have to be initialized once, so it will return if {@link #initialized} is already set to true - * - * @throws VersionIncompatibleException if your bukkit version is not supported by this library - */ - public static void initialize() throws VersionIncompatibleException { - if (initialized) { - return; - } - try { - version = Integer.valueOf(PackageType.getServerVersion().split("_")[1]); - if (version > 7) { - enumParticle = PackageType.MINECRAFT_SERVER.getClass("EnumParticle"); - } - Class packetClass = PackageType.MINECRAFT_SERVER.getClass(version < 7 ? "Packet63WorldParticles" : "PacketPlayOutWorldParticles"); - packetConstructor = ReflectionUtils.getConstructor(packetClass); - getHandle = ReflectionUtils.getMethod("CraftPlayer", PackageType.CRAFTBUKKIT_ENTITY, "getHandle"); - playerConnection = ReflectionUtils.getField("EntityPlayer", PackageType.MINECRAFT_SERVER, false, "playerConnection"); - sendPacket = ReflectionUtils.getMethod(playerConnection.getType(), "sendPacket", PackageType.MINECRAFT_SERVER.getClass("Packet")); - } catch (Exception exception) { - throw new VersionIncompatibleException("Your current bukkit version seems to be incompatible with this library", exception); - } - initialized = true; - } - - /** - * Returns the version of your server (1.x) - * - * @return The version number - */ - public static int getVersion() { - if (!initialized) { - initialize(); - } - return version; - } - - /** - * Determine if {@link #packetConstructor}, {@link #getHandle}, {@link #playerConnection} and {@link #sendPacket} are initialized - * - * @return Whether these fields are initialized or not - * @see #initialize() - */ - public static boolean isInitialized() { - return initialized; - } - - /** - * Initializes {@link #packet} with all set values - * - * @param center Center location of the effect - * @throws PacketInstantiationException If instantion fails due to an unknown error - */ - private void initializePacket(Location center) throws PacketInstantiationException { - if (packet != null) { - return; - } - try { - packet = packetConstructor.newInstance(); - if (version < 8) { - String name = effect.getName(); - if (data != null) { - name += data.getPacketDataString(); - } - ReflectionUtils.setValue(packet, true, "a", name); - } else { - ReflectionUtils.setValue(packet, true, "a", enumParticle.getEnumConstants()[effect.getId()]); - ReflectionUtils.setValue(packet, true, "j", longDistance); - if (data != null) { - int[] packetData = data.getPacketData(); - ReflectionUtils.setValue(packet, true, "k", effect == EffLib.ITEM_CRACK ? packetData : new int[] {packetData[0] | (packetData[1] << 12)}); - } - } - ReflectionUtils.setValue(packet, true, "b", (float) center.getX()); - ReflectionUtils.setValue(packet, true, "c", (float) center.getY()); - ReflectionUtils.setValue(packet, true, "d", (float) center.getZ()); - ReflectionUtils.setValue(packet, true, "e", offsetX); - ReflectionUtils.setValue(packet, true, "f", offsetY); - ReflectionUtils.setValue(packet, true, "g", offsetZ); - ReflectionUtils.setValue(packet, true, "h", speed); - ReflectionUtils.setValue(packet, true, "i", amount); - } catch (Exception exception) { - throw new PacketInstantiationException("Packet instantiation failed", exception); - } - } - - /** - * Sends the packet to a single player and caches it - * - * @param center Center location of the effect - * @param player Receiver of the packet - * @throws PacketInstantiationException If instantion fails due to an unknown error - * @throws PacketSendingException If sending fails due to an unknown error - * @see #initializePacket(Location) - */ - public void sendTo(Location center, Player player) throws PacketInstantiationException, PacketSendingException { - initializePacket(center); - try { - sendPacket.invoke(playerConnection.get(getHandle.invoke(player)), packet); - } catch (Exception exception) { - throw new PacketSendingException("Failed to send the packet to player '" + player.getName() + "'", exception); - } - } - - /** - * Sends the packet to all players in the list - * - * @param center Center location of the effect - * @param players Receivers of the packet - * @throws IllegalArgumentException If the player list is empty - * @see #sendTo(Location center, Player player) - */ - public void sendTo(Location center, List players) throws IllegalArgumentException { - if (players.isEmpty()) { - throw new IllegalArgumentException("The player list is empty"); - } - for (Player player : players) { - sendTo(center, player); - } - } - - /** - * Sends the packet to all players in a certain range - * - * @param center Center location of the effect - * @param range Range in which players will receive the packet (Maximum range for particles is usually 16, but it can differ for some types) - * @throws IllegalArgumentException If the range is lower than 1 - * @see #sendTo(Location center, Player player) - */ - public void sendTo(Location center, double range) throws IllegalArgumentException { - if (range < 1) { - throw new IllegalArgumentException("The range is lower than 1"); - } - String worldName = center.getWorld().getName(); - double squared = range * range; - for (Player player : Bukkit.getOnlinePlayers()) { - if (!player.getWorld().getName().equals(worldName) || player.getLocation().distanceSquared(center) > squared) { - continue; - } - sendTo(center, player); - } - } - - /** - * Represents a runtime exception that is thrown if a bukkit version is not compatible with this library - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.5 - */ - private static final class VersionIncompatibleException extends RuntimeException { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new version incompatible exception - * - * @param message Message that will be logged - * @param cause Cause of the exception - */ - public VersionIncompatibleException(String message, Throwable cause) { - super(message, cause); - } - } - - /** - * Represents a runtime exception that is thrown if packet instantiation fails - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.4 - */ - private static final class PacketInstantiationException extends RuntimeException { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new packet instantiation exception - * - * @param message Message that will be logged - * @param cause Cause of the exception - */ - public PacketInstantiationException(String message, Throwable cause) { - super(message, cause); - } - } - - /** - * Represents a runtime exception that is thrown if packet sending fails - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.4 - */ - private static final class PacketSendingException extends RuntimeException { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new packet sending exception - * - * @param message Message that will be logged - * @param cause Cause of the exception - */ - public PacketSendingException(String message, Throwable cause) { - super(message, cause); - } - } - } -} \ No newline at end of file diff --git a/src/main/scala/me/skymc/taboolib/particle/pack/ParticleData.java b/src/main/scala/me/skymc/taboolib/particle/pack/ParticleData.java deleted file mode 100644 index 2d16501..0000000 --- a/src/main/scala/me/skymc/taboolib/particle/pack/ParticleData.java +++ /dev/null @@ -1,77 +0,0 @@ -package me.skymc.taboolib.particle.pack; - -import com.ilummc.tlib.util.Strings; -import me.skymc.taboolib.inventory.ItemUtils; -import me.skymc.taboolib.particle.EffLib; -import org.bukkit.Location; -import org.bukkit.util.NumberConversions; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * @Author 坏黑 - * @Since 2019-01-11 17:37 - */ -public class ParticleData { - - private static final Pattern ITEM_PATTERN = Pattern.compile("(\\S+)\\((\\S+):(\\S+)\\)", Pattern.CASE_INSENSITIVE); - - private ParticleType particleType = ParticleType.NORMAL; - private EffLib particle = EffLib.BARRIER; - private EffLib.ParticleData particleData; - private float x = 0; - private float y = 0; - private float z = 0; - private float speed = 0; - private int amount = 0; - - /** - * NORMAL: - * frame-0.1-0.1-0.1-0-10 - * ITEM_CRACK: - * iconcrack(Stone:0)-0.1-0.1-0.1-0-10 - */ - public ParticleData(String str) { - if (!Strings.isEmpty(str)) { - try { - String[] split = str.split("-"); - Matcher matcher = ITEM_PATTERN.matcher(split[0]); - if (matcher.find()) { - particle = EffLib.fromName(matcher.group(1)); - particleType = ParticleType.ITEM; - particleData = isBlockParticle(particle.getName()) ? new EffLib.BlockData(ItemUtils.asMaterial(matcher.group(2).toUpperCase()), NumberConversions.toByte(matcher.group(3))) : new EffLib.ItemData(ItemUtils.asMaterial(matcher.group(2).toUpperCase()), NumberConversions.toByte(matcher.group(3))); - } else { - particle = EffLib.fromName(split[0]); - } - x = NumberConversions.toFloat(split[1]); - y = NumberConversions.toFloat(split[2]); - z = NumberConversions.toFloat(split[3]); - speed = NumberConversions.toFloat(split[4]); - amount = NumberConversions.toInt(split[5]); - } catch (Throwable t) { - t.printStackTrace(); - } - } - } - - public void play(Location location) { - try { - switch (particleType) { - case NORMAL: - particle.display(x, y, z, speed, amount, location, 50); - break; - case ITEM: - particle.display(particleData, x, y, z, speed, amount, location, 50); - break; - default: - } - } catch (Throwable t) { - t.printStackTrace(); - } - } - - private boolean isBlockParticle(String name) { - return name.equalsIgnoreCase("blockdust") || name.equalsIgnoreCase("blockcrack") || name.equalsIgnoreCase("fallingdust"); - } -} diff --git a/src/main/scala/me/skymc/taboolib/particle/pack/ParticlePack.java b/src/main/scala/me/skymc/taboolib/particle/pack/ParticlePack.java deleted file mode 100644 index 6f1212c..0000000 --- a/src/main/scala/me/skymc/taboolib/particle/pack/ParticlePack.java +++ /dev/null @@ -1,40 +0,0 @@ -package me.skymc.taboolib.particle.pack; - -import com.google.common.collect.Lists; -import me.skymc.taboolib.TabooLib; -import org.bukkit.Bukkit; -import org.bukkit.Location; - -import java.util.Arrays; -import java.util.List; - -/** - * @Author 坏黑 - * @Since 2019-01-11 17:35 - */ -public class ParticlePack { - - private List particles = Lists.newArrayList(); - - public ParticlePack(String str) { - Arrays.stream(str.split(";")).forEach(this::add); - } - - public void add(String str) { - particles.add(new ParticleData(str)); - } - - public void play(Location location) { - Bukkit.getScheduler().runTaskAsynchronously(TabooLib.instance(), () -> particles.forEach(p -> p.play(location))); - } - - // ********************************* - // - // Getter and Setter - // - // ********************************* - - public List getParticles() { - return particles; - } -} diff --git a/src/main/scala/me/skymc/taboolib/particle/pack/ParticleType.java b/src/main/scala/me/skymc/taboolib/particle/pack/ParticleType.java deleted file mode 100644 index f98f2cf..0000000 --- a/src/main/scala/me/skymc/taboolib/particle/pack/ParticleType.java +++ /dev/null @@ -1,11 +0,0 @@ -package me.skymc.taboolib.particle.pack; - -/** - * @Author 坏黑 - * @Since 2019-01-11 17:45 - */ -public enum ParticleType { - - NORMAL, ITEM - -} diff --git a/src/main/scala/me/skymc/taboolib/playerdata/DataUtils.java b/src/main/scala/me/skymc/taboolib/playerdata/DataUtils.java deleted file mode 100644 index a80089a..0000000 --- a/src/main/scala/me/skymc/taboolib/playerdata/DataUtils.java +++ /dev/null @@ -1,148 +0,0 @@ -package me.skymc.taboolib.playerdata; - -import com.ilummc.tlib.resources.TLocale; -import me.skymc.taboolib.Main; -import me.skymc.taboolib.database.PlayerDataManager; -import me.skymc.taboolib.exception.PlayerOfflineException; -import me.skymc.taboolib.fileutils.FileUtils; -import me.skymc.taboolib.listener.TListener; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.server.PluginDisableEvent; -import org.bukkit.plugin.Plugin; - -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.concurrent.ConcurrentHashMap; - -@TListener -public class DataUtils implements Listener { - - public static final ConcurrentHashMap> CACHE_DATA_PLUGIN = new ConcurrentHashMap<>(); - - public static void saveAllCaches(Plugin plugin) { - saveAllCaches(plugin, false); - } - - public static void saveAllCaches(Plugin plugin, boolean remove) { - if (plugin == null || !CACHE_DATA_PLUGIN.containsKey(plugin.getName())) { - return; - } - for (String fileName : CACHE_DATA_PLUGIN.get(plugin.getName()).keySet()) { - saveConfiguration(CACHE_DATA_PLUGIN.get(plugin.getName()).get(fileName), FileUtils.file(getDataSaveFolder(plugin), fileName)); - } - if (remove) { - CACHE_DATA_PLUGIN.remove(plugin.getName()); - } - } - - public static void saveAllCaches() { - saveAllCaches(false); - } - - public static void saveAllCaches(boolean remove) { - CACHE_DATA_PLUGIN.keySet().forEach(plugin -> saveAllCaches(getFixedPlugin(plugin), remove)); - } - - public static void saveConfiguration(FileConfiguration conf, File file) { - try { - conf.save(file); - } catch (IOException e) { - TLocale.Logger.error("DATA-UTILS.FAIL-SAVE-FILE", file.getName(), e.toString()); - } - } - - public static String getFixedFileName(String name) { - return name.contains(".") ? name : name + ".yml"; - } - - public static Plugin getFixedPlugin(String pluginName) { - return Bukkit.getPluginManager().getPlugin(pluginName) == null ? Main.getInst() : Bukkit.getPluginManager().getPlugin(pluginName); - } - - public static File getDataSaveFolder(Plugin plugin) { - return plugin == null || plugin.equals(Main.getInst()) ? Main.getServerDataFolder() : plugin.getDataFolder(); - } - - public static String getDataSaveKey(Plugin plugin) { - return plugin == null || plugin.equals(Main.getInst()) ? Main.getInst().getName() : plugin.getName(); - } - - public static FileConfiguration addPluginData(String name, Plugin plugin) { - return setPluginData(getFixedFileName(name), plugin, YamlConfiguration.loadConfiguration(FileUtils.file(getDataSaveFolder(plugin), getFixedFileName(name)))); - } - - public static FileConfiguration getPluginData(String name, Plugin plugin) { - return !CACHE_DATA_PLUGIN.containsKey(getDataSaveKey(plugin)) ? new YamlConfiguration() : CACHE_DATA_PLUGIN.get(getDataSaveKey(plugin)).get(getFixedFileName(name)); - } - - public static FileConfiguration setPluginData(String name, Plugin plugin, FileConfiguration conf) { - if (!CACHE_DATA_PLUGIN.containsKey(getDataSaveKey(plugin))) { - CACHE_DATA_PLUGIN.put(getDataSaveKey(plugin), new HashMap<>()); - } - CACHE_DATA_PLUGIN.get(getDataSaveKey(plugin)).put(getFixedFileName(name), conf); - return conf; - } - - @Deprecated - public static FileConfiguration getPlayerData(String name) { - try { - return PlayerDataManager.getPlayerData(name, true); - } catch (PlayerOfflineException e) { - return new YamlConfiguration(); - } - } - - @Deprecated - public static FileConfiguration addPlayerData(String name) { - return PlayerDataManager.loadPlayerData(name); - } - - @Deprecated - public static void savePlayerData(String name, boolean remove) { - PlayerDataManager.savePlayerData(name, remove); - } - - @Deprecated - public static FileConfiguration registerServerData(String name) { - return addPluginData(name, null); - } - - @Deprecated - public static FileConfiguration getPlayerData(OfflinePlayer p) { - return getPlayerData(p.getName()); - } - - @Deprecated - public static void setPlayerData(OfflinePlayer p, String s, Object o) { - getPlayerData(p.getName()).set(s, o); - } - - @Deprecated - public static void saveData(OfflinePlayer p) { - saveOnline(p.getName()); - } - - public static Long getOnline(OfflinePlayer p) { - return getPlayerData(p).getLong("TabooLib.Offline"); - } - - public static void saveOnline(String p) { - getPlayerData(p).set("TabooLib.Offline", System.currentTimeMillis()); - } - - @EventHandler - public void disable(PluginDisableEvent e) { - if (e.getPlugin().equals(Main.getInst())) { - return; - } - if (CACHE_DATA_PLUGIN.containsKey(e.getPlugin().getName())) { - saveAllCaches(e.getPlugin(), true); - } - } -} diff --git a/src/main/scala/me/skymc/taboolib/scoreboard/SimpleScoreboard.java b/src/main/scala/me/skymc/taboolib/scoreboard/SimpleScoreboard.java deleted file mode 100644 index 45344f5..0000000 --- a/src/main/scala/me/skymc/taboolib/scoreboard/SimpleScoreboard.java +++ /dev/null @@ -1,216 +0,0 @@ -package me.skymc.taboolib.scoreboard; - -import com.google.common.base.Charsets; -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; -import org.bukkit.scoreboard.*; - -import java.lang.reflect.Constructor; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - -public class SimpleScoreboard { - - private static Map cache = new HashMap<>(); - - private Scoreboard scoreboard; - private String title; - private Map scores; - private Objective obj; - private List teams; - private List removed; - private Set updated; - - public SimpleScoreboard(String title) { - this.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); - this.title = ChatColor.translateAlternateColorCodes('&', title); - this.scores = new ConcurrentHashMap<>(); - this.teams = Collections.synchronizedList(Lists.newArrayList()); - this.removed = Lists.newArrayList(); - this.updated = Collections.synchronizedSet(new HashSet<>()); - } - - public void add(String text, Integer score) { - text = ChatColor.translateAlternateColorCodes('&', text); - if (remove(score, text, false) || !scores.containsValue(score)) { - updated.add(text); - } - scores.put(text, score); - } - - public boolean remove(Integer score, String text) { - return remove(score, text, true); - } - - public boolean remove(Integer score, String n, boolean b) { - String toRemove = get(score, n); - if (toRemove == null) { - return false; - } - scores.remove(toRemove); - if (b) { - removed.add(score); - } - return true; - } - - public String get(int score, String n) { - String str = null; - for (Map.Entry entry : scores.entrySet()) { - if (entry.getValue().equals(score) && !entry.getKey().equals(n)) { - str = entry.getKey(); - } - } - return str; - } - - private Map.Entry createTeam(String text, int pos) { - Team team; - ChatColor color = ChatColor.values()[pos]; - OfflinePlayer result; - if (!cache.containsKey(color.toString())) { - cache.put(color.toString(), getOfflinePlayerSkipLookup(color.toString())); - } - result = cache.get(color.toString()); - try { - team = scoreboard.registerNewTeam("text-" + (teams.size() + 1)); - } catch (IllegalArgumentException e) { - team = scoreboard.getTeam("text-" + (teams.size())); - } - applyText(team, text, result); - - teams.add(team); - return new AbstractMap.SimpleEntry<>(team, result); - } - - private void applyText(Team team, String text, OfflinePlayer result) { - Iterator iterator = Splitter.fixedLength(16).split(text).iterator(); - String prefix = iterator.next(); - team.setPrefix(prefix); - if (!team.hasPlayer(result)) { - team.addPlayer(result); - } - if (text.length() > 16) { - String prefixColor = ChatColor.getLastColors(prefix); - String suffix = iterator.next(); - if (prefix.endsWith(String.valueOf(ChatColor.COLOR_CHAR))) { - prefix = prefix.substring(0, prefix.length() - 1); - team.setPrefix(prefix); - prefixColor = ChatColor.getByChar(suffix.charAt(0)).toString(); - suffix = suffix.substring(1); - } - if (prefixColor == null) { - prefixColor = ""; - } - if (suffix.length() > 16) { - // cut off suffix, done if text is over 30 characters - suffix = suffix.substring(0, (13 - prefixColor.length())); - } - team.setSuffix((prefixColor.equals("") ? ChatColor.RESET : prefixColor) + suffix); - } - } - - public void update() { - if (updated.isEmpty()) { - return; - } - if (obj == null) { - obj = scoreboard.registerNewObjective((title.length() > 16 ? title.substring(0, 15) : title), "dummy"); - obj.setDisplayName(title); - obj.setDisplaySlot(DisplaySlot.SIDEBAR); - } - removed.forEach((remove) -> { - for (String s : scoreboard.getEntries()) { - Score score = obj.getScore(s); - if (score == null) { - continue; - } - if (score.getScore() != remove) { - continue; - } - scoreboard.resetScores(s); - } - }); - removed.clear(); - int index = scores.size(); - for (Map.Entry text : scores.entrySet()) { - Team t = scoreboard.getTeam(ChatColor.values()[text.getValue()].toString()); - Map.Entry team; - if (!updated.contains(text.getKey())) { - continue; - } - if (t != null) { - String color = ChatColor.values()[text.getValue()].toString(); - if (!cache.containsKey(color)) { - cache.put(color, getOfflinePlayerSkipLookup(color)); - } - team = new AbstractMap.SimpleEntry<>(t, cache.get(color)); - applyText(team.getKey(), text.getKey(), team.getValue()); - index -= 1; - continue; - } else { - team = createTeam(text.getKey(), text.getValue()); - } - Integer score = text.getValue() != null ? text.getValue() : index; - obj.getScore(team.getValue()).setScore(score); - index -= 1; - } - updated.clear(); - } - - public void setTitle(String title) { - this.title = ChatColor.translateAlternateColorCodes('&', title); - if (obj != null) { - obj.setDisplayName(this.title); - } - } - - public void reset() { - teams.forEach(Team::unregister); - teams.clear(); - scores.clear(); - } - - public Scoreboard getScoreboard() { - return scoreboard; - } - - public void send(Player... players) { - Arrays.stream(players).forEach(p -> p.setScoreboard(scoreboard)); - } - - private final UUID invalidUserUUID = UUID.nameUUIDFromBytes("InvalidUsername".getBytes(Charsets.UTF_8)); - private Class gameProfileClass; - private Constructor gameProfileConstructor; - private Constructor craftOfflinePlayerConstructor; - - @SuppressWarnings("deprecation") - private OfflinePlayer getOfflinePlayerSkipLookup(String name) { - try { - if (gameProfileConstructor == null) { - try { // 1.7 - gameProfileClass = Class.forName("net.minecraft.util.com.mojang.authlib.GameProfile"); - } catch (ClassNotFoundException e) { // 1.8 - gameProfileClass = Class.forName("com.mojang.authlib.GameProfile"); - } - gameProfileConstructor = gameProfileClass.getDeclaredConstructor(UUID.class, String.class); - gameProfileConstructor.setAccessible(true); - } - if (craftOfflinePlayerConstructor == null) { - Class serverClass = Bukkit.getServer().getClass(); - Class craftOfflinePlayerClass = Class.forName(serverClass.getName().replace("CraftServer", "CraftOfflinePlayer")); - craftOfflinePlayerConstructor = craftOfflinePlayerClass.getDeclaredConstructor(serverClass, gameProfileClass); - craftOfflinePlayerConstructor.setAccessible(true); - } - Object gameProfile = gameProfileConstructor.newInstance(invalidUserUUID, name); - Object craftOfflinePlayer = craftOfflinePlayerConstructor.newInstance(Bukkit.getServer(), gameProfile); - return (OfflinePlayer) craftOfflinePlayer; - } catch (Throwable t) { - return Bukkit.getOfflinePlayer(name); - } - } -} diff --git a/src/main/scala/me/skymc/taboolib/sound/SoundPack.java b/src/main/scala/me/skymc/taboolib/sound/SoundPack.java deleted file mode 100644 index 255914c..0000000 --- a/src/main/scala/me/skymc/taboolib/sound/SoundPack.java +++ /dev/null @@ -1,94 +0,0 @@ -package me.skymc.taboolib.sound; - -import me.skymc.taboolib.TabooLib; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Sound; -import org.bukkit.entity.Player; - -public class SoundPack { - - private Sound sound; - private Float a; - private Float b; - private int delay; - - /** - * ENTITY_VILLAGER_NO-0-0 - */ - public SoundPack() { - this.sound = Sound.valueOf(SoundUtils.getModifiedSound("ENTITY_VILLAGER_NO")); - this.a = 1.0F; - this.b = 1.0F; - } - - public SoundPack(Sound sound, float a, float b) { - this(sound, a, b, 0); - } - - public SoundPack(Sound sound, float a, float b, int delay) { - this.sound = sound; - this.a = a; - this.b = b; - this.delay = delay; - } - - public SoundPack(String s) { - parse(s); - } - - public void play(Player p) { - Bukkit.getScheduler().runTaskLater(TabooLib.instance(), () -> p.playSound(p.getLocation(), this.sound, this.a, this.b), delay); - } - - public void play(Location l) { - Bukkit.getScheduler().runTaskLater(TabooLib.instance(), () -> l.getWorld().playSound(l, this.sound, this.a, this.b), delay); - } - - public void parse(String s) { - try { - String[] split = s.split("-"); - this.sound = Sound.valueOf(SoundUtils.getModifiedSound(split[0])); - this.a = Float.parseFloat(split[1]); - this.b = Float.parseFloat(split[2]); - this.delay = split.length > 3 ? Integer.parseInt(split[3]) : 0; - } catch (Exception var3) { - this.sound = Sound.valueOf(SoundUtils.getModifiedSound("ENTITY_VILLAGER_NO")); - this.a = 1.0F; - this.b = 1.0F; - this.delay = 0; - } - } - - // ********************************* - // - // Getter and Setter - // - // ********************************* - - public Sound getSound() { - return sound; - } - - public Float getA() { - return a; - } - - public Float getB() { - return b; - } - - public int getDelay() { - return delay; - } - - @Override - public String toString() { - return "SoundPack{" + - "sound=" + sound + - ", a=" + a + - ", b=" + b + - ", delay=" + delay + - '}'; - } -} diff --git a/src/main/scala/me/skymc/taboolib/sound/SoundUtils.java b/src/main/scala/me/skymc/taboolib/sound/SoundUtils.java deleted file mode 100644 index 2c51e12..0000000 --- a/src/main/scala/me/skymc/taboolib/sound/SoundUtils.java +++ /dev/null @@ -1,43 +0,0 @@ -package me.skymc.taboolib.sound; - -import me.skymc.taboolib.TabooLib; -import me.skymc.taboolib.message.MsgUtils; -import org.bukkit.Location; -import org.bukkit.Sound; - -public class SoundUtils { - - public static void sound(Location paramLocation, String paramString, float paramFloat1, float paramFloat2) { - String str = getModifiedSound(paramString); - try { - paramLocation.getWorld().playSound(paramLocation, Sound.valueOf(str), paramFloat1, paramFloat2); - } catch (Exception localException) { - MsgUtils.send("§4Bug with " + paramString + ". No such sound found. Please report it to the plugin creator :)"); - } - } - - public static String getModifiedSound(String str) { - if (TabooLib.getVerint() < 10900) { - str = str.replace("BLOCK_FIRE_EXTINGUISH", "FIZZ"); - str = str.replace("BLOCK_NOTE_HAT", "NOTE_STICKS"); - str = str.replace("ENTITY_SHEEP_DEATH", "SHEEP_IDLE"); - str = str.replace("ENTITY_LLAMA_ANGRY", "HORSE_HIT"); - str = str.replace("BLOCK_BREWING_STAND_BREW", "CREEPER_HISS"); - str = str.replace("ENTITY_SHULKER_TELEPORT", "ENDERMAN_TELEPORT"); - str = str.replace("ENTITY_ZOMBIE_ATTACK_IRON_DOOR", "ZOMBIE_METAL"); - str = str.replace("BLOCK_GRAVEL_BREAK", "DIG_GRAVEL"); - str = str.replace("BLOCK_SNOW_BREAK", "DIG_SNOW"); - str = str.replace("BLOCK_GRAVEL_BREAK", "DIG_GRAVEL"); - str = str.replace("ENTITY_PLAYER_LEVELUP", "LEVEL_UP"); - str = str.replace("ENTITY_SNOWBALL_THROW", "SHOOT_ARROW"); - str = str.replace("PLAYER_ATTACK_CRIT", "ITEM_BREAK"); - str = str.replace("ENDERMEN", "ENDERMAN"); - str = str.replace("ARROW_SHOOT", "SHOOT_ARROW"); - str = str.replace("ENDERMAN_HURT", "ENDERMAN_HIT"); - str = str.replace("BLAZE_HURT", "BLAZE_HIT"); - str = str.replace("_FLAP", "_WINGS"); - str = str.replaceAll("ENTITY_|GENERIC_|BLOCK_|_AMBIENT|_BREAK|UI_BUTTON_|EXPERIENCE_", ""); - } - return str; - } -}