From ce110a5dd6806b3fdb7b540ffa528d9e1f78e484 Mon Sep 17 00:00:00 2001 From: 502647092 Date: Tue, 25 Oct 2016 15:03:21 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E4=BD=BF=E7=94=A8=E6=96=B0?= =?UTF-8?q?=E7=B1=BB=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 502647092 --- pom.xml | 13 +- src/main/java/pw/yumc/Yum/Yum.java | 13 +- src/main/java/pw/yumc/Yum/api/YumAPI.java | 93 +++--- .../pw/yumc/Yum/commands/FileCommand.java | 120 +++---- .../pw/yumc/Yum/commands/MonitorCommand.java | 204 +++++------ .../java/pw/yumc/Yum/commands/NetCommand.java | 34 +- .../yumc/Yum/commands/PluginTabComplete.java | 28 +- .../java/pw/yumc/Yum/commands/YumCommand.java | 316 +++++++++--------- .../yumc/Yum/events/PluginNetworkEvent.java | 12 +- .../java/pw/yumc/Yum/ext/BukkitUpdater.java | 130 +++---- .../java/pw/yumc/Yum/ext/SpigotUpdater.java | 33 +- src/main/java/pw/yumc/Yum/ext/Updater.java | 30 +- .../pw/yumc/Yum/inject/CommandInjector.java | 105 +++--- .../pw/yumc/Yum/inject/ListenerInjector.java | 79 ++--- .../java/pw/yumc/Yum/inject/TaskInjector.java | 64 ++-- .../pw/yumc/Yum/listeners/PluginListener.java | 6 +- .../Yum/listeners/PluginNetworkListener.java | 24 +- .../yumc/Yum/listeners/SecurityListener.java | 16 +- .../Yum/listeners/ThreadSafetyListener.java | 35 +- .../pw/yumc/Yum/managers/ConfigManager.java | 20 +- .../pw/yumc/Yum/managers/DataManager.java | 16 +- .../pw/yumc/Yum/managers/DownloadManager.java | 70 ++-- .../pw/yumc/Yum/managers/MonitorManager.java | 108 +++--- .../pw/yumc/Yum/managers/NetworkManager.java | 18 +- .../pw/yumc/Yum/managers/PluginsManager.java | 214 ++++++------ .../yumc/Yum/managers/RepositoryManager.java | 116 ++++--- .../java/pw/yumc/Yum/models/BukkitDev.java | 24 +- .../java/pw/yumc/Yum/models/PluginInfo.java | 49 ++- .../java/pw/yumc/Yum/models/RepoCache.java | 32 +- .../pw/yumc/Yum/models/RepoSerialization.java | 34 +- .../Yum/runnables/MainThreadCheckTask.java | 61 +++- 31 files changed, 1068 insertions(+), 1049 deletions(-) diff --git a/pom.xml b/pom.xml index d98565a..a0fb493 100644 --- a/pom.xml +++ b/pom.xml @@ -33,7 +33,6 @@ pw.yumc:YumCore - cn.citycraft:PluginHelper @@ -41,10 +40,6 @@ pw.yumc.YumCore ${project.groupId}.${project.artifactId} - - cn.citycraft.PluginHelper - ${project.groupId}.${project.artifactId} - @@ -97,17 +92,11 @@ jar 1.10.2-R0.1-SNAPSHOT - - cn.citycraft - PluginHelper - jar - 1.0 - pw.yumc YumCore jar - 1.0 + 1.1 pw.yumc diff --git a/src/main/java/pw/yumc/Yum/Yum.java b/src/main/java/pw/yumc/Yum/Yum.java index 797f189..d878f11 100644 --- a/src/main/java/pw/yumc/Yum/Yum.java +++ b/src/main/java/pw/yumc/Yum/Yum.java @@ -10,8 +10,6 @@ import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.java.JavaPlugin; -import cn.citycraft.CommonData.UpdatePlugin; -import cn.citycraft.PluginHelper.ext.kit.Reflect; import pw.yumc.Yum.api.YumAPI; import pw.yumc.Yum.commands.FileCommand; import pw.yumc.Yum.commands.MonitorCommand; @@ -26,6 +24,7 @@ import pw.yumc.Yum.managers.MonitorManager; import pw.yumc.Yum.managers.NetworkManager; import pw.yumc.Yum.runnables.MainThreadCheckTask; import pw.yumc.YumCore.bukkit.Log; +import pw.yumc.YumCore.reflect.Reflect; import pw.yumc.YumCore.statistic.Statistics; import pw.yumc.YumCore.update.SubscribeTask; @@ -73,7 +72,7 @@ public class Yum extends JavaPlugin { // 初始化配置 ConfigManager.i(); // 初始化更新列 - UpdatePlugin.getUpdateList(); + // UpdatePlugin.getUpdateList(); // 启用网络注入 NetworkManager.register(this); } @@ -82,7 +81,7 @@ public class Yum extends JavaPlugin { * @return 主线程 */ private Thread getMainThread() { - final Object console = Reflect.on(Bukkit.getServer()).get("console"); + Object console = Reflect.on(Bukkit.getServer()).get("console"); return Reflect.on(console).get("primaryThread"); } @@ -102,15 +101,15 @@ public class Yum extends JavaPlugin { private void initListeners() { if (ConfigManager.i().isSetOpEnable()) { try { - final ClassLoader cl = Class.forName("pw.yumc.injected.event.SetOpEvent").getClassLoader(); + ClassLoader cl = Class.forName("pw.yumc.injected.event.SetOpEvent").getClassLoader(); try { cl.getClass().getDeclaredField("plugin"); throw new ClassNotFoundException(); - } catch (final NoSuchFieldException | SecurityException e) { + } catch (NoSuchFieldException | SecurityException e) { new SecurityListener(this); Log.console("§a安全管理系统已启用..."); } - } catch (final ClassNotFoundException e) { + } catch (ClassNotFoundException e) { Log.console("§c服务端未注入安全拦截器 关闭功能..."); } } diff --git a/src/main/java/pw/yumc/Yum/api/YumAPI.java b/src/main/java/pw/yumc/Yum/api/YumAPI.java index 400e415..c0969ff 100644 --- a/src/main/java/pw/yumc/Yum/api/YumAPI.java +++ b/src/main/java/pw/yumc/Yum/api/YumAPI.java @@ -4,13 +4,11 @@ import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; -import java.util.Map.Entry; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.plugin.Plugin; -import cn.citycraft.CommonData.UpdatePlugin; import pw.yumc.Yum.inject.CommandInjector; import pw.yumc.Yum.inject.ListenerInjector; import pw.yumc.Yum.inject.TaskInjector; @@ -55,7 +53,7 @@ public class YumAPI { * @param plugin * 插件实体 */ - public static void delete(final Plugin plugin) { + public static void delete(Plugin plugin) { plugman.deletePlugin(plugin); } @@ -86,16 +84,16 @@ public class YumAPI { return repo; } - public static List getUpdateList(final CommandSender sender) { - final List ulist = new ArrayList<>(); - try { - for (final Entry updateplugin : UpdatePlugin.getUpdateList().entrySet()) { - ulist.add(updateplugin.getValue()); - } - } catch (final Exception | Error e) { - sender.sendMessage("§4错误: §c无法检索全体更新列表!"); - sender.sendMessage("§4异常: §c" + e.getMessage()); - } + public static List getUpdateList(CommandSender sender) { + List ulist = new ArrayList<>(); + // try { + // for (Entry updateplugin : UpdatePlugin.getUpdateList().entrySet()) { + // ulist.add(updateplugin.getValue()); + // } + // } catch (Exception | Error e) { + // sender.sendMessage("§4错误: §c无法检索全体更新列表!"); + // sender.sendMessage("§4异常: §c" + e.getMessage()); + // } return ulist; } @@ -105,7 +103,7 @@ public class YumAPI { * @param plugin * 插件 */ - public static void inject(final Plugin plugin) { + public static void inject(Plugin plugin) { if (plugin.isEnabled() && !ConfigManager.i().getMonitorIgnoreList().contains(plugin.getName())) { CommandInjector.inject(plugin); ListenerInjector.inject(plugin); @@ -124,11 +122,9 @@ public class YumAPI { * 插件版本 * @return 是否安装成功 */ - public static boolean install(final CommandSender sender, final String pluginname, final String url) { - final File pluginFile = new File(Bukkit.getUpdateFolderFile().getParentFile(), pluginname + ".jar"); - if (download.run(sender, url, pluginFile)) { - return plugman.load(sender, pluginFile); - } + public static boolean install(CommandSender sender, String pluginname, String url) { + File pluginFile = new File(Bukkit.getUpdateFolderFile().getParentFile(), pluginname + ".jar"); + if (download.run(sender, url, pluginFile)) { return plugman.load(sender, pluginFile); } return false; } @@ -141,7 +137,7 @@ public class YumAPI { * 插件版本 * @return 是否安装成功 */ - public static boolean install(final String pluginname, final String url) { + public static boolean install(String pluginname, String url) { return install(null, pluginname, url); } @@ -154,7 +150,7 @@ public class YumAPI { * 插件名称 * @return 是否安装成功 */ - public static boolean installFromYum(final CommandSender sender, final String pluginname) { + public static boolean installFromYum(CommandSender sender, String pluginname) { return installFromYum(sender, pluginname, null); } @@ -169,11 +165,9 @@ public class YumAPI { * 插件版本 * @return 是否安装成功 */ - public static boolean installFromYum(final CommandSender sender, final String pluginname, final String version) { - final PluginInfo pi = repo.getPlugin(pluginname); - if (pi != null) { - return install(sender, pi.name, pi.getUrl(sender, version)); - } + public static boolean installFromYum(CommandSender sender, String pluginname, String version) { + PluginInfo pi = repo.getPlugin(pluginname); + if (pi != null) { return install(sender, pi.name, pi.getUrl(sender, version)); } sender.sendMessage("§4错误: §c仓库中未找到插件 §b" + pluginname + " §c安装失败!"); return false; } @@ -184,7 +178,7 @@ public class YumAPI { * @param pluginname * 插件名称 */ - public static void load(final File pluginFile) { + public static void load(File pluginFile) { plugman.load(pluginFile); } @@ -194,7 +188,7 @@ public class YumAPI { * @param pluginname * 插件名称 */ - public static void load(final String pluginname) { + public static void load(String pluginname) { plugman.load(pluginname); } @@ -204,7 +198,7 @@ public class YumAPI { * @param plugin * 插件实体 */ - public static void reload(final Plugin plugin) { + public static void reload(Plugin plugin) { plugman.reload(plugin); } @@ -215,7 +209,7 @@ public class YumAPI { * 插件 */ public static void uninject() { - for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { YumAPI.uninject(plugin); } } @@ -226,7 +220,7 @@ public class YumAPI { * @param plugin * 插件 */ - public static void uninject(final Plugin plugin) { + public static void uninject(Plugin plugin) { CommandInjector.uninject(plugin); ListenerInjector.uninject(plugin); TaskInjector.uninject(plugin); @@ -238,7 +232,7 @@ public class YumAPI { * @param plugin * 插件实体 */ - public static void unload(final Plugin plugin) { + public static void unload(Plugin plugin) { plugman.unload(plugin); } @@ -253,8 +247,10 @@ public class YumAPI { * 新插件的下载地址 * @return 是否更新成功 */ - public static boolean update(final CommandSender sender, final Plugin plugin, final URL url) { - if (download.run(sender, url, new File(Bukkit.getUpdateFolderFile(), plugman.getPluginFile(plugin).getName()))) { + public static boolean update(CommandSender sender, Plugin plugin, URL url) { + if (download.run(sender, + url, + new File(Bukkit.getUpdateFolderFile(), plugman.getPluginFile(plugin).getName()))) { sender.sendMessage("§6更新: §e已下载 " + plugin.getName() + " 插件到服务器更新文件夹"); sender.sendMessage("§6更新: §e插件将在重启后自动更新(或使用§b/yum upgrade§e直接升级)!"); return true; @@ -271,7 +267,7 @@ public class YumAPI { * 新插件的下载地址 * @return 是否更新成功 */ - public static boolean update(final Plugin plugin, final URL url) { + public static boolean update(Plugin plugin, URL url) { return update(null, plugin, url); } @@ -291,10 +287,10 @@ public class YumAPI { } runlock = true; int failed = 0; - final List ulist = getUpdateList(sender); + List ulist = getUpdateList(sender); if (ulist.size() > 0) { sender.sendMessage("§d开始更新服务器可更新插件"); - for (final Plugin updateplugin : ulist) { + for (Plugin updateplugin : ulist) { sender.sendMessage("§d一键更新: §a开始更新" + updateplugin.getName() + "!"); if (!updateFromYum(sender, updateplugin, null, true)) { failed++; @@ -324,9 +320,10 @@ public class YumAPI { PKit.runTaskLaterAsync(new Runnable() { @Override public void run() { - final List ulist = getUpdateList(sender); + List ulist = getUpdateList(sender); if (ulist.size() > 0) { - sender.sendMessage("§6[§bYum§6]§e自动更新: §a发现 §e" + ulist.size() + " §a个可更新插件 请使用 §b/yum ua §a更新所有插件!"); + sender.sendMessage( + "§6[§bYum§6]§e自动更新: §a发现 §e" + ulist.size() + " §a个可更新插件 请使用 §b/yum ua §a更新所有插件!"); } } }, 60); @@ -341,7 +338,7 @@ public class YumAPI { * 插件实体 * @return 是否更新成功 */ - public static boolean updateFromYum(final CommandSender sender, final Plugin plugin) { + public static boolean updateFromYum(CommandSender sender, Plugin plugin) { return updateFromYum(sender, plugin, null); } @@ -356,7 +353,7 @@ public class YumAPI { * 插件版本(null则自动获取) * @return */ - public static boolean updateFromYum(final CommandSender sender, final Plugin plugin, final String version) { + public static boolean updateFromYum(CommandSender sender, Plugin plugin, String version) { return updateFromYum(sender, plugin, version, false); } @@ -373,16 +370,16 @@ public class YumAPI { * 是否一键更新 * @return */ - public static boolean updateFromYum(final CommandSender sender, final Plugin plugin, final String version, final boolean oneKeyUpdate) { - final PluginInfo pi = repo.getPlugin(plugin.getName()); + public static boolean updateFromYum(CommandSender sender, Plugin plugin, String version, boolean oneKeyUpdate) { + PluginInfo pi = repo.getPlugin(plugin.getName()); if (pi != null) { - final File pFile = new File(Bukkit.getUpdateFolderFile(), plugman.getPluginFile(plugin).getName()); + File pFile = new File(Bukkit.getUpdateFolderFile(), plugman.getPluginFile(plugin).getName()); if (download.run(sender, pi.getUrl(sender, version), pFile)) { if (!oneKeyUpdate) { sender.sendMessage("§6更新: §e已下载 " + plugin.getName() + " 插件到服务器更新文件夹"); sender.sendMessage("§6更新: §e插件将在重启后自动更新(或使用§b/yum upgrade§e直接升级)!"); } - UpdatePlugin.getUpdateList().remove(plugin.getName()); + //UpdatePlugin.getUpdateList().remove(plugin.getName()); return true; } } else { @@ -398,7 +395,7 @@ public class YumAPI { PKit.runTaskLater(new Runnable() { @Override public void run() { - for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { YumAPI.inject(plugin); } } @@ -423,7 +420,7 @@ public class YumAPI { * @param sender * 命令发送者 */ - public static void upgrade(final CommandSender sender) { + public static void upgrade(CommandSender sender) { plugman.upgrade(sender); } @@ -435,7 +432,7 @@ public class YumAPI { * @param plugin * 插件实体 */ - public static void upgrade(final CommandSender sender, final Plugin plugin) { + public static void upgrade(CommandSender sender, Plugin plugin) { plugman.upgrade(sender, plugin); } } diff --git a/src/main/java/pw/yumc/Yum/commands/FileCommand.java b/src/main/java/pw/yumc/Yum/commands/FileCommand.java index b0ebd6b..bd56b5f 100644 --- a/src/main/java/pw/yumc/Yum/commands/FileCommand.java +++ b/src/main/java/pw/yumc/Yum/commands/FileCommand.java @@ -12,16 +12,15 @@ import java.nio.file.StandardCopyOption; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; -import cn.citycraft.PluginHelper.kit.StrKit; -import cn.citycraft.PluginHelper.utils.FileUtil; import pw.yumc.Yum.Yum; import pw.yumc.Yum.api.YumAPI; -import pw.yumc.YumCore.commands.CommandArgument; -import pw.yumc.YumCore.commands.CommandExecutor; import pw.yumc.YumCore.commands.CommandManager; import pw.yumc.YumCore.commands.annotation.Async; import pw.yumc.YumCore.commands.annotation.Cmd; import pw.yumc.YumCore.commands.annotation.Help; +import pw.yumc.YumCore.commands.annotation.KeyValue; +import pw.yumc.YumCore.commands.interfaces.CommandExecutor; +import pw.yumc.YumCore.kit.FileKit; /** * File命令基类 @@ -43,13 +42,13 @@ public class FileCommand implements CommandExecutor { private static String noResult = prefix + "§d当前命令没有返回结果!"; private static String runError = prefix + "§c命令运行错误: %s %s"; - private static String addStartupSuccess = "§a成功添加开机自动启..."; - private static String addStartupFailed = "§c添加开机自动启失败!"; + private static String addStartupSuccess = "§e %s §a成功添加开机自动启..."; + private static String addStartupFailed = "§c添加开机自动启失败 %s %s!"; private static String STARTPATH = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp"; Yum plugin; - public FileCommand(final Yum yum) { + public FileCommand(Yum yum) { plugin = yum; new CommandManager("file", this, PluginTabComplete.instence); } @@ -57,34 +56,23 @@ public class FileCommand implements CommandExecutor { @Cmd(aliases = "cp", minimumArguments = 2) @Help(value = "复制文件", possibleArguments = "<源文件> <目标目录>") @Async - public void copy(final CommandArgument e) throws FileNotFoundException, IOException { - final String[] args = e.getArgs(); - final CommandSender sender = e.getSender(); - final File src = new File(args[0]); - final File des = new File(args[1]); - if (!src.exists()) { - sender.sendMessage(String.format(file_not_found, args[0])); - return; - } + public void copy(CommandSender sender, @KeyValue(key = "check") File src, File des) throws FileNotFoundException, IOException { if (src.isDirectory()) { - sender.sendMessage(String.format(file_is_dir, args[0])); + sender.sendMessage(String.format(file_is_dir, src.getPath())); return; } if (Files.copy(new FileInputStream(src), des.toPath(), StandardCopyOption.REPLACE_EXISTING) != 0) { - sender.sendMessage(String.format(copySuccess, args[0])); + sender.sendMessage(String.format(copySuccess, src.getPath())); } else { - sender.sendMessage(String.format(copyFailed, args[0])); + sender.sendMessage(String.format(copyFailed, src.getPath())); } } @Cmd(aliases = "del", minimumArguments = 1) @Help(value = "删除文件(服务器JAR为根目录)", possibleArguments = "<文件相对目录>") @Async - public void delete(final CommandArgument e) { - final String[] args = e.getArgs(); - String fpath = args[0]; - final File file = new File(fpath); - final CommandSender sender = e.getSender(); + public void delete(CommandSender sender, String fpath) { + File file = new File(fpath); fpath = file.getAbsolutePath(); if (!file.exists()) { sender.sendMessage(String.format(file_not_found, fpath)); @@ -95,7 +83,7 @@ public class FileCommand implements CommandExecutor { } try { sender.sendMessage("§d文件 §e" + fpath + " " + (file.delete() ? "§a删除成功!" : "§c删除失败!")); - } catch (final Exception ex) { + } catch (Exception ex) { sender.sendMessage("§d文件 §e" + fpath + " 删除失败: " + ex.getMessage()); } } @@ -104,37 +92,33 @@ public class FileCommand implements CommandExecutor { @Cmd(aliases = "d", minimumArguments = 1) @Help(value = "下载文件(默认保存到服务器更新文件夹)", possibleArguments = "<下载地址> [保存文件路径]") @Async - public void download(final CommandArgument e) { - final String[] args = e.getArgs(); - String urlstr = args[0]; + public void download(CommandSender sender, String urlstr, String path) { if (!urlstr.startsWith("http")) { urlstr = "http://" + urlstr; } File file = null; - if (args.length == 2) { - file = new File(args[1]); + if (path != null) { + file = new File(path); } else { file = new File(Bukkit.getUpdateFolderFile(), YumAPI.getDownload().getFileName(urlstr)); } - YumAPI.getDownload().run(e.getSender(), urlstr, file); + YumAPI.getDownload().run(sender, urlstr, file); } @Cmd(aliases = "ls") @Help(value = "列出当前目录(服务器JAR为根目录)", possibleArguments = "<相对目录>") @Async - public void ls(final CommandArgument e) { - final String[] args = e.getArgs(); - final CommandSender sender = e.getSender(); + public void ls(CommandSender sender, String filename) { File dir = new File("."); - if (args.length == 1) { - dir = new File(args[0]); + if (filename != null) { + dir = new File(filename); } if (!dir.isDirectory()) { sender.sendMessage("§6路径: §e " + dir.getAbsolutePath() + " §c不是一个目录!"); return; } - final StringBuffer sb = new StringBuffer(); - for (final File file : dir.listFiles()) { + StringBuffer sb = new StringBuffer(); + for (File file : dir.listFiles()) { if (file.isDirectory()) { sb.append("§b"); } else { @@ -142,7 +126,7 @@ public class FileCommand implements CommandExecutor { } sb.append(file.getName() + " "); } - final String filelist = sb.toString(); + String filelist = sb.toString(); if (filelist.isEmpty()) { sender.sendMessage("§6目录: §e" + dir.getAbsolutePath() + " §c下没有文件或文件夹!"); } else { @@ -154,19 +138,16 @@ public class FileCommand implements CommandExecutor { @Cmd(aliases = "rn", minimumArguments = 2) @Help(value = "重命名文件(服务器JAR为根目录)", possibleArguments = "<文件相对路径> <文件名称>") @Async - public void rename(final CommandArgument e) { - final String[] args = e.getArgs(); - final CommandSender sender = e.getSender(); - final String fpath = args[0]; - final File file = new File(fpath); + public void rename(CommandSender sender, String fpath, String des) { + File file = new File(fpath); if (!file.exists()) { sender.sendMessage("§c文件 " + file.getAbsolutePath() + " 不存在!"); } else { try { - final File newFile = new File(file.getParentFile(), args[1]); + File newFile = new File(file.getParentFile(), des); file.renameTo(newFile); sender.sendMessage("§a文件 §e" + file.getAbsolutePath() + " §a重命名为 §d" + newFile.getAbsolutePath()); - } catch (final Exception ex) { + } catch (Exception ex) { sender.sendMessage("§c文件 §e" + file.getAbsolutePath() + " §c重命名失败: " + ex.getMessage()); } } @@ -175,11 +156,8 @@ public class FileCommand implements CommandExecutor { @Cmd(minimumArguments = 1) @Help(value = "删除文件夹(服务器JAR为根目录)", possibleArguments = "<相对目录>") @Async - public void rm(final CommandArgument e) { - final String[] args = e.getArgs(); - final CommandSender sender = e.getSender(); - final String fpath = args[0]; - final File file = new File(fpath); + public void rm(CommandSender sender, String fpath, String option) { + File file = new File(fpath); if (!file.exists()) { sender.sendMessage("§c目录 " + file.getAbsolutePath() + " 不存在!"); } else { @@ -187,33 +165,32 @@ public class FileCommand implements CommandExecutor { sender.sendMessage("§d路径 §e" + file.getAbsolutePath() + " §c是一个文件 请使用file delete!"); return; } - for (final String name : plugin.getConfig().getStringList("blacklist")) { + for (String name : plugin.getConfig().getStringList("blacklist")) { if (file.getAbsolutePath().toLowerCase().endsWith(name)) { sender.sendMessage("§d路径 §e" + file.getAbsolutePath() + " §c不允许被删除!"); return; } } - if (file.listFiles().length != 0 && !(args.length > 1 && args[1].equalsIgnoreCase("-rf"))) { + if (file.listFiles().length != 0 && !(option != null && option.equalsIgnoreCase("-rf"))) { sender.sendMessage("§d目录 §e" + file.getAbsolutePath() + " §c不为空!"); sender.sendMessage("§c请使用 §a/file rm " + fpath + " -rf §c强行删除!"); return; } - sender.sendMessage("§d目录 §e" + file.getAbsolutePath() + " " + (FileUtil.deleteDir(sender, file) ? "§a删除成功!" : "§c删除失败!")); + sender.sendMessage("§d目录 §e" + file.getAbsolutePath() + " " + + (FileKit.deleteDir(sender, file) ? "§a删除成功!" : "§c删除失败!")); } } @Cmd(aliases = "r", minimumArguments = 1) @Help(value = "运行一个命令或文件", possibleArguments = "<命令或文件绝对路径>") @Async - public void run(final CommandArgument e) { - final String[] args = e.getArgs(); - final CommandSender sender = e.getSender(); + public void run(CommandSender sender, String args) { try { - final Process process = Runtime.getRuntime().exec(StrKit.join(args, " ")); + Process process = Runtime.getRuntime().exec(args); sender.sendMessage(waitCommand); - final BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); + BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null; - final StringBuilder build = new StringBuilder(); + StringBuilder build = new StringBuilder(); while ((line = br.readLine()) != null) { build.append(line); build.append("\n"); @@ -224,7 +201,7 @@ public class FileCommand implements CommandExecutor { sender.sendMessage(runResult); sender.sendMessage(build.toString().split("\n")); } - } catch (final Exception e2) { + } catch (Exception e2) { sender.sendMessage(String.format(runError, e2.getClass().getSimpleName(), e2.getMessage())); } } @@ -232,23 +209,22 @@ public class FileCommand implements CommandExecutor { @Cmd(minimumArguments = 1) @Help(value = "添加开机自启动", possibleArguments = "<文件绝对路径>") @Async - public void startup(final CommandArgument e) { - final String[] args = e.getArgs(); - final CommandSender sender = e.getSender(); - final File src = new File(args[0]); - final File des = new File(STARTPATH, src.getName()); + public void startup(CommandSender sender, String filepath) { + File src = new File(filepath); + File des = new File(STARTPATH, src.getName()); if (!src.exists()) { - sender.sendMessage(String.format(file_not_found, args[0])); + sender.sendMessage(String.format(file_not_found, filepath)); return; } if (src.isDirectory()) { - sender.sendMessage(String.format(file_is_dir, args[0])); + sender.sendMessage(String.format(file_is_dir, filepath)); return; } - if (FileUtil.copyFile(src, des)) { - sender.sendMessage(String.format(addStartupSuccess, args[0])); - } else { - sender.sendMessage(String.format(addStartupFailed, args[0])); + try { + Files.copy(new FileInputStream(src), des.toPath(), StandardCopyOption.REPLACE_EXISTING); + sender.sendMessage(String.format(addStartupSuccess, filepath)); + } catch (Exception e2) { + sender.sendMessage(String.format(addStartupFailed, e2.getClass().getName(), e2.getMessage())); } } } diff --git a/src/main/java/pw/yumc/Yum/commands/MonitorCommand.java b/src/main/java/pw/yumc/Yum/commands/MonitorCommand.java index d4afd60..03bdd29 100644 --- a/src/main/java/pw/yumc/Yum/commands/MonitorCommand.java +++ b/src/main/java/pw/yumc/Yum/commands/MonitorCommand.java @@ -20,8 +20,6 @@ import org.bukkit.plugin.RegisteredListener; import org.bukkit.plugin.TimedRegisteredListener; import org.bukkit.scheduler.BukkitTask; -import cn.citycraft.PluginHelper.ext.kit.Reflect; -import cn.citycraft.PluginHelper.kit.StrKit; import pw.yumc.Yum.Yum; import pw.yumc.Yum.api.YumAPI; import pw.yumc.Yum.inject.CommandInjector; @@ -29,13 +27,14 @@ import pw.yumc.Yum.inject.ListenerInjector; import pw.yumc.Yum.inject.TaskInjector; import pw.yumc.Yum.managers.MonitorManager; import pw.yumc.Yum.managers.MonitorManager.MonitorInfo; -import pw.yumc.YumCore.commands.CommandArgument; -import pw.yumc.YumCore.commands.CommandExecutor; import pw.yumc.YumCore.commands.CommandManager; import pw.yumc.YumCore.commands.annotation.Async; import pw.yumc.YumCore.commands.annotation.Cmd; import pw.yumc.YumCore.commands.annotation.Help; +import pw.yumc.YumCore.commands.interfaces.CommandExecutor; import pw.yumc.YumCore.kit.PKit; +import pw.yumc.YumCore.kit.StrKit; +import pw.yumc.YumCore.reflect.Reflect; /** * @@ -45,53 +44,51 @@ import pw.yumc.YumCore.kit.PKit; public class MonitorCommand implements CommandExecutor { public static Throwable lastError = null; - private final String prefix = "§6[§bYum §a能耗监控§6] "; + private String prefix = "§6[§bYum §a能耗监控§6] "; - private final String no_mi = prefix + "§6%s §a自服务器启动以来尚未执行任何操作"; - private final String micprefix = " §6命令名称 §a总耗时 §b执行次数 §d平均耗时"; - private final String mieprefix = " §6事件名称 §a总耗时 §b执行次数 §d平均耗时"; - private final String mitprefix = " §6任务名称 §a总耗时 §b执行次数 §d平均耗时"; - private final String milist = "§6- §e%-20s §a%-9.2f §b%-9s §d%-9.5f"; - private final String miwlist = "§6- §c%-20s §a%-9.2f §b%-9s §c%-9.5f"; + private String no_mi = prefix + "§6%s §a自服务器启动以来尚未执行任何操作"; + private String micprefix = " §6命令名称 §a总耗时 §b执行次数 §d平均耗时"; + private String mieprefix = " §6事件名称 §a总耗时 §b执行次数 §d平均耗时"; + private String mitprefix = " §6任务名称 §a总耗时 §b执行次数 §d平均耗时"; + private String milist = "§6- §e%-20s §a%-9.2f §b%-9s §d%-9.5f"; + private String miwlist = "§6- §c%-20s §a%-9.2f §b%-9s §c%-9.5f"; - private final String reinject = prefix + "§a能耗监控器重载完毕!"; - private final String injected = prefix + "§a插件 §b%s §a成功注入能耗监控器!"; - private final String uninjected = prefix + "§a插件 §b%s §a成功撤销能耗监控器!"; - private final String notEnable = prefix + "§c插件 §b%s §c未成功加载 无法执行注入!"; + private String reinject = prefix + "§a能耗监控器重载完毕!"; + private String injected = prefix + "§a插件 §b%s §a成功注入能耗监控器!"; + private String uninjected = prefix + "§a插件 §b%s §a成功撤销能耗监控器!"; + private String notEnable = prefix + "§c插件 §b%s §c未成功加载 无法执行注入!"; - private final String lag = prefix + "§a当前服务器插件能耗如下§6(单位: %)"; - private final String lagprefix = " §6插件名称 §c主线程 §a命令 §b事件 §d任务"; - private final String laglist = "§6%-2s §b%-20s §c%-25s §a%-5.2f §b%-5.2f §d%-5.2f"; + private String lag = prefix + "§a当前服务器插件能耗如下§6(单位: %)"; + private String lagprefix = " §6插件名称 §c主线程 §a命令 §b事件 §d任务"; + private String laglist = "§6%-2s §b%-20s §c%-25s §a%-5.2f §b%-5.2f §d%-5.2f"; - private final String no_error = prefix + "§a自服务器启动以来尚未发现报错!"; - private final String last_error = prefix + "§c最后一次错误异常由 §b%s §c造成 详细如下:"; + private String no_error = prefix + "§a自服务器启动以来尚未发现报错!"; + private String last_error = prefix + "§c最后一次错误异常由 §b%s §c造成 详细如下:"; - private final String p_n_f = prefix + "§c插件 §b%s §c不存在!"; + private String p_n_f = prefix + "§c插件 §b%s §c不存在!"; - private final double um = 1000000.00; + private double um = 1000000.00; - public MonitorCommand(final Yum yum) { + public MonitorCommand(Yum yum) { new CommandManager("monitor", this, PluginTabComplete.instence); } @Cmd(aliases = "c", minimumArguments = 1) @Help(value = "查看插件命令能耗", possibleArguments = "[插件名称]") @Async - public void cmd(final CommandArgument e) { - final String pname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); + public void cmd(CommandSender sender, String pname) { if (Bukkit.getPluginManager().getPlugin(pname) == null) { sender.sendMessage(String.format(p_n_f, pname)); return; } - final PluginManager pluginManager = Bukkit.getPluginManager(); - final SimpleCommandMap commandMap = Reflect.on(pluginManager).get("commandMap"); + PluginManager pluginManager = Bukkit.getPluginManager(); + SimpleCommandMap commandMap = Reflect.on(pluginManager).get("commandMap"); sender.sendMessage(prefix + "§6插件 §b" + pname + " §6的命令能耗如下!"); - final Map temp = new HashMap<>(); - for (final Command command : commandMap.getCommands()) { + Map temp = new HashMap<>(); + for (Command command : commandMap.getCommands()) { if (command instanceof PluginCommand) { - final PluginCommand pluginCommand = (PluginCommand) command; - final Plugin plugin = pluginCommand.getPlugin(); + PluginCommand pluginCommand = (PluginCommand) command; + Plugin plugin = pluginCommand.getPlugin(); if (plugin.getName().equalsIgnoreCase(pname)) { temp.put(command.getName(), command); } @@ -102,15 +99,23 @@ public class MonitorCommand implements CommandExecutor { return; } sender.sendMessage(micprefix); - for (final Entry command : temp.entrySet()) { - final org.bukkit.command.CommandExecutor executor = Reflect.on(command.getValue()).get("executor"); + for (Entry command : temp.entrySet()) { + org.bukkit.command.CommandExecutor executor = Reflect.on(command.getValue()).get("executor"); if (executor instanceof CommandInjector) { - final CommandInjector injected = (CommandInjector) executor; + CommandInjector injected = (CommandInjector) executor; if (injected.count != 0) { - final double avgTime = injected.totalTime / um / injected.count; - sender.sendMessage(String.format(avgTime < 10 ? milist : miwlist, command.getValue().getName(), injected.totalTime / um, injected.count, avgTime)); + double avgTime = injected.totalTime / um / injected.count; + sender.sendMessage(String.format(avgTime < 10 ? milist : miwlist, + command.getValue().getName(), + injected.totalTime / um, + injected.count, + avgTime)); } else { - sender.sendMessage(String.format(milist, command.getValue().getName(), injected.totalTime / um, injected.count, 0D)); + sender.sendMessage(String.format(milist, + command.getValue().getName(), + injected.totalTime / um, + injected.count, + 0D)); } } } @@ -119,34 +124,32 @@ public class MonitorCommand implements CommandExecutor { @Cmd(aliases = "e", minimumArguments = 1) @Help(value = "查看插件事件能耗", possibleArguments = "[插件名称]") @Async - public void event(final CommandArgument e) throws InstantiationException, IllegalAccessException, NoSuchFieldException { - final String pname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); - final Plugin plugin = Bukkit.getPluginManager().getPlugin(pname); + public void event(CommandSender sender, String pname) throws InstantiationException, IllegalAccessException, NoSuchFieldException { + Plugin plugin = Bukkit.getPluginManager().getPlugin(pname); if (plugin == null) { sender.sendMessage(String.format(p_n_f, pname)); return; } sender.sendMessage(prefix + "§6插件 §b" + pname + " §6的事件能耗如下!"); - final List listeners = HandlerList.getRegisteredListeners(plugin); - final Map eventTotalTime = new HashMap<>(); - final Map eventCount = new HashMap<>(); - for (final RegisteredListener listener : listeners) { + List listeners = HandlerList.getRegisteredListeners(plugin); + Map eventTotalTime = new HashMap<>(); + Map eventCount = new HashMap<>(); + for (RegisteredListener listener : listeners) { if (listener instanceof TimedRegisteredListener) { - final TimedRegisteredListener trl = (TimedRegisteredListener) listener; + TimedRegisteredListener trl = (TimedRegisteredListener) listener; eventTotalTime.put(trl.getEventClass().getSimpleName(), trl.getTotalTime()); eventCount.put(trl.getEventClass().getSimpleName(), trl.getCount()); continue; } EventExecutor executor = Reflect.on(listener).get("executor"); if (listener.getClass().getName().contains("PWPRegisteredListener")) { - final Field f = Reflect.getDeclaredField(RegisteredListener.class, "executor"); + Field f = Reflect.getDeclaredField(RegisteredListener.class, "executor"); f.setAccessible(true); executor = (EventExecutor) f.get(listener); } if (executor instanceof ListenerInjector) { - final ListenerInjector injected = (ListenerInjector) executor; - for (final String entry : injected.eventTotalTime.keySet()) { + ListenerInjector injected = (ListenerInjector) executor; + for (String entry : injected.eventTotalTime.keySet()) { if (eventTotalTime.containsKey(entry)) { eventTotalTime.put(entry, eventTotalTime.get(entry) + injected.eventTotalTime.get(entry)); eventCount.put(entry, eventCount.get(entry) + injected.eventCount.get(entry)); @@ -162,18 +165,20 @@ public class MonitorCommand implements CommandExecutor { return; } sender.sendMessage(mieprefix); - for (final String event : MonitorManager.sortMapByValue(eventTotalTime).keySet()) { - final double avgTime = eventTotalTime.get(event) / um / eventCount.get(event); - sender.sendMessage(String.format(avgTime < 10 ? milist : miwlist, event, eventTotalTime.get(event) / um, eventCount.get(event), avgTime)); + for (String event : MonitorManager.sortMapByValue(eventTotalTime).keySet()) { + double avgTime = eventTotalTime.get(event) / um / eventCount.get(event); + sender.sendMessage(String.format(avgTime < 10 ? milist : miwlist, + event, + eventTotalTime.get(event) / um, + eventCount.get(event), + avgTime)); } } @Cmd(aliases = "i", minimumArguments = 1) @Help(value = "注入能耗监控器", possibleArguments = "[插件名称]") - public void inject(final CommandArgument e) { - final String pname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); - final Plugin plugin = Bukkit.getPluginManager().getPlugin(pname); + public void inject(CommandSender sender, String pname) { + Plugin plugin = Bukkit.getPluginManager().getPlugin(pname); if (plugin == null) { sender.sendMessage(String.format(p_n_f, pname)); return; @@ -189,49 +194,47 @@ public class MonitorCommand implements CommandExecutor { @Cmd(aliases = "l") @Help("查看插件总耗时") @Async - public void lag(final CommandArgument e) { - final CommandSender sender = e.getSender(); - final Map mm = MonitorManager.getMonitor(); - int i = 0; + public void lag(CommandSender sender, int size) { + Map mm = MonitorManager.getMonitor(); int max = 8; - try { - max = Integer.parseInt(e.getArgs()[0]); - } catch (final Exception ignore) { - } sender.sendMessage(lag); sender.sendMessage(lagprefix); - for (final Entry entry : mm.entrySet()) { - if (++i > max) { + for (Entry entry : mm.entrySet()) { + if (++size > max) { break; } - final MonitorInfo mi = MonitorManager.getMonitorInfo(entry.getKey()); - sender.sendMessage(String.format(laglist, i, entry.getKey(), getPer(sender, mi.monitor), mi.cmd, mi.event, mi.task)); + MonitorInfo mi = MonitorManager.getMonitorInfo(entry.getKey()); + sender.sendMessage(String.format(laglist, + size, + entry.getKey(), + getPer(sender, mi.monitor), + mi.cmd, + mi.event, + mi.task)); } } @Cmd(aliases = "la") @Help("查看最后一次报错") @Async - public void lasterror(final CommandArgument e) { - final CommandSender sender = e.getSender(); + public void lasterror(CommandSender sender) { if (lastError == null) { sender.sendMessage(no_error); return; } - final Plugin plugin = PKit.getOperatePlugin(lastError.getStackTrace()); + Plugin plugin = PKit.getOperatePlugin(lastError.getStackTrace()); sender.sendMessage(String.format(last_error, plugin != null ? plugin.getName() : "未知")); lastError.printStackTrace(); } @Cmd - public void lk(final CommandArgument e) { - MonitorManager.sendObject(e.getSender()); + public void lk(CommandSender sender) { + MonitorManager.sendObject(sender); } @Cmd(aliases = "ri") @Help("重载能耗监控器") - public void reinject(final CommandArgument e) { - final CommandSender sender = e.getSender(); + public void reinject(CommandSender sender) { YumAPI.updateInject(); sender.sendMessage(reinject); } @@ -239,38 +242,44 @@ public class MonitorCommand implements CommandExecutor { @Cmd @Help("重置能耗监控器") @Async - public void reset(final CommandArgument e) { + public void reset(CommandSender sender) { MonitorManager.init(); } @Cmd(aliases = "t", minimumArguments = 1) @Help(value = "查看插件任务能耗", possibleArguments = "[插件名称]") @Async - public void task(final CommandArgument e) { - final String pname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); - final Plugin plugin = Bukkit.getPluginManager().getPlugin(pname); + public void task(CommandSender sender, String pname) { + Plugin plugin = Bukkit.getPluginManager().getPlugin(pname); if (plugin == null) { sender.sendMessage(String.format(p_n_f, pname)); return; } - final List pendingTasks = Bukkit.getScheduler().getPendingTasks(); + List pendingTasks = Bukkit.getScheduler().getPendingTasks(); if (pendingTasks.isEmpty()) { sender.sendMessage(String.format(no_mi, pname)); return; } sender.sendMessage(prefix + "§6插件 §b" + pname + " §6的任务能耗如下!"); sender.sendMessage(mitprefix); - for (final BukkitTask pendingTask : pendingTasks) { + for (BukkitTask pendingTask : pendingTasks) { if (pendingTask.getOwner().getName().equalsIgnoreCase(pname)) { - final Runnable task = Reflect.on(pendingTask).get("task"); + Runnable task = Reflect.on(pendingTask).get("task"); if (task instanceof TaskInjector) { - final TaskInjector executor = (TaskInjector) task; + TaskInjector executor = (TaskInjector) task; if (executor.count != 0) { - final double avgTime = executor.totalTime / um / executor.count; - sender.sendMessage(String.format(avgTime < 10 ? milist : miwlist, getClassName(executor.getOriginalTask().getClass()), executor.totalTime / um, executor.count, avgTime)); + double avgTime = executor.totalTime / um / executor.count; + sender.sendMessage(String.format(avgTime < 10 ? milist : miwlist, + getClassName(executor.getOriginalTask().getClass()), + executor.totalTime / um, + executor.count, + avgTime)); } else { - sender.sendMessage(String.format(milist, getClassName(executor.getOriginalTask().getClass()), executor.totalTime / um, executor.count, 0D)); + sender.sendMessage(String.format(milist, + getClassName(executor.getOriginalTask().getClass()), + executor.totalTime / um, + executor.count, + 0D)); } } } @@ -279,10 +288,8 @@ public class MonitorCommand implements CommandExecutor { @Cmd(aliases = "ui", minimumArguments = 1) @Help(value = "撤销能耗监控器", possibleArguments = "[插件名称]") - public void uninject(final CommandArgument e) { - final String pname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); - final Plugin plugin = Bukkit.getPluginManager().getPlugin(pname); + public void uninject(CommandSender sender, String pname) { + Plugin plugin = Bukkit.getPluginManager().getPlugin(pname); if (plugin == null) { sender.sendMessage(String.format(p_n_f, pname)); return; @@ -293,14 +300,15 @@ public class MonitorCommand implements CommandExecutor { } } - private String getClassName(final Class clazz) { - return StrKit.isBlank(clazz.getSimpleName()) ? clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1) : clazz.getSimpleName(); + private String getClassName(Class clazz) { + return StrKit.isBlank(clazz.getSimpleName()) ? clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1) + : clazz.getSimpleName(); } - private String getPer(final CommandSender sender, final double per) { - final String ps = sender instanceof Player ? "||" : "|"; - final double p = per / 5; - final StringBuilder sb = new StringBuilder(); + private String getPer(CommandSender sender, double per) { + String ps = sender instanceof Player ? "||" : "|"; + double p = per / 5; + StringBuilder sb = new StringBuilder(); if (p < 3) { sb.append("§a"); } else if (p < 6) { diff --git a/src/main/java/pw/yumc/Yum/commands/NetCommand.java b/src/main/java/pw/yumc/Yum/commands/NetCommand.java index 9516e01..3114637 100644 --- a/src/main/java/pw/yumc/Yum/commands/NetCommand.java +++ b/src/main/java/pw/yumc/Yum/commands/NetCommand.java @@ -8,31 +8,30 @@ import org.bukkit.command.CommandSender; import pw.yumc.Yum.Yum; import pw.yumc.Yum.managers.ConfigManager; -import pw.yumc.YumCore.commands.CommandArgument; -import pw.yumc.YumCore.commands.CommandExecutor; import pw.yumc.YumCore.commands.CommandManager; import pw.yumc.YumCore.commands.annotation.Async; import pw.yumc.YumCore.commands.annotation.Cmd; import pw.yumc.YumCore.commands.annotation.Help; +import pw.yumc.YumCore.commands.interfaces.CommandExecutor; public class NetCommand implements CommandExecutor { public static HashMap netlist = new HashMap<>(); - private final String prefix = "§6[§bYum §a网络管理§6] "; + private String prefix = "§6[§bYum §a网络管理§6] "; - private final String showlist = prefix + "§a自服务器启动以来尝试联网的插件列表如下:"; - private final String listprefix = " §6插件名称 §d联网次数"; - private final String list = "§6- §b%-20s §d%s"; - private final String no_net = prefix + "§a尚未检测到尝试联网的插件!"; - private final String add = prefix + "§a已添加插件 §b%s §a到网络 %s §a列表!"; + private String showlist = prefix + "§a自服务器启动以来尝试联网的插件列表如下:"; + private String listprefix = " §6插件名称 §d联网次数"; + private String list = "§6- §b%-20s §d%s"; + private String no_net = prefix + "§a尚未检测到尝试联网的插件!"; + private String add = prefix + "§a已添加插件 §b%s §a到网络 %s §a列表!"; - private final String p_n_f = prefix + "§c插件 §b%s §c不存在!"; + private String p_n_f = prefix + "§c插件 §b%s §c不存在!"; - public NetCommand(final Yum yum) { + public NetCommand(Yum yum) { new CommandManager("net", this, PluginTabComplete.instence); } - public static void addNetCount(final String pname) { + public static void addNetCount(String pname) { if (netlist.containsKey(pname)) { netlist.put(pname, netlist.get(pname) + 1); } else { @@ -43,24 +42,21 @@ public class NetCommand implements CommandExecutor { @Cmd(aliases = "l") @Help("列出联网的插件详情") @Async - public void list(final CommandArgument e) { - final CommandSender sender = e.getSender(); + public void list(CommandSender sender) { if (netlist.isEmpty()) { sender.sendMessage(no_net); return; } sender.sendMessage(showlist); sender.sendMessage(listprefix); - for (final Entry entry : netlist.entrySet()) { + for (Entry entry : netlist.entrySet()) { sender.sendMessage(String.format(list, entry.getKey(), entry.getValue())); } } @Cmd(minimumArguments = 1) @Help(value = "禁止插件联网", possibleArguments = "[插件名称]") - public void off(final CommandArgument e) { - final String pname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); + public void off(CommandSender sender, String pname) { if (Bukkit.getPluginManager().getPlugin(pname) == null) { sender.sendMessage(String.format(p_n_f, pname)); return; @@ -71,9 +67,7 @@ public class NetCommand implements CommandExecutor { @Cmd(minimumArguments = 1) @Help(value = "允许插件联网", possibleArguments = "[插件名称]") - public void on(final CommandArgument e) { - final String pname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); + public void on(CommandSender sender, String pname) { if (Bukkit.getPluginManager().getPlugin(pname) == null) { sender.sendMessage(String.format(p_n_f, pname)); return; diff --git a/src/main/java/pw/yumc/Yum/commands/PluginTabComplete.java b/src/main/java/pw/yumc/Yum/commands/PluginTabComplete.java index 5279a16..a05cd93 100644 --- a/src/main/java/pw/yumc/Yum/commands/PluginTabComplete.java +++ b/src/main/java/pw/yumc/Yum/commands/PluginTabComplete.java @@ -4,11 +4,11 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import cn.citycraft.PluginHelper.utils.StrKit; import pw.yumc.Yum.api.YumAPI; import pw.yumc.YumCore.commands.CommandArgument; -import pw.yumc.YumCore.commands.CommandExecutor; import pw.yumc.YumCore.commands.annotation.Tab; +import pw.yumc.YumCore.commands.interfaces.CommandExecutor; +import pw.yumc.YumCore.kit.StrKit; /** * @@ -19,21 +19,25 @@ public class PluginTabComplete implements CommandExecutor { public static PluginTabComplete instence = new PluginTabComplete(); @Tab - public List listtab(final CommandArgument e) { - final String[] args = e.getArgs(); + public List listtab(CommandArgument e) { + String[] args = e.getArgs(); if (args[0].equalsIgnoreCase("install") || args[0].equalsIgnoreCase("i")) { return StrKit.copyPartialMatches(args[1], YumAPI.getRepo().getAllPluginName(), new ArrayList()); } else if (args[0].equalsIgnoreCase("repo") || args[0].equalsIgnoreCase("r")) { - if (args.length == 2) { - return StrKit.copyPartialMatches(args[1], Arrays.asList(new String[] { "add", "all", "list", "delall", "clean", "update", "del" }), new ArrayList()); - } - if (args.length == 3 && (args[1] == "add" || args[1] == "del")) { - return StrKit.copyPartialMatches(args[2], YumAPI.getRepo().getRepos().keySet(), new ArrayList()); - } + if (args.length == 2) { return StrKit.copyPartialMatches(args[1], + Arrays.asList(new String[] { "add", "all", "list", "delall", "clean", "update", "del" }), + new ArrayList()); } + if (args.length == 3 && (args[1] == "add" || args[1] == "del")) { return StrKit.copyPartialMatches(args[2], + YumAPI.getRepo().getRepos().keySet(), + new ArrayList()); } } else if (args[0].equalsIgnoreCase("bukkitrepo") || args[0].equalsIgnoreCase("br")) { - return StrKit.copyPartialMatches(args[1], Arrays.asList(new String[] { "look", "install" }), new ArrayList()); + return StrKit.copyPartialMatches(args[1], + Arrays.asList(new String[] { "look", "install" }), + new ArrayList()); } else { - return StrKit.copyPartialMatches(args[1], YumAPI.getPlugman().getPluginNames(false), new ArrayList()); + return StrKit.copyPartialMatches(args[1], + YumAPI.getPlugman().getPluginNames(false), + new ArrayList()); } return null; } diff --git a/src/main/java/pw/yumc/Yum/commands/YumCommand.java b/src/main/java/pw/yumc/Yum/commands/YumCommand.java index 95a6f5c..cc669ba 100644 --- a/src/main/java/pw/yumc/Yum/commands/YumCommand.java +++ b/src/main/java/pw/yumc/Yum/commands/YumCommand.java @@ -3,6 +3,7 @@ package pw.yumc.Yum.commands; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -18,11 +19,6 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; -import cn.citycraft.PluginHelper.callback.CallBack.One; -import cn.citycraft.PluginHelper.kit.ZipKit; -import cn.citycraft.PluginHelper.utils.FileUtil; -import cn.citycraft.PluginHelper.utils.IOUtil; -import cn.citycraft.PluginHelper.utils.StrKit; import pw.yumc.Yum.Yum; import pw.yumc.Yum.api.YumAPI; import pw.yumc.Yum.managers.ConfigManager; @@ -30,14 +26,17 @@ import pw.yumc.Yum.models.BukkitDev; import pw.yumc.Yum.models.BukkitDev.Files; import pw.yumc.Yum.models.BukkitDev.Projects; import pw.yumc.Yum.models.RepoSerialization.Repositories; -import pw.yumc.YumCore.commands.CommandArgument; -import pw.yumc.YumCore.commands.CommandExecutor; +import pw.yumc.YumCore.callback.CallBack.One; import pw.yumc.YumCore.commands.CommandManager; import pw.yumc.YumCore.commands.annotation.Async; import pw.yumc.YumCore.commands.annotation.Cmd; import pw.yumc.YumCore.commands.annotation.Help; import pw.yumc.YumCore.commands.annotation.Sort; +import pw.yumc.YumCore.commands.interfaces.CommandExecutor; +import pw.yumc.YumCore.kit.FileKit; +import pw.yumc.YumCore.kit.HttpKit; import pw.yumc.YumCore.kit.PKit; +import pw.yumc.YumCore.kit.ZipKit; import pw.yumc.YumCore.tellraw.Tellraw; /** @@ -47,36 +46,36 @@ import pw.yumc.YumCore.tellraw.Tellraw; * @author 喵♂呜 */ public class YumCommand implements Listener, CommandExecutor { - private final String prefix = "§6[§bYum §a插件管理§6] "; + private String prefix = "§6[§bYum §a插件管理§6] "; - private final String searchlimit = prefix + "§c为保证搜索速度和准确性 关键词必须大于 3 个字符!"; - private final String searching = prefix + "§a正在从 §eBukkitDev §a获取 §b%s §a的相关数据..."; - private final String not_found_from_bukkit = prefix + "§c未在 §eBukkitDev §c搜索到 §b%s §c的相关插件!"; - private final String result = prefix + "§6关键词 §b%s §6的搜索结果如下:"; - private final String bukkitlistprefix = " §6插件ID §3插件名称 §d发布类型 §a操作"; - private final String bukkitlist = "§6- §e%-6s §b%-25s §d%-10s"; + private String searchlimit = prefix + "§c为保证搜索速度和准确性 关键词必须大于 3 个字符!"; + private String searching = prefix + "§a正在从 §eBukkitDev §a获取 §b%s §a的相关数据..."; + private String not_found_from_bukkit = prefix + "§c未在 §eBukkitDev §c搜索到 §b%s §c的相关插件!"; + private String result = prefix + "§6关键词 §b%s §6的搜索结果如下:"; + private String bukkitlistprefix = " §6插件ID §3插件名称 §d发布类型 §a操作"; + private String bukkitlist = "§6- §e%-6s §b%-25s §d%-10s"; - private final String fsearching = prefix + "§a正在从 §eBukkitDev §a获取ID §b%s §a的文件列表..."; - private final String not_found_id_from_bukkit = prefix + "§c未在 §eBukkitDev §c搜索到ID为 §b%s §c的相关插件!"; - private final String filelistprefix = " §6插件名称 §3游戏版本 §d发布类型 §a操作"; - private final String filelist = "§6- §b%-20s §3%-15s §d%-10s"; + private String fsearching = prefix + "§a正在从 §eBukkitDev §a获取ID §b%s §a的文件列表..."; + private String not_found_id_from_bukkit = prefix + "§c未在 §eBukkitDev §c搜索到ID为 §b%s §c的相关插件!"; + private String filelistprefix = " §6插件名称 §3游戏版本 §d发布类型 §a操作"; + private String filelist = "§6- §b%-20s §3%-15s §d%-10s"; - private final String del = "§c删除: §a插件 §b%s §a版本 §d%s §a已从服务器卸载并删除!"; - private final String delFailed = "§c删除: §a插件 §b%s §c卸载或删除时发生错误 删除失败!"; + private String del = "§c删除: §a插件 §b%s §a版本 §d%s §a已从服务器卸载并删除!"; + private String delFailed = "§c删除: §a插件 §b%s §c卸载或删除时发生错误 删除失败!"; - private final String look = "§6查看"; - private final String install = "§a安装"; - private final String install_tip = "§a点击安装"; - private final String update = "§a更新"; - private final String unload = "§d卸载"; - private final String reload = "§6重载"; - private final String delete = "§c删除"; + private String look = "§6查看"; + private String install = "§a安装"; + private String install_tip = "§a点击安装"; + private String update = "§a更新"; + private String unload = "§d卸载"; + private String reload = "§6重载"; + private String delete = "§c删除"; - private final String unzip_error = prefix + "ZIP文件解压错误!"; + private String unzip_error = prefix + "ZIP文件解压错误!"; Yum main; - public YumCommand(final Yum yum) { + public YumCommand(Yum yum) { main = yum; Bukkit.getPluginManager().registerEvents(this, yum); new CommandManager("yum", this, PluginTabComplete.instence); @@ -84,25 +83,22 @@ public class YumCommand implements Listener, CommandExecutor { @Cmd(aliases = "br", minimumArguments = 2) @Help(value = "从BukkitDev查看安装插件", possibleArguments = "<操作符> <项目ID|项目名称> [地址]") - public void bukkitrepo(final CommandArgument e) { - final String[] args = e.getArgs(); - final CommandSender sender = e.getSender(); + public void bukkitrepo(final CommandSender sender, final String opt, final String id, final String url) { PKit.runTaskAsync(new Runnable() { @Override public void run() { - final String id = args[1]; - switch (args[0]) { + switch (opt) { case "look": { sender.sendMessage(String.format(fsearching, id)); - final List lf = Files.parseList(IOUtil.getData(String.format(BukkitDev.PLUGIN, id))); + List lf = Files.parseList(HttpKit.get(String.format(BukkitDev.PLUGIN, id))); if (lf.isEmpty()) { sender.sendMessage(String.format(not_found_id_from_bukkit, id)); return; } sender.sendMessage(filelistprefix); for (int i = 0; i < lf.size() || i < 8; i++) { - final Files f = lf.get(i); - final Tellraw tr = Tellraw.create(); + Files f = lf.get(i); + Tellraw tr = Tellraw.create(); tr.text(String.format(filelist, f.name, f.gameVersion, f.releaseType)); tr.then(" "); tr.then(install).command(String.format("/yum br ai %s %s", f.name, f.downloadUrl)); @@ -112,19 +108,16 @@ public class YumCommand implements Listener, CommandExecutor { break; } case "ai": { - if (args.length < 3) { - return; - } - final String url = args[2]; - final File file = new File(Bukkit.getUpdateFolderFile(), YumAPI.getDownload().getFileName(url)); - YumAPI.getDownload().run(e.getSender(), url, file, new One() { + if (url == null) { return; } + File file = new File(Bukkit.getUpdateFolderFile(), YumAPI.getDownload().getFileName(url)); + YumAPI.getDownload().run(sender, url, file, new One() { @Override - public void run(final File file) { + public void run(File file) { if (file.getName().endsWith(".zip")) { try { ZipKit.unzip(file, Bukkit.getUpdateFolderFile(), ".jar"); file.delete(); - } catch (final IOException e) { + } catch (IOException e) { sender.sendMessage(unzip_error); } } @@ -136,21 +129,21 @@ public class YumCommand implements Listener, CommandExecutor { case "i": case "install": { sender.sendMessage(String.format(fsearching, id)); - final List lf = Files.parseList(IOUtil.getData(String.format(BukkitDev.PLUGIN, id))); + List lf = Files.parseList(HttpKit.get(String.format(BukkitDev.PLUGIN, id))); if (lf.isEmpty()) { sender.sendMessage(String.format(not_found_id_from_bukkit, id)); return; } - final Files f = lf.get(0); - final String url = f.downloadUrl; - final File file = new File(Bukkit.getUpdateFolderFile(), YumAPI.getDownload().getFileName(url)); - YumAPI.getDownload().run(e.getSender(), url, file, new One() { + Files f = lf.get(0); + String url = f.downloadUrl; + File file = new File(Bukkit.getUpdateFolderFile(), YumAPI.getDownload().getFileName(url)); + YumAPI.getDownload().run(sender, url, file, new One() { @Override - public void run(final File file) { + public void run(File file) { if (file.getName().endsWith(".zip")) { try { ZipKit.unzip(file, Bukkit.getUpdateFolderFile(), ".jar"); - } catch (final IOException e) { + } catch (IOException e) { sender.sendMessage(unzip_error); } } @@ -170,12 +163,10 @@ public class YumCommand implements Listener, CommandExecutor { @Cmd(aliases = "del", minimumArguments = 1) @Help(value = "删除插件", possibleArguments = "<插件名称>") @Sort(6) - public void delete(final CommandArgument e) { - final String pluginname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); - final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); + public void delete(CommandSender sender, String pluginname) { + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); if (plugin != null) { - final String version = StringUtils.substring(plugin.getDescription().getVersion(), 0, 15); + String version = StringUtils.substring(plugin.getDescription().getVersion(), 0, 15); if (YumAPI.getPlugman().deletePlugin(sender, plugin)) { sender.sendMessage(String.format(del, pluginname, version)); } else { @@ -189,12 +180,10 @@ public class YumCommand implements Listener, CommandExecutor { @Cmd(aliases = "ddel", minimumArguments = 1) @Help(value = "删除插件数据文件夹", possibleArguments = "<插件名称>") @Sort(7) - public void dirdelete(final CommandArgument e) { - final String pluginname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); - final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); + public void dirdelete(CommandSender sender, String pluginname) { + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); if (plugin != null) { - FileUtil.deleteDir(sender, plugin.getDataFolder()); + FileKit.deleteDir(sender, plugin.getDataFolder()); } else { sender.sendMessage(pnf(pluginname)); } @@ -203,29 +192,26 @@ public class YumCommand implements Listener, CommandExecutor { @Cmd(aliases = "f", minimumArguments = 1) @Help(value = "通过类名查找插件", possibleArguments = "<插件类名>") @Sort(10) - public void find(final CommandArgument e) { - final String classname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); + public void find(CommandSender sender, String classname) { try { - final Class clazz = Class.forName(classname); - final Field field = clazz.getClassLoader().getClass().getDeclaredField("plugin"); + Class clazz = Class.forName(classname); + Field field = clazz.getClassLoader().getClass().getDeclaredField("plugin"); field.setAccessible(true); - final Plugin plugin = (JavaPlugin) field.get(clazz.getClassLoader()); + Plugin plugin = (JavaPlugin) field.get(clazz.getClassLoader()); Bukkit.dispatchCommand(sender, "yum info " + plugin.getName()); - } catch (final ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e2) { - sender.sendMessage("§4错误: 无法找到类 " + classname + " 所对应的插件信息 异常:" + e2.getClass().getSimpleName() + " " + e2.getMessage() + "!"); + } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e2) { + sender.sendMessage("§4错误: 无法找到类 " + classname + " 所对应的插件信息 异常:" + e2.getClass().getSimpleName() + " " + + e2.getMessage() + "!"); } } @Cmd(aliases = "fdel", minimumArguments = 1) @Help(value = "删除插件以及数据文件夹", possibleArguments = "<插件名称>") @Sort(7) - public void fulldelete(final CommandArgument e) { - final String pluginname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); - final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); + public void fulldelete(CommandSender sender, String pluginname) { + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); if (plugin != null) { - final String version = StringUtils.substring(plugin.getDescription().getVersion(), 0, 15); + String version = StringUtils.substring(plugin.getDescription().getVersion(), 0, 15); if (YumAPI.getPlugman().fullDeletePlugin(sender, plugin)) { sender.sendMessage(String.format(del, pluginname, version)); } else { @@ -240,24 +226,22 @@ public class YumCommand implements Listener, CommandExecutor { @Help(value = "查看插件详情", possibleArguments = "<插件名称>") @Sort(2) @Async - public void info(final CommandArgument e) { - final String pluginname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); - final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); + public void info(CommandSender sender, String pluginname) { + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); if (plugin != null) { - final PluginDescriptionFile desc = plugin.getDescription(); + PluginDescriptionFile desc = plugin.getDescription(); sender.sendMessage("§6插件名称: §3" + plugin.getName()); sender.sendMessage("§6插件版本: §3" + StringUtils.substring(plugin.getDescription().getVersion(), 0, 15)); sender.sendMessage("§6插件作者: §3" + StringUtils.join(desc.getAuthors(), " ")); sender.sendMessage("§6插件描述: §3" + (desc.getDescription() == null ? "无" : desc.getDescription())); sender.sendMessage("§6插件依赖: §3" + (desc.getDepend().isEmpty() ? "无" : "")); - StrKit.sendStringArray(sender, desc.getDepend(), "§6 - §a"); + sendStringArray(sender, desc.getDepend(), "§6 - §a"); sender.sendMessage("§6插件软依赖: §3" + (desc.getSoftDepend().isEmpty() ? "无" : "")); - StrKit.sendStringArray(sender, desc.getSoftDepend(), "§6 - §a"); - final Map> clist = desc.getCommands(); + sendStringArray(sender, desc.getSoftDepend(), "§6 - §a"); + Map> clist = desc.getCommands(); if (clist != null) { sender.sendMessage("§6插件注册命令: §3" + (clist.isEmpty() ? "无" : "")); - for (final Entry> entry : clist.entrySet()) { + for (Entry> entry : clist.entrySet()) { sender.sendMessage("§6 - §a" + entry.getKey()); sendEntryList(sender, "§6 别名: §a", entry.getValue(), "aliases"); sendEntry(sender, "§6 描述: §a", entry.getValue(), "description"); @@ -265,11 +249,12 @@ public class YumCommand implements Listener, CommandExecutor { sendEntry(sender, "§6 用法: §a", entry.getValue(), "usage"); } } - final List plist = desc.getPermissions(); + List plist = desc.getPermissions(); if (plist != null) { sender.sendMessage("§6插件注册权限: " + (plist.isEmpty() ? "无" : "")); - for (final Permission perm : plist) { - sender.sendMessage("§6 - §a" + perm.getName() + "§6 - §e" + (perm.getDescription().isEmpty() ? "无描述" : perm.getDescription())); + for (Permission perm : plist) { + sender.sendMessage("§6 - §a" + perm.getName() + "§6 - §e" + + (perm.getDescription().isEmpty() ? "无描述" : perm.getDescription())); } } sender.sendMessage("§6插件物理路径: §3" + YumAPI.getPlugman().getPluginFile(plugin).getAbsolutePath()); @@ -281,19 +266,16 @@ public class YumCommand implements Listener, CommandExecutor { @Cmd(aliases = "i", minimumArguments = 1) @Help(value = "安装插件", possibleArguments = "<插件名称>") @Sort(12) - public void install(final CommandArgument e) { - final String[] args = e.getArgs(); - final CommandSender sender = e.getSender(); - final String pluginname = args[0]; - final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); + public void install(final CommandSender sender, final String pluginname, final String pluginversion) { + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); if (plugin == null) { Bukkit.getScheduler().runTaskAsynchronously(main, new Runnable() { @Override public void run() { - if (args.length < 2) { + if (pluginversion == null) { YumAPI.installFromYum(sender, pluginname); } else { - YumAPI.installFromYum(sender, pluginname, args[1]); + YumAPI.installFromYum(sender, pluginname, pluginversion); } } }); @@ -306,12 +288,11 @@ public class YumCommand implements Listener, CommandExecutor { @Help(value = "列出已安装插件列表") @Sort(1) @Async - public void list(final CommandArgument e) { - final CommandSender sender = e.getSender(); + public void list(CommandSender sender) { sender.sendMessage("§6[Yum仓库]§3服务器已安装插件: "); - for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - final String pname = plugin.getName(); - final Tellraw fm = Tellraw.create(); + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + String pname = plugin.getName(); + Tellraw fm = Tellraw.create(); fm.text(String.format("§6- %-32s", YumAPI.getPlugman().getFormattedName(plugin, true))); fm.then(" "); fm.then(update).cmd_tip("/yum u " + pname, update); @@ -328,10 +309,8 @@ public class YumCommand implements Listener, CommandExecutor { @Cmd(minimumArguments = 1) @Help(value = "载入插件", possibleArguments = "<插件名称>") @Sort(3) - public void load(final CommandArgument e) { - final CommandSender sender = e.getSender(); - final String pluginname = e.getArgs()[0]; - final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); + public void load(CommandSender sender, String pluginname) { + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); if (plugin == null) { YumAPI.getPlugman().load(sender, pluginname); } else { @@ -340,7 +319,7 @@ public class YumCommand implements Listener, CommandExecutor { } @EventHandler - public void onAdminJoin(final PlayerJoinEvent e) { + public void onAdminJoin(PlayerJoinEvent e) { if (e.getPlayer().isOp()) { YumAPI.updateCheck(e.getPlayer()); } @@ -349,19 +328,17 @@ public class YumCommand implements Listener, CommandExecutor { @Cmd(aliases = "re") @Help(value = "重载插件", possibleArguments = "<插件名称|all|*>") @Sort(5) - public void reload(final CommandArgument e) { - final CommandSender sender = e.getSender(); - if (e.getArgs().length == 0) { + public void reload(CommandSender sender, String pluginname) { + if (pluginname == null) { ConfigManager.i().reload(); sender.sendMessage("§6重载: §a配置文件已重载!"); return; } - final String pluginname = e.getArgs()[0]; if (pluginname.equalsIgnoreCase("all") || pluginname.equalsIgnoreCase("*")) { YumAPI.getPlugman().reloadAll(sender); return; } - final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); if (plugin != null) { YumAPI.getPlugman().reload(sender, plugin); } else { @@ -373,15 +350,12 @@ public class YumCommand implements Listener, CommandExecutor { @Help(value = "插件源命令", possibleArguments = " <仓库名称>") @Sort(16) @Async - public void repo(final CommandArgument e) { - final String[] args = e.getArgs(); - final CommandSender sender = e.getSender(); - final String cmd = args[0]; + public void repo(CommandSender sender, String cmd, String arg1) { switch (cmd) { case "add": - if (args.length == 2) { - if (YumAPI.getRepo().addRepositories(sender, args[1])) { - final String reponame = YumAPI.getRepo().getRepoCache(args[1]).name; + if (arg1 != null) { + if (YumAPI.getRepo().addRepositories(sender, arg1)) { + String reponame = YumAPI.getRepo().getRepoCache(arg1).name; sender.sendMessage("§6仓库: §a源仓库 §e" + reponame + " §a的插件信息已缓存!"); } else { sender.sendMessage("§6仓库: §c源地址未找到仓库信息或当前地址已缓存!"); @@ -391,10 +365,10 @@ public class YumCommand implements Listener, CommandExecutor { } break; case "del": - if (args.length == 2) { - final Repositories delrepo = YumAPI.getRepo().getRepoCache(args[1]); + if (arg1 != null) { + Repositories delrepo = YumAPI.getRepo().getRepoCache(arg1); if (delrepo != null) { - YumAPI.getRepo().delRepositories(sender, args[1]); + YumAPI.getRepo().delRepositories(sender, arg1); sender.sendMessage("§6仓库: §a源仓库 §e" + delrepo.name + " §c已删除 §a请使用 §b/yum repo update §a更新缓存!"); } else { sender.sendMessage("§6仓库: §c源地址未找到!"); @@ -409,11 +383,11 @@ public class YumCommand implements Listener, CommandExecutor { break; case "list": sender.sendMessage("§6仓库: §b缓存的插件信息如下 "); - StrKit.sendStringArray(sender, YumAPI.getRepo().getAllPluginsInfo()); + sendStringArray(sender, YumAPI.getRepo().getAllPluginsInfo()); break; case "all": sender.sendMessage("§6仓库: §b缓存的仓库信息如下 "); - StrKit.sendStringArray(sender, YumAPI.getRepo().getRepoCache().getAllRepoInfo()); + sendStringArray(sender, YumAPI.getRepo().getRepoCache().getAllRepoInfo()); break; case "clean": YumAPI.getRepo().clean(); @@ -430,23 +404,21 @@ public class YumCommand implements Listener, CommandExecutor { @Help(value = "从BukkitDev搜索插件", possibleArguments = "插件名称") @Sort(11) @Async - public void search(final CommandArgument e) { - final String pname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); + public void search(CommandSender sender, String pname) { if (pname.length() < 3) { sender.sendMessage(searchlimit); return; } sender.sendMessage(String.format(searching, pname)); - final List list = Projects.parseList(IOUtil.getData(String.format(BukkitDev.SEARCH, pname.toLowerCase()))); + List list = Projects.parseList(HttpKit.get(String.format(BukkitDev.SEARCH, pname.toLowerCase()))); if (list.isEmpty()) { sender.sendMessage(String.format(not_found_from_bukkit, pname)); return; } sender.sendMessage(String.format(result, pname)); sender.sendMessage(bukkitlistprefix); - for (final Projects p : list) { - final Tellraw fm = Tellraw.create(); + for (Projects p : list) { + Tellraw fm = Tellraw.create(); fm.text(String.format(bukkitlist, p.id, p.name, p.stage)); fm.then(" "); fm.then(look).cmd_tip("/yum br look " + p.id, look); @@ -457,10 +429,8 @@ public class YumCommand implements Listener, CommandExecutor { @Cmd(minimumArguments = 1) @Help(value = "卸载插件", possibleArguments = "<插件名称>") @Sort(4) - public void unload(final CommandArgument e) { - final String pluginname = e.getArgs()[0]; - final CommandSender sender = e.getSender(); - final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); + public void unload(CommandSender sender, String pluginname) { + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); if (plugin != null) { YumAPI.getPlugman().unload(sender, plugin); } else { @@ -472,9 +442,8 @@ public class YumCommand implements Listener, CommandExecutor { @Help(value = "更新插件或缓存", possibleArguments = "[插件名称] [插件版本]") @Sort(13) @Async - public void update(final CommandArgument e) { - final String[] args = e.getArgs(); - final CommandSender sender = e.getSender(); + public void update(CommandSender sender, String argstring) { + String[] args = argstring.split(" "); switch (args.length) { case 0: YumAPI.getRepo().updateRepositories(sender); @@ -482,8 +451,8 @@ public class YumCommand implements Listener, CommandExecutor { break; case 1: case 2: - final String pluginname = args[0]; - final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); + String pluginname = args[0]; + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); sender.sendMessage("§a开始更新插件: " + pluginname); if (plugin != null) { if (args.length < 2) { @@ -503,31 +472,29 @@ public class YumCommand implements Listener, CommandExecutor { @Cmd(aliases = "ua") @Help("更新所有可更新插件") @Sort(14) - public void updateall(final CommandArgument e) { - YumAPI.updateAll(e.getSender()); + public void updateall(CommandSender sender) { + YumAPI.updateAll(sender); } @Cmd(aliases = "ug") @Help(value = "升级或安装插件", possibleArguments = "[插件名称]") @Sort(15) - public void upgrade(final CommandArgument e) { - final String[] args = e.getArgs(); - final CommandSender sender = e.getSender(); - if (args.length == 0) { + public void upgrade(CommandSender sender, String pluginname) { + if (pluginname == null) { YumAPI.getPlugman().upgrade(sender); } else { - final String pluginname = args[0]; - final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); + Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); sender.sendMessage("§a开始升级插件: §b" + pluginname); if (plugin != null) { YumAPI.upgrade(sender, plugin); } else { - sender.sendMessage("§c错误: §b插件 " + pluginname + " §c未安装或已卸载 需要安装请使用 §b/yum install " + pluginname + "!"); + sender.sendMessage( + "§c错误: §b插件 " + pluginname + " §c未安装或已卸载 需要安装请使用 §b/yum install " + pluginname + "!"); } } } - private String pnf(final String pname) { + private String pnf(String pname) { return String.format("§4错误: §c插件 §b %s §c不存在或已卸载!", pname); } @@ -543,8 +510,8 @@ public class YumCommand implements Listener, CommandExecutor { * @param key * 实体Key */ - private void sendEntry(final CommandSender sender, final String prefix, final Map map, final String key) { - final Object value = map.get(key); + private void sendEntry(CommandSender sender, String prefix, Map map, String key) { + Object value = map.get(key); if (value != null) { sender.sendMessage(prefix + (String) value); } @@ -563,13 +530,60 @@ public class YumCommand implements Listener, CommandExecutor { * 实体Key */ @SuppressWarnings("unchecked") - private void sendEntryList(final CommandSender sender, final String prefix, final Map map, final String key) { - final List values = (List) map.get(key); + private void sendEntryList(CommandSender sender, String prefix, Map map, String key) { + List values = (List) map.get(key); if (values != null) { - for (final String value : values) { + for (String value : values) { sender.sendMessage(prefix + value); } } } + /** + * 给玩家或控制台发送消息组 + * + * @param sender + * 接收消息的玩家 + * @param msg + * 消息组 + */ + public static void sendStringArray(CommandSender sender, Collection msg) { + for (String string : msg) { + sender.sendMessage(string); + } + } + + /** + * 给玩家或控制台发送消息组 + * + * @param sender + * 接收消息的玩家 + * @param msg + * 消息组 + * @param prefix + * 消息前缀 + */ + public static void sendStringArray(CommandSender sender, Collection msg, String prefix) { + for (String string : msg) { + sender.sendMessage(prefix + string); + } + } + + /** + * 给玩家或控制台发送消息组 + * + * @param sender + * 接收消息的玩家 + * @param msg + * 消息组 + * @param prefix + * 消息前缀 + * @param suffix + * 消息后缀 + */ + public static void sendStringArray(CommandSender sender, Collection msg, String prefix, String suffix) { + for (String string : msg) { + sender.sendMessage(prefix + string + suffix); + } + } } diff --git a/src/main/java/pw/yumc/Yum/events/PluginNetworkEvent.java b/src/main/java/pw/yumc/Yum/events/PluginNetworkEvent.java index fce7381..3cb60db 100644 --- a/src/main/java/pw/yumc/Yum/events/PluginNetworkEvent.java +++ b/src/main/java/pw/yumc/Yum/events/PluginNetworkEvent.java @@ -9,10 +9,10 @@ import org.bukkit.plugin.Plugin; public class PluginNetworkEvent extends Event implements Cancellable { - private static final HandlerList handlers = new HandlerList(); + private static HandlerList handlers = new HandlerList(); - private final boolean isPrimaryThread; - private final Plugin plugin; + private boolean isPrimaryThread; + private Plugin plugin; private boolean cancel; private URI url; @@ -30,7 +30,7 @@ public class PluginNetworkEvent extends Event implements Cancellable { * @param isMainThread * 是否为主线程 */ - public PluginNetworkEvent(final Plugin plugin, final URI url, final boolean isPrimaryThread) { + public PluginNetworkEvent(Plugin plugin, URI url, boolean isPrimaryThread) { this.plugin = plugin; this.url = url; this.isPrimaryThread = isPrimaryThread; @@ -68,7 +68,7 @@ public class PluginNetworkEvent extends Event implements Cancellable { } @Override - public void setCancelled(final boolean value) { + public void setCancelled(boolean value) { cancel = value; } @@ -76,7 +76,7 @@ public class PluginNetworkEvent extends Event implements Cancellable { * @param url * 设置新的URL地址 */ - public void setUrl(final URI url) { + public void setUrl(URI url) { this.url = url; } diff --git a/src/main/java/pw/yumc/Yum/ext/BukkitUpdater.java b/src/main/java/pw/yumc/Yum/ext/BukkitUpdater.java index 2ea893a..93c0bb2 100644 --- a/src/main/java/pw/yumc/Yum/ext/BukkitUpdater.java +++ b/src/main/java/pw/yumc/Yum/ext/BukkitUpdater.java @@ -1,6 +1,5 @@ /* * Updater for Bukkit. - * * This class provides the means to safely and easily update a plugin, or check to see if it is updated using dev.bukkit.org */ @@ -46,20 +45,20 @@ import org.json.simple.JSONValue; */ public class BukkitUpdater extends Updater { - private static final String TITLE_VALUE = "name"; // Gets remote file's title - private static final String LINK_VALUE = "downloadUrl"; // Gets remote file's download link - private static final String TYPE_VALUE = "releaseType"; // Gets remote file's release type + private static String TITLE_VALUE = "name"; // Gets remote file's title + private static String LINK_VALUE = "downloadUrl"; // Gets remote file's download link + private static String TYPE_VALUE = "releaseType"; // Gets remote file's release type - private static final String VERSION_VALUE = "gameVersion"; // Gets remote file's build version - private static final Object FILE_NAME = "fileName"; // Gets remote file's name - private static final String QUERY = "/servermods/files?projectIds="; // Path to GET - private static final String HOST = "https://api.curseforge.com"; // Slugs will be appended to this to get to the project's RSS feed + private static String VERSION_VALUE = "gameVersion"; // Gets remote file's build version + private static Object FILE_NAME = "fileName"; // Gets remote file's name + private static String QUERY = "/servermods/files?projectIds="; // Path to GET + private static String HOST = "https://api.curseforge.com"; // Slugs will be appended to this to get to the project's RSS feed - private static final int BYTE_SIZE = 1024; // Used for downloading files + private static int BYTE_SIZE = 1024; // Used for downloading files // Update information - // private static final String BUKKIT_DEV_SLUG = "protocollib"; - // private static final int BUKKIT_DEV_ID = 45564; + // private static String BUKKIT_DEV_SLUG = "protocollib"; + // private static int BUKKIT_DEV_ID = 45564; private URL url; // Connecting to RSS private File file; // The plugin's file @@ -88,18 +87,18 @@ public class BukkitUpdater extends Updater { * @param announce * True if the program should announce the progress of new updates in console */ - public BukkitUpdater(final Plugin plugin, final int id, final File file, final UpdateType type, final boolean announce) { + public BukkitUpdater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { super(plugin, type, announce); this.file = file; this.id = id; this.updateFolder = plugin.getServer().getUpdateFolder(); - final File dataFolder = plugin.getDataFolder(); + File dataFolder = plugin.getDataFolder(); if (dataFolder != null) { - final File pluginFile = plugin.getDataFolder().getParentFile(); - final File updaterFile = new File(pluginFile, "Updater"); - final File updaterConfigFile = new File(updaterFile, "config.yml"); + File pluginFile = plugin.getDataFolder().getParentFile(); + File updaterFile = new File(pluginFile, "Updater"); + File updaterConfigFile = new File(updaterFile, "config.yml"); if (!updaterFile.exists()) { updaterFile.mkdir(); @@ -107,8 +106,9 @@ public class BukkitUpdater extends Updater { if (!updaterConfigFile.exists()) { try { updaterConfigFile.createNewFile(); - } catch (final IOException e) { - plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath()); + } catch (IOException e) { + plugin.getLogger().severe( + "The updater could not create a configuration in " + updaterFile.getAbsolutePath()); e.printStackTrace(); } } @@ -128,8 +128,9 @@ public class BukkitUpdater extends Updater { this.config.options().copyDefaults(true); try { this.config.save(updaterConfigFile); - } catch (final IOException e) { - plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath()); + } catch (IOException e) { + plugin.getLogger().severe( + "The updater could not save the configuration in " + updaterFile.getAbsolutePath()); e.printStackTrace(); } } @@ -149,7 +150,7 @@ public class BukkitUpdater extends Updater { try { this.url = new URL(BukkitUpdater.HOST + BukkitUpdater.QUERY + id); - } catch (final MalformedURLException e) { + } catch (MalformedURLException e) { plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid."); this.result = UpdateResult.FAIL_BADID; e.printStackTrace(); @@ -166,7 +167,7 @@ public class BukkitUpdater extends Updater { */ /* * private boolean hasTag(String version) { - * for (final String string : BukkitUpdater.NO_UPDATE_TAG) { + * for (String string : BukkitUpdater.NO_UPDATE_TAG) { * if (version.contains(string)) { * return true; * } @@ -177,7 +178,7 @@ public class BukkitUpdater extends Updater { public boolean read() { try { - final URLConnection conn = this.url.openConnection(); + URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { @@ -186,10 +187,10 @@ public class BukkitUpdater extends Updater { conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); conn.setDoOutput(true); - final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); - final String response = reader.readLine(); + BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String response = reader.readLine(); - final JSONArray array = (JSONArray) JSONValue.parse(response); + JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); @@ -197,7 +198,7 @@ public class BukkitUpdater extends Updater { return false; } - final JSONObject jsonObject = (JSONObject) array.get(array.size() - 1); + JSONObject jsonObject = (JSONObject) array.get(array.size() - 1); this.versionFileName = (String) jsonObject.get(BukkitUpdater.FILE_NAME); this.versionName = (String) jsonObject.get(BukkitUpdater.TITLE_VALUE); this.versionLink = (String) jsonObject.get(BukkitUpdater.LINK_VALUE); @@ -205,14 +206,16 @@ public class BukkitUpdater extends Updater { this.versionGameVersion = (String) jsonObject.get(BukkitUpdater.VERSION_VALUE); return true; - } catch (final IOException e) { + } catch (IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { - this.plugin.getLogger().warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); + this.plugin.getLogger().warning( + "dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating."); - this.plugin.getLogger().warning("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); + this.plugin.getLogger().warning( + "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } e.printStackTrace(); @@ -228,7 +231,7 @@ public class BukkitUpdater extends Updater { * - the update type. */ @Override - public void start(final UpdateType type) { + public void start(UpdateType type) { waitForThread(); this.type = type; @@ -239,11 +242,9 @@ public class BukkitUpdater extends Updater { /** * Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip. */ - private boolean pluginFile(final String name) { - for (final File file : new File("plugins").listFiles()) { - if (file.getName().equals(name)) { - return true; - } + private boolean pluginFile(String name) { + for (File file : new File("plugins").listFiles()) { + if (file.getName().equals(name)) { return true; } } return false; } @@ -251,7 +252,7 @@ public class BukkitUpdater extends Updater { /** * Save an update from dev.bukkit.org into the server's update folder. */ - private void saveFile(final File folder, final String file, final String u) { + private void saveFile(File folder, String file, String u) { if (!folder.exists()) { folder.mkdir(); } @@ -259,12 +260,12 @@ public class BukkitUpdater extends Updater { FileOutputStream fout = null; try { // Download the file - final URL url = new URL(u); - final int fileLength = url.openConnection().getContentLength(); + URL url = new URL(u); + int fileLength = url.openConnection().getContentLength(); in = new BufferedInputStream(url.openStream()); fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file); - final byte[] data = new byte[BukkitUpdater.BYTE_SIZE]; + byte[] data = new byte[BukkitUpdater.BYTE_SIZE]; int count; if (this.announce) { this.plugin.getLogger().info("About to download a new update: " + this.versionName); @@ -273,19 +274,19 @@ public class BukkitUpdater extends Updater { while ((count = in.read(data, 0, BukkitUpdater.BYTE_SIZE)) != -1) { downloaded += count; fout.write(data, 0, count); - final int percent = (int) ((downloaded * 100) / fileLength); + int percent = (int) ((downloaded * 100) / fileLength); if (this.announce && ((percent % 10) == 0)) { this.plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); } } // Just a quick check to make sure we didn't leave any files from last time... - for (final File xFile : new File(this.plugin.getDataFolder().getParent(), this.updateFolder).listFiles()) { + for (File xFile : new File(this.plugin.getDataFolder().getParent(), this.updateFolder).listFiles()) { if (xFile.getName().endsWith(".zip")) { xFile.delete(); } } // Check to see if it's a zip file, if it is, unzip it. - final File dFile = new File(folder.getAbsolutePath() + "/" + file); + File dFile = new File(folder.getAbsolutePath() + "/" + file); if (dFile.getName().endsWith(".zip")) { // Unzip this.unzip(dFile.getCanonicalPath()); @@ -293,7 +294,7 @@ public class BukkitUpdater extends Updater { if (this.announce) { this.plugin.getLogger().info("Finished updating."); } - } catch (final Exception ex) { + } catch (Exception ex) { this.plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful."); this.result = BukkitUpdater.UpdateResult.FAIL_DOWNLOAD; } finally { @@ -304,7 +305,7 @@ public class BukkitUpdater extends Updater { if (fout != null) { fout.close(); } - } catch (final Exception ex) { + } catch (Exception ex) { } } } @@ -312,10 +313,10 @@ public class BukkitUpdater extends Updater { /** * Part of Zip-File-Extractor, modified by Gravity for use with Bukkit */ - private void unzip(final String file) { + private void unzip(String file) { try { - final File fSourceZip = new File(file); - final String zipPath = file.substring(0, file.length() - 4); + File fSourceZip = new File(file); + String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration e = zipFile.entries(); while (e.hasMoreElements()) { @@ -325,20 +326,21 @@ public class BukkitUpdater extends Updater { if (entry.isDirectory()) { continue; } - final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); + BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; - final byte buffer[] = new byte[BukkitUpdater.BYTE_SIZE]; - final FileOutputStream fos = new FileOutputStream(destinationFilePath); - final BufferedOutputStream bos = new BufferedOutputStream(fos, BukkitUpdater.BYTE_SIZE); + byte buffer[] = new byte[BukkitUpdater.BYTE_SIZE]; + FileOutputStream fos = new FileOutputStream(destinationFilePath); + BufferedOutputStream bos = new BufferedOutputStream(fos, BukkitUpdater.BYTE_SIZE); while ((b = bis.read(buffer, 0, BukkitUpdater.BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); - final String name = destinationFilePath.getName(); + String name = destinationFilePath.getName(); if (name.endsWith(".jar") && this.pluginFile(name)) { - destinationFilePath.renameTo(new File(this.plugin.getDataFolder().getParent(), this.updateFolder + "/" + name)); + destinationFilePath.renameTo( + new File(this.plugin.getDataFolder().getParent(), this.updateFolder + "/" + name)); } entry = null; destinationFilePath = null; @@ -348,15 +350,15 @@ public class BukkitUpdater extends Updater { zipFile = null; // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. - for (final File dFile : new File(zipPath).listFiles()) { + for (File dFile : new File(zipPath).listFiles()) { if (dFile.isDirectory()) { if (this.pluginFile(dFile.getName())) { - final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // Get current dir - final File[] contents = oFile.listFiles(); // List of existing files in the current dir - for (final File cFile : dFile.listFiles()) // Loop through all the files in the new dir + File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // Get current dir + File[] contents = oFile.listFiles(); // List of existing files in the current dir + for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir { boolean found = false; - for (final File xFile : contents) // Loop through contents to see if it exists + for (File xFile : contents) // Loop through contents to see if it exists { if (xFile.getName().equals(cFile.getName())) { found = true; @@ -377,7 +379,7 @@ public class BukkitUpdater extends Updater { } new File(zipPath).delete(); fSourceZip.delete(); - } catch (final IOException ex) { + } catch (IOException ex) { this.plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); this.result = BukkitUpdater.UpdateResult.FAIL_DOWNLOAD; ex.printStackTrace(); @@ -398,11 +400,11 @@ public class BukkitUpdater extends Updater { } } } - } catch (final Exception e) { + } catch (Exception e) { // Any generic error will be handled here } finally { // Invoke the listeners on the main thread - for (final Runnable listener : listeners) { + for (Runnable listener : listeners) { plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, listener); } } @@ -410,8 +412,8 @@ public class BukkitUpdater extends Updater { private void performUpdate() { if ((BukkitUpdater.this.versionLink != null) && (BukkitUpdater.this.type != UpdateType.NO_DOWNLOAD)) { - final File pluginFolder = plugin.getDataFolder().getParentFile(); - final File destinationFolder = new File(pluginFolder, updateFolder); + File pluginFolder = plugin.getDataFolder().getParentFile(); + File destinationFolder = new File(pluginFolder, updateFolder); String name = BukkitUpdater.this.file.getName(); // If it's a zip file, it shouldn't be downloaded as the plugin's name diff --git a/src/main/java/pw/yumc/Yum/ext/SpigotUpdater.java b/src/main/java/pw/yumc/Yum/ext/SpigotUpdater.java index 26b93c3..bfb9efd 100644 --- a/src/main/java/pw/yumc/Yum/ext/SpigotUpdater.java +++ b/src/main/java/pw/yumc/Yum/ext/SpigotUpdater.java @@ -33,21 +33,22 @@ import com.google.common.io.Closer; * @author dmulloy2 */ -public final class SpigotUpdater extends Updater { - private static final String PROTOCOL = "https://"; +public class SpigotUpdater extends Updater { + private static String PROTOCOL = "https://"; - private static final String RESOURCE_URL = PROTOCOL + "www.spigotmc.org/resources/protocollib.1997/"; + private static String RESOURCE_URL = PROTOCOL + "www.spigotmc.org/resources/protocollib.1997/"; - private static final String API_URL = PROTOCOL + "www.spigotmc.org/api/general.php"; + private static String API_URL = PROTOCOL + "www.spigotmc.org/api/general.php"; - private static final String ACTION = "POST"; + private static String ACTION = "POST"; - private static final int ID = 1997; + private static int ID = 1997; - private static final byte[] API_KEY = ("key=98BE0FE67F88AB82B4C197FAF1DC3B69206EFDCC4D3B80FC83A00037510B99B4&resource=" + ID).getBytes(Charsets.UTF_8); + private static byte[] API_KEY = ("key=98BE0FE67F88AB82B4C197FAF1DC3B69206EFDCC4D3B80FC83A00037510B99B4&resource=" + + ID).getBytes(Charsets.UTF_8); private String remoteVersion; - public SpigotUpdater(final Plugin plugin, final UpdateType type, final boolean announce) { + public SpigotUpdater(Plugin plugin, UpdateType type, boolean announce) { super(plugin, type, announce); } @@ -63,15 +64,15 @@ public final class SpigotUpdater extends Updater { } public String getSpigotVersion() throws IOException { - final Closer closer = Closer.create(); + Closer closer = Closer.create(); try { - final HttpURLConnection con = (HttpURLConnection) new URL(API_URL).openConnection(); + HttpURLConnection con = (HttpURLConnection) new URL(API_URL).openConnection(); con.setDoOutput(true); con.setRequestMethod(ACTION); con.getOutputStream().write(API_KEY); - final InputStreamReader isr = closer.register(new InputStreamReader(con.getInputStream())); - final BufferedReader br = closer.register(new BufferedReader(isr)); + InputStreamReader isr = closer.register(new InputStreamReader(con.getInputStream())); + BufferedReader br = closer.register(new BufferedReader(isr)); return br.readLine(); } finally { closer.close(); @@ -79,7 +80,7 @@ public final class SpigotUpdater extends Updater { } @Override - public void start(final UpdateType type) { + public void start(UpdateType type) { waitForThread(); this.type = type; this.thread = new Thread(new SpigotUpdateRunnable()); @@ -90,17 +91,17 @@ public final class SpigotUpdater extends Updater { @Override public void run() { try { - final String version = getSpigotVersion(); + String version = getSpigotVersion(); remoteVersion = version; if (versionCheck(version)) { result = UpdateResult.SPIGOT_UPDATE_AVAILABLE; } else { result = UpdateResult.NO_UPDATE; } - } catch (final Throwable ex) { + } catch (Throwable ex) { } finally { // Invoke the listeners on the main thread - for (final Runnable listener : listeners) { + for (Runnable listener : listeners) { plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, listener); } } diff --git a/src/main/java/pw/yumc/Yum/ext/Updater.java b/src/main/java/pw/yumc/Yum/ext/Updater.java index 965f84e..9df7f95 100644 --- a/src/main/java/pw/yumc/Yum/ext/Updater.java +++ b/src/main/java/pw/yumc/Yum/ext/Updater.java @@ -45,7 +45,7 @@ public abstract class Updater { protected List listeners = new CopyOnWriteArrayList(); - public static Updater create(final Plugin protocolLib, final int id, final File file, final UpdateType type, final boolean announce) { + public static Updater create(Plugin protocolLib, int id, File file, UpdateType type, boolean announce) { // if (Util.isUsingSpigot()) { return new SpigotUpdater(protocolLib, type, announce); // } else { @@ -53,7 +53,7 @@ public abstract class Updater { // } } - protected Updater(final Plugin plugin, final UpdateType type, final boolean announce) { + protected Updater(Plugin plugin, UpdateType type, boolean announce) { this.plugin = plugin; this.type = type; this.announce = announce; @@ -67,7 +67,7 @@ public abstract class Updater { * @param listener * - the listener to add. */ - public void addListener(final Runnable listener) { + public void addListener(Runnable listener) { listeners.add(Preconditions.checkNotNull(listener, "listener cannot be NULL")); } @@ -129,7 +129,7 @@ public abstract class Updater { * - the listener to remove. * @return TRUE if the listener was removed, FALSE otherwise. */ - public boolean removeListener(final Runnable listener) { + public boolean removeListener(Runnable listener) { return listeners.remove(listener); } @@ -146,7 +146,7 @@ public abstract class Updater { public abstract void start(UpdateType type); - public boolean versionCheck(final String title) { + public boolean versionCheck(String title) { if (this.type != UpdateType.NO_VERSION_CHECK) { String version = this.plugin.getDescription().getVersion(); @@ -156,7 +156,7 @@ public abstract class Updater { version = version.substring(0, version.indexOf("-")); } - final String[] splitTitle = title.split(" "); + String[] splitTitle = title.split(" "); String remoteVersion; if (splitTitle.length == 2) { @@ -165,9 +165,13 @@ public abstract class Updater { remoteVersion = splitTitle[0]; } else { // The file's name did not contain the string 'vVersion' - final String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; - this.plugin.getLogger().warning("The author of this plugin " + authorInfo + " has misconfigured their Auto Update system"); - this.plugin.getLogger().warning("File versions should follow the format 'PluginName VERSION[-SNAPSHOT]'"); + String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? "" + : " (" + this.plugin.getDescription().getAuthors().get(0) + ")"; + this.plugin.getLogger().warning( + "The author of this plugin " + authorInfo + " has misconfigured their Auto Update system"); + this.plugin + .getLogger() + .warning("File versions should follow the format 'PluginName VERSION[-SNAPSHOT]'"); this.plugin.getLogger().warning("Please notify the author of this error."); this.result = BukkitUpdater.UpdateResult.FAIL_NOVERSION; return false; @@ -178,7 +182,7 @@ public abstract class Updater { remoteVersion = remoteVersion.substring(1); } - final String localVersion = plugin.getDescription().getVersion(); + String localVersion = plugin.getDescription().getVersion(); if (devBuild && remoteVersion.equals(localVersion)) { // They're using a dev build and this version has been released @@ -196,7 +200,7 @@ public abstract class Updater { if (thread != null && thread.isAlive()) { try { thread.join(); - } catch (final InterruptedException ex) { + } catch (InterruptedException ex) { ex.printStackTrace(); } } @@ -255,9 +259,9 @@ public abstract class Updater { */ SPIGOT_UPDATE_AVAILABLE("The updater found an update: %s (Running %s). Download at %s"); - private final String description; + private String description; - private UpdateResult(final String description) { + private UpdateResult(String description) { this.description = description; } diff --git a/src/main/java/pw/yumc/Yum/inject/CommandInjector.java b/src/main/java/pw/yumc/Yum/inject/CommandInjector.java index 136db59..954e6b4 100644 --- a/src/main/java/pw/yumc/Yum/inject/CommandInjector.java +++ b/src/main/java/pw/yumc/Yum/inject/CommandInjector.java @@ -15,81 +15,79 @@ import org.bukkit.command.TabExecutor; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; -import cn.citycraft.PluginHelper.ext.kit.Reflect; -import cn.citycraft.PluginHelper.kit.StrKit; import pw.yumc.Yum.commands.MonitorCommand; import pw.yumc.Yum.managers.MonitorManager; +import pw.yumc.YumCore.kit.StrKit; +import pw.yumc.YumCore.reflect.Reflect; public class CommandInjector implements TabExecutor { - private final static String prefix = "§6[§bYum §a命令监控§6] "; - private final static String warn = "§c注意! §6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6命令 §c耗时 §4%sms §c平均耗时 §4%sms!"; - private final static String err = prefix + "§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6命令时发生异常!"; - private final static String inject_error = prefix + "§6插件 §b%s §c注入能耗监控失败!"; - private final static String plugin_is_null = "插件不得为NULL!"; - private final CommandExecutor originalExecutor; - private final TabCompleter originalCompleter; + private static String prefix = "§6[§bYum §a命令监控§6] "; + private static String warn = "§c注意! §6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6命令 §c耗时 §4%sms §c平均耗时 §4%sms!"; + private static String err = prefix + "§6玩家 §a%s §6执行 §b%s §6插件 §d%s %s §6命令时发生异常!"; + private static String inject_error = prefix + "§6插件 §b%s §c注入能耗监控失败!"; + private static String plugin_is_null = "插件不得为NULL!"; + private CommandExecutor originalExecutor; + private TabCompleter originalCompleter; - private final Plugin plugin; + private Plugin plugin; public long totalTime; public int count; - public CommandInjector(final CommandExecutor originalCommandExecutor, final TabCompleter originalTabCompleter, final Plugin plugin) { + public CommandInjector(CommandExecutor originalCommandExecutor, TabCompleter originalTabCompleter, Plugin plugin) { this.originalExecutor = originalCommandExecutor; this.originalCompleter = originalTabCompleter; this.plugin = plugin; } - public static void inject(final Plugin plugin) { + public static void inject(Plugin plugin) { Validate.notNull(plugin, plugin_is_null); try { - final PluginManager pluginManager = Bukkit.getPluginManager(); - final SimpleCommandMap commandMap = Reflect.on(pluginManager).get("commandMap"); - for (final Command command : commandMap.getCommands()) { + PluginManager pluginManager = Bukkit.getPluginManager(); + SimpleCommandMap commandMap = Reflect.on(pluginManager).get("commandMap"); + for (Command command : commandMap.getCommands()) { if (command instanceof PluginCommand) { - final PluginCommand pluginCommand = (PluginCommand) command; - final Plugin cp = pluginCommand.getPlugin(); + PluginCommand pluginCommand = (PluginCommand) command; + Plugin cp = pluginCommand.getPlugin(); if (cp.equals(plugin)) { - final CommandExecutor executor = Reflect.on(command).get("executor"); - if (executor instanceof CommandInjector) { - return; - } - final TabCompleter completer = Reflect.on(command).get("completer"); - final CommandInjector commandInjector = new CommandInjector(executor, completer, plugin); + CommandExecutor executor = Reflect.on(command).get("executor"); + if (executor instanceof CommandInjector) { return; } + TabCompleter completer = Reflect.on(command).get("completer"); + CommandInjector commandInjector = new CommandInjector(executor, completer, plugin); Reflect.on(command).set("executor", commandInjector); Reflect.on(command).set("completer", commandInjector); } } } - } catch (final Throwable e) { + } catch (Throwable e) { MonitorManager.log(String.format(inject_error, plugin.getName())); } } - public static void uninject(final Plugin plugin) { + public static void uninject(Plugin plugin) { Validate.notNull(plugin, plugin_is_null); try { - final PluginManager pluginManager = Bukkit.getPluginManager(); - final SimpleCommandMap commandMap = Reflect.on(pluginManager).get("commandMap"); - for (final Command command : commandMap.getCommands()) { + PluginManager pluginManager = Bukkit.getPluginManager(); + SimpleCommandMap commandMap = Reflect.on(pluginManager).get("commandMap"); + for (Command command : commandMap.getCommands()) { if (command instanceof PluginCommand) { - final PluginCommand pluginCommand = (PluginCommand) command; - final Plugin cp = pluginCommand.getPlugin(); + PluginCommand pluginCommand = (PluginCommand) command; + Plugin cp = pluginCommand.getPlugin(); if (cp.equals(plugin)) { - final CommandExecutor executor = Reflect.on(command).get("executor"); + CommandExecutor executor = Reflect.on(command).get("executor"); if (executor instanceof CommandInjector) { - final CommandInjector injected = (CommandInjector) executor; + CommandInjector injected = (CommandInjector) executor; Reflect.on(command).set("executor", injected.getOriginalExecutor()); } - final TabCompleter completer = Reflect.on(command).get("completer"); + TabCompleter completer = Reflect.on(command).get("completer"); if (completer instanceof CommandInjector) { - final CommandInjector injected = (CommandInjector) completer; + CommandInjector injected = (CommandInjector) completer; Reflect.on(command).set("completer", injected.getOriginalCompleter()); } } } } - } catch (final Throwable e) { + } catch (Throwable e) { } } @@ -102,18 +100,24 @@ public class CommandInjector implements TabExecutor { } @Override - public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) { + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { try { - final long start = System.nanoTime(); - final boolean result = originalExecutor.onCommand(sender, command, label, args); - final long end = System.nanoTime(); - final long lag = end - start; + long start = System.nanoTime(); + boolean result = originalExecutor.onCommand(sender, command, label, args); + long end = System.nanoTime(); + long lag = end - start; totalTime += lag; count++; - final long lagms = lag / MonitorManager.um; - final long avglagms = totalTime / count / MonitorManager.um; + long lagms = lag / MonitorManager.um; + long avglagms = totalTime / count / MonitorManager.um; if (Bukkit.isPrimaryThread() && lagms > MonitorManager.lagTime && avglagms > MonitorManager.lagTime) { - MonitorManager.lagTip(String.format(warn, sender.getName(), plugin.getName(), label, StrKit.join(args, " "), lagms, avglagms)); + MonitorManager.lagTip(String.format(warn, + sender.getName(), + plugin.getName(), + label, + StrKit.join(args, " "), + lagms, + avglagms)); } MonitorManager.addCmd(plugin.getName(), lag); return result; @@ -123,19 +127,18 @@ public class CommandInjector implements TabExecutor { } MonitorCommand.lastError = e; MonitorManager.sendError(sender, plugin, e); - MonitorManager.printThrowable(String.format(err, sender.getName(), plugin.getName(), label, StrKit.join(args, " ")), e); + MonitorManager.printThrowable( + String.format(err, sender.getName(), plugin.getName(), label, StrKit.join(args, " ")), e); } return false; } @Override - public List onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { - if (originalCompleter == null) { - return Collections.emptyList(); - } - final long start = System.nanoTime(); - final List result = originalCompleter.onTabComplete(sender, command, alias, args); - final long end = System.nanoTime(); + public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { + if (originalCompleter == null) { return Collections.emptyList(); } + long start = System.nanoTime(); + List result = originalCompleter.onTabComplete(sender, command, alias, args); + long end = System.nanoTime(); totalTime += end - start; count++; return result; diff --git a/src/main/java/pw/yumc/Yum/inject/ListenerInjector.java b/src/main/java/pw/yumc/Yum/inject/ListenerInjector.java index 897cfd6..8b6067a 100644 --- a/src/main/java/pw/yumc/Yum/inject/ListenerInjector.java +++ b/src/main/java/pw/yumc/Yum/inject/ListenerInjector.java @@ -15,88 +15,80 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredListener; import org.bukkit.plugin.TimedRegisteredListener; -import cn.citycraft.PluginHelper.ext.kit.Reflect; import pw.yumc.Yum.commands.MonitorCommand; import pw.yumc.Yum.managers.ConfigManager; import pw.yumc.Yum.managers.MonitorManager; +import pw.yumc.YumCore.reflect.Reflect; public class ListenerInjector implements EventExecutor { - private final static String prefix = "§6[§bYum §a事件监控§6] "; - private final static String warn = "§c注意! §6插件 §b%s §6处理 §d%s §6事件 §c耗时 §4%sms §c平均耗时 §4%sms!"; - private final static String err = prefix + "§6插件 §b%s §6处理 §d%s §6事件时发生异常!"; - private final static String inject_error = prefix + "§6插件 §b%s §c注入能耗监控失败 §6注入类: §3%s!"; - private final static String plugin_is_null = "插件不得为NULL!"; - private final EventExecutor originalExecutor; + private static String prefix = "§6[§bYum §a事件监控§6] "; + private static String warn = "§c注意! §6插件 §b%s §6处理 §d%s §6事件 §c耗时 §4%sms §c平均耗时 §4%sms!"; + private static String err = prefix + "§6插件 §b%s §6处理 §d%s §6事件时发生异常!"; + private static String inject_error = prefix + "§6插件 §b%s §c注入能耗监控失败 §6注入类: §3%s!"; + private static String plugin_is_null = "插件不得为NULL!"; + private EventExecutor originalExecutor; - private final Plugin plugin; + private Plugin plugin; public Map eventTotalTime = new ConcurrentHashMap<>(); public Map eventCount = new ConcurrentHashMap<>(); - public ListenerInjector(final EventExecutor originalExecutor, final Plugin plugin) { + public ListenerInjector(EventExecutor originalExecutor, Plugin plugin) { this.originalExecutor = originalExecutor; this.plugin = plugin; } - public static void inject(final Plugin plugin) { + public static void inject(Plugin plugin) { Validate.notNull(plugin, plugin_is_null); - final List listeners = HandlerList.getRegisteredListeners(plugin); - for (final RegisteredListener listener : listeners) { + List listeners = HandlerList.getRegisteredListeners(plugin); + for (RegisteredListener listener : listeners) { try { - if (listener instanceof TimedRegisteredListener) { - return; - } + if (listener instanceof TimedRegisteredListener) { return; } // 兼容PerWorldPlugin if (listener.getClass().getName().contains("PWPRegisteredListener")) { - final Field f = Reflect.getDeclaredField(RegisteredListener.class, "executor"); + Field f = Reflect.getDeclaredField(RegisteredListener.class, "executor"); f.setAccessible(true); - final EventExecutor originalExecutor = (EventExecutor) f.get(listener); - if (originalExecutor instanceof ListenerInjector) { - return; - } - final ListenerInjector listenerInjector = new ListenerInjector(originalExecutor, plugin); + EventExecutor originalExecutor = (EventExecutor) f.get(listener); + if (originalExecutor instanceof ListenerInjector) { return; } + ListenerInjector listenerInjector = new ListenerInjector(originalExecutor, plugin); f.set(listener, listenerInjector); } else { - final EventExecutor originalExecutor = Reflect.on(listener).get("executor"); - if (originalExecutor instanceof ListenerInjector) { - return; - } - final ListenerInjector listenerInjector = new ListenerInjector(originalExecutor, plugin); + EventExecutor originalExecutor = Reflect.on(listener).get("executor"); + if (originalExecutor instanceof ListenerInjector) { return; } + ListenerInjector listenerInjector = new ListenerInjector(originalExecutor, plugin); Reflect.on(listener).set("executor", listenerInjector); } - } catch (final Throwable e) { + } catch (Throwable e) { MonitorManager.log(String.format(inject_error, plugin.getName(), listener.getClass().getName())); e.printStackTrace(); } } } - public static void uninject(final Plugin plugin) { + public static void uninject(Plugin plugin) { Validate.notNull(plugin, plugin_is_null); try { - final List listeners = HandlerList.getRegisteredListeners(plugin); - for (final RegisteredListener listener : listeners) { - if (listener instanceof TimedRegisteredListener) { - return; - } - final EventExecutor executor = Reflect.on(listener).get("executor"); + List listeners = HandlerList.getRegisteredListeners(plugin); + for (RegisteredListener listener : listeners) { + if (listener instanceof TimedRegisteredListener) { return; } + EventExecutor executor = Reflect.on(listener).get("executor"); if (executor instanceof ListenerInjector) { Reflect.on(listener).set("executor", ((ListenerInjector) executor).getOriginalExecutor()); } } - } catch (final Throwable e) { + } catch (Throwable e) { } } @Override - public void execute(final Listener listener, final Event event) throws EventException { + public void execute(Listener listener, Event event) throws EventException { try { if (!event.isAsynchronous()) { - final long start = System.nanoTime(); + long start = System.nanoTime(); originalExecutor.execute(listener, event); - final long end = System.nanoTime(); - final String en = event.getEventName(); - final long lag = end - start; + long end = System.nanoTime(); + String en = event.getEventName(); + long lag = end - start; if (eventTotalTime.containsKey(en)) { eventTotalTime.put(en, eventTotalTime.get(en) + lag); eventCount.put(en, eventCount.get(en) + 1); @@ -104,9 +96,10 @@ public class ListenerInjector implements EventExecutor { eventTotalTime.put(en, end - start); eventCount.put(en, 1); } - final long lagms = lag / MonitorManager.um; - final long avglagms = eventTotalTime.get(en) / eventCount.get(en) / MonitorManager.um; - if (avglagms > MonitorManager.lagTime && lagms > MonitorManager.lagTime && !ConfigManager.i().getMonitorIgnoreList().contains(plugin.getName())) { + long lagms = lag / MonitorManager.um; + long avglagms = eventTotalTime.get(en) / eventCount.get(en) / MonitorManager.um; + if (avglagms > MonitorManager.lagTime && lagms > MonitorManager.lagTime + && !ConfigManager.i().getMonitorIgnoreList().contains(plugin.getName())) { MonitorManager.lagTip(String.format(warn, plugin.getName(), event.getEventName(), lagms, avglagms)); } MonitorManager.addEvent(plugin.getName(), lag); diff --git a/src/main/java/pw/yumc/Yum/inject/TaskInjector.java b/src/main/java/pw/yumc/Yum/inject/TaskInjector.java index 05681d5..f40df3c 100644 --- a/src/main/java/pw/yumc/Yum/inject/TaskInjector.java +++ b/src/main/java/pw/yumc/Yum/inject/TaskInjector.java @@ -8,70 +8,68 @@ import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; -import cn.citycraft.PluginHelper.ext.kit.Reflect; -import cn.citycraft.PluginHelper.kit.StrKit; import pw.yumc.Yum.commands.MonitorCommand; import pw.yumc.Yum.managers.MonitorManager; +import pw.yumc.YumCore.kit.StrKit; +import pw.yumc.YumCore.reflect.Reflect; public class TaskInjector implements Runnable { - private final static String prefix = "§6[§bYum §a任务监控§6] "; - private final static String warn = "§c注意! §6插件 §b%s §6处理 §d%s §6任务 §c耗时 §4%sms §c平均耗时 §4%sms!"; - private final static String err = prefix + "§6插件 §b%s §6处理 §d%s §6任务时发生异常!"; - private final static String inject_error = prefix + "§6插件 §b%s §c注入能耗监控失败!"; - private final static String plugin_is_null = "插件不得为NULL!"; - private final Runnable originalTask; - private final Plugin plugin; + private static String prefix = "§6[§bYum §a任务监控§6] "; + private static String warn = "§c注意! §6插件 §b%s §6处理 §d%s §6任务 §c耗时 §4%sms §c平均耗时 §4%sms!"; + private static String err = prefix + "§6插件 §b%s §6处理 §d%s §6任务时发生异常!"; + private static String inject_error = prefix + "§6插件 §b%s §c注入能耗监控失败!"; + private static String plugin_is_null = "插件不得为NULL!"; + private Runnable originalTask; + private Plugin plugin; - private final String taskName; + private String taskName; public long totalTime; public int count; - public TaskInjector(final Runnable originalTask, final Plugin plugin) { + public TaskInjector(Runnable originalTask, Plugin plugin) { this.originalTask = originalTask; this.plugin = plugin; - final Class taskClass = getOriginalTask().getClass(); + Class taskClass = getOriginalTask().getClass(); taskName = StrKit.isBlank(taskClass.getSimpleName()) ? taskClass.getName() : taskClass.getSimpleName(); } // 当前注入只能对TimerTask有效 // 对于单次执行的任务 我们需要注册一个动态的代理 - public static void inject(final Plugin plugin) { + public static void inject(Plugin plugin) { Validate.notNull(plugin, plugin_is_null); try { - final BukkitScheduler scheduler = Bukkit.getScheduler(); - final List pendingTasks = scheduler.getPendingTasks(); - for (final BukkitTask pendingTask : pendingTasks) { + BukkitScheduler scheduler = Bukkit.getScheduler(); + List pendingTasks = scheduler.getPendingTasks(); + for (BukkitTask pendingTask : pendingTasks) { // 忽略异步任务 if (pendingTask.isSync() && pendingTask.getOwner().equals(plugin)) { - final Runnable originalTask = Reflect.on(pendingTask).get("task"); - if (originalTask instanceof TaskInjector) { - return; - } - final TaskInjector taskInjector = new TaskInjector(originalTask, plugin); + Runnable originalTask = Reflect.on(pendingTask).get("task"); + if (originalTask instanceof TaskInjector) { return; } + TaskInjector taskInjector = new TaskInjector(originalTask, plugin); Reflect.on(pendingTask).set("task", taskInjector); } } - } catch (final Throwable e) { + } catch (Throwable e) { MonitorManager.log(String.format(inject_error, plugin.getName())); } } - public static void uninject(final Plugin plugin) { + public static void uninject(Plugin plugin) { Validate.notNull(plugin, plugin_is_null); try { - final BukkitScheduler scheduler = Bukkit.getScheduler(); - final List pendingTasks = scheduler.getPendingTasks(); - for (final BukkitTask pendingTask : pendingTasks) { + BukkitScheduler scheduler = Bukkit.getScheduler(); + List pendingTasks = scheduler.getPendingTasks(); + for (BukkitTask pendingTask : pendingTasks) { // 忽略异步任务 if (pendingTask.isSync() && pendingTask.getOwner().equals(plugin)) { - final Runnable originalTask = Reflect.on(pendingTask).get("task"); + Runnable originalTask = Reflect.on(pendingTask).get("task"); if (originalTask instanceof TaskInjector) { Reflect.on(pendingTask).set("task", ((TaskInjector) originalTask).getOriginalTask()); } } } - } catch (final Throwable e) { + } catch (Throwable e) { } } @@ -82,14 +80,14 @@ public class TaskInjector implements Runnable { @Override public void run() { try { - final long start = System.nanoTime(); + long start = System.nanoTime(); originalTask.run(); - final long end = System.nanoTime(); - final long lag = end - start; + long end = System.nanoTime(); + long lag = end - start; totalTime += lag; count++; - final long lagms = lag / MonitorManager.um; - final long avglagms = totalTime / count / MonitorManager.um; + long lagms = lag / MonitorManager.um; + long avglagms = totalTime / count / MonitorManager.um; if (Bukkit.isPrimaryThread() && lagms > MonitorManager.lagTime && avglagms > MonitorManager.lagTime) { MonitorManager.lagTip(String.format(warn, plugin.getName(), taskName, lagms, avglagms)); } diff --git a/src/main/java/pw/yumc/Yum/listeners/PluginListener.java b/src/main/java/pw/yumc/Yum/listeners/PluginListener.java index 987489b..e72df2f 100644 --- a/src/main/java/pw/yumc/Yum/listeners/PluginListener.java +++ b/src/main/java/pw/yumc/Yum/listeners/PluginListener.java @@ -26,15 +26,13 @@ public class PluginListener implements Listener { } @EventHandler - public void onPluginDisable(final PluginDisableEvent e) { + public void onPluginDisable(PluginDisableEvent e) { YumAPI.uninject(e.getPlugin()); } @EventHandler public void onPluginEnable(final PluginEnableEvent e) { - if (ConfigManager.i().getMonitorIgnoreList().contains(e.getPlugin().getName())) { - return; - } + if (ConfigManager.i().getMonitorIgnoreList().contains(e.getPlugin().getName())) { return; } MonitorManager.reset(e.getPlugin().getName()); PKit.runTaskLater(new Runnable() { @Override diff --git a/src/main/java/pw/yumc/Yum/listeners/PluginNetworkListener.java b/src/main/java/pw/yumc/Yum/listeners/PluginNetworkListener.java index 26de8fc..2cee3fc 100644 --- a/src/main/java/pw/yumc/Yum/listeners/PluginNetworkListener.java +++ b/src/main/java/pw/yumc/Yum/listeners/PluginNetworkListener.java @@ -18,11 +18,11 @@ public class PluginNetworkListener implements Listener { public String breaked = "§c已阻止插件 §b%s §c访问网络!"; public String url = "§6地址: §c%s"; - public PluginNetworkListener(final Yum yum) { + public PluginNetworkListener(Yum yum) { Bukkit.getPluginManager().registerEvents(this, yum); } - public void breakNetwork(final PluginNetworkEvent e) { + public void breakNetwork(PluginNetworkEvent e) { if (ConfigManager.i().isNetworkShowInfo()) { Log.console(prefix + breaked, e.getPlugin().getName()); Log.console(prefix + url, e.getUrl().toString()); @@ -31,17 +31,13 @@ public class PluginNetworkListener implements Listener { } @EventHandler - public void onPluginNetworkConect(final PluginNetworkEvent e) { - final Plugin plugin = e.getPlugin(); - final String urlinfo = e.getUrl().toString(); - if (urlinfo.startsWith("socket")) { - return; - } - if (ConfigManager.i().getNetworkWhiteURL().contains(e.getUrl().getHost())) { - return; - } + public void onPluginNetworkConect(PluginNetworkEvent e) { + Plugin plugin = e.getPlugin(); + String urlinfo = e.getUrl().toString(); + if (urlinfo.startsWith("socket")) { return; } + if (ConfigManager.i().getNetworkWhiteURL().contains(e.getUrl().getHost())) { return; } if (urlinfo.contains("yumc") || urlinfo.contains("citycraft") || urlinfo.contains("502647092")) { - final String 大神你好 = "反编译的大神们我知道你们又要说了这货有后门"; + String 大神你好 = "反编译的大神们我知道你们又要说了这货有后门"; 大神你好.isEmpty(); return; } @@ -51,9 +47,7 @@ public class PluginNetworkListener implements Listener { breakNetwork(e); return; } - if (ConfigManager.i().getNetworkIgnoreList().contains(plugin.getName())) { - return; - } + if (ConfigManager.i().getNetworkIgnoreList().contains(plugin.getName())) { return; } if (e.isPrimaryThread()) { Log.console(prefix + warnMain, plugin.getName()); if (!ConfigManager.i().isAllowPrimaryThread()) { diff --git a/src/main/java/pw/yumc/Yum/listeners/SecurityListener.java b/src/main/java/pw/yumc/Yum/listeners/SecurityListener.java index b0cea09..b3e9fdc 100644 --- a/src/main/java/pw/yumc/Yum/listeners/SecurityListener.java +++ b/src/main/java/pw/yumc/Yum/listeners/SecurityListener.java @@ -17,26 +17,24 @@ import pw.yumc.injected.event.SetOpEvent; * @author 喵♂呜 */ public class SecurityListener implements Listener { - private final String prefix = "§6[§bYum §a安全系统§6] "; - private final String warn = "§c插件 §e%s §c已设置玩家 §a%s §c为OP §4请注意服务器安全!"; - private final String prevent = "§c黑名单插件 §e%s §c尝试设置玩家 §a%s §c为OP §a安全系统已成功拦截!"; + private String prefix = "§6[§bYum §a安全系统§6] "; + private String warn = "§c插件 §e%s §c已设置玩家 §a%s §c为OP §4请注意服务器安全!"; + private String prevent = "§c黑名单插件 §e%s §c尝试设置玩家 §a%s §c为OP §a安全系统已成功拦截!"; - public SecurityListener(final Yum yum) { + public SecurityListener(Yum yum) { Bukkit.getPluginManager().registerEvents(this, yum); } @EventHandler - public void setop(final SetOpEvent e) { - final Plugin plugin = PKit.getOperatePlugin(); + public void setop(SetOpEvent e) { + Plugin plugin = PKit.getOperatePlugin(); if (plugin != null) { if (ConfigManager.i().getSetOpBlackList().contains(plugin.getName())) { Log.console(prefix + prevent, plugin, e.getOfflinePlayer().getName()); e.setCancelled(true); return; } - if (ConfigManager.i().getSetOpIgnoreList().contains(plugin.getName())) { - return; - } + if (ConfigManager.i().getSetOpIgnoreList().contains(plugin.getName())) { return; } Bukkit.getConsoleSender().sendMessage(String.format(prefix + warn, plugin, e.getOfflinePlayer().getName())); } } diff --git a/src/main/java/pw/yumc/Yum/listeners/ThreadSafetyListener.java b/src/main/java/pw/yumc/Yum/listeners/ThreadSafetyListener.java index 8ff06a0..d88f2d1 100644 --- a/src/main/java/pw/yumc/Yum/listeners/ThreadSafetyListener.java +++ b/src/main/java/pw/yumc/Yum/listeners/ThreadSafetyListener.java @@ -27,69 +27,68 @@ import pw.yumc.YumCore.kit.PKit; */ public class ThreadSafetyListener implements Listener { - public ThreadSafetyListener(final Yum yum) { + public ThreadSafetyListener(Yum yum) { Bukkit.getPluginManager().registerEvents(this, yum); } @EventHandler - public void onChunkLoad(final ChunkLoadEvent chunkLoadEvent) { + public void onChunkLoad(ChunkLoadEvent chunkLoadEvent) { checkSafety(chunkLoadEvent); } @EventHandler - public void onChunkUnload(final ChunkUnloadEvent chunkUnloadEvent) { + public void onChunkUnload(ChunkUnloadEvent chunkUnloadEvent) { checkSafety(chunkUnloadEvent); } @EventHandler - public void onCreatureSpawn(final CreatureSpawnEvent creatureSpawnEvent) { + public void onCreatureSpawn(CreatureSpawnEvent creatureSpawnEvent) { checkSafety(creatureSpawnEvent); } - public void onInventoryOpen(final InventoryOpenEvent inventoryOpenEvent) { + public void onInventoryOpen(InventoryOpenEvent inventoryOpenEvent) { checkSafety(inventoryOpenEvent); } @EventHandler - public void onItemSpawn(final ItemSpawnEvent itemSpawnEvent) { + public void onItemSpawn(ItemSpawnEvent itemSpawnEvent) { checkSafety(itemSpawnEvent); } @EventHandler - public void onPlayerMove(final PlayerMoveEvent moveEvent) { + public void onPlayerMove(PlayerMoveEvent moveEvent) { checkSafety(moveEvent); } @EventHandler - public void onPlayerQuit(final PlayerQuitEvent quitEvent) { + public void onPlayerQuit(PlayerQuitEvent quitEvent) { checkSafety(quitEvent); } - public void onPlayerTeleport(final PlayerTeleportEvent teleportEvent) { + public void onPlayerTeleport(PlayerTeleportEvent teleportEvent) { checkSafety(teleportEvent); } @EventHandler - public void onWorldLoad(final WorldLoadEvent worldLoadEvent) { + public void onWorldLoad(WorldLoadEvent worldLoadEvent) { checkSafety(worldLoadEvent); } - public void onWorldSave(final WorldSaveEvent worldSaveEvent) { + public void onWorldSave(WorldSaveEvent worldSaveEvent) { checkSafety(worldSaveEvent); } @EventHandler - public void onWorldUnload(final WorldUnloadEvent worldUnloadEvent) { + public void onWorldUnload(WorldUnloadEvent worldUnloadEvent) { checkSafety(worldUnloadEvent); } - private void checkSafety(final Event eventType) { + private void checkSafety(Event eventType) { if (Yum.mainThread != null && Thread.currentThread() != Yum.mainThread && !eventType.isAsynchronous()) { - final String eventName = eventType.getEventName(); - final Plugin plugin = PKit.getOperatePlugin(); - if (plugin != null) { - throw new IllegalAccessError("[Yum 线程安全]: 请勿异步调用一个同步事件 " + eventName + " 操作插件: " + plugin.getName()); - } + String eventName = eventType.getEventName(); + Plugin plugin = PKit.getOperatePlugin(); + if (plugin != null) { throw new IllegalAccessError("[Yum 线程安全]: 请勿异步调用一个同步事件 " + eventName + " 操作插件: " + + plugin.getName()); } } } } diff --git a/src/main/java/pw/yumc/Yum/managers/ConfigManager.java b/src/main/java/pw/yumc/Yum/managers/ConfigManager.java index 0d37e15..594c858 100644 --- a/src/main/java/pw/yumc/Yum/managers/ConfigManager.java +++ b/src/main/java/pw/yumc/Yum/managers/ConfigManager.java @@ -9,19 +9,19 @@ import pw.yumc.YumCore.config.FileConfig; import pw.yumc.YumCore.sql.DataBase; public class ConfigManager { - public final static String ENABLE = "Enable"; - public final static String BLACK = "Black"; - public final static String IGNORE = "Ignore"; + public static String ENABLE = "Enable"; + public static String BLACK = "Black"; + public static String IGNORE = "Ignore"; - private final static ConfigManager i = new ConfigManager(P.instance); + private static ConfigManager i = new ConfigManager(P.instance); - public final FileConfig config; - public final FileConfig setop; - public final FileConfig network; - public final FileConfig thread; - public final FileConfig monitor; + public FileConfig config; + public FileConfig setop; + public FileConfig network; + public FileConfig thread; + public FileConfig monitor; - public ConfigManager(final JavaPlugin plugin) { + public ConfigManager(JavaPlugin plugin) { config = new FileConfig(); setop = new FileConfig("setop.yml"); network = new FileConfig("network.yml"); diff --git a/src/main/java/pw/yumc/Yum/managers/DataManager.java b/src/main/java/pw/yumc/Yum/managers/DataManager.java index dd2a38e..a285da6 100644 --- a/src/main/java/pw/yumc/Yum/managers/DataManager.java +++ b/src/main/java/pw/yumc/Yum/managers/DataManager.java @@ -1,6 +1,5 @@ package pw.yumc.Yum.managers; -import cn.citycraft.PluginHelper.sql.Type; import pw.yumc.YumCore.sql.DataBase; import pw.yumc.YumCore.sql.core.KeyValue; @@ -8,9 +7,18 @@ public class DataManager { private static DataBase db = ConfigManager.i().getDataBase(); public static void init() { - db.createTables(TableName.cmd, new KeyValue("plugin", Type.VARCHAR.get()).add("name", Type.VARCHAR.get()).add("total", Type.DOUBLE.get()).add("count", Type.INTEGER.get()), null); - db.createTables(TableName.event, new KeyValue("plugin", Type.VARCHAR.get()).add("name", Type.VARCHAR.get()).add("total", Type.DOUBLE.get()).add("count", Type.INTEGER.get()), null); - db.createTables(TableName.task, new KeyValue("plugin", Type.VARCHAR.get()).add("name", Type.VARCHAR.get()).add("total", Type.DOUBLE.get()).add("count", Type.INTEGER.get()), null); + db.createTables(TableName.cmd, + new KeyValue("plugin", "VARCHAR(30)").add("name", "VARCHAR(30)").add("total", "INT").add("count", + "INT"), + null); + db.createTables(TableName.event, + new KeyValue("plugin", "VARCHAR(30)").add("name", "VARCHAR(30)").add("total", "INT").add("count", + "INT"), + null); + db.createTables(TableName.task, + new KeyValue("plugin", "VARCHAR(30)").add("name", "VARCHAR(30)").add("total", "INT").add("count", + "INT"), + null); } static class TableName { diff --git a/src/main/java/pw/yumc/Yum/managers/DownloadManager.java b/src/main/java/pw/yumc/Yum/managers/DownloadManager.java index 56d7fa4..6672b91 100644 --- a/src/main/java/pw/yumc/Yum/managers/DownloadManager.java +++ b/src/main/java/pw/yumc/Yum/managers/DownloadManager.java @@ -14,7 +14,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; -import cn.citycraft.PluginHelper.callback.CallBack.One; +import pw.yumc.YumCore.callback.CallBack.One; /** * 下载管理类 @@ -25,7 +25,7 @@ import cn.citycraft.PluginHelper.callback.CallBack.One; public class DownloadManager { Plugin plugin; - public DownloadManager(final Plugin main) { + public DownloadManager(Plugin main) { this.plugin = main; } @@ -36,8 +36,8 @@ public class DownloadManager { * - 地址 * @return 文件名称 */ - public String getFileName(final String url) { - final int end = url.lastIndexOf('/'); + public String getFileName(String url) { + int end = url.lastIndexOf('/'); return url.substring(end + 1); } @@ -48,7 +48,7 @@ public class DownloadManager { * - 地址 * @return 文件名称 */ - public String getFileName(final URL url) { + public String getFileName(URL url) { return getFileName(url.getFile()); } @@ -61,7 +61,7 @@ public class DownloadManager { * - 下载地址 * @return 是否成功 */ - public boolean run(final CommandSender sender, final String urlstring) { + public boolean run(CommandSender sender, String urlstring) { return run(sender, urlstring, new File("plugins", getFileName(urlstring)), null); } @@ -76,11 +76,11 @@ public class DownloadManager { * - 保存文件 * @return 是否成功 */ - public boolean run(final CommandSender sender, final String urlstring, final File file) { + public boolean run(CommandSender sender, String urlstring, File file) { try { - final URL url = new URL(urlstring); + URL url = new URL(urlstring); return run(sender, url, file); - } catch (final MalformedURLException e) { + } catch (MalformedURLException e) { sender.sendMessage("§4错误: §c无法识别的URL地址..."); sender.sendMessage("§4地址: §c" + urlstring); return false; @@ -100,11 +100,11 @@ public class DownloadManager { * -回调函数 * @return 是否成功 */ - public boolean run(final CommandSender sender, final String urlstring, final File file, final One callback) { + public boolean run(CommandSender sender, String urlstring, File file, One callback) { try { - final URL url = new URL(urlstring); + URL url = new URL(urlstring); return run(sender, url, file, callback); - } catch (final MalformedURLException e) { + } catch (MalformedURLException e) { sender.sendMessage("§4错误: §c无法识别的URL地址..."); sender.sendMessage("§4地址: §c" + urlstring); return false; @@ -122,7 +122,7 @@ public class DownloadManager { * - 保存文件 * @return 是否成功 */ - public boolean run(final CommandSender sender, final URL url, final File file) { + public boolean run(CommandSender sender, URL url, File file) { return run(sender, url, file, null); } @@ -139,7 +139,7 @@ public class DownloadManager { * -回调函数 * @return 是否成功 */ - public boolean run(CommandSender sender, final URL url, final File file, final One callback) { + public boolean run(CommandSender sender, URL url, File file, One callback) { BufferedInputStream in = null; FileOutputStream fout = null; if (sender == null) { @@ -148,8 +148,8 @@ public class DownloadManager { try { sender.sendMessage("§6开始下载: §3" + getFileName(url)); sender.sendMessage("§6下载地址: §3" + url.toString()); - final URLConnection uc = reload(sender, url.openConnection()); - final int status = ((HttpURLConnection) uc).getResponseCode(); + URLConnection uc = reload(sender, url.openConnection()); + int status = ((HttpURLConnection) uc).getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { switch (status) { case HttpURLConnection.HTTP_NOT_FOUND: @@ -160,8 +160,8 @@ public class DownloadManager { throw new IllegalStateException(status + " 无效的网关!"); } } - final int fileLength = uc.getContentLength(); - final boolean dyml = "chunked".equalsIgnoreCase(uc.getHeaderField("Transfer-Encoding")); + int fileLength = uc.getContentLength(); + boolean dyml = "chunked".equalsIgnoreCase(uc.getHeaderField("Transfer-Encoding")); if (fileLength < 0 && !dyml) { sender.sendMessage("§6下载: §c文件 " + file.getName() + " 获取长度错误(可能是网络问题)!"); sender.sendMessage("§6文件: §c" + file.getName() + " 下载失败!"); @@ -179,7 +179,7 @@ public class DownloadManager { file.createNewFile(); sender.sendMessage("§6创建新文件: §d" + file.getAbsolutePath()); fout = new FileOutputStream(file); - final byte[] data = new byte[1024]; + byte[] data = new byte[1024]; long downloaded = 0L; int count; long time = System.currentTimeMillis(); @@ -192,7 +192,7 @@ public class DownloadManager { time = System.currentTimeMillis(); } } else { - final int percent = (int) (downloaded * 100L / fileLength); + int percent = (int) (downloaded * 100L / fileLength); if (percent % 10 == 0) { if (System.currentTimeMillis() - time > 500) { sender.sendMessage(String.format("§6已下载: §a" + getPer(percent / 10) + " %s%%", percent)); @@ -203,13 +203,14 @@ public class DownloadManager { } String pVer = null; try { - final PluginDescriptionFile desc = plugin.getPluginLoader().getPluginDescription(file); + PluginDescriptionFile desc = plugin.getPluginLoader().getPluginDescription(file); pVer = StringUtils.substring(desc.getVersion(), 0, 15); - } catch (final Exception e) { + } catch (Exception e) { pVer = ""; } - sender.sendMessage("§6" + (pVer.isEmpty() ? "文件" : "插件") + ": §b" + file.getName() + (pVer.isEmpty() ? "" : " §a版本 §e" + pVer) + " §a下载完成!"); - } catch (final Exception ex) { + sender.sendMessage("§6" + (pVer.isEmpty() ? "文件" : "插件") + ": §b" + file.getName() + + (pVer.isEmpty() ? "" : " §a版本 §e" + pVer) + " §a下载完成!"); + } catch (Exception ex) { sender.sendMessage("§6异常: §c" + ex.getMessage()); sender.sendMessage("§6文件: §c" + file.getName() + " 下载失败!"); return false; @@ -221,7 +222,7 @@ public class DownloadManager { if (fout != null) { fout.close(); } - } catch (final Exception ex) { + } catch (Exception ex) { } } if (callback != null) { @@ -237,7 +238,7 @@ public class DownloadManager { * - 下载地址 * @return 是否成功 */ - public boolean run(final String urlstring) { + public boolean run(String urlstring) { return run(null, urlstring); } @@ -250,7 +251,7 @@ public class DownloadManager { * - 保存文件 * @return 是否成功 */ - public boolean run(final String urlstring, final File file) { + public boolean run(String urlstring, File file) { return run(null, urlstring, file, null); } @@ -263,12 +264,12 @@ public class DownloadManager { * - 保存文件 * @return 是否成功 */ - public boolean run(final URL url, final File file) { + public boolean run(URL url, File file) { return run(null, url, file, null); } - private String getPer(final int per) { - final StringBuilder sb = new StringBuilder(); + private String getPer(int per) { + StringBuilder sb = new StringBuilder(); for (int i = 0; i < 11; i++) { if (per > i) { sb.append("=="); @@ -288,11 +289,12 @@ public class DownloadManager { * @return 最终地址 * @throws Exception */ - private URLConnection reload(final CommandSender sender, final URLConnection uc) throws Exception { - final HttpURLConnection huc = (HttpURLConnection) uc; + private URLConnection reload(CommandSender sender, URLConnection uc) throws Exception { + HttpURLConnection huc = (HttpURLConnection) uc; // 302, 301, 307 - if (huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP || huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || huc.getResponseCode() == 307) { - final String url = huc.getHeaderField("Location"); + if (huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP + || huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || huc.getResponseCode() == 307) { + String url = huc.getHeaderField("Location"); sender.sendMessage("§6跳转至地址: §3" + url); return reload(sender, new URL(url).openConnection()); } diff --git a/src/main/java/pw/yumc/Yum/managers/MonitorManager.java b/src/main/java/pw/yumc/Yum/managers/MonitorManager.java index b57048e..f12074a 100644 --- a/src/main/java/pw/yumc/Yum/managers/MonitorManager.java +++ b/src/main/java/pw/yumc/Yum/managers/MonitorManager.java @@ -15,8 +15,8 @@ import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.plugin.Plugin; -import cn.citycraft.PluginHelper.kit.LogKit; import pw.yumc.YumCore.bukkit.Log; +import pw.yumc.YumCore.kit.LogKit; /** * 能耗监控管理 @@ -25,43 +25,43 @@ import pw.yumc.YumCore.bukkit.Log; * @author 喵♂呜 */ public class MonitorManager { - public final static String prefix = "§6[§bYum §a能耗监控§6] "; - private final static String errMsg = prefix + "§c命令执行异常 请反馈下列信息给腐竹!"; - private final static String errP = "§6插件名称: §b%s"; - private final static String errN = "§6异常名称: §c%s"; - private final static String errM = "§6异常说明: §3%s"; - private final static String errInfo = "§6简易错误信息如下:"; - private final static String errStackTrace = " §e位于 §c%s.%s(§4%s:%s§c)"; - private final static String devInfo = "§c开发人员调试信息如下:"; + public static String prefix = "§6[§bYum §a能耗监控§6] "; + private static String errMsg = prefix + "§c命令执行异常 请反馈下列信息给腐竹!"; + private static String errP = "§6插件名称: §b%s"; + private static String errN = "§6异常名称: §c%s"; + private static String errM = "§6异常说明: §3%s"; + private static String errInfo = "§6简易错误信息如下:"; + private static String errStackTrace = " §e位于 §c%s.%s(§4%s:%s§c)"; + private static String devInfo = "§c开发人员调试信息如下:"; - public final static int lagTime = 20; - public final static int um = 1000000; - public final static boolean debug = ConfigManager.i().isMonitorDebug(); - public final static boolean log_to_file = ConfigManager.i().isLogToFile(); + public static int lagTime = 20; + public static int um = 1000000; + public static boolean debug = ConfigManager.i().isMonitorDebug(); + public static boolean log_to_file = ConfigManager.i().isLogToFile(); private static double totalTime = 0; - private final static Map monitor = new ConcurrentHashMap<>(); - private final static Map task = new ConcurrentHashMap<>(); - private final static Map event = new ConcurrentHashMap<>(); - private final static Map cmd = new ConcurrentHashMap<>(); + private static Map monitor = new ConcurrentHashMap<>(); + private static Map task = new ConcurrentHashMap<>(); + private static Map event = new ConcurrentHashMap<>(); + private static Map cmd = new ConcurrentHashMap<>(); - private final static LogKit mlog = new LogKit("monitor.log"); - private final static LogKit elog = new LogKit("error.log"); + private static LogKit mlog = new LogKit("monitor.log"); + private static LogKit elog = new LogKit("error.log"); - public static void addCmd(final String pname, final long time) { + public static void addCmd(String pname, long time) { add(pname, time, monitor, cmd); } - public static void addEvent(final String pname, final long time) { + public static void addEvent(String pname, long time) { add(pname, time, monitor, event); } - public static void addTask(final String pname, final long time) { + public static void addTask(String pname, long time) { add(pname, time, monitor, task); } - public static void elog(final String message) { + public static void elog(String message) { if (log_to_file) { elog.logSender(message); } else { @@ -73,22 +73,23 @@ public class MonitorManager { return sortMapByValue(monitor); } - public static MonitorInfo getMonitorInfo(final String pname) { - final double per = 100.00; - return new MonitorInfo(monitor.get(pname) / totalTime * per, cmd.get(pname) / totalTime * per, event.get(pname) / totalTime * per, task.get(pname) / totalTime * per); + public static MonitorInfo getMonitorInfo(String pname) { + double per = 100.00; + return new MonitorInfo(monitor.get(pname) / totalTime * per, cmd.get(pname) / totalTime * per, event.get(pname) + / totalTime * per, task.get(pname) / totalTime * per); } public static void init() { - for (final Plugin p : Bukkit.getPluginManager().getPlugins()) { + for (Plugin p : Bukkit.getPluginManager().getPlugins()) { reset(p.getName()); } } - public static void lagTip(final String message) { + public static void lagTip(String message) { log(prefix + message); } - public static void log(final String message) { + public static void log(String message) { if (log_to_file) { mlog.logSender(message); } else { @@ -96,15 +97,19 @@ public class MonitorManager { } } - public static void printThrowable(final String title, final Throwable e) { + public static void printThrowable(String title, Throwable e) { elog(title); elog(String.format(errN, e.getClass().getName())); elog(String.format(errM, e.getMessage())); elog(errInfo); - final int l = e.getStackTrace().length > 5 ? 5 : e.getStackTrace().length; + int l = e.getStackTrace().length > 5 ? 5 : e.getStackTrace().length; for (int i = 0; i < l; i++) { - final StackTraceElement ste = e.getStackTrace()[i]; - elog(String.format(errStackTrace, ste.getClassName(), ste.getMethodName(), ste.getFileName(), ste.getLineNumber())); + StackTraceElement ste = e.getStackTrace()[i]; + elog(String.format(errStackTrace, + ste.getClassName(), + ste.getMethodName(), + ste.getFileName(), + ste.getLineNumber())); } if (debug) { Log.console(devInfo); @@ -112,22 +117,27 @@ public class MonitorManager { } } - public static void reset(final String pname) { + public static void reset(String pname) { monitor.put(pname, 0L); task.put(pname, 0L); event.put(pname, 0L); cmd.put(pname, 0L); } - public static void sendError(final CommandSender sender, final Plugin plugin, final Throwable e) { + public static void sendError(CommandSender sender, Plugin plugin, Throwable e) { sender.sendMessage(errMsg); sender.sendMessage(String.format(errP, plugin.getName())); sender.sendMessage(String.format(errN, e.getClass().getName())); sender.sendMessage(String.format(errM, e.getMessage())); } - public static void sendObject(final CommandSender sender) { - sender.sendMessage(String.format("totalTime@%s monitor@%s cmd@%s event@%s task@%s", totalTime, sum(monitor.values()), sum(cmd.values()), sum(event.values()), sum(task.values()))); + public static void sendObject(CommandSender sender) { + sender.sendMessage(String.format("totalTime@%s monitor@%s cmd@%s event@%s task@%s", + totalTime, + sum(monitor.values()), + sum(cmd.values()), + sum(event.values()), + sum(task.values()))); } /** @@ -136,14 +146,12 @@ public class MonitorManager { * @param map * @return */ - public static Map sortMapByValue(final Map oriMap) { - if (oriMap == null || oriMap.isEmpty()) { - return oriMap; - } - final Map sortedMap = new LinkedHashMap<>(); - final List> entryList = new ArrayList<>(oriMap.entrySet()); + public static Map sortMapByValue(Map oriMap) { + if (oriMap == null || oriMap.isEmpty()) { return oriMap; } + Map sortedMap = new LinkedHashMap<>(); + List> entryList = new ArrayList<>(oriMap.entrySet()); Collections.sort(entryList, new MonitorComparator()); - final Iterator> iter = entryList.iterator(); + Iterator> iter = entryList.iterator(); Entry tmpEntry = null; while (iter.hasNext()) { tmpEntry = iter.next(); @@ -153,16 +161,16 @@ public class MonitorManager { } @SafeVarargs - private static void add(final String pname, final long time, final Map... maps) { + private static void add(String pname, long time, Map... maps) { totalTime += time; - for (final Map map : maps) { + for (Map map : maps) { map.put(pname, map.get(pname) + time); } } - private static long sum(final Collection numbers) { + private static long sum(Collection numbers) { int result = 0; - for (final Long num : numbers) { + for (Long num : numbers) { result += num; } return result; @@ -174,7 +182,7 @@ public class MonitorManager { public double event; public double task; - public MonitorInfo(final double monitor, final double cmd, final double event, final double task) { + public MonitorInfo(double monitor, double cmd, double event, double task) { this.monitor = monitor; this.cmd = cmd; this.event = event; @@ -184,7 +192,7 @@ public class MonitorManager { static class MonitorComparator implements Comparator> { @Override - public int compare(final Entry o1, final Entry o2) { + public int compare(Entry o1, Entry o2) { return o2.getValue().compareTo(o1.getValue()); } } diff --git a/src/main/java/pw/yumc/Yum/managers/NetworkManager.java b/src/main/java/pw/yumc/Yum/managers/NetworkManager.java index dfe99a5..1053154 100644 --- a/src/main/java/pw/yumc/Yum/managers/NetworkManager.java +++ b/src/main/java/pw/yumc/Yum/managers/NetworkManager.java @@ -9,9 +9,9 @@ import java.util.List; import org.bukkit.Bukkit; -import cn.citycraft.PluginHelper.kit.ExceptionKit; import pw.yumc.Yum.Yum; import pw.yumc.Yum.events.PluginNetworkEvent; +import pw.yumc.YumCore.kit.ExKit; import pw.yumc.YumCore.kit.PKit; /** @@ -22,27 +22,27 @@ import pw.yumc.YumCore.kit.PKit; */ public class NetworkManager { - public static void register(final Yum plugin) { + public static void register(Yum plugin) { Bukkit.getConsoleSender().sendMessage("§6[§bYum §a网络管理§6] §a注入网络管理系统 将托管服务器网络!"); ProxySelector.setDefault(new YumProxySelector(ProxySelector.getDefault(), plugin)); } public static void unregister() { - final ProxySelector cur = ProxySelector.getDefault(); + ProxySelector cur = ProxySelector.getDefault(); if (cur instanceof YumProxySelector) { ProxySelector.setDefault(((YumProxySelector) cur).getDefaultSelector()); } } static class YumProxySelector extends ProxySelector { - private final ProxySelector defaultSelector; + private ProxySelector defaultSelector; - public YumProxySelector(final ProxySelector defaultSelector, final Yum plugin) { + public YumProxySelector(ProxySelector defaultSelector, Yum plugin) { this.defaultSelector = defaultSelector; } @Override - public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) { + public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { defaultSelector.connectFailed(uri, sa, ioe); } @@ -51,11 +51,11 @@ public class NetworkManager { } @Override - public List select(final URI uri) { - final PluginNetworkEvent pne = new PluginNetworkEvent(PKit.getOperatePlugin(), uri, Bukkit.isPrimaryThread()); + public List select(URI uri) { + PluginNetworkEvent pne = new PluginNetworkEvent(PKit.getOperatePlugin(), uri, Bukkit.isPrimaryThread()); Bukkit.getPluginManager().callEvent(pne); if (pne.isCancelled()) { - ExceptionKit.throwException(new IOException("[Yum 网络防护] 已开启网络防护 并被联网规则拦截!")); + ExKit.throwException(new IOException("[Yum 网络防护] 已开启网络防护 并被联网规则拦截!")); } return defaultSelector.select(uri); } diff --git a/src/main/java/pw/yumc/Yum/managers/PluginsManager.java b/src/main/java/pw/yumc/Yum/managers/PluginsManager.java index f177da5..a6fd7ee 100644 --- a/src/main/java/pw/yumc/Yum/managers/PluginsManager.java +++ b/src/main/java/pw/yumc/Yum/managers/PluginsManager.java @@ -33,8 +33,8 @@ import org.bukkit.plugin.UnknownDependencyException; import com.google.common.base.Joiner; -import cn.citycraft.PluginHelper.kit.StrKit; -import cn.citycraft.PluginHelper.utils.FileUtil; +import pw.yumc.YumCore.kit.FileKit; +import pw.yumc.YumCore.kit.StrKit; /** * 插件管理类 @@ -43,14 +43,14 @@ import cn.citycraft.PluginHelper.utils.FileUtil; * @since 2015年8月21日下午7:03:26 */ public class PluginsManager { - private final Set ignoreList = new HashSet<>(); - private final Plugin main; + private Set ignoreList = new HashSet<>(); + private Plugin main; - public PluginsManager(final Plugin plugin) { + public PluginsManager(Plugin plugin) { this.main = plugin; } - public static String getVersion(final Plugin plugin) { + public static String getVersion(Plugin plugin) { return StringUtils.substring(plugin.getDescription().getVersion(), 0, 15); } @@ -61,7 +61,7 @@ public class PluginsManager { * - 插件名称 * @return 是否成功 */ - public boolean addIgnore(final Collection name) { + public boolean addIgnore(Collection name) { return ignoreList.addAll(name); } @@ -72,7 +72,7 @@ public class PluginsManager { * - 插件名称 * @return 是否成功 */ - public boolean addIgnore(final String name) { + public boolean addIgnore(String name) { return ignoreList.add(name); } @@ -85,7 +85,7 @@ public class PluginsManager { * - 插件 * @return 是否成功 */ - public boolean deletePlugin(final CommandSender sender, final Plugin plugin) { + public boolean deletePlugin(CommandSender sender, Plugin plugin) { return unload(sender, plugin) && getPluginFile(plugin).delete(); } @@ -96,7 +96,7 @@ public class PluginsManager { * - 插件 * @return 是否成功 */ - public boolean deletePlugin(final Plugin plugin) { + public boolean deletePlugin(Plugin plugin) { return deletePlugin(Bukkit.getConsoleSender(), plugin); } @@ -106,7 +106,7 @@ public class PluginsManager { * @param plugin * - 插件 */ - public void disable(final Plugin plugin) { + public void disable(Plugin plugin) { if ((plugin != null) && (plugin.isEnabled())) { Bukkit.getPluginManager().disablePlugin(plugin); } @@ -116,7 +116,7 @@ public class PluginsManager { * 关闭所有插件 */ public void disableAll() { - for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (!isIgnored(plugin)) { disable(plugin); } @@ -129,7 +129,7 @@ public class PluginsManager { * @param plugin * - 插件 */ - public void enable(final Plugin plugin) { + public void enable(Plugin plugin) { if ((plugin != null) && (!plugin.isEnabled())) { Bukkit.getPluginManager().enablePlugin(plugin); } @@ -139,7 +139,7 @@ public class PluginsManager { * 启用所有插件 */ public void enableAll() { - for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (!isIgnored(plugin)) { enable(plugin); } @@ -155,8 +155,9 @@ public class PluginsManager { * - 插件 * @return 是否成功 */ - public boolean fullDeletePlugin(final CommandSender sender, final Plugin plugin) { - return unload(sender, plugin) && getPluginFile(plugin).delete() && FileUtil.deleteDir(sender, plugin.getDataFolder()); + public boolean fullDeletePlugin(CommandSender sender, Plugin plugin) { + return unload(sender, plugin) && getPluginFile(plugin).delete() + && FileKit.deleteDir(sender, plugin.getDataFolder()); } /** @@ -166,7 +167,7 @@ public class PluginsManager { * - 插件 * @return 格式化的插件名称 */ - public String getFormattedName(final Plugin plugin) { + public String getFormattedName(Plugin plugin) { return getFormattedName(plugin, false); } @@ -179,8 +180,8 @@ public class PluginsManager { * - 是否包括版本 * @return 格式化的插件名称 */ - public String getFormattedName(final Plugin plugin, final boolean includeVersions) { - final ChatColor color = plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED; + public String getFormattedName(Plugin plugin, boolean includeVersions) { + ChatColor color = plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED; String pluginName = color + plugin.getName(); if (includeVersions) { pluginName = pluginName + " (" + getVersion(plugin) + ")"; @@ -195,7 +196,7 @@ public class PluginsManager { * - 名称 * @return 插件 */ - public Plugin getPluginByName(final String name) { + public Plugin getPluginByName(String name) { return Bukkit.getPluginManager().getPlugin(name); } @@ -206,7 +207,7 @@ public class PluginsManager { * - 名称 * @return 插件 */ - public Plugin getPluginByName(final String[] args, final int start) { + public Plugin getPluginByName(String[] args, int start) { return getPluginByName(StrKit.consolidateStrings(args, start)); } @@ -217,24 +218,24 @@ public class PluginsManager { * - 插件 * @return 插件的绝对路径 */ - public File getPluginFile(final Plugin plugin) { + public File getPluginFile(Plugin plugin) { File file = null; - final ClassLoader cl = plugin.getClass().getClassLoader(); + ClassLoader cl = plugin.getClass().getClassLoader(); if ((cl instanceof URLClassLoader)) { @SuppressWarnings("resource") - final URLClassLoader ucl = (URLClassLoader) cl; - final URL url = ucl.getURLs()[0]; + URLClassLoader ucl = (URLClassLoader) cl; + URL url = ucl.getURLs()[0]; try { file = new File(URLDecoder.decode(url.getFile(), "UTF-8")); - } catch (final UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { } } return file; } - public List getPluginNames(final boolean fullName) { - final List plugins = new ArrayList<>(); - for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + public List getPluginNames(boolean fullName) { + List plugins = new ArrayList<>(); + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { plugins.add(fullName ? plugin.getDescription().getFullName() : plugin.getName()); } return plugins; @@ -247,11 +248,9 @@ public class PluginsManager { * - 插件名称 * @return 插件版本 */ - public String getPluginVersion(final String name) { - final Plugin plugin = getPluginByName(name); - if ((plugin != null) && (plugin.getDescription() != null)) { - return getVersion(plugin); - } + public String getPluginVersion(String name) { + Plugin plugin = getPluginByName(name); + if ((plugin != null) && (plugin.getDescription() != null)) { return getVersion(plugin); } return null; } @@ -262,23 +261,21 @@ public class PluginsManager { * - 插件 * @return 插件命令 */ - public String getUsages(final Plugin plugin) { - final List parsedCommands = new ArrayList<>(); + public String getUsages(Plugin plugin) { + List parsedCommands = new ArrayList<>(); - final Map> commands = plugin.getDescription().getCommands(); + Map> commands = plugin.getDescription().getCommands(); if (commands != null) { - final Iterator>> commandsIt = commands.entrySet().iterator(); + Iterator>> commandsIt = commands.entrySet().iterator(); while (commandsIt.hasNext()) { - final Entry> thisEntry = commandsIt.next(); + Entry> thisEntry = commandsIt.next(); if (thisEntry != null) { parsedCommands.add(thisEntry.getKey()); } } } - if (parsedCommands.isEmpty()) { - return null; - } + if (parsedCommands.isEmpty()) { return null; } return Joiner.on(", ").join(parsedCommands); } @@ -289,7 +286,7 @@ public class PluginsManager { * - 插件 * @return 是否 */ - public boolean isIgnored(final Plugin plugin) { + public boolean isIgnored(Plugin plugin) { return isIgnored(plugin.getName()); } @@ -300,11 +297,9 @@ public class PluginsManager { * - 插件名称 * @return 是否 */ - public boolean isIgnored(final String plugin) { - for (final String name : ignoreList) { - if (name.equalsIgnoreCase(plugin)) { - return true; - } + public boolean isIgnored(String plugin) { + for (String name : ignoreList) { + if (name.equalsIgnoreCase(plugin)) { return true; } } return false; } @@ -318,17 +313,17 @@ public class PluginsManager { * - 插件文件 * @return 是否成功 */ - public boolean load(final CommandSender sender, final File pluginFile) { + public boolean load(CommandSender sender, File pluginFile) { Plugin target = null; - final String name = pluginFile.getName(); + String name = pluginFile.getName(); try { try { target = Bukkit.getPluginManager().loadPlugin(pluginFile); - } catch (final UnsupportedClassVersionError e) { + } catch (UnsupportedClassVersionError e) { sender.sendMessage("§4异常: §c" + e.getMessage()); sender.sendMessage("§c服务器或JAVA的版本低于插件: " + name + " 所需要的版本!!"); return false; - } catch (final InvalidPluginException e) { + } catch (InvalidPluginException e) { if (e.getMessage().equalsIgnoreCase("Plugin already initialized!")) { sender.sendMessage("§4异常: §c" + e.getMessage()); sender.sendMessage("§4插件: §c" + name + " 已载入到服务器!"); @@ -339,7 +334,7 @@ public class PluginsManager { sender.sendMessage("§4文件: §c" + name + " 不是一个可载入的插件!"); sender.sendMessage("§4注意: §cMOD服重载插件3次以上需重启服务器"); return false; - } catch (final UnknownDependencyException e) { + } catch (UnknownDependencyException e) { sender.sendMessage("§4异常: §c服务器未安装必须依赖: " + e.getMessage()); sender.sendMessage("§4插件: §c" + name + " 载入失败 缺少部分依赖项目!"); return false; @@ -352,7 +347,7 @@ public class PluginsManager { Bukkit.getPluginManager().enablePlugin(target); sender.sendMessage("§6载入: §a插件 §b" + target.getName() + " §a版本 §d" + getVersion(target) + " §a已成功载入到服务器!"); return true; - } catch (final Throwable e) { + } catch (Throwable e) { sender.sendMessage("§4错误: §c" + e.getClass().getName() + ": " + e.getMessage()); sender.sendMessage("§4异常: §c具体信息请查看后台异常堆栈!"); e.printStackTrace(); @@ -370,7 +365,7 @@ public class PluginsManager { * - 插件名称 * @return 是否成功 */ - public boolean load(CommandSender sender, final String name) { + public boolean load(CommandSender sender, String name) { String filename = name; if (sender == null) { sender = Bukkit.getConsoleSender(); @@ -378,8 +373,8 @@ public class PluginsManager { if (!name.endsWith(".jar")) { filename = name + ".jar"; } - final File pluginDir = new File("plugins"); - final File updateDir = new File(pluginDir, "update"); + File pluginDir = new File("plugins"); + File updateDir = new File(pluginDir, "update"); if (!pluginDir.isDirectory()) { sender.sendMessage("§6载入: §c插件目录不存在或IO错误!"); return false; @@ -389,15 +384,15 @@ public class PluginsManager { if (!pluginFile.isFile() && !new File(updateDir, filename).isFile()) { pluginFile = null; - for (final File file : pluginDir.listFiles()) { + for (File file : pluginDir.listFiles()) { if (file.getName().endsWith(".jar")) { try { - final PluginDescriptionFile desc = main.getPluginLoader().getPluginDescription(file); + PluginDescriptionFile desc = main.getPluginLoader().getPluginDescription(file); if (desc.getName().equalsIgnoreCase(name)) { pluginFile = file; break; } - } catch (final InvalidDescriptionException e) { + } catch (InvalidDescriptionException e) { } } } @@ -416,7 +411,7 @@ public class PluginsManager { * - 插件名称 * @return 是否成功 */ - public boolean load(final File pluginFile) { + public boolean load(File pluginFile) { return load(Bukkit.getConsoleSender(), pluginFile); } @@ -427,7 +422,7 @@ public class PluginsManager { * - 插件名称 * @return 是否成功 */ - public boolean load(final String name) { + public boolean load(String name) { return load(Bukkit.getConsoleSender(), name); } @@ -440,10 +435,8 @@ public class PluginsManager { * - 插件 * @return 是否成功 */ - public boolean reload(final CommandSender sender, final Plugin plugin) { - if (plugin != null) { - return unload(sender, plugin) && load(sender, plugin.getName()); - } + public boolean reload(CommandSender sender, Plugin plugin) { + if (plugin != null) { return unload(sender, plugin) && load(sender, plugin.getName()); } return false; } @@ -456,10 +449,8 @@ public class PluginsManager { * - 插件 * @return 是否成功 */ - public boolean reload(final CommandSender sender, final String name) { - if (name != null) { - return unload(sender, name) && load(sender, name); - } + public boolean reload(CommandSender sender, String name) { + if (name != null) { return unload(sender, name) && load(sender, name); } return false; } @@ -470,7 +461,7 @@ public class PluginsManager { * - 插件 * @return 是否成功 */ - public boolean reload(final Plugin plugin) { + public boolean reload(Plugin plugin) { return reload(Bukkit.getConsoleSender(), plugin); } @@ -478,7 +469,7 @@ public class PluginsManager { * 重载所有插件 */ public void reloadAll() { - for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { if (!isIgnored(plugin)) { unload(plugin); } @@ -489,14 +480,14 @@ public class PluginsManager { /** * 重载所有插件 */ - public void reloadAll(final CommandSender sender) { - final Plugin[] plist = Bukkit.getPluginManager().getPlugins(); - for (final Plugin plugin : plist) { + public void reloadAll(CommandSender sender) { + Plugin[] plist = Bukkit.getPluginManager().getPlugins(); + for (Plugin plugin : plist) { if (!isIgnored(plugin)) { unload(sender, plugin); } } - for (final Plugin plugin : plist) { + for (Plugin plugin : plist) { if (!isIgnored(plugin)) { load(sender, plugin.getName()); } @@ -510,7 +501,7 @@ public class PluginsManager { * - 插件名称 * @return 是否成功 */ - public boolean removeIgnore(final String name) { + public boolean removeIgnore(String name) { return ignoreList.remove(name); } @@ -523,7 +514,7 @@ public class PluginsManager { * - 插件 * @return 是否成功 */ - public boolean unload(final CommandSender sender, final Plugin plugin) { + public boolean unload(CommandSender sender, Plugin plugin) { return unload(sender, plugin.getName()); } @@ -537,47 +528,47 @@ public class PluginsManager { * @return 是否成功 */ @SuppressWarnings("unchecked") - public boolean unload(CommandSender sender, final String name) { + public boolean unload(CommandSender sender, String name) { if (sender == null) { sender = Bukkit.getConsoleSender(); } - final PluginManager pluginManager = Bukkit.getPluginManager(); + PluginManager pluginManager = Bukkit.getPluginManager(); SimpleCommandMap commandMap = null; List plugins = null; Map lookupNames = null; Map knownCommands = null; - // final Map fileAssociations = null; + // Map fileAssociations = null; if (pluginManager == null) { sender.sendMessage("§4异常: §c插件管理类反射获取失败!"); return false; } try { - final Field pluginsField = pluginManager.getClass().getDeclaredField("plugins"); + Field pluginsField = pluginManager.getClass().getDeclaredField("plugins"); pluginsField.setAccessible(true); plugins = (List) pluginsField.get(pluginManager); - final Field lookupNamesField = pluginManager.getClass().getDeclaredField("lookupNames"); + Field lookupNamesField = pluginManager.getClass().getDeclaredField("lookupNames"); lookupNamesField.setAccessible(true); lookupNames = (Map) lookupNamesField.get(pluginManager); - final Field commandMapField = pluginManager.getClass().getDeclaredField("commandMap"); + Field commandMapField = pluginManager.getClass().getDeclaredField("commandMap"); commandMapField.setAccessible(true); commandMap = (SimpleCommandMap) commandMapField.get(pluginManager); - final Field knownCommandsField = commandMap.getClass().getDeclaredField("knownCommands"); + Field knownCommandsField = commandMap.getClass().getDeclaredField("knownCommands"); knownCommandsField.setAccessible(true); knownCommands = (Map) knownCommandsField.get(commandMap); - // final Field fileAssociationsField = pluginManager.getClass().getDeclaredField("fileAssociations"); + // Field fileAssociationsField = pluginManager.getClass().getDeclaredField("fileAssociations"); // fileAssociationsField.setAccessible(true); // fileAssociations = (Map) fileAssociationsField.get(pluginManager); - } catch (final Exception e) { + } catch (Exception e) { sender.sendMessage("§4异常: §c" + e.getMessage() + " 插件 §b" + name + " §c卸载失败!"); return false; } String pluginVersion = ""; - for (final Plugin next : pluginManager.getPlugins()) { + for (Plugin next : pluginManager.getPlugins()) { if (next.getName().equals(name)) { pluginManager.disablePlugin(next); if ((plugins != null) && (plugins.contains(next))) { @@ -591,10 +582,10 @@ public class PluginsManager { sender.sendMessage("§6卸载: §a从插件查找列表删除 §b" + name + " §a的实例!"); } - for (final Iterator> it = knownCommands.entrySet().iterator(); it.hasNext();) { - final Map.Entry entry = it.next(); + for (Iterator> it = knownCommands.entrySet().iterator(); it.hasNext();) { + Map.Entry entry = it.next(); if ((entry.getValue() instanceof PluginCommand)) { - final PluginCommand command = (PluginCommand) entry.getValue(); + PluginCommand command = (PluginCommand) entry.getValue(); if (command.getPlugin() == next) { command.unregister(commandMap); it.remove(); @@ -603,31 +594,31 @@ public class PluginsManager { } // try { // if (fileAssociations != null) { - // for (final Entry entry : fileAssociations.entrySet()) { - // final Matcher match = entry.getKey().matcher(getPluginFile(next).getName()); + // for (Entry entry : fileAssociations.entrySet()) { + // Matcher match = entry.getKey().matcher(getPluginFile(next).getName()); // if (match.find()) { // PluginLoader pluginLoader = entry.getValue(); // if (pluginLoader instanceof YumPluginLoader) { // pluginLoader = ((YumPluginLoader) pluginLoader).internal_loader; // } - // final Field loadersField = pluginLoader.getClass().getDeclaredField("loaders"); + // Field loadersField = pluginLoader.getClass().getDeclaredField("loaders"); // loadersField.setAccessible(true); - // final Map loaders = (Map) loadersField.get(pluginLoader); - // for (final Entry entry2 : loaders.entrySet()) { + // Map loaders = (Map) loadersField.get(pluginLoader); + // for (Entry entry2 : loaders.entrySet()) { // Reflect.on(entry2.getValue()).set("pluginInit", null).set("plugin", null); // } // sender.sendMessage("§6卸载: §a移除插件 §b" + name + " §a的类实例缓存!"); // } // } // } - // } catch (final Exception e) { + // } catch (Exception e) { // e.printStackTrace(); // } sender.sendMessage("§6卸载: §a注销插件 §b" + name + " §a的所有命令!"); - final ClassLoader cl = next.getClass().getClassLoader(); + ClassLoader cl = next.getClass().getClassLoader(); try { ((URLClassLoader) cl).close(); - } catch (final IOException ex) { + } catch (IOException ex) { } System.gc(); } @@ -646,7 +637,7 @@ public class PluginsManager { * - 卸载插件 * @return 是否成功 */ - public boolean unload(final Plugin plugin) { + public boolean unload(Plugin plugin) { return unload(Bukkit.getConsoleSender(), plugin); } @@ -655,7 +646,7 @@ public class PluginsManager { * * @return 是否成功 */ - public boolean upgrade(final CommandSender sender) { + public boolean upgrade(CommandSender sender) { sender.sendMessage("§6升级: §a开始升级 服务器更新 目录下的所有插件!"); return upgrade(sender, null, null); } @@ -669,9 +660,9 @@ public class PluginsManager { * - 更新目录 * @return 是否成功 */ - public boolean upgrade(final CommandSender sender, final File directory, final Plugin plugin) { + public boolean upgrade(CommandSender sender, File directory, Plugin plugin) { boolean result = false; - final PluginLoader loader = main.getPluginLoader(); + PluginLoader loader = main.getPluginLoader(); File updateDirectory; if (directory == null || !directory.isDirectory()) { updateDirectory = Bukkit.getServer().getUpdateFolderFile(); @@ -691,23 +682,23 @@ public class PluginsManager { sender.sendMessage("§4异常: §c文件夹 §d" + updateDirectory.getName() + " §c权限不足或IO错误!"); return false; } - final File[] plugins = updateDirectory.listFiles(); + File[] plugins = updateDirectory.listFiles(); if (plugins.length == 0) { sender.sendMessage("§6升级: §d更新文件夹未找到插件!"); return false; } - for (final File file : updateDirectory.listFiles()) { + for (File file : updateDirectory.listFiles()) { if (file.isDirectory()) { continue; } PluginDescriptionFile description = null; try { description = loader.getPluginDescription(file); - final String name = description.getName(); + String name = description.getName(); if (plugin != null && !name.equals(plugin.getName())) { continue; } - final Plugin oldplugin = Bukkit.getPluginManager().getPlugin(name); + Plugin oldplugin = Bukkit.getPluginManager().getPlugin(name); result = true; File dest = null; if (!unload(sender, name)) { @@ -715,7 +706,8 @@ public class PluginsManager { dest = new File(Bukkit.getUpdateFolderFile().getParentFile(), File.separatorChar + file.getName()); } else { if (oldplugin != null) { - dest = new File(Bukkit.getUpdateFolderFile(), File.separatorChar + getPluginFile(oldplugin).getName()); + dest = new File(Bukkit.getUpdateFolderFile(), File.separatorChar + + getPluginFile(oldplugin).getName()); } sender.sendMessage("§6升级: §a开始升级 §b" + name + " §a插件!"); } @@ -723,7 +715,7 @@ public class PluginsManager { file.renameTo(dest); } load(sender, name); - } catch (final InvalidDescriptionException e) { + } catch (InvalidDescriptionException e) { sender.sendMessage("§4异常: §c" + e.getMessage()); sender.sendMessage("§4文件: §c" + file.getName() + " 的plugin.yml文件存在错误!"); } @@ -740,7 +732,7 @@ public class PluginsManager { * * @return 是否成功 */ - public boolean upgrade(final CommandSender sender, final Plugin plugin) { + public boolean upgrade(CommandSender sender, Plugin plugin) { return upgrade(sender, null, plugin); } @@ -749,7 +741,7 @@ public class PluginsManager { * * @return 是否成功 */ - public boolean upgrade(final File directory) { + public boolean upgrade(File directory) { Bukkit.getConsoleSender().sendMessage("§6升级: §a开始升级 §d" + directory.getName() + " §a目录下的所有插件!"); return upgrade(Bukkit.getConsoleSender(), directory, null); } diff --git a/src/main/java/pw/yumc/Yum/managers/RepositoryManager.java b/src/main/java/pw/yumc/Yum/managers/RepositoryManager.java index 8f6e376..8a22764 100644 --- a/src/main/java/pw/yumc/Yum/managers/RepositoryManager.java +++ b/src/main/java/pw/yumc/Yum/managers/RepositoryManager.java @@ -14,7 +14,6 @@ import org.bukkit.command.CommandSender; import org.json.simple.JSONObject; import org.json.simple.JSONValue; -import cn.citycraft.PluginHelper.kit.StrKit; import pw.yumc.Yum.models.PluginInfo; import pw.yumc.Yum.models.RepoCache; import pw.yumc.Yum.models.RepoSerialization.PackageInfo; @@ -35,30 +34,24 @@ public class RepositoryManager { org.bukkit.plugin.Plugin main; RepoCache repocache; - public RepositoryManager(final org.bukkit.plugin.Plugin plugin) { + public RepositoryManager(org.bukkit.plugin.Plugin plugin) { this.main = plugin; repocache = new RepoCache(); } - public boolean addPackage(final CommandSender sender, final String urlstring) { - final String json = HttpKit.get(urlstring); - if (json == null || json.isEmpty()) { - return false; - } - final PackageInfo pkg = jsonToPackage(json); - if (pkg == null) { - return false; - } + public boolean addPackage(CommandSender sender, String urlstring) { + String json = HttpKit.get(urlstring); + if (json == null || json.isEmpty()) { return false; } + PackageInfo pkg = jsonToPackage(json); + if (pkg == null) { return false; } updatePackage(sender, pkg); return true; } - public boolean addRepositories(final CommandSender sender, final String urlstring) { - final String url = handerRepoUrl(urlstring); - final Repositories repo = repocache.addRepo(url); - if (repo == null) { - return false; - } + public boolean addRepositories(CommandSender sender, String urlstring) { + String url = handerRepoUrl(urlstring); + Repositories repo = repocache.addRepo(url); + if (repo == null) { return false; } return updateRepositories(sender, repo); } @@ -66,56 +59,57 @@ public class RepositoryManager { repocache.getPlugins().clear(); } - public boolean delRepositories(final CommandSender sender, final String urlstring) { + public boolean delRepositories(CommandSender sender, String urlstring) { return repocache.removeRepo(handerRepoUrl(urlstring)); } public List getAllPlugin() { - final List li = new ArrayList<>(); - for (final Entry plugin : repocache.getPlugins().entrySet()) { + List li = new ArrayList<>(); + for (Entry plugin : repocache.getPlugins().entrySet()) { li.add(plugin.getValue()); } return li; } public List getAllPluginName() { - final List li = new ArrayList<>(); - for (final Entry plugin : repocache.getPlugins().entrySet()) { + List li = new ArrayList<>(); + for (Entry plugin : repocache.getPlugins().entrySet()) { li.add(plugin.getValue().name); } return li; } public List getAllPluginsInfo() { - final List li = new ArrayList<>(); + List li = new ArrayList<>(); li.add("§d仓库名称 §a插件名称 §e插件描述"); - for (final Entry pi : repocache.getPlugins().entrySet()) { - final Plugin plugin = pi.getValue().plugin; + for (Entry pi : repocache.getPlugins().entrySet()) { + Plugin plugin = pi.getValue().plugin; li.add(String.format("§d%s §a%s §6- §e%s", pi.getValue().repo, pi.getValue().name, plugin.description)); if (plugin.tags != null) { li.add(" §b┗Tags §c标签 §a版本 §e类型"); - final List taglist = plugin.tags; + List taglist = plugin.tags; for (int i = 0; i < taglist.size(); i++) { - final TagInfo tag = taglist.get(i); - li.add(" §b" + (i == taglist.size() - 1 ? "┗ " : "┣ ") + String.format("§c%s §a%s §e%s", tag.tag, tag.version, tag.type != null ? tag.type : URLType.Maven)); + TagInfo tag = taglist.get(i); + li.add(" §b" + (i == taglist.size() - 1 ? "┗ " : "┣ ") + String.format("§c%s §a%s §e%s", + tag.tag, + tag.version, + tag.type != null ? tag.type : URLType.Maven)); } } } return li; } - public PluginInfo getPlugin(final String name) { - for (final Entry plugin : repocache.getPlugins().entrySet()) { - if (plugin.getValue().name.equalsIgnoreCase(name)) { - return plugin.getValue(); - } + public PluginInfo getPlugin(String name) { + for (Entry plugin : repocache.getPlugins().entrySet()) { + if (plugin.getValue().name.equalsIgnoreCase(name)) { return plugin.getValue(); } } return null; } - public List getPluginInfo(final String name) { - final List li = new ArrayList<>(); - for (final Entry plugin : repocache.getPlugins().entrySet()) { + public List getPluginInfo(String name) { + List li = new ArrayList<>(); + for (Entry plugin : repocache.getPlugins().entrySet()) { if (plugin.getValue().name.equalsIgnoreCase(name)) { li.add(plugin.getValue()); } @@ -123,7 +117,7 @@ public class RepositoryManager { return li; } - public PluginInfo getPluginInfo(final String groupId, final String artifactId) { + public PluginInfo getPluginInfo(String groupId, String artifactId) { return repocache.getPlugins().get(groupId + "." + artifactId); } @@ -135,7 +129,7 @@ public class RepositoryManager { return repocache; } - public Repositories getRepoCache(final String urlstring) { + public Repositories getRepoCache(String urlstring) { return repocache.getRepos().get(handerRepoUrl(urlstring)); } @@ -143,28 +137,26 @@ public class RepositoryManager { return repocache.getRepos(); } - public boolean getRepositories(final CommandSender sender, final String urlstring) { - final int urllength = urlstring.length(); - final String url = urlstring.substring(0, urlstring.endsWith("/") ? urllength - 1 : urllength); + public boolean getRepositories(CommandSender sender, String urlstring) { + int urllength = urlstring.length(); + String url = urlstring.substring(0, urlstring.endsWith("/") ? urllength - 1 : urllength); handerRepoUrl(url); - final Repositories repo = repocache.addRepo(urlstring); - if (repo == null) { - return false; - } + Repositories repo = repocache.addRepo(urlstring); + if (repo == null) { return false; } return updateRepositories(sender, repo); } - public PackageInfo jsonToPackage(final String json) { + public PackageInfo jsonToPackage(String json) { return new PackageInfo((JSONObject) JSONValue.parse(json)); } - public void updatePackage(final CommandSender sender, final PackageInfo pkg) { - for (final Plugin plugin : pkg.plugins) { - final PluginInfo pi = new PluginInfo(); - pi.name = StrKit.getNotNull(plugin.name, plugin.artifactId); - pi.branch = StrKit.getNotNull(plugin.branch, "master"); - pi.pom = StrKit.getNotNull(plugin.pom, pkg.pom); - pi.url = StrKit.getNotNull(plugin.url, pkg.url); + public void updatePackage(CommandSender sender, PackageInfo pkg) { + for (Plugin plugin : pkg.plugins) { + PluginInfo pi = new PluginInfo(); + pi.name = getNotNull(plugin.name, plugin.artifactId); + pi.branch = getNotNull(plugin.branch, "master"); + pi.pom = getNotNull(plugin.pom, pkg.pom); + pi.url = getNotNull(plugin.url, pkg.url); pi.type = plugin.type != null ? plugin.type : pkg.type; pi.type = pi.type != null ? pi.type : URLType.Maven; pi.plugin = plugin; @@ -174,15 +166,19 @@ public class RepositoryManager { sender.sendMessage("§6仓库: §e" + pkg.name + " §a更新成功!"); } - public boolean updateRepositories(final CommandSender sender) { + public static String getNotNull(final String vault, final String def) { + return (vault == null || vault.isEmpty() || vault.equalsIgnoreCase("null")) ? def : vault; + } + + public boolean updateRepositories(CommandSender sender) { repocache.getPlugins().clear(); if (repocache.getRepos().isEmpty()) { repocache.addRepo("http://data.yumc.pw/yumcenter/repo.info"); } - final Iterator> keys = repocache.getRepos().entrySet().iterator(); + Iterator> keys = repocache.getRepos().entrySet().iterator(); while (keys.hasNext()) { - final Entry string = keys.next(); - final Repositories repo = repocache.getRepo(string.getKey()); + Entry string = keys.next(); + Repositories repo = repocache.getRepo(string.getKey()); if (updateRepositories(sender, repo)) { sender.sendMessage("§6源: §e" + repo.name + " §a更新成功!"); } else { @@ -193,7 +189,7 @@ public class RepositoryManager { return true; } - public boolean updateRepositories(CommandSender sender, final Repositories repocenter) { + public boolean updateRepositories(CommandSender sender, Repositories repocenter) { if (sender == null) { sender = Bukkit.getConsoleSender(); } @@ -201,14 +197,14 @@ public class RepositoryManager { sender.sendMessage(String.format("§6[§bYum§6] 源 %s 数据为空或列表为空!", repocenter.name)); return false; } - for (final Repository repo : repocenter.repos) { + for (Repository repo : repocenter.repos) { addPackage(sender, repo.url); } return true; } private String handerRepoUrl(String url) { - final int urllength = url.length(); + int urllength = url.length(); url = url.substring(0, url.endsWith("/") ? urllength - 1 : urllength); if (!url.startsWith("http://")) { url = "http://" + url; diff --git a/src/main/java/pw/yumc/Yum/models/BukkitDev.java b/src/main/java/pw/yumc/Yum/models/BukkitDev.java index f4363ea..0e5ad2d 100644 --- a/src/main/java/pw/yumc/Yum/models/BukkitDev.java +++ b/src/main/java/pw/yumc/Yum/models/BukkitDev.java @@ -27,7 +27,7 @@ public class BukkitDev implements Serializable { public String md5; public String releaseType; - public Files(final JSONObject obj) { + public Files(JSONObject obj) { projectId = Integer.parseInt(obj.get("projectId").toString()); name = obj.get("name").toString(); fileUrl = obj.get("fileUrl").toString(); @@ -38,12 +38,10 @@ public class BukkitDev implements Serializable { releaseType = obj.get("releaseType").toString(); } - public static List parseList(final String json) { - if (StrKit.isBlank(json) || json.equals("[]")) { - return Collections.emptyList(); - } - final List temp = new ArrayList<>(); - final JSONArray ja = (JSONArray) JSONValue.parse(json); + public static List parseList(String json) { + if (StrKit.isBlank(json) || json.equals("[]")) { return Collections.emptyList(); } + List temp = new ArrayList<>(); + JSONArray ja = (JSONArray) JSONValue.parse(json); for (int i = 0; i < ja.size(); i++) { temp.add(new Files((JSONObject) ja.get(i))); } @@ -58,19 +56,17 @@ public class BukkitDev implements Serializable { public String slug; public String stage; - public Projects(final JSONObject obj) { + public Projects(JSONObject obj) { id = Integer.parseInt(obj.get("id").toString()); name = obj.get("name").toString(); slug = obj.get("slug").toString(); stage = obj.get("stage").toString(); } - public static List parseList(final String json) { - if (StrKit.isBlank(json) || json.equals("[]")) { - return Collections.emptyList(); - } - final List temp = new ArrayList<>(); - final JSONArray ja = (JSONArray) JSONValue.parse(json); + public static List parseList(String json) { + if (StrKit.isBlank(json) || json.equals("[]")) { return Collections.emptyList(); } + List temp = new ArrayList<>(); + JSONArray ja = (JSONArray) JSONValue.parse(json); for (int i = 0; i < ja.size(); i++) { temp.add(new Projects((JSONObject) ja.get(i))); } diff --git a/src/main/java/pw/yumc/Yum/models/PluginInfo.java b/src/main/java/pw/yumc/Yum/models/PluginInfo.java index 9d00b0a..de4123a 100644 --- a/src/main/java/pw/yumc/Yum/models/PluginInfo.java +++ b/src/main/java/pw/yumc/Yum/models/PluginInfo.java @@ -2,10 +2,12 @@ package pw.yumc.Yum.models; import java.io.Serializable; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; -import cn.citycraft.PluginHelper.utils.IOUtil; import pw.yumc.Yum.models.RepoSerialization.Plugin; import pw.yumc.Yum.models.RepoSerialization.TagInfo; import pw.yumc.Yum.models.RepoSerialization.URLType; @@ -17,7 +19,7 @@ public class PluginInfo implements Serializable { static { try { NMSVersion = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; - } catch (final Exception e) { + } catch (Exception e) { Log.warning("服务器NMS解析失败: " + Bukkit.getServer().getClass().getPackage().getName()); NMSVersion = "NONMS"; } @@ -53,7 +55,7 @@ public class PluginInfo implements Serializable { * 版本 * @return 下载直链 */ - public String getDirectUrl(final String version) { + public String getDirectUrl(String version) { return url.replace("[version]", version); } @@ -73,7 +75,7 @@ public class PluginInfo implements Serializable { * 插件版本 * @return 文件名称 */ - public String getFileName(final String version) { + public String getFileName(String version) { return String.format("%1$s-%2$s.jar", plugin.artifactId, version); } @@ -86,29 +88,30 @@ public class PluginInfo implements Serializable { * - 需要更新的版本 * @return 更新地址 */ - public String getMavenUrl(final String ver) { - return String.format(url + (url.endsWith("/") ? "" : "/") + "%1$s/%2$s/%3$s/%2$s-%3$s.jar", plugin.groupId.replace(".", "/"), plugin.artifactId, (ver == null || ver.isEmpty()) ? plugin.version : ver); + public String getMavenUrl(String ver) { + return String.format(url + (url.endsWith("/") ? "" : "/") + "%1$s/%2$s/%3$s/%2$s-%3$s.jar", + plugin.groupId.replace(".", "/"), + plugin.artifactId, + (ver == null || ver.isEmpty()) ? plugin.version : ver); } - public String getUrl(final CommandSender sender, final String version) { + public String getUrl(CommandSender sender, String version) { String ver = version; if (ver == null) { if (plugin.tags != null) { Log.debug("发现存在TAG标签 开始检索: " + NMSVersion); - for (final TagInfo tagInfo : plugin.tags) { + for (TagInfo tagInfo : plugin.tags) { if (tagInfo.tag.equalsIgnoreCase(NMSVersion)) { sender.sendMessage("§6版本: §b从Tag标签中获取 §e" + NMSVersion + " §b的最新版本..."); ver = tagInfo.version; - if (tagInfo.type == URLType.DirectUrl) { - return tagInfo.url; - } + if (tagInfo.type == URLType.DirectUrl) { return tagInfo.url; } break; } } } else if (pom != null && !pom.isEmpty()) { pom = pom.replace("[name]", name).replace("[branch]", branch); sender.sendMessage("§6版本: §b尝试从在线POM文件获取最新版本..."); - ver = IOUtil.getXMLTag(pom, "version", null); + ver = getXMLTag(pom, "version", null); if (ver != null) { sender.sendMessage("§6版本: §a成功获取到最新版本 §e" + ver + " §a..."); } @@ -127,4 +130,26 @@ public class PluginInfo implements Serializable { return null; } } + + /** + * 获得XML文件标签信息 + * + * @param url + * XML文件地址 + * @param tag + * 信息标签 + * @param def + * 默认值 + * @return 插件信息 + */ + public static String getXMLTag(final String url, final String tag, final String def) { + String result = def; + try { + final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + final DocumentBuilder builder = factory.newDocumentBuilder(); + result = builder.parse(url).getElementsByTagName(tag).item(0).getTextContent(); + } catch (final Exception e) { + } + return result; + } } \ No newline at end of file diff --git a/src/main/java/pw/yumc/Yum/models/RepoCache.java b/src/main/java/pw/yumc/Yum/models/RepoCache.java index 3b5c5ea..55f0815 100644 --- a/src/main/java/pw/yumc/Yum/models/RepoCache.java +++ b/src/main/java/pw/yumc/Yum/models/RepoCache.java @@ -10,33 +10,29 @@ import java.util.Map.Entry; import org.json.simple.JSONObject; import org.json.simple.JSONValue; -import cn.citycraft.PluginHelper.utils.IOUtil; import pw.yumc.Yum.models.RepoSerialization.Repositories; import pw.yumc.YumCore.bukkit.Log; +import pw.yumc.YumCore.kit.HttpKit; public class RepoCache implements Serializable { Map plugins = new HashMap<>(); Map repos = new HashMap<>(); - public void addPlugins(final String name, final PluginInfo info) { + public void addPlugins(String name, PluginInfo info) { plugins.put(name, info); } - public Repositories addRepo(final String repo) { - if (repos.containsKey(repo) || repo.isEmpty()) { - return null; - } - final Repositories reposes = getRepo(repo); - if (reposes == null) { - return null; - } + public Repositories addRepo(String repo) { + if (repos.containsKey(repo) || repo.isEmpty()) { return null; } + Repositories reposes = getRepo(repo); + if (reposes == null) { return null; } repos.put(repo, reposes); return reposes; } public List getAllRepoInfo() { - final List repoinfo = new ArrayList<>(); - for (final Entry repo : repos.entrySet()) { + List repoinfo = new ArrayList<>(); + for (Entry repo : repos.entrySet()) { repoinfo.add(String.format("§d仓库: §e%s §6- §3%s", repo.getValue().name, repo.getKey())); } return repoinfo; @@ -46,13 +42,13 @@ public class RepoCache implements Serializable { return plugins; } - public Repositories getRepo(final String repo) { - final String json = IOUtil.getData(repo); + public Repositories getRepo(String repo) { + String json = HttpKit.get(repo); if (json == null || json.isEmpty()) { Log.console("§c源地址获取数据为空 §b" + repo); return null; } - final Repositories reposes = new Repositories((JSONObject) JSONValue.parse(json)); + Repositories reposes = new Repositories((JSONObject) JSONValue.parse(json)); if (reposes.repos.isEmpty()) { Log.console("§c源地址解析Json为空 §b" + repo); return null; @@ -64,10 +60,8 @@ public class RepoCache implements Serializable { return repos; } - public boolean removeRepo(final String repo) { - if (repo.isEmpty() || !repos.containsKey(repo)) { - return false; - } + public boolean removeRepo(String repo) { + if (repo.isEmpty() || !repos.containsKey(repo)) { return false; } repos.remove(repo); return true; } diff --git a/src/main/java/pw/yumc/Yum/models/RepoSerialization.java b/src/main/java/pw/yumc/Yum/models/RepoSerialization.java index 51d597e..2f321ff 100644 --- a/src/main/java/pw/yumc/Yum/models/RepoSerialization.java +++ b/src/main/java/pw/yumc/Yum/models/RepoSerialization.java @@ -20,12 +20,10 @@ import org.json.simple.JSONValue; */ public class RepoSerialization { @SuppressWarnings("unchecked") - public static List parse(final String json, final Class clazz) { - if (json == null || "null".equals(json) || json.isEmpty()) { - return null; - } - final List temp = new ArrayList<>(); - final JSONArray ja = (JSONArray) JSONValue.parse(json); + public static List parse(String json, Class clazz) { + if (json == null || "null".equals(json) || json.isEmpty()) { return null; } + List temp = new ArrayList<>(); + JSONArray ja = (JSONArray) JSONValue.parse(json); for (int i = 0; i < ja.size(); i++) { try { temp.add((E) clazz.getConstructor(JSONObject.class).newInstance((JSONObject) ja.get(i))); @@ -43,12 +41,12 @@ public class RepoSerialization { public String url; public URLType type; - public PackageInfo(final JSONObject obj) { + public PackageInfo(JSONObject obj) { name = String.valueOf(obj.get("name")); plugins = Plugin.parseList(String.valueOf(obj.get("plugins"))); pom = String.valueOf(obj.get("pom")); url = String.valueOf(obj.get("url")); - final Object tt = obj.get("type"); + Object tt = obj.get("type"); type = tt == null ? null : URLType.valueOf(tt.toString()); } } @@ -65,7 +63,7 @@ public class RepoSerialization { public String version; public URLType type; - public Plugin(final JSONObject obj) { + public Plugin(JSONObject obj) { artifactId = String.valueOf(obj.get("artifactId")); branch = String.valueOf(obj.get("branch")); description = String.valueOf(obj.get("description")); @@ -75,11 +73,11 @@ public class RepoSerialization { pom = String.valueOf(obj.get("pom")); tags = TagInfo.parseList(String.valueOf(obj.get("tags"))); version = String.valueOf(obj.get("version")); - final Object tt = obj.get("type"); + Object tt = obj.get("type"); type = tt == null ? null : URLType.valueOf(tt.toString()); } - public static List parseList(final String json) { + public static List parseList(String json) { return parse(json, Plugin.class); } } @@ -88,7 +86,7 @@ public class RepoSerialization { public String name; public List repos; - public Repositories(final JSONObject obj) { + public Repositories(JSONObject obj) { name = String.valueOf(obj.get("name")); repos = Repository.parseList(String.valueOf(obj.get("repos"))); } @@ -99,14 +97,14 @@ public class RepoSerialization { public URLType type; public String url; - public Repository(final JSONObject obj) { + public Repository(JSONObject obj) { id = String.valueOf(obj.get("id")); - final Object tt = obj.get("type"); + Object tt = obj.get("type"); type = tt == null ? null : URLType.valueOf(tt.toString()); url = String.valueOf(obj.get("url")); } - public static List parseList(final String json) { + public static List parseList(String json) { return parse(json, Repository.class); } } @@ -117,15 +115,15 @@ public class RepoSerialization { public URLType type; public String url; - public TagInfo(final JSONObject obj) { + public TagInfo(JSONObject obj) { tag = String.valueOf(obj.get("tag")); version = String.valueOf(obj.get("version")); - final Object tt = obj.get("type"); + Object tt = obj.get("type"); type = tt == null ? null : URLType.valueOf(tt.toString()); url = String.valueOf(obj.get("url")); } - public static List parseList(final String json) { + public static List parseList(String json) { return parse(json, TagInfo.class); } } diff --git a/src/main/java/pw/yumc/Yum/runnables/MainThreadCheckTask.java b/src/main/java/pw/yumc/Yum/runnables/MainThreadCheckTask.java index 7591454..7efe4b5 100644 --- a/src/main/java/pw/yumc/Yum/runnables/MainThreadCheckTask.java +++ b/src/main/java/pw/yumc/Yum/runnables/MainThreadCheckTask.java @@ -1,13 +1,16 @@ package pw.yumc.Yum.runnables; import java.lang.Thread.State; +import java.lang.reflect.Method; import java.util.TimerTask; +import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -import cn.citycraft.PluginHelper.kit.ServerKit; import pw.yumc.YumCore.bukkit.Log; +import pw.yumc.YumCore.bukkit.compatible.C; import pw.yumc.YumCore.kit.PKit; +import pw.yumc.YumCore.plugin.protocollib.PacketKit; /** * 线程安全检查任务 @@ -16,16 +19,25 @@ import pw.yumc.YumCore.kit.PKit; * @author 喵♂呜 */ public class MainThreadCheckTask extends TimerTask { - private final String prefix = "§6[§bYum §a线程管理§6] "; - private final String warnPNet = "§6插件 §b%s §c在主线程进行网络操作 §4服务器处于停止状态..."; - private final String warnPIO = "§6插件 §b%s §c在主线程进行IO操作 §4服务器处于停止状态..."; - private final String warnNet = "§c主线程存在网络操作 §4服务器处于停止状态..."; - private final String warnIO = "§c主线程存在IO操作 §4服务器处于停止状态..."; - private final String deliver = "§c服务器处于停止状态 已超过 %s 秒 激活心跳 防止线程关闭..."; + private static Method tickMethod; + private String prefix = "§6[§bYum §a线程管理§6] "; + private String warnPNet = "§6插件 §b%s §c在主线程进行网络操作 §4服务器处于停止状态..."; + private String warnPIO = "§6插件 §b%s §c在主线程进行IO操作 §4服务器处于停止状态..."; + private String warnNet = "§c主线程存在网络操作 §4服务器处于停止状态..."; + private String warnIO = "§c主线程存在IO操作 §4服务器处于停止状态..."; + private String deliver = "§c服务器处于停止状态 已超过 %s 秒 激活心跳 防止线程关闭..."; private int stopTime = 0; - private final Thread mainThread; + private Thread mainThread; - public MainThreadCheckTask(final Thread mainThread) { + static { + try { + Class clazz = Class.forName("org.spigotmc.WatchdogThread"); + tickMethod = clazz.getDeclaredMethod("tick"); + } catch (Exception e) { + } + } + + public MainThreadCheckTask(Thread mainThread) { this.mainThread = mainThread; } @@ -37,8 +49,8 @@ public class MainThreadCheckTask extends TimerTask { if (mainThread.getState() == State.RUNNABLE) { // Based on this post we have to check the top element of the stack // https://stackoverflow.com/questions/20891386/how-to-detect-thread-being-blocked-by-io - final StackTraceElement[] stackTrace = mainThread.getStackTrace(); - final StackTraceElement topElement = stackTrace[0]; + StackTraceElement[] stackTrace = mainThread.getStackTrace(); + StackTraceElement topElement = stackTrace[0]; if (topElement.isNativeMethod()) { // Socket/SQL (connect) - java.net.DualStackPlainSocketImpl.connect0 // Socket/SQL (read) - java.net.SocketInputStream.socketRead0 @@ -46,7 +58,7 @@ public class MainThreadCheckTask extends TimerTask { if (isElementEqual(topElement, "java.net.DualStackPlainSocketImpl", "connect0") || isElementEqual(topElement, "java.net.SocketInputStream", "socketRead0") || isElementEqual(topElement, "java.net.SocketOutputStream", "socketWrite0")) { - final Plugin plugin = PKit.getOperatePlugin(stackTrace); + Plugin plugin = PKit.getOperatePlugin(stackTrace); if (plugin != null) { Log.console(prefix + warnPNet, plugin.getName()); } else { @@ -56,8 +68,9 @@ public class MainThreadCheckTask extends TimerTask { } // File (in) - java.io.FileInputStream.readBytes // File (out) - java.io.FileOutputStream.writeBytes - else if (isElementEqual(topElement, "java.io.FileInputStream", "readBytes") || isElementEqual(topElement, "java.io.FileOutputStream", "writeBytes")) { - final Plugin plugin = PKit.getOperatePlugin(stackTrace); + else if (isElementEqual(topElement, "java.io.FileInputStream", "readBytes") + || isElementEqual(topElement, "java.io.FileOutputStream", "writeBytes")) { + Plugin plugin = PKit.getOperatePlugin(stackTrace); if (plugin != null) { Log.console(prefix + warnPIO, plugin.getName()); } else { @@ -73,7 +86,7 @@ public class MainThreadCheckTask extends TimerTask { } } - private boolean isElementEqual(final StackTraceElement traceElement, final String className, final String methodName) { + private boolean isElementEqual(StackTraceElement traceElement, String className, String methodName) { return traceElement.getClassName().equals(className) && traceElement.getMethodName().equals(methodName); } @@ -81,7 +94,23 @@ public class MainThreadCheckTask extends TimerTask { stopTime += 5; if (stopTime >= 45) { Log.console(prefix + deliver, stopTime); - ServerKit.tick(); + wttick(); + } + } + + /** + * 保持服务器心跳 + */ + public static void wttick() { + try { + if (tickMethod != null) { + tickMethod.invoke(null); + } + for (final Player player : C.Player.getOnlinePlayers()) { + player.sendMessage("§4注意: §c服务器主线程处于停止状态 请等待操作完成!"); + PacketKit.keep_live(player); + } + } catch (final Throwable e) { } } }