refactor: 使用新类库

Signed-off-by: 502647092 <admin@yumc.pw>
This commit is contained in:
502647092 2016-10-25 15:03:21 +08:00
parent 277f42bd2e
commit ce110a5dd6
31 changed files with 1068 additions and 1049 deletions

13
pom.xml
View File

@ -33,7 +33,6 @@
<artifactSet> <artifactSet>
<includes> <includes>
<include>pw.yumc:YumCore</include> <include>pw.yumc:YumCore</include>
<include>cn.citycraft:PluginHelper</include>
</includes> </includes>
</artifactSet> </artifactSet>
<relocations> <relocations>
@ -41,10 +40,6 @@
<pattern>pw.yumc.YumCore</pattern> <pattern>pw.yumc.YumCore</pattern>
<shadedPattern>${project.groupId}.${project.artifactId}</shadedPattern> <shadedPattern>${project.groupId}.${project.artifactId}</shadedPattern>
</relocation> </relocation>
<relocation>
<pattern>cn.citycraft.PluginHelper</pattern>
<shadedPattern>${project.groupId}.${project.artifactId}</shadedPattern>
</relocation>
</relocations> </relocations>
</configuration> </configuration>
<executions> <executions>
@ -97,17 +92,11 @@
<type>jar</type> <type>jar</type>
<version>1.10.2-R0.1-SNAPSHOT</version> <version>1.10.2-R0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency>
<groupId>cn.citycraft</groupId>
<artifactId>PluginHelper</artifactId>
<type>jar</type>
<version>1.0</version>
</dependency>
<dependency> <dependency>
<groupId>pw.yumc</groupId> <groupId>pw.yumc</groupId>
<artifactId>YumCore</artifactId> <artifactId>YumCore</artifactId>
<type>jar</type> <type>jar</type>
<version>1.0</version> <version>1.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>pw.yumc</groupId> <groupId>pw.yumc</groupId>

View File

@ -10,8 +10,6 @@ import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin; 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.api.YumAPI;
import pw.yumc.Yum.commands.FileCommand; import pw.yumc.Yum.commands.FileCommand;
import pw.yumc.Yum.commands.MonitorCommand; 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.managers.NetworkManager;
import pw.yumc.Yum.runnables.MainThreadCheckTask; import pw.yumc.Yum.runnables.MainThreadCheckTask;
import pw.yumc.YumCore.bukkit.Log; import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.reflect.Reflect;
import pw.yumc.YumCore.statistic.Statistics; import pw.yumc.YumCore.statistic.Statistics;
import pw.yumc.YumCore.update.SubscribeTask; import pw.yumc.YumCore.update.SubscribeTask;
@ -73,7 +72,7 @@ public class Yum extends JavaPlugin {
// 初始化配置 // 初始化配置
ConfigManager.i(); ConfigManager.i();
// 初始化更新列 // 初始化更新列
UpdatePlugin.getUpdateList(); // UpdatePlugin.getUpdateList();
// 启用网络注入 // 启用网络注入
NetworkManager.register(this); NetworkManager.register(this);
} }
@ -82,7 +81,7 @@ public class Yum extends JavaPlugin {
* @return 主线程 * @return 主线程
*/ */
private Thread getMainThread() { 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"); return Reflect.on(console).get("primaryThread");
} }
@ -102,15 +101,15 @@ public class Yum extends JavaPlugin {
private void initListeners() { private void initListeners() {
if (ConfigManager.i().isSetOpEnable()) { if (ConfigManager.i().isSetOpEnable()) {
try { try {
final ClassLoader cl = Class.forName("pw.yumc.injected.event.SetOpEvent").getClassLoader(); ClassLoader cl = Class.forName("pw.yumc.injected.event.SetOpEvent").getClassLoader();
try { try {
cl.getClass().getDeclaredField("plugin"); cl.getClass().getDeclaredField("plugin");
throw new ClassNotFoundException(); throw new ClassNotFoundException();
} catch (final NoSuchFieldException | SecurityException e) { } catch (NoSuchFieldException | SecurityException e) {
new SecurityListener(this); new SecurityListener(this);
Log.console("§a安全管理系统已启用..."); Log.console("§a安全管理系统已启用...");
} }
} catch (final ClassNotFoundException e) { } catch (ClassNotFoundException e) {
Log.console("§c服务端未注入安全拦截器 关闭功能..."); Log.console("§c服务端未注入安全拦截器 关闭功能...");
} }
} }

View File

@ -4,13 +4,11 @@ import java.io.File;
import java.net.URL; import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map.Entry;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import cn.citycraft.CommonData.UpdatePlugin;
import pw.yumc.Yum.inject.CommandInjector; import pw.yumc.Yum.inject.CommandInjector;
import pw.yumc.Yum.inject.ListenerInjector; import pw.yumc.Yum.inject.ListenerInjector;
import pw.yumc.Yum.inject.TaskInjector; import pw.yumc.Yum.inject.TaskInjector;
@ -55,7 +53,7 @@ public class YumAPI {
* @param plugin * @param plugin
* 插件实体 * 插件实体
*/ */
public static void delete(final Plugin plugin) { public static void delete(Plugin plugin) {
plugman.deletePlugin(plugin); plugman.deletePlugin(plugin);
} }
@ -86,16 +84,16 @@ public class YumAPI {
return repo; return repo;
} }
public static List<Plugin> getUpdateList(final CommandSender sender) { public static List<Plugin> getUpdateList(CommandSender sender) {
final List<Plugin> ulist = new ArrayList<>(); List<Plugin> ulist = new ArrayList<>();
try { // try {
for (final Entry<String, Plugin> updateplugin : UpdatePlugin.getUpdateList().entrySet()) { // for (Entry<String, Plugin> updateplugin : UpdatePlugin.getUpdateList().entrySet()) {
ulist.add(updateplugin.getValue()); // ulist.add(updateplugin.getValue());
} // }
} catch (final Exception | Error e) { // } catch (Exception | Error e) {
sender.sendMessage("§4错误: §c无法检索全体更新列表!"); // sender.sendMessage("§4错误: §c无法检索全体更新列表!");
sender.sendMessage("§4异常: §c" + e.getMessage()); // sender.sendMessage("§4异常: §c" + e.getMessage());
} // }
return ulist; return ulist;
} }
@ -105,7 +103,7 @@ public class YumAPI {
* @param plugin * @param plugin
* 插件 * 插件
*/ */
public static void inject(final Plugin plugin) { public static void inject(Plugin plugin) {
if (plugin.isEnabled() && !ConfigManager.i().getMonitorIgnoreList().contains(plugin.getName())) { if (plugin.isEnabled() && !ConfigManager.i().getMonitorIgnoreList().contains(plugin.getName())) {
CommandInjector.inject(plugin); CommandInjector.inject(plugin);
ListenerInjector.inject(plugin); ListenerInjector.inject(plugin);
@ -124,11 +122,9 @@ public class YumAPI {
* 插件版本 * 插件版本
* @return 是否安装成功 * @return 是否安装成功
*/ */
public static boolean install(final CommandSender sender, final String pluginname, final String url) { public static boolean install(CommandSender sender, String pluginname, String url) {
final File pluginFile = new File(Bukkit.getUpdateFolderFile().getParentFile(), pluginname + ".jar"); File pluginFile = new File(Bukkit.getUpdateFolderFile().getParentFile(), pluginname + ".jar");
if (download.run(sender, url, pluginFile)) { if (download.run(sender, url, pluginFile)) { return plugman.load(sender, pluginFile); }
return plugman.load(sender, pluginFile);
}
return false; return false;
} }
@ -141,7 +137,7 @@ public class YumAPI {
* 插件版本 * 插件版本
* @return 是否安装成功 * @return 是否安装成功
*/ */
public static boolean install(final String pluginname, final String url) { public static boolean install(String pluginname, String url) {
return install(null, pluginname, url); return install(null, pluginname, url);
} }
@ -154,7 +150,7 @@ public class YumAPI {
* 插件名称 * 插件名称
* @return 是否安装成功 * @return 是否安装成功
*/ */
public static boolean installFromYum(final CommandSender sender, final String pluginname) { public static boolean installFromYum(CommandSender sender, String pluginname) {
return installFromYum(sender, pluginname, null); return installFromYum(sender, pluginname, null);
} }
@ -169,11 +165,9 @@ public class YumAPI {
* 插件版本 * 插件版本
* @return 是否安装成功 * @return 是否安装成功
*/ */
public static boolean installFromYum(final CommandSender sender, final String pluginname, final String version) { public static boolean installFromYum(CommandSender sender, String pluginname, String version) {
final PluginInfo pi = repo.getPlugin(pluginname); PluginInfo pi = repo.getPlugin(pluginname);
if (pi != null) { if (pi != null) { return install(sender, pi.name, pi.getUrl(sender, version)); }
return install(sender, pi.name, pi.getUrl(sender, version));
}
sender.sendMessage("§4错误: §c仓库中未找到插件 §b" + pluginname + " §c安装失败!"); sender.sendMessage("§4错误: §c仓库中未找到插件 §b" + pluginname + " §c安装失败!");
return false; return false;
} }
@ -184,7 +178,7 @@ public class YumAPI {
* @param pluginname * @param pluginname
* 插件名称 * 插件名称
*/ */
public static void load(final File pluginFile) { public static void load(File pluginFile) {
plugman.load(pluginFile); plugman.load(pluginFile);
} }
@ -194,7 +188,7 @@ public class YumAPI {
* @param pluginname * @param pluginname
* 插件名称 * 插件名称
*/ */
public static void load(final String pluginname) { public static void load(String pluginname) {
plugman.load(pluginname); plugman.load(pluginname);
} }
@ -204,7 +198,7 @@ public class YumAPI {
* @param plugin * @param plugin
* 插件实体 * 插件实体
*/ */
public static void reload(final Plugin plugin) { public static void reload(Plugin plugin) {
plugman.reload(plugin); plugman.reload(plugin);
} }
@ -215,7 +209,7 @@ public class YumAPI {
* 插件 * 插件
*/ */
public static void uninject() { public static void uninject() {
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
YumAPI.uninject(plugin); YumAPI.uninject(plugin);
} }
} }
@ -226,7 +220,7 @@ public class YumAPI {
* @param plugin * @param plugin
* 插件 * 插件
*/ */
public static void uninject(final Plugin plugin) { public static void uninject(Plugin plugin) {
CommandInjector.uninject(plugin); CommandInjector.uninject(plugin);
ListenerInjector.uninject(plugin); ListenerInjector.uninject(plugin);
TaskInjector.uninject(plugin); TaskInjector.uninject(plugin);
@ -238,7 +232,7 @@ public class YumAPI {
* @param plugin * @param plugin
* 插件实体 * 插件实体
*/ */
public static void unload(final Plugin plugin) { public static void unload(Plugin plugin) {
plugman.unload(plugin); plugman.unload(plugin);
} }
@ -253,8 +247,10 @@ public class YumAPI {
* 新插件的下载地址 * 新插件的下载地址
* @return 是否更新成功 * @return 是否更新成功
*/ */
public static boolean update(final CommandSender sender, final Plugin plugin, final URL url) { public static boolean update(CommandSender sender, Plugin plugin, URL url) {
if (download.run(sender, url, new File(Bukkit.getUpdateFolderFile(), plugman.getPluginFile(plugin).getName()))) { if (download.run(sender,
url,
new File(Bukkit.getUpdateFolderFile(), plugman.getPluginFile(plugin).getName()))) {
sender.sendMessage("§6更新: §e已下载 " + plugin.getName() + " 插件到服务器更新文件夹"); sender.sendMessage("§6更新: §e已下载 " + plugin.getName() + " 插件到服务器更新文件夹");
sender.sendMessage("§6更新: §e插件将在重启后自动更新(或使用§b/yum upgrade§e直接升级)!"); sender.sendMessage("§6更新: §e插件将在重启后自动更新(或使用§b/yum upgrade§e直接升级)!");
return true; return true;
@ -271,7 +267,7 @@ public class YumAPI {
* 新插件的下载地址 * 新插件的下载地址
* @return 是否更新成功 * @return 是否更新成功
*/ */
public static boolean update(final Plugin plugin, final URL url) { public static boolean update(Plugin plugin, URL url) {
return update(null, plugin, url); return update(null, plugin, url);
} }
@ -291,10 +287,10 @@ public class YumAPI {
} }
runlock = true; runlock = true;
int failed = 0; int failed = 0;
final List<Plugin> ulist = getUpdateList(sender); List<Plugin> ulist = getUpdateList(sender);
if (ulist.size() > 0) { if (ulist.size() > 0) {
sender.sendMessage("§d开始更新服务器可更新插件"); sender.sendMessage("§d开始更新服务器可更新插件");
for (final Plugin updateplugin : ulist) { for (Plugin updateplugin : ulist) {
sender.sendMessage("§d一键更新: §a开始更新" + updateplugin.getName() + "!"); sender.sendMessage("§d一键更新: §a开始更新" + updateplugin.getName() + "!");
if (!updateFromYum(sender, updateplugin, null, true)) { if (!updateFromYum(sender, updateplugin, null, true)) {
failed++; failed++;
@ -324,9 +320,10 @@ public class YumAPI {
PKit.runTaskLaterAsync(new Runnable() { PKit.runTaskLaterAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
final List<Plugin> ulist = getUpdateList(sender); List<Plugin> ulist = getUpdateList(sender);
if (ulist.size() > 0) { 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); }, 60);
@ -341,7 +338,7 @@ public class YumAPI {
* 插件实体 * 插件实体
* @return 是否更新成功 * @return 是否更新成功
*/ */
public static boolean updateFromYum(final CommandSender sender, final Plugin plugin) { public static boolean updateFromYum(CommandSender sender, Plugin plugin) {
return updateFromYum(sender, plugin, null); return updateFromYum(sender, plugin, null);
} }
@ -356,7 +353,7 @@ public class YumAPI {
* 插件版本(null则自动获取) * 插件版本(null则自动获取)
* @return * @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); return updateFromYum(sender, plugin, version, false);
} }
@ -373,16 +370,16 @@ public class YumAPI {
* 是否一键更新 * 是否一键更新
* @return * @return
*/ */
public static boolean updateFromYum(final CommandSender sender, final Plugin plugin, final String version, final boolean oneKeyUpdate) { public static boolean updateFromYum(CommandSender sender, Plugin plugin, String version, boolean oneKeyUpdate) {
final PluginInfo pi = repo.getPlugin(plugin.getName()); PluginInfo pi = repo.getPlugin(plugin.getName());
if (pi != null) { 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 (download.run(sender, pi.getUrl(sender, version), pFile)) {
if (!oneKeyUpdate) { if (!oneKeyUpdate) {
sender.sendMessage("§6更新: §e已下载 " + plugin.getName() + " 插件到服务器更新文件夹"); sender.sendMessage("§6更新: §e已下载 " + plugin.getName() + " 插件到服务器更新文件夹");
sender.sendMessage("§6更新: §e插件将在重启后自动更新(或使用§b/yum upgrade§e直接升级)!"); sender.sendMessage("§6更新: §e插件将在重启后自动更新(或使用§b/yum upgrade§e直接升级)!");
} }
UpdatePlugin.getUpdateList().remove(plugin.getName()); //UpdatePlugin.getUpdateList().remove(plugin.getName());
return true; return true;
} }
} else { } else {
@ -398,7 +395,7 @@ public class YumAPI {
PKit.runTaskLater(new Runnable() { PKit.runTaskLater(new Runnable() {
@Override @Override
public void run() { public void run() {
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
YumAPI.inject(plugin); YumAPI.inject(plugin);
} }
} }
@ -423,7 +420,7 @@ public class YumAPI {
* @param sender * @param sender
* 命令发送者 * 命令发送者
*/ */
public static void upgrade(final CommandSender sender) { public static void upgrade(CommandSender sender) {
plugman.upgrade(sender); plugman.upgrade(sender);
} }
@ -435,7 +432,7 @@ public class YumAPI {
* @param plugin * @param plugin
* 插件实体 * 插件实体
*/ */
public static void upgrade(final CommandSender sender, final Plugin plugin) { public static void upgrade(CommandSender sender, Plugin plugin) {
plugman.upgrade(sender, plugin); plugman.upgrade(sender, plugin);
} }
} }

View File

@ -12,16 +12,15 @@ import java.nio.file.StandardCopyOption;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; 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.Yum;
import pw.yumc.Yum.api.YumAPI; 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.CommandManager;
import pw.yumc.YumCore.commands.annotation.Async; import pw.yumc.YumCore.commands.annotation.Async;
import pw.yumc.YumCore.commands.annotation.Cmd; import pw.yumc.YumCore.commands.annotation.Cmd;
import pw.yumc.YumCore.commands.annotation.Help; 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命令基类 * File命令基类
@ -43,13 +42,13 @@ public class FileCommand implements CommandExecutor {
private static String noResult = prefix + "§d当前命令没有返回结果!"; private static String noResult = prefix + "§d当前命令没有返回结果!";
private static String runError = prefix + "§c命令运行错误: %s %s"; private static String runError = prefix + "§c命令运行错误: %s %s";
private static String addStartupSuccess = "§a成功添加开机自动启..."; private static String addStartupSuccess = "§e %s §a成功添加开机自动启...";
private static String addStartupFailed = "§c添加开机自动启失败!"; private static String addStartupFailed = "§c添加开机自动启失败 %s %s!";
private static String STARTPATH = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp"; private static String STARTPATH = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp";
Yum plugin; Yum plugin;
public FileCommand(final Yum yum) { public FileCommand(Yum yum) {
plugin = yum; plugin = yum;
new CommandManager("file", this, PluginTabComplete.instence); new CommandManager("file", this, PluginTabComplete.instence);
} }
@ -57,34 +56,23 @@ public class FileCommand implements CommandExecutor {
@Cmd(aliases = "cp", minimumArguments = 2) @Cmd(aliases = "cp", minimumArguments = 2)
@Help(value = "复制文件", possibleArguments = "<源文件> <目标目录>") @Help(value = "复制文件", possibleArguments = "<源文件> <目标目录>")
@Async @Async
public void copy(final CommandArgument e) throws FileNotFoundException, IOException { public void copy(CommandSender sender, @KeyValue(key = "check") File src, File des) 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;
}
if (src.isDirectory()) { if (src.isDirectory()) {
sender.sendMessage(String.format(file_is_dir, args[0])); sender.sendMessage(String.format(file_is_dir, src.getPath()));
return; return;
} }
if (Files.copy(new FileInputStream(src), des.toPath(), StandardCopyOption.REPLACE_EXISTING) != 0) { 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 { } else {
sender.sendMessage(String.format(copyFailed, args[0])); sender.sendMessage(String.format(copyFailed, src.getPath()));
} }
} }
@Cmd(aliases = "del", minimumArguments = 1) @Cmd(aliases = "del", minimumArguments = 1)
@Help(value = "删除文件(服务器JAR为根目录)", possibleArguments = "<文件相对目录>") @Help(value = "删除文件(服务器JAR为根目录)", possibleArguments = "<文件相对目录>")
@Async @Async
public void delete(final CommandArgument e) { public void delete(CommandSender sender, String fpath) {
final String[] args = e.getArgs(); File file = new File(fpath);
String fpath = args[0];
final File file = new File(fpath);
final CommandSender sender = e.getSender();
fpath = file.getAbsolutePath(); fpath = file.getAbsolutePath();
if (!file.exists()) { if (!file.exists()) {
sender.sendMessage(String.format(file_not_found, fpath)); sender.sendMessage(String.format(file_not_found, fpath));
@ -95,7 +83,7 @@ public class FileCommand implements CommandExecutor {
} }
try { try {
sender.sendMessage("§d文件 §e" + fpath + " " + (file.delete() ? "§a删除成功!" : "§c删除失败!")); sender.sendMessage("§d文件 §e" + fpath + " " + (file.delete() ? "§a删除成功!" : "§c删除失败!"));
} catch (final Exception ex) { } catch (Exception ex) {
sender.sendMessage("§d文件 §e" + fpath + " 删除失败: " + ex.getMessage()); sender.sendMessage("§d文件 §e" + fpath + " 删除失败: " + ex.getMessage());
} }
} }
@ -104,37 +92,33 @@ public class FileCommand implements CommandExecutor {
@Cmd(aliases = "d", minimumArguments = 1) @Cmd(aliases = "d", minimumArguments = 1)
@Help(value = "下载文件(默认保存到服务器更新文件夹)", possibleArguments = "<下载地址> [保存文件路径]") @Help(value = "下载文件(默认保存到服务器更新文件夹)", possibleArguments = "<下载地址> [保存文件路径]")
@Async @Async
public void download(final CommandArgument e) { public void download(CommandSender sender, String urlstr, String path) {
final String[] args = e.getArgs();
String urlstr = args[0];
if (!urlstr.startsWith("http")) { if (!urlstr.startsWith("http")) {
urlstr = "http://" + urlstr; urlstr = "http://" + urlstr;
} }
File file = null; File file = null;
if (args.length == 2) { if (path != null) {
file = new File(args[1]); file = new File(path);
} else { } else {
file = new File(Bukkit.getUpdateFolderFile(), YumAPI.getDownload().getFileName(urlstr)); 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") @Cmd(aliases = "ls")
@Help(value = "列出当前目录(服务器JAR为根目录)", possibleArguments = "<相对目录>") @Help(value = "列出当前目录(服务器JAR为根目录)", possibleArguments = "<相对目录>")
@Async @Async
public void ls(final CommandArgument e) { public void ls(CommandSender sender, String filename) {
final String[] args = e.getArgs();
final CommandSender sender = e.getSender();
File dir = new File("."); File dir = new File(".");
if (args.length == 1) { if (filename != null) {
dir = new File(args[0]); dir = new File(filename);
} }
if (!dir.isDirectory()) { if (!dir.isDirectory()) {
sender.sendMessage("§6路径: §e " + dir.getAbsolutePath() + " §c不是一个目录!"); sender.sendMessage("§6路径: §e " + dir.getAbsolutePath() + " §c不是一个目录!");
return; return;
} }
final StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (final File file : dir.listFiles()) { for (File file : dir.listFiles()) {
if (file.isDirectory()) { if (file.isDirectory()) {
sb.append("§b"); sb.append("§b");
} else { } else {
@ -142,7 +126,7 @@ public class FileCommand implements CommandExecutor {
} }
sb.append(file.getName() + " "); sb.append(file.getName() + " ");
} }
final String filelist = sb.toString(); String filelist = sb.toString();
if (filelist.isEmpty()) { if (filelist.isEmpty()) {
sender.sendMessage("§6目录: §e" + dir.getAbsolutePath() + " §c下没有文件或文件夹!"); sender.sendMessage("§6目录: §e" + dir.getAbsolutePath() + " §c下没有文件或文件夹!");
} else { } else {
@ -154,19 +138,16 @@ public class FileCommand implements CommandExecutor {
@Cmd(aliases = "rn", minimumArguments = 2) @Cmd(aliases = "rn", minimumArguments = 2)
@Help(value = "重命名文件(服务器JAR为根目录)", possibleArguments = "<文件相对路径> <文件名称>") @Help(value = "重命名文件(服务器JAR为根目录)", possibleArguments = "<文件相对路径> <文件名称>")
@Async @Async
public void rename(final CommandArgument e) { public void rename(CommandSender sender, String fpath, String des) {
final String[] args = e.getArgs(); File file = new File(fpath);
final CommandSender sender = e.getSender();
final String fpath = args[0];
final File file = new File(fpath);
if (!file.exists()) { if (!file.exists()) {
sender.sendMessage("§c文件 " + file.getAbsolutePath() + " 不存在!"); sender.sendMessage("§c文件 " + file.getAbsolutePath() + " 不存在!");
} else { } else {
try { try {
final File newFile = new File(file.getParentFile(), args[1]); File newFile = new File(file.getParentFile(), des);
file.renameTo(newFile); file.renameTo(newFile);
sender.sendMessage("§a文件 §e" + file.getAbsolutePath() + " §a重命名为 §d" + newFile.getAbsolutePath()); 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()); sender.sendMessage("§c文件 §e" + file.getAbsolutePath() + " §c重命名失败: " + ex.getMessage());
} }
} }
@ -175,11 +156,8 @@ public class FileCommand implements CommandExecutor {
@Cmd(minimumArguments = 1) @Cmd(minimumArguments = 1)
@Help(value = "删除文件夹(服务器JAR为根目录)", possibleArguments = "<相对目录>") @Help(value = "删除文件夹(服务器JAR为根目录)", possibleArguments = "<相对目录>")
@Async @Async
public void rm(final CommandArgument e) { public void rm(CommandSender sender, String fpath, String option) {
final String[] args = e.getArgs(); File file = new File(fpath);
final CommandSender sender = e.getSender();
final String fpath = args[0];
final File file = new File(fpath);
if (!file.exists()) { if (!file.exists()) {
sender.sendMessage("§c目录 " + file.getAbsolutePath() + " 不存在!"); sender.sendMessage("§c目录 " + file.getAbsolutePath() + " 不存在!");
} else { } else {
@ -187,33 +165,32 @@ public class FileCommand implements CommandExecutor {
sender.sendMessage("§d路径 §e" + file.getAbsolutePath() + " §c是一个文件 请使用file delete!"); sender.sendMessage("§d路径 §e" + file.getAbsolutePath() + " §c是一个文件 请使用file delete!");
return; return;
} }
for (final String name : plugin.getConfig().getStringList("blacklist")) { for (String name : plugin.getConfig().getStringList("blacklist")) {
if (file.getAbsolutePath().toLowerCase().endsWith(name)) { if (file.getAbsolutePath().toLowerCase().endsWith(name)) {
sender.sendMessage("§d路径 §e" + file.getAbsolutePath() + " §c不允许被删除!"); sender.sendMessage("§d路径 §e" + file.getAbsolutePath() + " §c不允许被删除!");
return; 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("§d目录 §e" + file.getAbsolutePath() + " §c不为空!");
sender.sendMessage("§c请使用 §a/file rm " + fpath + " -rf §c强行删除!"); sender.sendMessage("§c请使用 §a/file rm " + fpath + " -rf §c强行删除!");
return; 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) @Cmd(aliases = "r", minimumArguments = 1)
@Help(value = "运行一个命令或文件", possibleArguments = "<命令或文件绝对路径>") @Help(value = "运行一个命令或文件", possibleArguments = "<命令或文件绝对路径>")
@Async @Async
public void run(final CommandArgument e) { public void run(CommandSender sender, String args) {
final String[] args = e.getArgs();
final CommandSender sender = e.getSender();
try { try {
final Process process = Runtime.getRuntime().exec(StrKit.join(args, " ")); Process process = Runtime.getRuntime().exec(args);
sender.sendMessage(waitCommand); sender.sendMessage(waitCommand);
final BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null; String line = null;
final StringBuilder build = new StringBuilder(); StringBuilder build = new StringBuilder();
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
build.append(line); build.append(line);
build.append("\n"); build.append("\n");
@ -224,7 +201,7 @@ public class FileCommand implements CommandExecutor {
sender.sendMessage(runResult); sender.sendMessage(runResult);
sender.sendMessage(build.toString().split("\n")); sender.sendMessage(build.toString().split("\n"));
} }
} catch (final Exception e2) { } catch (Exception e2) {
sender.sendMessage(String.format(runError, e2.getClass().getSimpleName(), e2.getMessage())); sender.sendMessage(String.format(runError, e2.getClass().getSimpleName(), e2.getMessage()));
} }
} }
@ -232,23 +209,22 @@ public class FileCommand implements CommandExecutor {
@Cmd(minimumArguments = 1) @Cmd(minimumArguments = 1)
@Help(value = "添加开机自启动", possibleArguments = "<文件绝对路径>") @Help(value = "添加开机自启动", possibleArguments = "<文件绝对路径>")
@Async @Async
public void startup(final CommandArgument e) { public void startup(CommandSender sender, String filepath) {
final String[] args = e.getArgs(); File src = new File(filepath);
final CommandSender sender = e.getSender(); File des = new File(STARTPATH, src.getName());
final File src = new File(args[0]);
final File des = new File(STARTPATH, src.getName());
if (!src.exists()) { if (!src.exists()) {
sender.sendMessage(String.format(file_not_found, args[0])); sender.sendMessage(String.format(file_not_found, filepath));
return; return;
} }
if (src.isDirectory()) { if (src.isDirectory()) {
sender.sendMessage(String.format(file_is_dir, args[0])); sender.sendMessage(String.format(file_is_dir, filepath));
return; return;
} }
if (FileUtil.copyFile(src, des)) { try {
sender.sendMessage(String.format(addStartupSuccess, args[0])); Files.copy(new FileInputStream(src), des.toPath(), StandardCopyOption.REPLACE_EXISTING);
} else { sender.sendMessage(String.format(addStartupSuccess, filepath));
sender.sendMessage(String.format(addStartupFailed, args[0])); } catch (Exception e2) {
sender.sendMessage(String.format(addStartupFailed, e2.getClass().getName(), e2.getMessage()));
} }
} }
} }

View File

@ -20,8 +20,6 @@ import org.bukkit.plugin.RegisteredListener;
import org.bukkit.plugin.TimedRegisteredListener; import org.bukkit.plugin.TimedRegisteredListener;
import org.bukkit.scheduler.BukkitTask; 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.Yum;
import pw.yumc.Yum.api.YumAPI; import pw.yumc.Yum.api.YumAPI;
import pw.yumc.Yum.inject.CommandInjector; 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.inject.TaskInjector;
import pw.yumc.Yum.managers.MonitorManager; import pw.yumc.Yum.managers.MonitorManager;
import pw.yumc.Yum.managers.MonitorManager.MonitorInfo; 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.CommandManager;
import pw.yumc.YumCore.commands.annotation.Async; import pw.yumc.YumCore.commands.annotation.Async;
import pw.yumc.YumCore.commands.annotation.Cmd; import pw.yumc.YumCore.commands.annotation.Cmd;
import pw.yumc.YumCore.commands.annotation.Help; 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.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 class MonitorCommand implements CommandExecutor {
public static Throwable lastError = null; 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 String no_mi = prefix + "§6%s §a自服务器启动以来尚未执行任何操作";
private final String micprefix = " §6命令名称 §a总耗时 §b执行次数 §d平均耗时"; private String micprefix = " §6命令名称 §a总耗时 §b执行次数 §d平均耗时";
private final String mieprefix = " §6事件名称 §a总耗时 §b执行次数 §d平均耗时"; private String mieprefix = " §6事件名称 §a总耗时 §b执行次数 §d平均耗时";
private final String mitprefix = " §6任务名称 §a总耗时 §b执行次数 §d平均耗时"; private String mitprefix = " §6任务名称 §a总耗时 §b执行次数 §d平均耗时";
private final String milist = "§6- §e%-20s §a%-9.2f §b%-9s §d%-9.5f"; private 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 miwlist = "§6- §c%-20s §a%-9.2f §b%-9s §c%-9.5f";
private final String reinject = prefix + "§a能耗监控器重载完毕!"; private String reinject = prefix + "§a能耗监控器重载完毕!";
private final String injected = prefix + "§a插件 §b%s §a成功注入能耗监控器!"; private String injected = prefix + "§a插件 §b%s §a成功注入能耗监控器!";
private final String uninjected = prefix + "§a插件 §b%s §a成功撤销能耗监控器!"; private String uninjected = prefix + "§a插件 §b%s §a成功撤销能耗监控器!";
private final String notEnable = prefix + "§c插件 §b%s §c未成功加载 无法执行注入!"; private String notEnable = prefix + "§c插件 §b%s §c未成功加载 无法执行注入!";
private final String lag = prefix + "§a当前服务器插件能耗如下§6(单位: %)"; private String lag = prefix + "§a当前服务器插件能耗如下§6(单位: %)";
private final String lagprefix = " §6插件名称 §c主线程 §a命令 §b事件 §d任务"; private 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 laglist = "§6%-2s §b%-20s §c%-25s §a%-5.2f §b%-5.2f §d%-5.2f";
private final String no_error = prefix + "§a自服务器启动以来尚未发现报错!"; private String no_error = prefix + "§a自服务器启动以来尚未发现报错!";
private final String last_error = prefix + "§c最后一次错误异常由 §b%s §c造成 详细如下:"; 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); new CommandManager("monitor", this, PluginTabComplete.instence);
} }
@Cmd(aliases = "c", minimumArguments = 1) @Cmd(aliases = "c", minimumArguments = 1)
@Help(value = "查看插件命令能耗", possibleArguments = "[插件名称]") @Help(value = "查看插件命令能耗", possibleArguments = "[插件名称]")
@Async @Async
public void cmd(final CommandArgument e) { public void cmd(CommandSender sender, String pname) {
final String pname = e.getArgs()[0];
final CommandSender sender = e.getSender();
if (Bukkit.getPluginManager().getPlugin(pname) == null) { if (Bukkit.getPluginManager().getPlugin(pname) == null) {
sender.sendMessage(String.format(p_n_f, pname)); sender.sendMessage(String.format(p_n_f, pname));
return; return;
} }
final PluginManager pluginManager = Bukkit.getPluginManager(); PluginManager pluginManager = Bukkit.getPluginManager();
final SimpleCommandMap commandMap = Reflect.on(pluginManager).get("commandMap"); SimpleCommandMap commandMap = Reflect.on(pluginManager).get("commandMap");
sender.sendMessage(prefix + "§6插件 §b" + pname + " §6的命令能耗如下!"); sender.sendMessage(prefix + "§6插件 §b" + pname + " §6的命令能耗如下!");
final Map<String, Command> temp = new HashMap<>(); Map<String, Command> temp = new HashMap<>();
for (final Command command : commandMap.getCommands()) { for (Command command : commandMap.getCommands()) {
if (command instanceof PluginCommand) { if (command instanceof PluginCommand) {
final PluginCommand pluginCommand = (PluginCommand) command; PluginCommand pluginCommand = (PluginCommand) command;
final Plugin plugin = pluginCommand.getPlugin(); Plugin plugin = pluginCommand.getPlugin();
if (plugin.getName().equalsIgnoreCase(pname)) { if (plugin.getName().equalsIgnoreCase(pname)) {
temp.put(command.getName(), command); temp.put(command.getName(), command);
} }
@ -102,15 +99,23 @@ public class MonitorCommand implements CommandExecutor {
return; return;
} }
sender.sendMessage(micprefix); sender.sendMessage(micprefix);
for (final Entry<String, Command> command : temp.entrySet()) { for (Entry<String, Command> command : temp.entrySet()) {
final org.bukkit.command.CommandExecutor executor = Reflect.on(command.getValue()).get("executor"); org.bukkit.command.CommandExecutor executor = Reflect.on(command.getValue()).get("executor");
if (executor instanceof CommandInjector) { if (executor instanceof CommandInjector) {
final CommandInjector injected = (CommandInjector) executor; CommandInjector injected = (CommandInjector) executor;
if (injected.count != 0) { if (injected.count != 0) {
final double avgTime = injected.totalTime / um / injected.count; double avgTime = injected.totalTime / um / injected.count;
sender.sendMessage(String.format(avgTime < 10 ? milist : miwlist, command.getValue().getName(), injected.totalTime / um, injected.count, avgTime)); sender.sendMessage(String.format(avgTime < 10 ? milist : miwlist,
command.getValue().getName(),
injected.totalTime / um,
injected.count,
avgTime));
} else { } 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) @Cmd(aliases = "e", minimumArguments = 1)
@Help(value = "查看插件事件能耗", possibleArguments = "[插件名称]") @Help(value = "查看插件事件能耗", possibleArguments = "[插件名称]")
@Async @Async
public void event(final CommandArgument e) throws InstantiationException, IllegalAccessException, NoSuchFieldException { public void event(CommandSender sender, String pname) throws InstantiationException, IllegalAccessException, NoSuchFieldException {
final String pname = e.getArgs()[0]; Plugin plugin = Bukkit.getPluginManager().getPlugin(pname);
final CommandSender sender = e.getSender();
final Plugin plugin = Bukkit.getPluginManager().getPlugin(pname);
if (plugin == null) { if (plugin == null) {
sender.sendMessage(String.format(p_n_f, pname)); sender.sendMessage(String.format(p_n_f, pname));
return; return;
} }
sender.sendMessage(prefix + "§6插件 §b" + pname + " §6的事件能耗如下!"); sender.sendMessage(prefix + "§6插件 §b" + pname + " §6的事件能耗如下!");
final List<RegisteredListener> listeners = HandlerList.getRegisteredListeners(plugin); List<RegisteredListener> listeners = HandlerList.getRegisteredListeners(plugin);
final Map<String, Long> eventTotalTime = new HashMap<>(); Map<String, Long> eventTotalTime = new HashMap<>();
final Map<String, Integer> eventCount = new HashMap<>(); Map<String, Integer> eventCount = new HashMap<>();
for (final RegisteredListener listener : listeners) { for (RegisteredListener listener : listeners) {
if (listener instanceof TimedRegisteredListener) { if (listener instanceof TimedRegisteredListener) {
final TimedRegisteredListener trl = (TimedRegisteredListener) listener; TimedRegisteredListener trl = (TimedRegisteredListener) listener;
eventTotalTime.put(trl.getEventClass().getSimpleName(), trl.getTotalTime()); eventTotalTime.put(trl.getEventClass().getSimpleName(), trl.getTotalTime());
eventCount.put(trl.getEventClass().getSimpleName(), trl.getCount()); eventCount.put(trl.getEventClass().getSimpleName(), trl.getCount());
continue; continue;
} }
EventExecutor executor = Reflect.on(listener).get("executor"); EventExecutor executor = Reflect.on(listener).get("executor");
if (listener.getClass().getName().contains("PWPRegisteredListener")) { if (listener.getClass().getName().contains("PWPRegisteredListener")) {
final Field f = Reflect.getDeclaredField(RegisteredListener.class, "executor"); Field f = Reflect.getDeclaredField(RegisteredListener.class, "executor");
f.setAccessible(true); f.setAccessible(true);
executor = (EventExecutor) f.get(listener); executor = (EventExecutor) f.get(listener);
} }
if (executor instanceof ListenerInjector) { if (executor instanceof ListenerInjector) {
final ListenerInjector injected = (ListenerInjector) executor; ListenerInjector injected = (ListenerInjector) executor;
for (final String entry : injected.eventTotalTime.keySet()) { for (String entry : injected.eventTotalTime.keySet()) {
if (eventTotalTime.containsKey(entry)) { if (eventTotalTime.containsKey(entry)) {
eventTotalTime.put(entry, eventTotalTime.get(entry) + injected.eventTotalTime.get(entry)); eventTotalTime.put(entry, eventTotalTime.get(entry) + injected.eventTotalTime.get(entry));
eventCount.put(entry, eventCount.get(entry) + injected.eventCount.get(entry)); eventCount.put(entry, eventCount.get(entry) + injected.eventCount.get(entry));
@ -162,18 +165,20 @@ public class MonitorCommand implements CommandExecutor {
return; return;
} }
sender.sendMessage(mieprefix); sender.sendMessage(mieprefix);
for (final String event : MonitorManager.sortMapByValue(eventTotalTime).keySet()) { for (String event : MonitorManager.sortMapByValue(eventTotalTime).keySet()) {
final double avgTime = eventTotalTime.get(event) / um / eventCount.get(event); 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)); sender.sendMessage(String.format(avgTime < 10 ? milist : miwlist,
event,
eventTotalTime.get(event) / um,
eventCount.get(event),
avgTime));
} }
} }
@Cmd(aliases = "i", minimumArguments = 1) @Cmd(aliases = "i", minimumArguments = 1)
@Help(value = "注入能耗监控器", possibleArguments = "[插件名称]") @Help(value = "注入能耗监控器", possibleArguments = "[插件名称]")
public void inject(final CommandArgument e) { public void inject(CommandSender sender, String pname) {
final String pname = e.getArgs()[0]; Plugin plugin = Bukkit.getPluginManager().getPlugin(pname);
final CommandSender sender = e.getSender();
final Plugin plugin = Bukkit.getPluginManager().getPlugin(pname);
if (plugin == null) { if (plugin == null) {
sender.sendMessage(String.format(p_n_f, pname)); sender.sendMessage(String.format(p_n_f, pname));
return; return;
@ -189,49 +194,47 @@ public class MonitorCommand implements CommandExecutor {
@Cmd(aliases = "l") @Cmd(aliases = "l")
@Help("查看插件总耗时") @Help("查看插件总耗时")
@Async @Async
public void lag(final CommandArgument e) { public void lag(CommandSender sender, int size) {
final CommandSender sender = e.getSender(); Map<String, Long> mm = MonitorManager.getMonitor();
final Map<String, Long> mm = MonitorManager.getMonitor();
int i = 0;
int max = 8; int max = 8;
try {
max = Integer.parseInt(e.getArgs()[0]);
} catch (final Exception ignore) {
}
sender.sendMessage(lag); sender.sendMessage(lag);
sender.sendMessage(lagprefix); sender.sendMessage(lagprefix);
for (final Entry<String, Long> entry : mm.entrySet()) { for (Entry<String, Long> entry : mm.entrySet()) {
if (++i > max) { if (++size > max) {
break; break;
} }
final MonitorInfo mi = MonitorManager.getMonitorInfo(entry.getKey()); MonitorInfo mi = MonitorManager.getMonitorInfo(entry.getKey());
sender.sendMessage(String.format(laglist, i, entry.getKey(), getPer(sender, mi.monitor), mi.cmd, mi.event, mi.task)); sender.sendMessage(String.format(laglist,
size,
entry.getKey(),
getPer(sender, mi.monitor),
mi.cmd,
mi.event,
mi.task));
} }
} }
@Cmd(aliases = "la") @Cmd(aliases = "la")
@Help("查看最后一次报错") @Help("查看最后一次报错")
@Async @Async
public void lasterror(final CommandArgument e) { public void lasterror(CommandSender sender) {
final CommandSender sender = e.getSender();
if (lastError == null) { if (lastError == null) {
sender.sendMessage(no_error); sender.sendMessage(no_error);
return; return;
} }
final Plugin plugin = PKit.getOperatePlugin(lastError.getStackTrace()); Plugin plugin = PKit.getOperatePlugin(lastError.getStackTrace());
sender.sendMessage(String.format(last_error, plugin != null ? plugin.getName() : "未知")); sender.sendMessage(String.format(last_error, plugin != null ? plugin.getName() : "未知"));
lastError.printStackTrace(); lastError.printStackTrace();
} }
@Cmd @Cmd
public void lk(final CommandArgument e) { public void lk(CommandSender sender) {
MonitorManager.sendObject(e.getSender()); MonitorManager.sendObject(sender);
} }
@Cmd(aliases = "ri") @Cmd(aliases = "ri")
@Help("重载能耗监控器") @Help("重载能耗监控器")
public void reinject(final CommandArgument e) { public void reinject(CommandSender sender) {
final CommandSender sender = e.getSender();
YumAPI.updateInject(); YumAPI.updateInject();
sender.sendMessage(reinject); sender.sendMessage(reinject);
} }
@ -239,38 +242,44 @@ public class MonitorCommand implements CommandExecutor {
@Cmd @Cmd
@Help("重置能耗监控器") @Help("重置能耗监控器")
@Async @Async
public void reset(final CommandArgument e) { public void reset(CommandSender sender) {
MonitorManager.init(); MonitorManager.init();
} }
@Cmd(aliases = "t", minimumArguments = 1) @Cmd(aliases = "t", minimumArguments = 1)
@Help(value = "查看插件任务能耗", possibleArguments = "[插件名称]") @Help(value = "查看插件任务能耗", possibleArguments = "[插件名称]")
@Async @Async
public void task(final CommandArgument e) { public void task(CommandSender sender, String pname) {
final String pname = e.getArgs()[0]; Plugin plugin = Bukkit.getPluginManager().getPlugin(pname);
final CommandSender sender = e.getSender();
final Plugin plugin = Bukkit.getPluginManager().getPlugin(pname);
if (plugin == null) { if (plugin == null) {
sender.sendMessage(String.format(p_n_f, pname)); sender.sendMessage(String.format(p_n_f, pname));
return; return;
} }
final List<BukkitTask> pendingTasks = Bukkit.getScheduler().getPendingTasks(); List<BukkitTask> pendingTasks = Bukkit.getScheduler().getPendingTasks();
if (pendingTasks.isEmpty()) { if (pendingTasks.isEmpty()) {
sender.sendMessage(String.format(no_mi, pname)); sender.sendMessage(String.format(no_mi, pname));
return; return;
} }
sender.sendMessage(prefix + "§6插件 §b" + pname + " §6的任务能耗如下!"); sender.sendMessage(prefix + "§6插件 §b" + pname + " §6的任务能耗如下!");
sender.sendMessage(mitprefix); sender.sendMessage(mitprefix);
for (final BukkitTask pendingTask : pendingTasks) { for (BukkitTask pendingTask : pendingTasks) {
if (pendingTask.getOwner().getName().equalsIgnoreCase(pname)) { 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) { if (task instanceof TaskInjector) {
final TaskInjector executor = (TaskInjector) task; TaskInjector executor = (TaskInjector) task;
if (executor.count != 0) { if (executor.count != 0) {
final double avgTime = executor.totalTime / um / executor.count; 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)); sender.sendMessage(String.format(avgTime < 10 ? milist : miwlist,
getClassName(executor.getOriginalTask().getClass()),
executor.totalTime / um,
executor.count,
avgTime));
} else { } 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) @Cmd(aliases = "ui", minimumArguments = 1)
@Help(value = "撤销能耗监控器", possibleArguments = "[插件名称]") @Help(value = "撤销能耗监控器", possibleArguments = "[插件名称]")
public void uninject(final CommandArgument e) { public void uninject(CommandSender sender, String pname) {
final String pname = e.getArgs()[0]; Plugin plugin = Bukkit.getPluginManager().getPlugin(pname);
final CommandSender sender = e.getSender();
final Plugin plugin = Bukkit.getPluginManager().getPlugin(pname);
if (plugin == null) { if (plugin == null) {
sender.sendMessage(String.format(p_n_f, pname)); sender.sendMessage(String.format(p_n_f, pname));
return; return;
@ -293,14 +300,15 @@ public class MonitorCommand implements CommandExecutor {
} }
} }
private String getClassName(final Class<?> clazz) { private String getClassName(Class<?> clazz) {
return StrKit.isBlank(clazz.getSimpleName()) ? clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1) : clazz.getSimpleName(); return StrKit.isBlank(clazz.getSimpleName()) ? clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1)
: clazz.getSimpleName();
} }
private String getPer(final CommandSender sender, final double per) { private String getPer(CommandSender sender, double per) {
final String ps = sender instanceof Player ? "||" : "|"; String ps = sender instanceof Player ? "||" : "|";
final double p = per / 5; double p = per / 5;
final StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (p < 3) { if (p < 3) {
sb.append("§a"); sb.append("§a");
} else if (p < 6) { } else if (p < 6) {

View File

@ -8,31 +8,30 @@ import org.bukkit.command.CommandSender;
import pw.yumc.Yum.Yum; import pw.yumc.Yum.Yum;
import pw.yumc.Yum.managers.ConfigManager; 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.CommandManager;
import pw.yumc.YumCore.commands.annotation.Async; import pw.yumc.YumCore.commands.annotation.Async;
import pw.yumc.YumCore.commands.annotation.Cmd; import pw.yumc.YumCore.commands.annotation.Cmd;
import pw.yumc.YumCore.commands.annotation.Help; import pw.yumc.YumCore.commands.annotation.Help;
import pw.yumc.YumCore.commands.interfaces.CommandExecutor;
public class NetCommand implements CommandExecutor { public class NetCommand implements CommandExecutor {
public static HashMap<String, Integer> netlist = new HashMap<>(); public static HashMap<String, Integer> 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 String showlist = prefix + "§a自服务器启动以来尝试联网的插件列表如下:";
private final String listprefix = " §6插件名称 §d联网次数"; private String listprefix = " §6插件名称 §d联网次数";
private final String list = "§6- §b%-20s §d%s"; private String list = "§6- §b%-20s §d%s";
private final String no_net = prefix + "§a尚未检测到尝试联网的插件!"; private String no_net = prefix + "§a尚未检测到尝试联网的插件!";
private final String add = prefix + "§a已添加插件 §b%s §a到网络 %s §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); new CommandManager("net", this, PluginTabComplete.instence);
} }
public static void addNetCount(final String pname) { public static void addNetCount(String pname) {
if (netlist.containsKey(pname)) { if (netlist.containsKey(pname)) {
netlist.put(pname, netlist.get(pname) + 1); netlist.put(pname, netlist.get(pname) + 1);
} else { } else {
@ -43,24 +42,21 @@ public class NetCommand implements CommandExecutor {
@Cmd(aliases = "l") @Cmd(aliases = "l")
@Help("列出联网的插件详情") @Help("列出联网的插件详情")
@Async @Async
public void list(final CommandArgument e) { public void list(CommandSender sender) {
final CommandSender sender = e.getSender();
if (netlist.isEmpty()) { if (netlist.isEmpty()) {
sender.sendMessage(no_net); sender.sendMessage(no_net);
return; return;
} }
sender.sendMessage(showlist); sender.sendMessage(showlist);
sender.sendMessage(listprefix); sender.sendMessage(listprefix);
for (final Entry<String, Integer> entry : netlist.entrySet()) { for (Entry<String, Integer> entry : netlist.entrySet()) {
sender.sendMessage(String.format(list, entry.getKey(), entry.getValue())); sender.sendMessage(String.format(list, entry.getKey(), entry.getValue()));
} }
} }
@Cmd(minimumArguments = 1) @Cmd(minimumArguments = 1)
@Help(value = "禁止插件联网", possibleArguments = "[插件名称]") @Help(value = "禁止插件联网", possibleArguments = "[插件名称]")
public void off(final CommandArgument e) { public void off(CommandSender sender, String pname) {
final String pname = e.getArgs()[0];
final CommandSender sender = e.getSender();
if (Bukkit.getPluginManager().getPlugin(pname) == null) { if (Bukkit.getPluginManager().getPlugin(pname) == null) {
sender.sendMessage(String.format(p_n_f, pname)); sender.sendMessage(String.format(p_n_f, pname));
return; return;
@ -71,9 +67,7 @@ public class NetCommand implements CommandExecutor {
@Cmd(minimumArguments = 1) @Cmd(minimumArguments = 1)
@Help(value = "允许插件联网", possibleArguments = "[插件名称]") @Help(value = "允许插件联网", possibleArguments = "[插件名称]")
public void on(final CommandArgument e) { public void on(CommandSender sender, String pname) {
final String pname = e.getArgs()[0];
final CommandSender sender = e.getSender();
if (Bukkit.getPluginManager().getPlugin(pname) == null) { if (Bukkit.getPluginManager().getPlugin(pname) == null) {
sender.sendMessage(String.format(p_n_f, pname)); sender.sendMessage(String.format(p_n_f, pname));
return; return;

View File

@ -4,11 +4,11 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import cn.citycraft.PluginHelper.utils.StrKit;
import pw.yumc.Yum.api.YumAPI; import pw.yumc.Yum.api.YumAPI;
import pw.yumc.YumCore.commands.CommandArgument; import pw.yumc.YumCore.commands.CommandArgument;
import pw.yumc.YumCore.commands.CommandExecutor;
import pw.yumc.YumCore.commands.annotation.Tab; 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(); public static PluginTabComplete instence = new PluginTabComplete();
@Tab @Tab
public List<String> listtab(final CommandArgument e) { public List<String> listtab(CommandArgument e) {
final String[] args = e.getArgs(); String[] args = e.getArgs();
if (args[0].equalsIgnoreCase("install") || args[0].equalsIgnoreCase("i")) { if (args[0].equalsIgnoreCase("install") || args[0].equalsIgnoreCase("i")) {
return StrKit.copyPartialMatches(args[1], YumAPI.getRepo().getAllPluginName(), new ArrayList<String>()); return StrKit.copyPartialMatches(args[1], YumAPI.getRepo().getAllPluginName(), new ArrayList<String>());
} else if (args[0].equalsIgnoreCase("repo") || args[0].equalsIgnoreCase("r")) { } else if (args[0].equalsIgnoreCase("repo") || args[0].equalsIgnoreCase("r")) {
if (args.length == 2) { if (args.length == 2) { return StrKit.copyPartialMatches(args[1],
return StrKit.copyPartialMatches(args[1], Arrays.asList(new String[] { "add", "all", "list", "delall", "clean", "update", "del" }), new ArrayList<String>()); Arrays.asList(new String[] { "add", "all", "list", "delall", "clean", "update", "del" }),
} new ArrayList<String>()); }
if (args.length == 3 && (args[1] == "add" || args[1] == "del")) { if (args.length == 3 && (args[1] == "add" || args[1] == "del")) { return StrKit.copyPartialMatches(args[2],
return StrKit.copyPartialMatches(args[2], YumAPI.getRepo().getRepos().keySet(), new ArrayList<String>()); YumAPI.getRepo().getRepos().keySet(),
} new ArrayList<String>()); }
} else if (args[0].equalsIgnoreCase("bukkitrepo") || args[0].equalsIgnoreCase("br")) { } else if (args[0].equalsIgnoreCase("bukkitrepo") || args[0].equalsIgnoreCase("br")) {
return StrKit.copyPartialMatches(args[1], Arrays.asList(new String[] { "look", "install" }), new ArrayList<String>()); return StrKit.copyPartialMatches(args[1],
Arrays.asList(new String[] { "look", "install" }),
new ArrayList<String>());
} else { } else {
return StrKit.copyPartialMatches(args[1], YumAPI.getPlugman().getPluginNames(false), new ArrayList<String>()); return StrKit.copyPartialMatches(args[1],
YumAPI.getPlugman().getPluginNames(false),
new ArrayList<String>());
} }
return null; return null;
} }

View File

@ -3,6 +3,7 @@ package pw.yumc.Yum.commands;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@ -18,11 +19,6 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin; 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.Yum;
import pw.yumc.Yum.api.YumAPI; import pw.yumc.Yum.api.YumAPI;
import pw.yumc.Yum.managers.ConfigManager; 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.Files;
import pw.yumc.Yum.models.BukkitDev.Projects; import pw.yumc.Yum.models.BukkitDev.Projects;
import pw.yumc.Yum.models.RepoSerialization.Repositories; import pw.yumc.Yum.models.RepoSerialization.Repositories;
import pw.yumc.YumCore.commands.CommandArgument; import pw.yumc.YumCore.callback.CallBack.One;
import pw.yumc.YumCore.commands.CommandExecutor;
import pw.yumc.YumCore.commands.CommandManager; import pw.yumc.YumCore.commands.CommandManager;
import pw.yumc.YumCore.commands.annotation.Async; import pw.yumc.YumCore.commands.annotation.Async;
import pw.yumc.YumCore.commands.annotation.Cmd; import pw.yumc.YumCore.commands.annotation.Cmd;
import pw.yumc.YumCore.commands.annotation.Help; import pw.yumc.YumCore.commands.annotation.Help;
import pw.yumc.YumCore.commands.annotation.Sort; 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.PKit;
import pw.yumc.YumCore.kit.ZipKit;
import pw.yumc.YumCore.tellraw.Tellraw; import pw.yumc.YumCore.tellraw.Tellraw;
/** /**
@ -47,36 +46,36 @@ import pw.yumc.YumCore.tellraw.Tellraw;
* @author * @author
*/ */
public class YumCommand implements Listener, CommandExecutor { 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 String searchlimit = prefix + "§c为保证搜索速度和准确性 关键词必须大于 3 个字符!";
private final String searching = prefix + "§a正在从 §eBukkitDev §a获取 §b%s §a的相关数据..."; private String searching = prefix + "§a正在从 §eBukkitDev §a获取 §b%s §a的相关数据...";
private final String not_found_from_bukkit = prefix + "§c未在 §eBukkitDev §c搜索到 §b%s §c的相关插件!"; private String not_found_from_bukkit = prefix + "§c未在 §eBukkitDev §c搜索到 §b%s §c的相关插件!";
private final String result = prefix + "§6关键词 §b%s §6的搜索结果如下:"; private String result = prefix + "§6关键词 §b%s §6的搜索结果如下:";
private final String bukkitlistprefix = " §6插件ID §3插件名称 §d发布类型 §a操作"; private String bukkitlistprefix = " §6插件ID §3插件名称 §d发布类型 §a操作";
private final String bukkitlist = "§6- §e%-6s §b%-25s §d%-10s"; private String bukkitlist = "§6- §e%-6s §b%-25s §d%-10s";
private final String fsearching = prefix + "§a正在从 §eBukkitDev §a获取ID §b%s §a的文件列表..."; private 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 String not_found_id_from_bukkit = prefix + "§c未在 §eBukkitDev §c搜索到ID为 §b%s §c的相关插件!";
private final String filelistprefix = " §6插件名称 §3游戏版本 §d发布类型 §a操作"; private String filelistprefix = " §6插件名称 §3游戏版本 §d发布类型 §a操作";
private final String filelist = "§6- §b%-20s §3%-15s §d%-10s"; private String filelist = "§6- §b%-20s §3%-15s §d%-10s";
private final String del = "§c删除: §a插件 §b%s §a版本 §d%s §a已从服务器卸载并删除!"; private String del = "§c删除: §a插件 §b%s §a版本 §d%s §a已从服务器卸载并删除!";
private final String delFailed = "§c删除: §a插件 §b%s §c卸载或删除时发生错误 删除失败!"; private String delFailed = "§c删除: §a插件 §b%s §c卸载或删除时发生错误 删除失败!";
private final String look = "§6查看"; private String look = "§6查看";
private final String install = "§a安装"; private String install = "§a安装";
private final String install_tip = "§a点击安装"; private String install_tip = "§a点击安装";
private final String update = "§a更新"; private String update = "§a更新";
private final String unload = "§d卸载"; private String unload = "§d卸载";
private final String reload = "§6重载"; private String reload = "§6重载";
private final String delete = "§c删除"; private String delete = "§c删除";
private final String unzip_error = prefix + "ZIP文件解压错误!"; private String unzip_error = prefix + "ZIP文件解压错误!";
Yum main; Yum main;
public YumCommand(final Yum yum) { public YumCommand(Yum yum) {
main = yum; main = yum;
Bukkit.getPluginManager().registerEvents(this, yum); Bukkit.getPluginManager().registerEvents(this, yum);
new CommandManager("yum", this, PluginTabComplete.instence); new CommandManager("yum", this, PluginTabComplete.instence);
@ -84,25 +83,22 @@ public class YumCommand implements Listener, CommandExecutor {
@Cmd(aliases = "br", minimumArguments = 2) @Cmd(aliases = "br", minimumArguments = 2)
@Help(value = "从BukkitDev查看安装插件", possibleArguments = "<操作符> <项目ID|项目名称> [地址]") @Help(value = "从BukkitDev查看安装插件", possibleArguments = "<操作符> <项目ID|项目名称> [地址]")
public void bukkitrepo(final CommandArgument e) { public void bukkitrepo(final CommandSender sender, final String opt, final String id, final String url) {
final String[] args = e.getArgs();
final CommandSender sender = e.getSender();
PKit.runTaskAsync(new Runnable() { PKit.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
final String id = args[1]; switch (opt) {
switch (args[0]) {
case "look": { case "look": {
sender.sendMessage(String.format(fsearching, id)); sender.sendMessage(String.format(fsearching, id));
final List<Files> lf = Files.parseList(IOUtil.getData(String.format(BukkitDev.PLUGIN, id))); List<Files> lf = Files.parseList(HttpKit.get(String.format(BukkitDev.PLUGIN, id)));
if (lf.isEmpty()) { if (lf.isEmpty()) {
sender.sendMessage(String.format(not_found_id_from_bukkit, id)); sender.sendMessage(String.format(not_found_id_from_bukkit, id));
return; return;
} }
sender.sendMessage(filelistprefix); sender.sendMessage(filelistprefix);
for (int i = 0; i < lf.size() || i < 8; i++) { for (int i = 0; i < lf.size() || i < 8; i++) {
final Files f = lf.get(i); Files f = lf.get(i);
final Tellraw tr = Tellraw.create(); Tellraw tr = Tellraw.create();
tr.text(String.format(filelist, f.name, f.gameVersion, f.releaseType)); tr.text(String.format(filelist, f.name, f.gameVersion, f.releaseType));
tr.then(" "); tr.then(" ");
tr.then(install).command(String.format("/yum br ai %s %s", f.name, f.downloadUrl)); 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; break;
} }
case "ai": { case "ai": {
if (args.length < 3) { if (url == null) { return; }
return; File file = new File(Bukkit.getUpdateFolderFile(), YumAPI.getDownload().getFileName(url));
} YumAPI.getDownload().run(sender, url, file, new One<File>() {
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<File>() {
@Override @Override
public void run(final File file) { public void run(File file) {
if (file.getName().endsWith(".zip")) { if (file.getName().endsWith(".zip")) {
try { try {
ZipKit.unzip(file, Bukkit.getUpdateFolderFile(), ".jar"); ZipKit.unzip(file, Bukkit.getUpdateFolderFile(), ".jar");
file.delete(); file.delete();
} catch (final IOException e) { } catch (IOException e) {
sender.sendMessage(unzip_error); sender.sendMessage(unzip_error);
} }
} }
@ -136,21 +129,21 @@ public class YumCommand implements Listener, CommandExecutor {
case "i": case "i":
case "install": { case "install": {
sender.sendMessage(String.format(fsearching, id)); sender.sendMessage(String.format(fsearching, id));
final List<Files> lf = Files.parseList(IOUtil.getData(String.format(BukkitDev.PLUGIN, id))); List<Files> lf = Files.parseList(HttpKit.get(String.format(BukkitDev.PLUGIN, id)));
if (lf.isEmpty()) { if (lf.isEmpty()) {
sender.sendMessage(String.format(not_found_id_from_bukkit, id)); sender.sendMessage(String.format(not_found_id_from_bukkit, id));
return; return;
} }
final Files f = lf.get(0); Files f = lf.get(0);
final String url = f.downloadUrl; String url = f.downloadUrl;
final File file = new File(Bukkit.getUpdateFolderFile(), YumAPI.getDownload().getFileName(url)); File file = new File(Bukkit.getUpdateFolderFile(), YumAPI.getDownload().getFileName(url));
YumAPI.getDownload().run(e.getSender(), url, file, new One<File>() { YumAPI.getDownload().run(sender, url, file, new One<File>() {
@Override @Override
public void run(final File file) { public void run(File file) {
if (file.getName().endsWith(".zip")) { if (file.getName().endsWith(".zip")) {
try { try {
ZipKit.unzip(file, Bukkit.getUpdateFolderFile(), ".jar"); ZipKit.unzip(file, Bukkit.getUpdateFolderFile(), ".jar");
} catch (final IOException e) { } catch (IOException e) {
sender.sendMessage(unzip_error); sender.sendMessage(unzip_error);
} }
} }
@ -170,12 +163,10 @@ public class YumCommand implements Listener, CommandExecutor {
@Cmd(aliases = "del", minimumArguments = 1) @Cmd(aliases = "del", minimumArguments = 1)
@Help(value = "删除插件", possibleArguments = "<插件名称>") @Help(value = "删除插件", possibleArguments = "<插件名称>")
@Sort(6) @Sort(6)
public void delete(final CommandArgument e) { public void delete(CommandSender sender, String pluginname) {
final String pluginname = e.getArgs()[0]; Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
final CommandSender sender = e.getSender();
final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
if (plugin != null) { 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)) { if (YumAPI.getPlugman().deletePlugin(sender, plugin)) {
sender.sendMessage(String.format(del, pluginname, version)); sender.sendMessage(String.format(del, pluginname, version));
} else { } else {
@ -189,12 +180,10 @@ public class YumCommand implements Listener, CommandExecutor {
@Cmd(aliases = "ddel", minimumArguments = 1) @Cmd(aliases = "ddel", minimumArguments = 1)
@Help(value = "删除插件数据文件夹", possibleArguments = "<插件名称>") @Help(value = "删除插件数据文件夹", possibleArguments = "<插件名称>")
@Sort(7) @Sort(7)
public void dirdelete(final CommandArgument e) { public void dirdelete(CommandSender sender, String pluginname) {
final String pluginname = e.getArgs()[0]; Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
final CommandSender sender = e.getSender();
final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
if (plugin != null) { if (plugin != null) {
FileUtil.deleteDir(sender, plugin.getDataFolder()); FileKit.deleteDir(sender, plugin.getDataFolder());
} else { } else {
sender.sendMessage(pnf(pluginname)); sender.sendMessage(pnf(pluginname));
} }
@ -203,29 +192,26 @@ public class YumCommand implements Listener, CommandExecutor {
@Cmd(aliases = "f", minimumArguments = 1) @Cmd(aliases = "f", minimumArguments = 1)
@Help(value = "通过类名查找插件", possibleArguments = "<插件类名>") @Help(value = "通过类名查找插件", possibleArguments = "<插件类名>")
@Sort(10) @Sort(10)
public void find(final CommandArgument e) { public void find(CommandSender sender, String classname) {
final String classname = e.getArgs()[0];
final CommandSender sender = e.getSender();
try { try {
final Class<?> clazz = Class.forName(classname); Class<?> clazz = Class.forName(classname);
final Field field = clazz.getClassLoader().getClass().getDeclaredField("plugin"); Field field = clazz.getClassLoader().getClass().getDeclaredField("plugin");
field.setAccessible(true); 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()); Bukkit.dispatchCommand(sender, "yum info " + plugin.getName());
} catch (final ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e2) { } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e2) {
sender.sendMessage("§4错误: 无法找到类 " + classname + " 所对应的插件信息 异常:" + e2.getClass().getSimpleName() + " " + e2.getMessage() + "!"); sender.sendMessage("§4错误: 无法找到类 " + classname + " 所对应的插件信息 异常:" + e2.getClass().getSimpleName() + " "
+ e2.getMessage() + "!");
} }
} }
@Cmd(aliases = "fdel", minimumArguments = 1) @Cmd(aliases = "fdel", minimumArguments = 1)
@Help(value = "删除插件以及数据文件夹", possibleArguments = "<插件名称>") @Help(value = "删除插件以及数据文件夹", possibleArguments = "<插件名称>")
@Sort(7) @Sort(7)
public void fulldelete(final CommandArgument e) { public void fulldelete(CommandSender sender, String pluginname) {
final String pluginname = e.getArgs()[0]; Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
final CommandSender sender = e.getSender();
final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
if (plugin != null) { 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)) { if (YumAPI.getPlugman().fullDeletePlugin(sender, plugin)) {
sender.sendMessage(String.format(del, pluginname, version)); sender.sendMessage(String.format(del, pluginname, version));
} else { } else {
@ -240,24 +226,22 @@ public class YumCommand implements Listener, CommandExecutor {
@Help(value = "查看插件详情", possibleArguments = "<插件名称>") @Help(value = "查看插件详情", possibleArguments = "<插件名称>")
@Sort(2) @Sort(2)
@Async @Async
public void info(final CommandArgument e) { public void info(CommandSender sender, String pluginname) {
final String pluginname = e.getArgs()[0]; Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
final CommandSender sender = e.getSender();
final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
if (plugin != null) { if (plugin != null) {
final PluginDescriptionFile desc = plugin.getDescription(); PluginDescriptionFile desc = plugin.getDescription();
sender.sendMessage("§6插件名称: §3" + plugin.getName()); sender.sendMessage("§6插件名称: §3" + plugin.getName());
sender.sendMessage("§6插件版本: §3" + StringUtils.substring(plugin.getDescription().getVersion(), 0, 15)); sender.sendMessage("§6插件版本: §3" + StringUtils.substring(plugin.getDescription().getVersion(), 0, 15));
sender.sendMessage("§6插件作者: §3" + StringUtils.join(desc.getAuthors(), " ")); sender.sendMessage("§6插件作者: §3" + StringUtils.join(desc.getAuthors(), " "));
sender.sendMessage("§6插件描述: §3" + (desc.getDescription() == null ? "" : desc.getDescription())); sender.sendMessage("§6插件描述: §3" + (desc.getDescription() == null ? "" : desc.getDescription()));
sender.sendMessage("§6插件依赖: §3" + (desc.getDepend().isEmpty() ? "" : "")); 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() ? "" : "")); sender.sendMessage("§6插件软依赖: §3" + (desc.getSoftDepend().isEmpty() ? "" : ""));
StrKit.sendStringArray(sender, desc.getSoftDepend(), "§6 - §a"); sendStringArray(sender, desc.getSoftDepend(), "§6 - §a");
final Map<String, Map<String, Object>> clist = desc.getCommands(); Map<String, Map<String, Object>> clist = desc.getCommands();
if (clist != null) { if (clist != null) {
sender.sendMessage("§6插件注册命令: §3" + (clist.isEmpty() ? "" : "")); sender.sendMessage("§6插件注册命令: §3" + (clist.isEmpty() ? "" : ""));
for (final Entry<String, Map<String, Object>> entry : clist.entrySet()) { for (Entry<String, Map<String, Object>> entry : clist.entrySet()) {
sender.sendMessage("§6 - §a" + entry.getKey()); sender.sendMessage("§6 - §a" + entry.getKey());
sendEntryList(sender, "§6 别名: §a", entry.getValue(), "aliases"); sendEntryList(sender, "§6 别名: §a", entry.getValue(), "aliases");
sendEntry(sender, "§6 描述: §a", entry.getValue(), "description"); sendEntry(sender, "§6 描述: §a", entry.getValue(), "description");
@ -265,11 +249,12 @@ public class YumCommand implements Listener, CommandExecutor {
sendEntry(sender, "§6 用法: §a", entry.getValue(), "usage"); sendEntry(sender, "§6 用法: §a", entry.getValue(), "usage");
} }
} }
final List<Permission> plist = desc.getPermissions(); List<Permission> plist = desc.getPermissions();
if (plist != null) { if (plist != null) {
sender.sendMessage("§6插件注册权限: " + (plist.isEmpty() ? "" : "")); sender.sendMessage("§6插件注册权限: " + (plist.isEmpty() ? "" : ""));
for (final Permission perm : plist) { for (Permission perm : plist) {
sender.sendMessage("§6 - §a" + perm.getName() + "§6 - §e" + (perm.getDescription().isEmpty() ? "无描述" : perm.getDescription())); sender.sendMessage("§6 - §a" + perm.getName() + "§6 - §e"
+ (perm.getDescription().isEmpty() ? "无描述" : perm.getDescription()));
} }
} }
sender.sendMessage("§6插件物理路径: §3" + YumAPI.getPlugman().getPluginFile(plugin).getAbsolutePath()); sender.sendMessage("§6插件物理路径: §3" + YumAPI.getPlugman().getPluginFile(plugin).getAbsolutePath());
@ -281,19 +266,16 @@ public class YumCommand implements Listener, CommandExecutor {
@Cmd(aliases = "i", minimumArguments = 1) @Cmd(aliases = "i", minimumArguments = 1)
@Help(value = "安装插件", possibleArguments = "<插件名称>") @Help(value = "安装插件", possibleArguments = "<插件名称>")
@Sort(12) @Sort(12)
public void install(final CommandArgument e) { public void install(final CommandSender sender, final String pluginname, final String pluginversion) {
final String[] args = e.getArgs(); Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
final CommandSender sender = e.getSender();
final String pluginname = args[0];
final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
if (plugin == null) { if (plugin == null) {
Bukkit.getScheduler().runTaskAsynchronously(main, new Runnable() { Bukkit.getScheduler().runTaskAsynchronously(main, new Runnable() {
@Override @Override
public void run() { public void run() {
if (args.length < 2) { if (pluginversion == null) {
YumAPI.installFromYum(sender, pluginname); YumAPI.installFromYum(sender, pluginname);
} else { } else {
YumAPI.installFromYum(sender, pluginname, args[1]); YumAPI.installFromYum(sender, pluginname, pluginversion);
} }
} }
}); });
@ -306,12 +288,11 @@ public class YumCommand implements Listener, CommandExecutor {
@Help(value = "列出已安装插件列表") @Help(value = "列出已安装插件列表")
@Sort(1) @Sort(1)
@Async @Async
public void list(final CommandArgument e) { public void list(CommandSender sender) {
final CommandSender sender = e.getSender();
sender.sendMessage("§6[Yum仓库]§3服务器已安装插件: "); sender.sendMessage("§6[Yum仓库]§3服务器已安装插件: ");
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
final String pname = plugin.getName(); String pname = plugin.getName();
final Tellraw fm = Tellraw.create(); Tellraw fm = Tellraw.create();
fm.text(String.format("§6- %-32s", YumAPI.getPlugman().getFormattedName(plugin, true))); fm.text(String.format("§6- %-32s", YumAPI.getPlugman().getFormattedName(plugin, true)));
fm.then(" "); fm.then(" ");
fm.then(update).cmd_tip("/yum u " + pname, update); fm.then(update).cmd_tip("/yum u " + pname, update);
@ -328,10 +309,8 @@ public class YumCommand implements Listener, CommandExecutor {
@Cmd(minimumArguments = 1) @Cmd(minimumArguments = 1)
@Help(value = "载入插件", possibleArguments = "<插件名称>") @Help(value = "载入插件", possibleArguments = "<插件名称>")
@Sort(3) @Sort(3)
public void load(final CommandArgument e) { public void load(CommandSender sender, String pluginname) {
final CommandSender sender = e.getSender(); Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
final String pluginname = e.getArgs()[0];
final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
if (plugin == null) { if (plugin == null) {
YumAPI.getPlugman().load(sender, pluginname); YumAPI.getPlugman().load(sender, pluginname);
} else { } else {
@ -340,7 +319,7 @@ public class YumCommand implements Listener, CommandExecutor {
} }
@EventHandler @EventHandler
public void onAdminJoin(final PlayerJoinEvent e) { public void onAdminJoin(PlayerJoinEvent e) {
if (e.getPlayer().isOp()) { if (e.getPlayer().isOp()) {
YumAPI.updateCheck(e.getPlayer()); YumAPI.updateCheck(e.getPlayer());
} }
@ -349,19 +328,17 @@ public class YumCommand implements Listener, CommandExecutor {
@Cmd(aliases = "re") @Cmd(aliases = "re")
@Help(value = "重载插件", possibleArguments = "<插件名称|all|*>") @Help(value = "重载插件", possibleArguments = "<插件名称|all|*>")
@Sort(5) @Sort(5)
public void reload(final CommandArgument e) { public void reload(CommandSender sender, String pluginname) {
final CommandSender sender = e.getSender(); if (pluginname == null) {
if (e.getArgs().length == 0) {
ConfigManager.i().reload(); ConfigManager.i().reload();
sender.sendMessage("§6重载: §a配置文件已重载!"); sender.sendMessage("§6重载: §a配置文件已重载!");
return; return;
} }
final String pluginname = e.getArgs()[0];
if (pluginname.equalsIgnoreCase("all") || pluginname.equalsIgnoreCase("*")) { if (pluginname.equalsIgnoreCase("all") || pluginname.equalsIgnoreCase("*")) {
YumAPI.getPlugman().reloadAll(sender); YumAPI.getPlugman().reloadAll(sender);
return; return;
} }
final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
if (plugin != null) { if (plugin != null) {
YumAPI.getPlugman().reload(sender, plugin); YumAPI.getPlugman().reload(sender, plugin);
} else { } else {
@ -373,15 +350,12 @@ public class YumCommand implements Listener, CommandExecutor {
@Help(value = "插件源命令", possibleArguments = "<add|del|all|clean|list> <仓库名称>") @Help(value = "插件源命令", possibleArguments = "<add|del|all|clean|list> <仓库名称>")
@Sort(16) @Sort(16)
@Async @Async
public void repo(final CommandArgument e) { public void repo(CommandSender sender, String cmd, String arg1) {
final String[] args = e.getArgs();
final CommandSender sender = e.getSender();
final String cmd = args[0];
switch (cmd) { switch (cmd) {
case "add": case "add":
if (args.length == 2) { if (arg1 != null) {
if (YumAPI.getRepo().addRepositories(sender, args[1])) { if (YumAPI.getRepo().addRepositories(sender, arg1)) {
final String reponame = YumAPI.getRepo().getRepoCache(args[1]).name; String reponame = YumAPI.getRepo().getRepoCache(arg1).name;
sender.sendMessage("§6仓库: §a源仓库 §e" + reponame + " §a的插件信息已缓存!"); sender.sendMessage("§6仓库: §a源仓库 §e" + reponame + " §a的插件信息已缓存!");
} else { } else {
sender.sendMessage("§6仓库: §c源地址未找到仓库信息或当前地址已缓存!"); sender.sendMessage("§6仓库: §c源地址未找到仓库信息或当前地址已缓存!");
@ -391,10 +365,10 @@ public class YumCommand implements Listener, CommandExecutor {
} }
break; break;
case "del": case "del":
if (args.length == 2) { if (arg1 != null) {
final Repositories delrepo = YumAPI.getRepo().getRepoCache(args[1]); Repositories delrepo = YumAPI.getRepo().getRepoCache(arg1);
if (delrepo != null) { 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更新缓存!"); sender.sendMessage("§6仓库: §a源仓库 §e" + delrepo.name + " §c已删除 §a请使用 §b/yum repo update §a更新缓存!");
} else { } else {
sender.sendMessage("§6仓库: §c源地址未找到!"); sender.sendMessage("§6仓库: §c源地址未找到!");
@ -409,11 +383,11 @@ public class YumCommand implements Listener, CommandExecutor {
break; break;
case "list": case "list":
sender.sendMessage("§6仓库: §b缓存的插件信息如下 "); sender.sendMessage("§6仓库: §b缓存的插件信息如下 ");
StrKit.sendStringArray(sender, YumAPI.getRepo().getAllPluginsInfo()); sendStringArray(sender, YumAPI.getRepo().getAllPluginsInfo());
break; break;
case "all": case "all":
sender.sendMessage("§6仓库: §b缓存的仓库信息如下 "); sender.sendMessage("§6仓库: §b缓存的仓库信息如下 ");
StrKit.sendStringArray(sender, YumAPI.getRepo().getRepoCache().getAllRepoInfo()); sendStringArray(sender, YumAPI.getRepo().getRepoCache().getAllRepoInfo());
break; break;
case "clean": case "clean":
YumAPI.getRepo().clean(); YumAPI.getRepo().clean();
@ -430,23 +404,21 @@ public class YumCommand implements Listener, CommandExecutor {
@Help(value = "从BukkitDev搜索插件", possibleArguments = "插件名称") @Help(value = "从BukkitDev搜索插件", possibleArguments = "插件名称")
@Sort(11) @Sort(11)
@Async @Async
public void search(final CommandArgument e) { public void search(CommandSender sender, String pname) {
final String pname = e.getArgs()[0];
final CommandSender sender = e.getSender();
if (pname.length() < 3) { if (pname.length() < 3) {
sender.sendMessage(searchlimit); sender.sendMessage(searchlimit);
return; return;
} }
sender.sendMessage(String.format(searching, pname)); sender.sendMessage(String.format(searching, pname));
final List<Projects> list = Projects.parseList(IOUtil.getData(String.format(BukkitDev.SEARCH, pname.toLowerCase()))); List<Projects> list = Projects.parseList(HttpKit.get(String.format(BukkitDev.SEARCH, pname.toLowerCase())));
if (list.isEmpty()) { if (list.isEmpty()) {
sender.sendMessage(String.format(not_found_from_bukkit, pname)); sender.sendMessage(String.format(not_found_from_bukkit, pname));
return; return;
} }
sender.sendMessage(String.format(result, pname)); sender.sendMessage(String.format(result, pname));
sender.sendMessage(bukkitlistprefix); sender.sendMessage(bukkitlistprefix);
for (final Projects p : list) { for (Projects p : list) {
final Tellraw fm = Tellraw.create(); Tellraw fm = Tellraw.create();
fm.text(String.format(bukkitlist, p.id, p.name, p.stage)); fm.text(String.format(bukkitlist, p.id, p.name, p.stage));
fm.then(" "); fm.then(" ");
fm.then(look).cmd_tip("/yum br look " + p.id, look); fm.then(look).cmd_tip("/yum br look " + p.id, look);
@ -457,10 +429,8 @@ public class YumCommand implements Listener, CommandExecutor {
@Cmd(minimumArguments = 1) @Cmd(minimumArguments = 1)
@Help(value = "卸载插件", possibleArguments = "<插件名称>") @Help(value = "卸载插件", possibleArguments = "<插件名称>")
@Sort(4) @Sort(4)
public void unload(final CommandArgument e) { public void unload(CommandSender sender, String pluginname) {
final String pluginname = e.getArgs()[0]; Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
final CommandSender sender = e.getSender();
final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
if (plugin != null) { if (plugin != null) {
YumAPI.getPlugman().unload(sender, plugin); YumAPI.getPlugman().unload(sender, plugin);
} else { } else {
@ -472,9 +442,8 @@ public class YumCommand implements Listener, CommandExecutor {
@Help(value = "更新插件或缓存", possibleArguments = "[插件名称] [插件版本]") @Help(value = "更新插件或缓存", possibleArguments = "[插件名称] [插件版本]")
@Sort(13) @Sort(13)
@Async @Async
public void update(final CommandArgument e) { public void update(CommandSender sender, String argstring) {
final String[] args = e.getArgs(); String[] args = argstring.split(" ");
final CommandSender sender = e.getSender();
switch (args.length) { switch (args.length) {
case 0: case 0:
YumAPI.getRepo().updateRepositories(sender); YumAPI.getRepo().updateRepositories(sender);
@ -482,8 +451,8 @@ public class YumCommand implements Listener, CommandExecutor {
break; break;
case 1: case 1:
case 2: case 2:
final String pluginname = args[0]; String pluginname = args[0];
final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname); Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
sender.sendMessage("§a开始更新插件: " + pluginname); sender.sendMessage("§a开始更新插件: " + pluginname);
if (plugin != null) { if (plugin != null) {
if (args.length < 2) { if (args.length < 2) {
@ -503,31 +472,29 @@ public class YumCommand implements Listener, CommandExecutor {
@Cmd(aliases = "ua") @Cmd(aliases = "ua")
@Help("更新所有可更新插件") @Help("更新所有可更新插件")
@Sort(14) @Sort(14)
public void updateall(final CommandArgument e) { public void updateall(CommandSender sender) {
YumAPI.updateAll(e.getSender()); YumAPI.updateAll(sender);
} }
@Cmd(aliases = "ug") @Cmd(aliases = "ug")
@Help(value = "升级或安装插件", possibleArguments = "[插件名称]") @Help(value = "升级或安装插件", possibleArguments = "[插件名称]")
@Sort(15) @Sort(15)
public void upgrade(final CommandArgument e) { public void upgrade(CommandSender sender, String pluginname) {
final String[] args = e.getArgs(); if (pluginname == null) {
final CommandSender sender = e.getSender();
if (args.length == 0) {
YumAPI.getPlugman().upgrade(sender); YumAPI.getPlugman().upgrade(sender);
} else { } else {
final String pluginname = args[0]; Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
final Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginname);
sender.sendMessage("§a开始升级插件: §b" + pluginname); sender.sendMessage("§a开始升级插件: §b" + pluginname);
if (plugin != null) { if (plugin != null) {
YumAPI.upgrade(sender, plugin); YumAPI.upgrade(sender, plugin);
} else { } 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); return String.format("§4错误: §c插件 §b %s §c不存在或已卸载!", pname);
} }
@ -543,8 +510,8 @@ public class YumCommand implements Listener, CommandExecutor {
* @param key * @param key
* 实体Key * 实体Key
*/ */
private void sendEntry(final CommandSender sender, final String prefix, final Map<String, Object> map, final String key) { private void sendEntry(CommandSender sender, String prefix, Map<String, Object> map, String key) {
final Object value = map.get(key); Object value = map.get(key);
if (value != null) { if (value != null) {
sender.sendMessage(prefix + (String) value); sender.sendMessage(prefix + (String) value);
} }
@ -563,13 +530,60 @@ public class YumCommand implements Listener, CommandExecutor {
* 实体Key * 实体Key
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void sendEntryList(final CommandSender sender, final String prefix, final Map<String, Object> map, final String key) { private void sendEntryList(CommandSender sender, String prefix, Map<String, Object> map, String key) {
final List<String> values = (List<String>) map.get(key); List<String> values = (List<String>) map.get(key);
if (values != null) { if (values != null) {
for (final String value : values) { for (String value : values) {
sender.sendMessage(prefix + value); sender.sendMessage(prefix + value);
} }
} }
} }
/**
* 给玩家或控制台发送消息组
*
* @param sender
* 接收消息的玩家
* @param msg
* 消息组
*/
public static void sendStringArray(CommandSender sender, Collection<String> msg) {
for (String string : msg) {
sender.sendMessage(string);
}
}
/**
* 给玩家或控制台发送消息组
*
* @param sender
* 接收消息的玩家
* @param msg
* 消息组
* @param prefix
* 消息前缀
*/
public static void sendStringArray(CommandSender sender, Collection<String> 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<String> msg, String prefix, String suffix) {
for (String string : msg) {
sender.sendMessage(prefix + string + suffix);
}
}
} }

View File

@ -9,10 +9,10 @@ import org.bukkit.plugin.Plugin;
public class PluginNetworkEvent extends Event implements Cancellable { 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 boolean isPrimaryThread;
private final Plugin plugin; private Plugin plugin;
private boolean cancel; private boolean cancel;
private URI url; private URI url;
@ -30,7 +30,7 @@ public class PluginNetworkEvent extends Event implements Cancellable {
* @param isMainThread * @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.plugin = plugin;
this.url = url; this.url = url;
this.isPrimaryThread = isPrimaryThread; this.isPrimaryThread = isPrimaryThread;
@ -68,7 +68,7 @@ public class PluginNetworkEvent extends Event implements Cancellable {
} }
@Override @Override
public void setCancelled(final boolean value) { public void setCancelled(boolean value) {
cancel = value; cancel = value;
} }
@ -76,7 +76,7 @@ public class PluginNetworkEvent extends Event implements Cancellable {
* @param url * @param url
* 设置新的URL地址 * 设置新的URL地址
*/ */
public void setUrl(final URI url) { public void setUrl(URI url) {
this.url = url; this.url = url;
} }

View File

@ -1,6 +1,5 @@
/* /*
* Updater for Bukkit. * 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 * 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 { public class BukkitUpdater extends Updater {
private static final String TITLE_VALUE = "name"; // Gets remote file's title private static String TITLE_VALUE = "name"; // Gets remote file's title
private static final String LINK_VALUE = "downloadUrl"; // Gets remote file's download link private static 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 TYPE_VALUE = "releaseType"; // Gets remote file's release type
private static final String VERSION_VALUE = "gameVersion"; // Gets remote file's build version private static String VERSION_VALUE = "gameVersion"; // Gets remote file's build version
private static final Object FILE_NAME = "fileName"; // Gets remote file's name private static Object FILE_NAME = "fileName"; // Gets remote file's name
private static final String QUERY = "/servermods/files?projectIds="; // Path to GET private static 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 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 // Update information
// private static final String BUKKIT_DEV_SLUG = "protocollib"; // private static String BUKKIT_DEV_SLUG = "protocollib";
// private static final int BUKKIT_DEV_ID = 45564; // private static int BUKKIT_DEV_ID = 45564;
private URL url; // Connecting to RSS private URL url; // Connecting to RSS
private File file; // The plugin's file private File file; // The plugin's file
@ -88,18 +87,18 @@ public class BukkitUpdater extends Updater {
* @param announce * @param announce
* True if the program should announce the progress of new updates in console * 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); super(plugin, type, announce);
this.file = file; this.file = file;
this.id = id; this.id = id;
this.updateFolder = plugin.getServer().getUpdateFolder(); this.updateFolder = plugin.getServer().getUpdateFolder();
final File dataFolder = plugin.getDataFolder(); File dataFolder = plugin.getDataFolder();
if (dataFolder != null) { if (dataFolder != null) {
final File pluginFile = plugin.getDataFolder().getParentFile(); File pluginFile = plugin.getDataFolder().getParentFile();
final File updaterFile = new File(pluginFile, "Updater"); File updaterFile = new File(pluginFile, "Updater");
final File updaterConfigFile = new File(updaterFile, "config.yml"); File updaterConfigFile = new File(updaterFile, "config.yml");
if (!updaterFile.exists()) { if (!updaterFile.exists()) {
updaterFile.mkdir(); updaterFile.mkdir();
@ -107,8 +106,9 @@ public class BukkitUpdater extends Updater {
if (!updaterConfigFile.exists()) { if (!updaterConfigFile.exists()) {
try { try {
updaterConfigFile.createNewFile(); updaterConfigFile.createNewFile();
} catch (final IOException e) { } catch (IOException e) {
plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath()); plugin.getLogger().severe(
"The updater could not create a configuration in " + updaterFile.getAbsolutePath());
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -128,8 +128,9 @@ public class BukkitUpdater extends Updater {
this.config.options().copyDefaults(true); this.config.options().copyDefaults(true);
try { try {
this.config.save(updaterConfigFile); this.config.save(updaterConfigFile);
} catch (final IOException e) { } catch (IOException e) {
plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath()); plugin.getLogger().severe(
"The updater could not save the configuration in " + updaterFile.getAbsolutePath());
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -149,7 +150,7 @@ public class BukkitUpdater extends Updater {
try { try {
this.url = new URL(BukkitUpdater.HOST + BukkitUpdater.QUERY + id); 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."); plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid.");
this.result = UpdateResult.FAIL_BADID; this.result = UpdateResult.FAIL_BADID;
e.printStackTrace(); e.printStackTrace();
@ -166,7 +167,7 @@ public class BukkitUpdater extends Updater {
*/ */
/* /*
* private boolean hasTag(String version) { * private boolean hasTag(String version) {
* for (final String string : BukkitUpdater.NO_UPDATE_TAG) { * for (String string : BukkitUpdater.NO_UPDATE_TAG) {
* if (version.contains(string)) { * if (version.contains(string)) {
* return true; * return true;
* } * }
@ -177,7 +178,7 @@ public class BukkitUpdater extends Updater {
public boolean read() { public boolean read() {
try { try {
final URLConnection conn = this.url.openConnection(); URLConnection conn = this.url.openConnection();
conn.setConnectTimeout(5000); conn.setConnectTimeout(5000);
if (this.apiKey != null) { if (this.apiKey != null) {
@ -186,10 +187,10 @@ public class BukkitUpdater extends Updater {
conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); conn.addRequestProperty("User-Agent", "Updater (by Gravity)");
conn.setDoOutput(true); conn.setDoOutput(true);
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final String response = reader.readLine(); String response = reader.readLine();
final JSONArray array = (JSONArray) JSONValue.parse(response); JSONArray array = (JSONArray) JSONValue.parse(response);
if (array.size() == 0) { if (array.size() == 0) {
this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); 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; 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.versionFileName = (String) jsonObject.get(BukkitUpdater.FILE_NAME);
this.versionName = (String) jsonObject.get(BukkitUpdater.TITLE_VALUE); this.versionName = (String) jsonObject.get(BukkitUpdater.TITLE_VALUE);
this.versionLink = (String) jsonObject.get(BukkitUpdater.LINK_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); this.versionGameVersion = (String) jsonObject.get(BukkitUpdater.VERSION_VALUE);
return true; return true;
} catch (final IOException e) { } catch (IOException e) {
if (e.getMessage().contains("HTTP response code: 403")) { 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.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct.");
this.result = UpdateResult.FAIL_APIKEY; this.result = UpdateResult.FAIL_APIKEY;
} else { } else {
this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating."); 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; this.result = UpdateResult.FAIL_DBO;
} }
e.printStackTrace(); e.printStackTrace();
@ -228,7 +231,7 @@ public class BukkitUpdater extends Updater {
* - the update type. * - the update type.
*/ */
@Override @Override
public void start(final UpdateType type) { public void start(UpdateType type) {
waitForThread(); waitForThread();
this.type = type; 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. * 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) { private boolean pluginFile(String name) {
for (final File file : new File("plugins").listFiles()) { for (File file : new File("plugins").listFiles()) {
if (file.getName().equals(name)) { if (file.getName().equals(name)) { return true; }
return true;
}
} }
return false; return false;
} }
@ -251,7 +252,7 @@ public class BukkitUpdater extends Updater {
/** /**
* Save an update from dev.bukkit.org into the server's update folder. * 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()) { if (!folder.exists()) {
folder.mkdir(); folder.mkdir();
} }
@ -259,12 +260,12 @@ public class BukkitUpdater extends Updater {
FileOutputStream fout = null; FileOutputStream fout = null;
try { try {
// Download the file // Download the file
final URL url = new URL(u); URL url = new URL(u);
final int fileLength = url.openConnection().getContentLength(); int fileLength = url.openConnection().getContentLength();
in = new BufferedInputStream(url.openStream()); in = new BufferedInputStream(url.openStream());
fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file); fout = new FileOutputStream(folder.getAbsolutePath() + "/" + file);
final byte[] data = new byte[BukkitUpdater.BYTE_SIZE]; byte[] data = new byte[BukkitUpdater.BYTE_SIZE];
int count; int count;
if (this.announce) { if (this.announce) {
this.plugin.getLogger().info("About to download a new update: " + this.versionName); 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) { while ((count = in.read(data, 0, BukkitUpdater.BYTE_SIZE)) != -1) {
downloaded += count; downloaded += count;
fout.write(data, 0, 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)) { if (this.announce && ((percent % 10) == 0)) {
this.plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes."); 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... // 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")) { if (xFile.getName().endsWith(".zip")) {
xFile.delete(); xFile.delete();
} }
} }
// Check to see if it's a zip file, if it is, unzip it. // 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")) { if (dFile.getName().endsWith(".zip")) {
// Unzip // Unzip
this.unzip(dFile.getCanonicalPath()); this.unzip(dFile.getCanonicalPath());
@ -293,7 +294,7 @@ public class BukkitUpdater extends Updater {
if (this.announce) { if (this.announce) {
this.plugin.getLogger().info("Finished updating."); 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.plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful.");
this.result = BukkitUpdater.UpdateResult.FAIL_DOWNLOAD; this.result = BukkitUpdater.UpdateResult.FAIL_DOWNLOAD;
} finally { } finally {
@ -304,7 +305,7 @@ public class BukkitUpdater extends Updater {
if (fout != null) { if (fout != null) {
fout.close(); 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 * Part of Zip-File-Extractor, modified by Gravity for use with Bukkit
*/ */
private void unzip(final String file) { private void unzip(String file) {
try { try {
final File fSourceZip = new File(file); File fSourceZip = new File(file);
final String zipPath = file.substring(0, file.length() - 4); String zipPath = file.substring(0, file.length() - 4);
ZipFile zipFile = new ZipFile(fSourceZip); ZipFile zipFile = new ZipFile(fSourceZip);
Enumeration<? extends ZipEntry> e = zipFile.entries(); Enumeration<? extends ZipEntry> e = zipFile.entries();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
@ -325,20 +326,21 @@ public class BukkitUpdater extends Updater {
if (entry.isDirectory()) { if (entry.isDirectory()) {
continue; continue;
} }
final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
int b; int b;
final byte buffer[] = new byte[BukkitUpdater.BYTE_SIZE]; byte buffer[] = new byte[BukkitUpdater.BYTE_SIZE];
final FileOutputStream fos = new FileOutputStream(destinationFilePath); FileOutputStream fos = new FileOutputStream(destinationFilePath);
final BufferedOutputStream bos = new BufferedOutputStream(fos, BukkitUpdater.BYTE_SIZE); BufferedOutputStream bos = new BufferedOutputStream(fos, BukkitUpdater.BYTE_SIZE);
while ((b = bis.read(buffer, 0, BukkitUpdater.BYTE_SIZE)) != -1) { while ((b = bis.read(buffer, 0, BukkitUpdater.BYTE_SIZE)) != -1) {
bos.write(buffer, 0, b); bos.write(buffer, 0, b);
} }
bos.flush(); bos.flush();
bos.close(); bos.close();
bis.close(); bis.close();
final String name = destinationFilePath.getName(); String name = destinationFilePath.getName();
if (name.endsWith(".jar") && this.pluginFile(name)) { 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; entry = null;
destinationFilePath = null; destinationFilePath = null;
@ -348,15 +350,15 @@ public class BukkitUpdater extends Updater {
zipFile = null; zipFile = null;
// Move any plugin data folders that were included to the right place, Bukkit won't do this for us. // 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 (dFile.isDirectory()) {
if (this.pluginFile(dFile.getName())) { if (this.pluginFile(dFile.getName())) {
final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // Get current dir 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 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 for (File cFile : dFile.listFiles()) // Loop through all the files in the new dir
{ {
boolean found = false; 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())) { if (xFile.getName().equals(cFile.getName())) {
found = true; found = true;
@ -377,7 +379,7 @@ public class BukkitUpdater extends Updater {
} }
new File(zipPath).delete(); new File(zipPath).delete();
fSourceZip.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.plugin.getLogger().warning("The auto-updater tried to unzip a new update file, but was unsuccessful.");
this.result = BukkitUpdater.UpdateResult.FAIL_DOWNLOAD; this.result = BukkitUpdater.UpdateResult.FAIL_DOWNLOAD;
ex.printStackTrace(); 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 // Any generic error will be handled here
} finally { } finally {
// Invoke the listeners on the main thread // Invoke the listeners on the main thread
for (final Runnable listener : listeners) { for (Runnable listener : listeners) {
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, listener); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, listener);
} }
} }
@ -410,8 +412,8 @@ public class BukkitUpdater extends Updater {
private void performUpdate() { private void performUpdate() {
if ((BukkitUpdater.this.versionLink != null) && (BukkitUpdater.this.type != UpdateType.NO_DOWNLOAD)) { if ((BukkitUpdater.this.versionLink != null) && (BukkitUpdater.this.type != UpdateType.NO_DOWNLOAD)) {
final File pluginFolder = plugin.getDataFolder().getParentFile(); File pluginFolder = plugin.getDataFolder().getParentFile();
final File destinationFolder = new File(pluginFolder, updateFolder); File destinationFolder = new File(pluginFolder, updateFolder);
String name = BukkitUpdater.this.file.getName(); String name = BukkitUpdater.this.file.getName();
// If it's a zip file, it shouldn't be downloaded as the plugin's name // If it's a zip file, it shouldn't be downloaded as the plugin's name

View File

@ -33,21 +33,22 @@ import com.google.common.io.Closer;
* @author dmulloy2 * @author dmulloy2
*/ */
public final class SpigotUpdater extends Updater { public class SpigotUpdater extends Updater {
private static final String PROTOCOL = "https://"; 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; 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); super(plugin, type, announce);
} }
@ -63,15 +64,15 @@ public final class SpigotUpdater extends Updater {
} }
public String getSpigotVersion() throws IOException { public String getSpigotVersion() throws IOException {
final Closer closer = Closer.create(); Closer closer = Closer.create();
try { try {
final HttpURLConnection con = (HttpURLConnection) new URL(API_URL).openConnection(); HttpURLConnection con = (HttpURLConnection) new URL(API_URL).openConnection();
con.setDoOutput(true); con.setDoOutput(true);
con.setRequestMethod(ACTION); con.setRequestMethod(ACTION);
con.getOutputStream().write(API_KEY); con.getOutputStream().write(API_KEY);
final InputStreamReader isr = closer.register(new InputStreamReader(con.getInputStream())); InputStreamReader isr = closer.register(new InputStreamReader(con.getInputStream()));
final BufferedReader br = closer.register(new BufferedReader(isr)); BufferedReader br = closer.register(new BufferedReader(isr));
return br.readLine(); return br.readLine();
} finally { } finally {
closer.close(); closer.close();
@ -79,7 +80,7 @@ public final class SpigotUpdater extends Updater {
} }
@Override @Override
public void start(final UpdateType type) { public void start(UpdateType type) {
waitForThread(); waitForThread();
this.type = type; this.type = type;
this.thread = new Thread(new SpigotUpdateRunnable()); this.thread = new Thread(new SpigotUpdateRunnable());
@ -90,17 +91,17 @@ public final class SpigotUpdater extends Updater {
@Override @Override
public void run() { public void run() {
try { try {
final String version = getSpigotVersion(); String version = getSpigotVersion();
remoteVersion = version; remoteVersion = version;
if (versionCheck(version)) { if (versionCheck(version)) {
result = UpdateResult.SPIGOT_UPDATE_AVAILABLE; result = UpdateResult.SPIGOT_UPDATE_AVAILABLE;
} else { } else {
result = UpdateResult.NO_UPDATE; result = UpdateResult.NO_UPDATE;
} }
} catch (final Throwable ex) { } catch (Throwable ex) {
} finally { } finally {
// Invoke the listeners on the main thread // Invoke the listeners on the main thread
for (final Runnable listener : listeners) { for (Runnable listener : listeners) {
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, listener); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, listener);
} }
} }

View File

@ -45,7 +45,7 @@ public abstract class Updater {
protected List<Runnable> listeners = new CopyOnWriteArrayList<Runnable>(); protected List<Runnable> listeners = new CopyOnWriteArrayList<Runnable>();
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()) { // if (Util.isUsingSpigot()) {
return new SpigotUpdater(protocolLib, type, announce); return new SpigotUpdater(protocolLib, type, announce);
// } else { // } 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.plugin = plugin;
this.type = type; this.type = type;
this.announce = announce; this.announce = announce;
@ -67,7 +67,7 @@ public abstract class Updater {
* @param listener * @param listener
* - the listener to add. * - the listener to add.
*/ */
public void addListener(final Runnable listener) { public void addListener(Runnable listener) {
listeners.add(Preconditions.checkNotNull(listener, "listener cannot be NULL")); listeners.add(Preconditions.checkNotNull(listener, "listener cannot be NULL"));
} }
@ -129,7 +129,7 @@ public abstract class Updater {
* - the listener to remove. * - the listener to remove.
* @return TRUE if the listener was removed, FALSE otherwise. * @return TRUE if the listener was removed, FALSE otherwise.
*/ */
public boolean removeListener(final Runnable listener) { public boolean removeListener(Runnable listener) {
return listeners.remove(listener); return listeners.remove(listener);
} }
@ -146,7 +146,7 @@ public abstract class Updater {
public abstract void start(UpdateType type); public abstract void start(UpdateType type);
public boolean versionCheck(final String title) { public boolean versionCheck(String title) {
if (this.type != UpdateType.NO_VERSION_CHECK) { if (this.type != UpdateType.NO_VERSION_CHECK) {
String version = this.plugin.getDescription().getVersion(); String version = this.plugin.getDescription().getVersion();
@ -156,7 +156,7 @@ public abstract class Updater {
version = version.substring(0, version.indexOf("-")); version = version.substring(0, version.indexOf("-"));
} }
final String[] splitTitle = title.split(" "); String[] splitTitle = title.split(" ");
String remoteVersion; String remoteVersion;
if (splitTitle.length == 2) { if (splitTitle.length == 2) {
@ -165,9 +165,13 @@ public abstract class Updater {
remoteVersion = splitTitle[0]; remoteVersion = splitTitle[0];
} else { } else {
// The file's name did not contain the string 'vVersion' // 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) + ")"; String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? ""
this.plugin.getLogger().warning("The author of this plugin " + authorInfo + " has misconfigured their Auto Update system"); : " (" + this.plugin.getDescription().getAuthors().get(0) + ")";
this.plugin.getLogger().warning("File versions should follow the format 'PluginName VERSION[-SNAPSHOT]'"); 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.plugin.getLogger().warning("Please notify the author of this error.");
this.result = BukkitUpdater.UpdateResult.FAIL_NOVERSION; this.result = BukkitUpdater.UpdateResult.FAIL_NOVERSION;
return false; return false;
@ -178,7 +182,7 @@ public abstract class Updater {
remoteVersion = remoteVersion.substring(1); remoteVersion = remoteVersion.substring(1);
} }
final String localVersion = plugin.getDescription().getVersion(); String localVersion = plugin.getDescription().getVersion();
if (devBuild && remoteVersion.equals(localVersion)) { if (devBuild && remoteVersion.equals(localVersion)) {
// They're using a dev build and this version has been released // 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()) { if (thread != null && thread.isAlive()) {
try { try {
thread.join(); thread.join();
} catch (final InterruptedException ex) { } catch (InterruptedException ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
@ -255,9 +259,9 @@ public abstract class Updater {
*/ */
SPIGOT_UPDATE_AVAILABLE("The updater found an update: %s (Running %s). Download at %s"); 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; this.description = description;
} }

View File

@ -15,81 +15,79 @@ import org.bukkit.command.TabExecutor;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager; 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.commands.MonitorCommand;
import pw.yumc.Yum.managers.MonitorManager; import pw.yumc.Yum.managers.MonitorManager;
import pw.yumc.YumCore.kit.StrKit;
import pw.yumc.YumCore.reflect.Reflect;
public class CommandInjector implements TabExecutor { public class CommandInjector implements TabExecutor {
private final static String prefix = "§6[§bYum §a命令监控§6] "; private 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 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 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 static String inject_error = prefix + "§6插件 §b%s §c注入能耗监控失败!";
private final static String plugin_is_null = "插件不得为NULL!"; private static String plugin_is_null = "插件不得为NULL!";
private final CommandExecutor originalExecutor; private CommandExecutor originalExecutor;
private final TabCompleter originalCompleter; private TabCompleter originalCompleter;
private final Plugin plugin; private Plugin plugin;
public long totalTime; public long totalTime;
public int count; 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.originalExecutor = originalCommandExecutor;
this.originalCompleter = originalTabCompleter; this.originalCompleter = originalTabCompleter;
this.plugin = plugin; this.plugin = plugin;
} }
public static void inject(final Plugin plugin) { public static void inject(Plugin plugin) {
Validate.notNull(plugin, plugin_is_null); Validate.notNull(plugin, plugin_is_null);
try { try {
final PluginManager pluginManager = Bukkit.getPluginManager(); PluginManager pluginManager = Bukkit.getPluginManager();
final SimpleCommandMap commandMap = Reflect.on(pluginManager).get("commandMap"); SimpleCommandMap commandMap = Reflect.on(pluginManager).get("commandMap");
for (final Command command : commandMap.getCommands()) { for (Command command : commandMap.getCommands()) {
if (command instanceof PluginCommand) { if (command instanceof PluginCommand) {
final PluginCommand pluginCommand = (PluginCommand) command; PluginCommand pluginCommand = (PluginCommand) command;
final Plugin cp = pluginCommand.getPlugin(); Plugin cp = pluginCommand.getPlugin();
if (cp.equals(plugin)) { if (cp.equals(plugin)) {
final CommandExecutor executor = Reflect.on(command).get("executor"); CommandExecutor executor = Reflect.on(command).get("executor");
if (executor instanceof CommandInjector) { if (executor instanceof CommandInjector) { return; }
return; TabCompleter completer = Reflect.on(command).get("completer");
} CommandInjector commandInjector = new CommandInjector(executor, completer, plugin);
final TabCompleter completer = Reflect.on(command).get("completer");
final CommandInjector commandInjector = new CommandInjector(executor, completer, plugin);
Reflect.on(command).set("executor", commandInjector); Reflect.on(command).set("executor", commandInjector);
Reflect.on(command).set("completer", commandInjector); Reflect.on(command).set("completer", commandInjector);
} }
} }
} }
} catch (final Throwable e) { } catch (Throwable e) {
MonitorManager.log(String.format(inject_error, plugin.getName())); 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); Validate.notNull(plugin, plugin_is_null);
try { try {
final PluginManager pluginManager = Bukkit.getPluginManager(); PluginManager pluginManager = Bukkit.getPluginManager();
final SimpleCommandMap commandMap = Reflect.on(pluginManager).get("commandMap"); SimpleCommandMap commandMap = Reflect.on(pluginManager).get("commandMap");
for (final Command command : commandMap.getCommands()) { for (Command command : commandMap.getCommands()) {
if (command instanceof PluginCommand) { if (command instanceof PluginCommand) {
final PluginCommand pluginCommand = (PluginCommand) command; PluginCommand pluginCommand = (PluginCommand) command;
final Plugin cp = pluginCommand.getPlugin(); Plugin cp = pluginCommand.getPlugin();
if (cp.equals(plugin)) { if (cp.equals(plugin)) {
final CommandExecutor executor = Reflect.on(command).get("executor"); CommandExecutor executor = Reflect.on(command).get("executor");
if (executor instanceof CommandInjector) { if (executor instanceof CommandInjector) {
final CommandInjector injected = (CommandInjector) executor; CommandInjector injected = (CommandInjector) executor;
Reflect.on(command).set("executor", injected.getOriginalExecutor()); 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) { if (completer instanceof CommandInjector) {
final CommandInjector injected = (CommandInjector) completer; CommandInjector injected = (CommandInjector) completer;
Reflect.on(command).set("completer", injected.getOriginalCompleter()); Reflect.on(command).set("completer", injected.getOriginalCompleter());
} }
} }
} }
} }
} catch (final Throwable e) { } catch (Throwable e) {
} }
} }
@ -102,18 +100,24 @@ public class CommandInjector implements TabExecutor {
} }
@Override @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 { try {
final long start = System.nanoTime(); long start = System.nanoTime();
final boolean result = originalExecutor.onCommand(sender, command, label, args); boolean result = originalExecutor.onCommand(sender, command, label, args);
final long end = System.nanoTime(); long end = System.nanoTime();
final long lag = end - start; long lag = end - start;
totalTime += lag; totalTime += lag;
count++; count++;
final long lagms = lag / MonitorManager.um; long lagms = lag / MonitorManager.um;
final long avglagms = totalTime / count / MonitorManager.um; long avglagms = totalTime / count / MonitorManager.um;
if (Bukkit.isPrimaryThread() && lagms > MonitorManager.lagTime && avglagms > MonitorManager.lagTime) { 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); MonitorManager.addCmd(plugin.getName(), lag);
return result; return result;
@ -123,19 +127,18 @@ public class CommandInjector implements TabExecutor {
} }
MonitorCommand.lastError = e; MonitorCommand.lastError = e;
MonitorManager.sendError(sender, plugin, 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; return false;
} }
@Override @Override
public List<String> onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) { public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
if (originalCompleter == null) { if (originalCompleter == null) { return Collections.emptyList(); }
return Collections.emptyList(); long start = System.nanoTime();
} List<String> result = originalCompleter.onTabComplete(sender, command, alias, args);
final long start = System.nanoTime(); long end = System.nanoTime();
final List<String> result = originalCompleter.onTabComplete(sender, command, alias, args);
final long end = System.nanoTime();
totalTime += end - start; totalTime += end - start;
count++; count++;
return result; return result;

View File

@ -15,88 +15,80 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredListener; import org.bukkit.plugin.RegisteredListener;
import org.bukkit.plugin.TimedRegisteredListener; import org.bukkit.plugin.TimedRegisteredListener;
import cn.citycraft.PluginHelper.ext.kit.Reflect;
import pw.yumc.Yum.commands.MonitorCommand; import pw.yumc.Yum.commands.MonitorCommand;
import pw.yumc.Yum.managers.ConfigManager; import pw.yumc.Yum.managers.ConfigManager;
import pw.yumc.Yum.managers.MonitorManager; import pw.yumc.Yum.managers.MonitorManager;
import pw.yumc.YumCore.reflect.Reflect;
public class ListenerInjector implements EventExecutor { public class ListenerInjector implements EventExecutor {
private final static String prefix = "§6[§bYum §a事件监控§6] "; private 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 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 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 static String inject_error = prefix + "§6插件 §b%s §c注入能耗监控失败 §6注入类: §3%s!";
private final static String plugin_is_null = "插件不得为NULL!"; private static String plugin_is_null = "插件不得为NULL!";
private final EventExecutor originalExecutor; private EventExecutor originalExecutor;
private final Plugin plugin; private Plugin plugin;
public Map<String, Long> eventTotalTime = new ConcurrentHashMap<>(); public Map<String, Long> eventTotalTime = new ConcurrentHashMap<>();
public Map<String, Integer> eventCount = new ConcurrentHashMap<>(); public Map<String, Integer> eventCount = new ConcurrentHashMap<>();
public ListenerInjector(final EventExecutor originalExecutor, final Plugin plugin) { public ListenerInjector(EventExecutor originalExecutor, Plugin plugin) {
this.originalExecutor = originalExecutor; this.originalExecutor = originalExecutor;
this.plugin = plugin; this.plugin = plugin;
} }
public static void inject(final Plugin plugin) { public static void inject(Plugin plugin) {
Validate.notNull(plugin, plugin_is_null); Validate.notNull(plugin, plugin_is_null);
final List<RegisteredListener> listeners = HandlerList.getRegisteredListeners(plugin); List<RegisteredListener> listeners = HandlerList.getRegisteredListeners(plugin);
for (final RegisteredListener listener : listeners) { for (RegisteredListener listener : listeners) {
try { try {
if (listener instanceof TimedRegisteredListener) { if (listener instanceof TimedRegisteredListener) { return; }
return;
}
// 兼容PerWorldPlugin // 兼容PerWorldPlugin
if (listener.getClass().getName().contains("PWPRegisteredListener")) { if (listener.getClass().getName().contains("PWPRegisteredListener")) {
final Field f = Reflect.getDeclaredField(RegisteredListener.class, "executor"); Field f = Reflect.getDeclaredField(RegisteredListener.class, "executor");
f.setAccessible(true); f.setAccessible(true);
final EventExecutor originalExecutor = (EventExecutor) f.get(listener); EventExecutor originalExecutor = (EventExecutor) f.get(listener);
if (originalExecutor instanceof ListenerInjector) { if (originalExecutor instanceof ListenerInjector) { return; }
return; ListenerInjector listenerInjector = new ListenerInjector(originalExecutor, plugin);
}
final ListenerInjector listenerInjector = new ListenerInjector(originalExecutor, plugin);
f.set(listener, listenerInjector); f.set(listener, listenerInjector);
} else { } else {
final EventExecutor originalExecutor = Reflect.on(listener).get("executor"); EventExecutor originalExecutor = Reflect.on(listener).get("executor");
if (originalExecutor instanceof ListenerInjector) { if (originalExecutor instanceof ListenerInjector) { return; }
return; ListenerInjector listenerInjector = new ListenerInjector(originalExecutor, plugin);
}
final ListenerInjector listenerInjector = new ListenerInjector(originalExecutor, plugin);
Reflect.on(listener).set("executor", listenerInjector); Reflect.on(listener).set("executor", listenerInjector);
} }
} catch (final Throwable e) { } catch (Throwable e) {
MonitorManager.log(String.format(inject_error, plugin.getName(), listener.getClass().getName())); MonitorManager.log(String.format(inject_error, plugin.getName(), listener.getClass().getName()));
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
public static void uninject(final Plugin plugin) { public static void uninject(Plugin plugin) {
Validate.notNull(plugin, plugin_is_null); Validate.notNull(plugin, plugin_is_null);
try { try {
final List<RegisteredListener> listeners = HandlerList.getRegisteredListeners(plugin); List<RegisteredListener> listeners = HandlerList.getRegisteredListeners(plugin);
for (final RegisteredListener listener : listeners) { for (RegisteredListener listener : listeners) {
if (listener instanceof TimedRegisteredListener) { if (listener instanceof TimedRegisteredListener) { return; }
return; EventExecutor executor = Reflect.on(listener).get("executor");
}
final EventExecutor executor = Reflect.on(listener).get("executor");
if (executor instanceof ListenerInjector) { if (executor instanceof ListenerInjector) {
Reflect.on(listener).set("executor", ((ListenerInjector) executor).getOriginalExecutor()); Reflect.on(listener).set("executor", ((ListenerInjector) executor).getOriginalExecutor());
} }
} }
} catch (final Throwable e) { } catch (Throwable e) {
} }
} }
@Override @Override
public void execute(final Listener listener, final Event event) throws EventException { public void execute(Listener listener, Event event) throws EventException {
try { try {
if (!event.isAsynchronous()) { if (!event.isAsynchronous()) {
final long start = System.nanoTime(); long start = System.nanoTime();
originalExecutor.execute(listener, event); originalExecutor.execute(listener, event);
final long end = System.nanoTime(); long end = System.nanoTime();
final String en = event.getEventName(); String en = event.getEventName();
final long lag = end - start; long lag = end - start;
if (eventTotalTime.containsKey(en)) { if (eventTotalTime.containsKey(en)) {
eventTotalTime.put(en, eventTotalTime.get(en) + lag); eventTotalTime.put(en, eventTotalTime.get(en) + lag);
eventCount.put(en, eventCount.get(en) + 1); eventCount.put(en, eventCount.get(en) + 1);
@ -104,9 +96,10 @@ public class ListenerInjector implements EventExecutor {
eventTotalTime.put(en, end - start); eventTotalTime.put(en, end - start);
eventCount.put(en, 1); eventCount.put(en, 1);
} }
final long lagms = lag / MonitorManager.um; long lagms = lag / MonitorManager.um;
final long avglagms = eventTotalTime.get(en) / eventCount.get(en) / 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())) { 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.lagTip(String.format(warn, plugin.getName(), event.getEventName(), lagms, avglagms));
} }
MonitorManager.addEvent(plugin.getName(), lag); MonitorManager.addEvent(plugin.getName(), lag);

View File

@ -8,70 +8,68 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask; 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.commands.MonitorCommand;
import pw.yumc.Yum.managers.MonitorManager; import pw.yumc.Yum.managers.MonitorManager;
import pw.yumc.YumCore.kit.StrKit;
import pw.yumc.YumCore.reflect.Reflect;
public class TaskInjector implements Runnable { public class TaskInjector implements Runnable {
private final static String prefix = "§6[§bYum §a任务监控§6] "; private 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 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 static String err = prefix + "§6插件 §b%s §6处理 §d%s §6任务时发生异常!";
private final static String inject_error = prefix + "§6插件 §b%s §c注入能耗监控失败!"; private static String inject_error = prefix + "§6插件 §b%s §c注入能耗监控失败!";
private final static String plugin_is_null = "插件不得为NULL!"; private static String plugin_is_null = "插件不得为NULL!";
private final Runnable originalTask; private Runnable originalTask;
private final Plugin plugin; private Plugin plugin;
private final String taskName; private String taskName;
public long totalTime; public long totalTime;
public int count; public int count;
public TaskInjector(final Runnable originalTask, final Plugin plugin) { public TaskInjector(Runnable originalTask, Plugin plugin) {
this.originalTask = originalTask; this.originalTask = originalTask;
this.plugin = plugin; this.plugin = plugin;
final Class<? extends Runnable> taskClass = getOriginalTask().getClass(); Class<? extends Runnable> taskClass = getOriginalTask().getClass();
taskName = StrKit.isBlank(taskClass.getSimpleName()) ? taskClass.getName() : taskClass.getSimpleName(); taskName = StrKit.isBlank(taskClass.getSimpleName()) ? taskClass.getName() : taskClass.getSimpleName();
} }
// 当前注入只能对TimerTask有效 // 当前注入只能对TimerTask有效
// 对于单次执行的任务 我们需要注册一个动态的代理 // 对于单次执行的任务 我们需要注册一个动态的代理
public static void inject(final Plugin plugin) { public static void inject(Plugin plugin) {
Validate.notNull(plugin, plugin_is_null); Validate.notNull(plugin, plugin_is_null);
try { try {
final BukkitScheduler scheduler = Bukkit.getScheduler(); BukkitScheduler scheduler = Bukkit.getScheduler();
final List<BukkitTask> pendingTasks = scheduler.getPendingTasks(); List<BukkitTask> pendingTasks = scheduler.getPendingTasks();
for (final BukkitTask pendingTask : pendingTasks) { for (BukkitTask pendingTask : pendingTasks) {
// 忽略异步任务 // 忽略异步任务
if (pendingTask.isSync() && pendingTask.getOwner().equals(plugin)) { 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) { if (originalTask instanceof TaskInjector) { return; }
return; TaskInjector taskInjector = new TaskInjector(originalTask, plugin);
}
final TaskInjector taskInjector = new TaskInjector(originalTask, plugin);
Reflect.on(pendingTask).set("task", taskInjector); Reflect.on(pendingTask).set("task", taskInjector);
} }
} }
} catch (final Throwable e) { } catch (Throwable e) {
MonitorManager.log(String.format(inject_error, plugin.getName())); 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); Validate.notNull(plugin, plugin_is_null);
try { try {
final BukkitScheduler scheduler = Bukkit.getScheduler(); BukkitScheduler scheduler = Bukkit.getScheduler();
final List<BukkitTask> pendingTasks = scheduler.getPendingTasks(); List<BukkitTask> pendingTasks = scheduler.getPendingTasks();
for (final BukkitTask pendingTask : pendingTasks) { for (BukkitTask pendingTask : pendingTasks) {
// 忽略异步任务 // 忽略异步任务
if (pendingTask.isSync() && pendingTask.getOwner().equals(plugin)) { 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) { if (originalTask instanceof TaskInjector) {
Reflect.on(pendingTask).set("task", ((TaskInjector) originalTask).getOriginalTask()); 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 @Override
public void run() { public void run() {
try { try {
final long start = System.nanoTime(); long start = System.nanoTime();
originalTask.run(); originalTask.run();
final long end = System.nanoTime(); long end = System.nanoTime();
final long lag = end - start; long lag = end - start;
totalTime += lag; totalTime += lag;
count++; count++;
final long lagms = lag / MonitorManager.um; long lagms = lag / MonitorManager.um;
final long avglagms = totalTime / count / MonitorManager.um; long avglagms = totalTime / count / MonitorManager.um;
if (Bukkit.isPrimaryThread() && lagms > MonitorManager.lagTime && avglagms > MonitorManager.lagTime) { if (Bukkit.isPrimaryThread() && lagms > MonitorManager.lagTime && avglagms > MonitorManager.lagTime) {
MonitorManager.lagTip(String.format(warn, plugin.getName(), taskName, lagms, avglagms)); MonitorManager.lagTip(String.format(warn, plugin.getName(), taskName, lagms, avglagms));
} }

View File

@ -26,15 +26,13 @@ public class PluginListener implements Listener {
} }
@EventHandler @EventHandler
public void onPluginDisable(final PluginDisableEvent e) { public void onPluginDisable(PluginDisableEvent e) {
YumAPI.uninject(e.getPlugin()); YumAPI.uninject(e.getPlugin());
} }
@EventHandler @EventHandler
public void onPluginEnable(final PluginEnableEvent e) { public void onPluginEnable(final PluginEnableEvent e) {
if (ConfigManager.i().getMonitorIgnoreList().contains(e.getPlugin().getName())) { if (ConfigManager.i().getMonitorIgnoreList().contains(e.getPlugin().getName())) { return; }
return;
}
MonitorManager.reset(e.getPlugin().getName()); MonitorManager.reset(e.getPlugin().getName());
PKit.runTaskLater(new Runnable() { PKit.runTaskLater(new Runnable() {
@Override @Override

View File

@ -18,11 +18,11 @@ public class PluginNetworkListener implements Listener {
public String breaked = "§c已阻止插件 §b%s §c访问网络!"; public String breaked = "§c已阻止插件 §b%s §c访问网络!";
public String url = "§6地址: §c%s"; public String url = "§6地址: §c%s";
public PluginNetworkListener(final Yum yum) { public PluginNetworkListener(Yum yum) {
Bukkit.getPluginManager().registerEvents(this, yum); Bukkit.getPluginManager().registerEvents(this, yum);
} }
public void breakNetwork(final PluginNetworkEvent e) { public void breakNetwork(PluginNetworkEvent e) {
if (ConfigManager.i().isNetworkShowInfo()) { if (ConfigManager.i().isNetworkShowInfo()) {
Log.console(prefix + breaked, e.getPlugin().getName()); Log.console(prefix + breaked, e.getPlugin().getName());
Log.console(prefix + url, e.getUrl().toString()); Log.console(prefix + url, e.getUrl().toString());
@ -31,17 +31,13 @@ public class PluginNetworkListener implements Listener {
} }
@EventHandler @EventHandler
public void onPluginNetworkConect(final PluginNetworkEvent e) { public void onPluginNetworkConect(PluginNetworkEvent e) {
final Plugin plugin = e.getPlugin(); Plugin plugin = e.getPlugin();
final String urlinfo = e.getUrl().toString(); String urlinfo = e.getUrl().toString();
if (urlinfo.startsWith("socket")) { if (urlinfo.startsWith("socket")) { return; }
return; if (ConfigManager.i().getNetworkWhiteURL().contains(e.getUrl().getHost())) { return; }
}
if (ConfigManager.i().getNetworkWhiteURL().contains(e.getUrl().getHost())) {
return;
}
if (urlinfo.contains("yumc") || urlinfo.contains("citycraft") || urlinfo.contains("502647092")) { if (urlinfo.contains("yumc") || urlinfo.contains("citycraft") || urlinfo.contains("502647092")) {
final String 大神你好 = "反编译的大神们我知道你们又要说了这货有后门"; String 大神你好 = "反编译的大神们我知道你们又要说了这货有后门";
大神你好.isEmpty(); 大神你好.isEmpty();
return; return;
} }
@ -51,9 +47,7 @@ public class PluginNetworkListener implements Listener {
breakNetwork(e); breakNetwork(e);
return; return;
} }
if (ConfigManager.i().getNetworkIgnoreList().contains(plugin.getName())) { if (ConfigManager.i().getNetworkIgnoreList().contains(plugin.getName())) { return; }
return;
}
if (e.isPrimaryThread()) { if (e.isPrimaryThread()) {
Log.console(prefix + warnMain, plugin.getName()); Log.console(prefix + warnMain, plugin.getName());
if (!ConfigManager.i().isAllowPrimaryThread()) { if (!ConfigManager.i().isAllowPrimaryThread()) {

View File

@ -17,26 +17,24 @@ import pw.yumc.injected.event.SetOpEvent;
* @author * @author
*/ */
public class SecurityListener implements Listener { public class SecurityListener implements Listener {
private final String prefix = "§6[§bYum §a安全系统§6] "; private String prefix = "§6[§bYum §a安全系统§6] ";
private final String warn = "§c插件 §e%s §c已设置玩家 §a%s §c为OP §4请注意服务器安全!"; private 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 prevent = "§c黑名单插件 §e%s §c尝试设置玩家 §a%s §c为OP §a安全系统已成功拦截!";
public SecurityListener(final Yum yum) { public SecurityListener(Yum yum) {
Bukkit.getPluginManager().registerEvents(this, yum); Bukkit.getPluginManager().registerEvents(this, yum);
} }
@EventHandler @EventHandler
public void setop(final SetOpEvent e) { public void setop(SetOpEvent e) {
final Plugin plugin = PKit.getOperatePlugin(); Plugin plugin = PKit.getOperatePlugin();
if (plugin != null) { if (plugin != null) {
if (ConfigManager.i().getSetOpBlackList().contains(plugin.getName())) { if (ConfigManager.i().getSetOpBlackList().contains(plugin.getName())) {
Log.console(prefix + prevent, plugin, e.getOfflinePlayer().getName()); Log.console(prefix + prevent, plugin, e.getOfflinePlayer().getName());
e.setCancelled(true); e.setCancelled(true);
return; return;
} }
if (ConfigManager.i().getSetOpIgnoreList().contains(plugin.getName())) { if (ConfigManager.i().getSetOpIgnoreList().contains(plugin.getName())) { return; }
return;
}
Bukkit.getConsoleSender().sendMessage(String.format(prefix + warn, plugin, e.getOfflinePlayer().getName())); Bukkit.getConsoleSender().sendMessage(String.format(prefix + warn, plugin, e.getOfflinePlayer().getName()));
} }
} }

View File

@ -27,69 +27,68 @@ import pw.yumc.YumCore.kit.PKit;
*/ */
public class ThreadSafetyListener implements Listener { public class ThreadSafetyListener implements Listener {
public ThreadSafetyListener(final Yum yum) { public ThreadSafetyListener(Yum yum) {
Bukkit.getPluginManager().registerEvents(this, yum); Bukkit.getPluginManager().registerEvents(this, yum);
} }
@EventHandler @EventHandler
public void onChunkLoad(final ChunkLoadEvent chunkLoadEvent) { public void onChunkLoad(ChunkLoadEvent chunkLoadEvent) {
checkSafety(chunkLoadEvent); checkSafety(chunkLoadEvent);
} }
@EventHandler @EventHandler
public void onChunkUnload(final ChunkUnloadEvent chunkUnloadEvent) { public void onChunkUnload(ChunkUnloadEvent chunkUnloadEvent) {
checkSafety(chunkUnloadEvent); checkSafety(chunkUnloadEvent);
} }
@EventHandler @EventHandler
public void onCreatureSpawn(final CreatureSpawnEvent creatureSpawnEvent) { public void onCreatureSpawn(CreatureSpawnEvent creatureSpawnEvent) {
checkSafety(creatureSpawnEvent); checkSafety(creatureSpawnEvent);
} }
public void onInventoryOpen(final InventoryOpenEvent inventoryOpenEvent) { public void onInventoryOpen(InventoryOpenEvent inventoryOpenEvent) {
checkSafety(inventoryOpenEvent); checkSafety(inventoryOpenEvent);
} }
@EventHandler @EventHandler
public void onItemSpawn(final ItemSpawnEvent itemSpawnEvent) { public void onItemSpawn(ItemSpawnEvent itemSpawnEvent) {
checkSafety(itemSpawnEvent); checkSafety(itemSpawnEvent);
} }
@EventHandler @EventHandler
public void onPlayerMove(final PlayerMoveEvent moveEvent) { public void onPlayerMove(PlayerMoveEvent moveEvent) {
checkSafety(moveEvent); checkSafety(moveEvent);
} }
@EventHandler @EventHandler
public void onPlayerQuit(final PlayerQuitEvent quitEvent) { public void onPlayerQuit(PlayerQuitEvent quitEvent) {
checkSafety(quitEvent); checkSafety(quitEvent);
} }
public void onPlayerTeleport(final PlayerTeleportEvent teleportEvent) { public void onPlayerTeleport(PlayerTeleportEvent teleportEvent) {
checkSafety(teleportEvent); checkSafety(teleportEvent);
} }
@EventHandler @EventHandler
public void onWorldLoad(final WorldLoadEvent worldLoadEvent) { public void onWorldLoad(WorldLoadEvent worldLoadEvent) {
checkSafety(worldLoadEvent); checkSafety(worldLoadEvent);
} }
public void onWorldSave(final WorldSaveEvent worldSaveEvent) { public void onWorldSave(WorldSaveEvent worldSaveEvent) {
checkSafety(worldSaveEvent); checkSafety(worldSaveEvent);
} }
@EventHandler @EventHandler
public void onWorldUnload(final WorldUnloadEvent worldUnloadEvent) { public void onWorldUnload(WorldUnloadEvent worldUnloadEvent) {
checkSafety(worldUnloadEvent); checkSafety(worldUnloadEvent);
} }
private void checkSafety(final Event eventType) { private void checkSafety(Event eventType) {
if (Yum.mainThread != null && Thread.currentThread() != Yum.mainThread && !eventType.isAsynchronous()) { if (Yum.mainThread != null && Thread.currentThread() != Yum.mainThread && !eventType.isAsynchronous()) {
final String eventName = eventType.getEventName(); String eventName = eventType.getEventName();
final Plugin plugin = PKit.getOperatePlugin(); Plugin plugin = PKit.getOperatePlugin();
if (plugin != null) { if (plugin != null) { throw new IllegalAccessError("[Yum 线程安全]: 请勿异步调用一个同步事件 " + eventName + " 操作插件: "
throw new IllegalAccessError("[Yum 线程安全]: 请勿异步调用一个同步事件 " + eventName + " 操作插件: " + plugin.getName()); + plugin.getName()); }
}
} }
} }
} }

View File

@ -9,19 +9,19 @@ import pw.yumc.YumCore.config.FileConfig;
import pw.yumc.YumCore.sql.DataBase; import pw.yumc.YumCore.sql.DataBase;
public class ConfigManager { public class ConfigManager {
public final static String ENABLE = "Enable"; public static String ENABLE = "Enable";
public final static String BLACK = "Black"; public static String BLACK = "Black";
public final static String IGNORE = "Ignore"; 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 FileConfig config;
public final FileConfig setop; public FileConfig setop;
public final FileConfig network; public FileConfig network;
public final FileConfig thread; public FileConfig thread;
public final FileConfig monitor; public FileConfig monitor;
public ConfigManager(final JavaPlugin plugin) { public ConfigManager(JavaPlugin plugin) {
config = new FileConfig(); config = new FileConfig();
setop = new FileConfig("setop.yml"); setop = new FileConfig("setop.yml");
network = new FileConfig("network.yml"); network = new FileConfig("network.yml");

View File

@ -1,6 +1,5 @@
package pw.yumc.Yum.managers; package pw.yumc.Yum.managers;
import cn.citycraft.PluginHelper.sql.Type;
import pw.yumc.YumCore.sql.DataBase; import pw.yumc.YumCore.sql.DataBase;
import pw.yumc.YumCore.sql.core.KeyValue; import pw.yumc.YumCore.sql.core.KeyValue;
@ -8,9 +7,18 @@ public class DataManager {
private static DataBase db = ConfigManager.i().getDataBase(); private static DataBase db = ConfigManager.i().getDataBase();
public static void init() { 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.cmd,
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); new KeyValue("plugin", "VARCHAR(30)").add("name", "VARCHAR(30)").add("total", "INT").add("count",
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); "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 { static class TableName {

View File

@ -14,7 +14,7 @@ import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile; 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 { public class DownloadManager {
Plugin plugin; Plugin plugin;
public DownloadManager(final Plugin main) { public DownloadManager(Plugin main) {
this.plugin = main; this.plugin = main;
} }
@ -36,8 +36,8 @@ public class DownloadManager {
* - 地址 * - 地址
* @return 文件名称 * @return 文件名称
*/ */
public String getFileName(final String url) { public String getFileName(String url) {
final int end = url.lastIndexOf('/'); int end = url.lastIndexOf('/');
return url.substring(end + 1); return url.substring(end + 1);
} }
@ -48,7 +48,7 @@ public class DownloadManager {
* - 地址 * - 地址
* @return 文件名称 * @return 文件名称
*/ */
public String getFileName(final URL url) { public String getFileName(URL url) {
return getFileName(url.getFile()); return getFileName(url.getFile());
} }
@ -61,7 +61,7 @@ public class DownloadManager {
* - 下载地址 * - 下载地址
* @return 是否成功 * @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); return run(sender, urlstring, new File("plugins", getFileName(urlstring)), null);
} }
@ -76,11 +76,11 @@ public class DownloadManager {
* - 保存文件 * - 保存文件
* @return 是否成功 * @return 是否成功
*/ */
public boolean run(final CommandSender sender, final String urlstring, final File file) { public boolean run(CommandSender sender, String urlstring, File file) {
try { try {
final URL url = new URL(urlstring); URL url = new URL(urlstring);
return run(sender, url, file); return run(sender, url, file);
} catch (final MalformedURLException e) { } catch (MalformedURLException e) {
sender.sendMessage("§4错误: §c无法识别的URL地址..."); sender.sendMessage("§4错误: §c无法识别的URL地址...");
sender.sendMessage("§4地址: §c" + urlstring); sender.sendMessage("§4地址: §c" + urlstring);
return false; return false;
@ -100,11 +100,11 @@ public class DownloadManager {
* -回调函数 * -回调函数
* @return 是否成功 * @return 是否成功
*/ */
public boolean run(final CommandSender sender, final String urlstring, final File file, final One<File> callback) { public boolean run(CommandSender sender, String urlstring, File file, One<File> callback) {
try { try {
final URL url = new URL(urlstring); URL url = new URL(urlstring);
return run(sender, url, file, callback); return run(sender, url, file, callback);
} catch (final MalformedURLException e) { } catch (MalformedURLException e) {
sender.sendMessage("§4错误: §c无法识别的URL地址..."); sender.sendMessage("§4错误: §c无法识别的URL地址...");
sender.sendMessage("§4地址: §c" + urlstring); sender.sendMessage("§4地址: §c" + urlstring);
return false; return false;
@ -122,7 +122,7 @@ public class DownloadManager {
* - 保存文件 * - 保存文件
* @return 是否成功 * @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); return run(sender, url, file, null);
} }
@ -139,7 +139,7 @@ public class DownloadManager {
* -回调函数 * -回调函数
* @return 是否成功 * @return 是否成功
*/ */
public boolean run(CommandSender sender, final URL url, final File file, final One<File> callback) { public boolean run(CommandSender sender, URL url, File file, One<File> callback) {
BufferedInputStream in = null; BufferedInputStream in = null;
FileOutputStream fout = null; FileOutputStream fout = null;
if (sender == null) { if (sender == null) {
@ -148,8 +148,8 @@ public class DownloadManager {
try { try {
sender.sendMessage("§6开始下载: §3" + getFileName(url)); sender.sendMessage("§6开始下载: §3" + getFileName(url));
sender.sendMessage("§6下载地址: §3" + url.toString()); sender.sendMessage("§6下载地址: §3" + url.toString());
final URLConnection uc = reload(sender, url.openConnection()); URLConnection uc = reload(sender, url.openConnection());
final int status = ((HttpURLConnection) uc).getResponseCode(); int status = ((HttpURLConnection) uc).getResponseCode();
if (status != HttpURLConnection.HTTP_OK) { if (status != HttpURLConnection.HTTP_OK) {
switch (status) { switch (status) {
case HttpURLConnection.HTTP_NOT_FOUND: case HttpURLConnection.HTTP_NOT_FOUND:
@ -160,8 +160,8 @@ public class DownloadManager {
throw new IllegalStateException(status + " 无效的网关!"); throw new IllegalStateException(status + " 无效的网关!");
} }
} }
final int fileLength = uc.getContentLength(); int fileLength = uc.getContentLength();
final boolean dyml = "chunked".equalsIgnoreCase(uc.getHeaderField("Transfer-Encoding")); boolean dyml = "chunked".equalsIgnoreCase(uc.getHeaderField("Transfer-Encoding"));
if (fileLength < 0 && !dyml) { if (fileLength < 0 && !dyml) {
sender.sendMessage("§6下载: §c文件 " + file.getName() + " 获取长度错误(可能是网络问题)!"); sender.sendMessage("§6下载: §c文件 " + file.getName() + " 获取长度错误(可能是网络问题)!");
sender.sendMessage("§6文件: §c" + file.getName() + " 下载失败!"); sender.sendMessage("§6文件: §c" + file.getName() + " 下载失败!");
@ -179,7 +179,7 @@ public class DownloadManager {
file.createNewFile(); file.createNewFile();
sender.sendMessage("§6创建新文件: §d" + file.getAbsolutePath()); sender.sendMessage("§6创建新文件: §d" + file.getAbsolutePath());
fout = new FileOutputStream(file); fout = new FileOutputStream(file);
final byte[] data = new byte[1024]; byte[] data = new byte[1024];
long downloaded = 0L; long downloaded = 0L;
int count; int count;
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
@ -192,7 +192,7 @@ public class DownloadManager {
time = System.currentTimeMillis(); time = System.currentTimeMillis();
} }
} else { } else {
final int percent = (int) (downloaded * 100L / fileLength); int percent = (int) (downloaded * 100L / fileLength);
if (percent % 10 == 0) { if (percent % 10 == 0) {
if (System.currentTimeMillis() - time > 500) { if (System.currentTimeMillis() - time > 500) {
sender.sendMessage(String.format("§6已下载: §a" + getPer(percent / 10) + " %s%%", percent)); sender.sendMessage(String.format("§6已下载: §a" + getPer(percent / 10) + " %s%%", percent));
@ -203,13 +203,14 @@ public class DownloadManager {
} }
String pVer = null; String pVer = null;
try { try {
final PluginDescriptionFile desc = plugin.getPluginLoader().getPluginDescription(file); PluginDescriptionFile desc = plugin.getPluginLoader().getPluginDescription(file);
pVer = StringUtils.substring(desc.getVersion(), 0, 15); pVer = StringUtils.substring(desc.getVersion(), 0, 15);
} catch (final Exception e) { } catch (Exception e) {
pVer = ""; pVer = "";
} }
sender.sendMessage("§6" + (pVer.isEmpty() ? "文件" : "插件") + ": §b" + file.getName() + (pVer.isEmpty() ? "" : " §a版本 §e" + pVer) + " §a下载完成!"); sender.sendMessage("§6" + (pVer.isEmpty() ? "文件" : "插件") + ": §b" + file.getName()
} catch (final Exception ex) { + (pVer.isEmpty() ? "" : " §a版本 §e" + pVer) + " §a下载完成!");
} catch (Exception ex) {
sender.sendMessage("§6异常: §c" + ex.getMessage()); sender.sendMessage("§6异常: §c" + ex.getMessage());
sender.sendMessage("§6文件: §c" + file.getName() + " 下载失败!"); sender.sendMessage("§6文件: §c" + file.getName() + " 下载失败!");
return false; return false;
@ -221,7 +222,7 @@ public class DownloadManager {
if (fout != null) { if (fout != null) {
fout.close(); fout.close();
} }
} catch (final Exception ex) { } catch (Exception ex) {
} }
} }
if (callback != null) { if (callback != null) {
@ -237,7 +238,7 @@ public class DownloadManager {
* - 下载地址 * - 下载地址
* @return 是否成功 * @return 是否成功
*/ */
public boolean run(final String urlstring) { public boolean run(String urlstring) {
return run(null, urlstring); return run(null, urlstring);
} }
@ -250,7 +251,7 @@ public class DownloadManager {
* - 保存文件 * - 保存文件
* @return 是否成功 * @return 是否成功
*/ */
public boolean run(final String urlstring, final File file) { public boolean run(String urlstring, File file) {
return run(null, urlstring, file, null); return run(null, urlstring, file, null);
} }
@ -263,12 +264,12 @@ public class DownloadManager {
* - 保存文件 * - 保存文件
* @return 是否成功 * @return 是否成功
*/ */
public boolean run(final URL url, final File file) { public boolean run(URL url, File file) {
return run(null, url, file, null); return run(null, url, file, null);
} }
private String getPer(final int per) { private String getPer(int per) {
final StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int i = 0; i < 11; i++) { for (int i = 0; i < 11; i++) {
if (per > i) { if (per > i) {
sb.append("=="); sb.append("==");
@ -288,11 +289,12 @@ public class DownloadManager {
* @return 最终地址 * @return 最终地址
* @throws Exception * @throws Exception
*/ */
private URLConnection reload(final CommandSender sender, final URLConnection uc) throws Exception { private URLConnection reload(CommandSender sender, URLConnection uc) throws Exception {
final HttpURLConnection huc = (HttpURLConnection) uc; HttpURLConnection huc = (HttpURLConnection) uc;
// 302, 301, 307 // 302, 301, 307
if (huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP || huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || huc.getResponseCode() == 307) { if (huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP
final String url = huc.getHeaderField("Location"); || huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || huc.getResponseCode() == 307) {
String url = huc.getHeaderField("Location");
sender.sendMessage("§6跳转至地址: §3" + url); sender.sendMessage("§6跳转至地址: §3" + url);
return reload(sender, new URL(url).openConnection()); return reload(sender, new URL(url).openConnection());
} }

View File

@ -15,8 +15,8 @@ import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import cn.citycraft.PluginHelper.kit.LogKit;
import pw.yumc.YumCore.bukkit.Log; import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.kit.LogKit;
/** /**
* 能耗监控管理 * 能耗监控管理
@ -25,43 +25,43 @@ import pw.yumc.YumCore.bukkit.Log;
* @author * @author
*/ */
public class MonitorManager { public class MonitorManager {
public final static String prefix = "§6[§bYum §a能耗监控§6] "; public static String prefix = "§6[§bYum §a能耗监控§6] ";
private final static String errMsg = prefix + "§c命令执行异常 请反馈下列信息给腐竹!"; private static String errMsg = prefix + "§c命令执行异常 请反馈下列信息给腐竹!";
private final static String errP = "§6插件名称: §b%s"; private static String errP = "§6插件名称: §b%s";
private final static String errN = "§6异常名称: §c%s"; private static String errN = "§6异常名称: §c%s";
private final static String errM = "§6异常说明: §3%s"; private static String errM = "§6异常说明: §3%s";
private final static String errInfo = "§6简易错误信息如下:"; private static String errInfo = "§6简易错误信息如下:";
private final static String errStackTrace = " §e位于 §c%s.%s(§4%s:%s§c)"; private static String errStackTrace = " §e位于 §c%s.%s(§4%s:%s§c)";
private final static String devInfo = "§c开发人员调试信息如下:"; private static String devInfo = "§c开发人员调试信息如下:";
public final static int lagTime = 20; public static int lagTime = 20;
public final static int um = 1000000; public static int um = 1000000;
public final static boolean debug = ConfigManager.i().isMonitorDebug(); public static boolean debug = ConfigManager.i().isMonitorDebug();
public final static boolean log_to_file = ConfigManager.i().isLogToFile(); public static boolean log_to_file = ConfigManager.i().isLogToFile();
private static double totalTime = 0; private static double totalTime = 0;
private final static Map<String, Long> monitor = new ConcurrentHashMap<>(); private static Map<String, Long> monitor = new ConcurrentHashMap<>();
private final static Map<String, Long> task = new ConcurrentHashMap<>(); private static Map<String, Long> task = new ConcurrentHashMap<>();
private final static Map<String, Long> event = new ConcurrentHashMap<>(); private static Map<String, Long> event = new ConcurrentHashMap<>();
private final static Map<String, Long> cmd = new ConcurrentHashMap<>(); private static Map<String, Long> cmd = new ConcurrentHashMap<>();
private final static LogKit mlog = new LogKit("monitor.log"); private static LogKit mlog = new LogKit("monitor.log");
private final static LogKit elog = new LogKit("error.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); 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); 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); add(pname, time, monitor, task);
} }
public static void elog(final String message) { public static void elog(String message) {
if (log_to_file) { if (log_to_file) {
elog.logSender(message); elog.logSender(message);
} else { } else {
@ -73,22 +73,23 @@ public class MonitorManager {
return sortMapByValue(monitor); return sortMapByValue(monitor);
} }
public static MonitorInfo getMonitorInfo(final String pname) { public static MonitorInfo getMonitorInfo(String pname) {
final double per = 100.00; 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); 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() { public static void init() {
for (final Plugin p : Bukkit.getPluginManager().getPlugins()) { for (Plugin p : Bukkit.getPluginManager().getPlugins()) {
reset(p.getName()); reset(p.getName());
} }
} }
public static void lagTip(final String message) { public static void lagTip(String message) {
log(prefix + message); log(prefix + message);
} }
public static void log(final String message) { public static void log(String message) {
if (log_to_file) { if (log_to_file) {
mlog.logSender(message); mlog.logSender(message);
} else { } 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(title);
elog(String.format(errN, e.getClass().getName())); elog(String.format(errN, e.getClass().getName()));
elog(String.format(errM, e.getMessage())); elog(String.format(errM, e.getMessage()));
elog(errInfo); 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++) { for (int i = 0; i < l; i++) {
final StackTraceElement ste = e.getStackTrace()[i]; StackTraceElement ste = e.getStackTrace()[i];
elog(String.format(errStackTrace, ste.getClassName(), ste.getMethodName(), ste.getFileName(), ste.getLineNumber())); elog(String.format(errStackTrace,
ste.getClassName(),
ste.getMethodName(),
ste.getFileName(),
ste.getLineNumber()));
} }
if (debug) { if (debug) {
Log.console(devInfo); 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); monitor.put(pname, 0L);
task.put(pname, 0L); task.put(pname, 0L);
event.put(pname, 0L); event.put(pname, 0L);
cmd.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(errMsg);
sender.sendMessage(String.format(errP, plugin.getName())); sender.sendMessage(String.format(errP, plugin.getName()));
sender.sendMessage(String.format(errN, e.getClass().getName())); sender.sendMessage(String.format(errN, e.getClass().getName()));
sender.sendMessage(String.format(errM, e.getMessage())); sender.sendMessage(String.format(errM, e.getMessage()));
} }
public static void sendObject(final CommandSender sender) { 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()))); 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 * @param map
* @return * @return
*/ */
public static Map<String, Long> sortMapByValue(final Map<String, Long> oriMap) { public static Map<String, Long> sortMapByValue(Map<String, Long> oriMap) {
if (oriMap == null || oriMap.isEmpty()) { if (oriMap == null || oriMap.isEmpty()) { return oriMap; }
return oriMap; Map<String, Long> sortedMap = new LinkedHashMap<>();
} List<Map.Entry<String, Long>> entryList = new ArrayList<>(oriMap.entrySet());
final Map<String, Long> sortedMap = new LinkedHashMap<>();
final List<Map.Entry<String, Long>> entryList = new ArrayList<>(oriMap.entrySet());
Collections.sort(entryList, new MonitorComparator()); Collections.sort(entryList, new MonitorComparator());
final Iterator<Map.Entry<String, Long>> iter = entryList.iterator(); Iterator<Map.Entry<String, Long>> iter = entryList.iterator();
Entry<String, Long> tmpEntry = null; Entry<String, Long> tmpEntry = null;
while (iter.hasNext()) { while (iter.hasNext()) {
tmpEntry = iter.next(); tmpEntry = iter.next();
@ -153,16 +161,16 @@ public class MonitorManager {
} }
@SafeVarargs @SafeVarargs
private static void add(final String pname, final long time, final Map<String, Long>... maps) { private static void add(String pname, long time, Map<String, Long>... maps) {
totalTime += time; totalTime += time;
for (final Map<String, Long> map : maps) { for (Map<String, Long> map : maps) {
map.put(pname, map.get(pname) + time); map.put(pname, map.get(pname) + time);
} }
} }
private static long sum(final Collection<? extends Long> numbers) { private static long sum(Collection<? extends Long> numbers) {
int result = 0; int result = 0;
for (final Long num : numbers) { for (Long num : numbers) {
result += num; result += num;
} }
return result; return result;
@ -174,7 +182,7 @@ public class MonitorManager {
public double event; public double event;
public double task; 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.monitor = monitor;
this.cmd = cmd; this.cmd = cmd;
this.event = event; this.event = event;
@ -184,7 +192,7 @@ public class MonitorManager {
static class MonitorComparator implements Comparator<Map.Entry<String, Long>> { static class MonitorComparator implements Comparator<Map.Entry<String, Long>> {
@Override @Override
public int compare(final Entry<String, Long> o1, final Entry<String, Long> o2) { public int compare(Entry<String, Long> o1, Entry<String, Long> o2) {
return o2.getValue().compareTo(o1.getValue()); return o2.getValue().compareTo(o1.getValue());
} }
} }

View File

@ -9,9 +9,9 @@ import java.util.List;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import cn.citycraft.PluginHelper.kit.ExceptionKit;
import pw.yumc.Yum.Yum; import pw.yumc.Yum.Yum;
import pw.yumc.Yum.events.PluginNetworkEvent; import pw.yumc.Yum.events.PluginNetworkEvent;
import pw.yumc.YumCore.kit.ExKit;
import pw.yumc.YumCore.kit.PKit; import pw.yumc.YumCore.kit.PKit;
/** /**
@ -22,27 +22,27 @@ import pw.yumc.YumCore.kit.PKit;
*/ */
public class NetworkManager { public class NetworkManager {
public static void register(final Yum plugin) { public static void register(Yum plugin) {
Bukkit.getConsoleSender().sendMessage("§6[§bYum §a网络管理§6] §a注入网络管理系统 将托管服务器网络!"); Bukkit.getConsoleSender().sendMessage("§6[§bYum §a网络管理§6] §a注入网络管理系统 将托管服务器网络!");
ProxySelector.setDefault(new YumProxySelector(ProxySelector.getDefault(), plugin)); ProxySelector.setDefault(new YumProxySelector(ProxySelector.getDefault(), plugin));
} }
public static void unregister() { public static void unregister() {
final ProxySelector cur = ProxySelector.getDefault(); ProxySelector cur = ProxySelector.getDefault();
if (cur instanceof YumProxySelector) { if (cur instanceof YumProxySelector) {
ProxySelector.setDefault(((YumProxySelector) cur).getDefaultSelector()); ProxySelector.setDefault(((YumProxySelector) cur).getDefaultSelector());
} }
} }
static class YumProxySelector extends ProxySelector { 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; this.defaultSelector = defaultSelector;
} }
@Override @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); defaultSelector.connectFailed(uri, sa, ioe);
} }
@ -51,11 +51,11 @@ public class NetworkManager {
} }
@Override @Override
public List<Proxy> select(final URI uri) { public List<Proxy> select(URI uri) {
final PluginNetworkEvent pne = new PluginNetworkEvent(PKit.getOperatePlugin(), uri, Bukkit.isPrimaryThread()); PluginNetworkEvent pne = new PluginNetworkEvent(PKit.getOperatePlugin(), uri, Bukkit.isPrimaryThread());
Bukkit.getPluginManager().callEvent(pne); Bukkit.getPluginManager().callEvent(pne);
if (pne.isCancelled()) { if (pne.isCancelled()) {
ExceptionKit.throwException(new IOException("[Yum 网络防护] 已开启网络防护 并被联网规则拦截!")); ExKit.throwException(new IOException("[Yum 网络防护] 已开启网络防护 并被联网规则拦截!"));
} }
return defaultSelector.select(uri); return defaultSelector.select(uri);
} }

View File

@ -33,8 +33,8 @@ import org.bukkit.plugin.UnknownDependencyException;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import cn.citycraft.PluginHelper.kit.StrKit; import pw.yumc.YumCore.kit.FileKit;
import cn.citycraft.PluginHelper.utils.FileUtil; import pw.yumc.YumCore.kit.StrKit;
/** /**
* 插件管理类 * 插件管理类
@ -43,14 +43,14 @@ import cn.citycraft.PluginHelper.utils.FileUtil;
* @since 2015年8月21日下午7:03:26 * @since 2015年8月21日下午7:03:26
*/ */
public class PluginsManager { public class PluginsManager {
private final Set<String> ignoreList = new HashSet<>(); private Set<String> ignoreList = new HashSet<>();
private final Plugin main; private Plugin main;
public PluginsManager(final Plugin plugin) { public PluginsManager(Plugin plugin) {
this.main = 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); return StringUtils.substring(plugin.getDescription().getVersion(), 0, 15);
} }
@ -61,7 +61,7 @@ public class PluginsManager {
* - 插件名称 * - 插件名称
* @return 是否成功 * @return 是否成功
*/ */
public boolean addIgnore(final Collection<? extends String> name) { public boolean addIgnore(Collection<? extends String> name) {
return ignoreList.addAll(name); return ignoreList.addAll(name);
} }
@ -72,7 +72,7 @@ public class PluginsManager {
* - 插件名称 * - 插件名称
* @return 是否成功 * @return 是否成功
*/ */
public boolean addIgnore(final String name) { public boolean addIgnore(String name) {
return ignoreList.add(name); return ignoreList.add(name);
} }
@ -85,7 +85,7 @@ public class PluginsManager {
* - 插件 * - 插件
* @return 是否成功 * @return 是否成功
*/ */
public boolean deletePlugin(final CommandSender sender, final Plugin plugin) { public boolean deletePlugin(CommandSender sender, Plugin plugin) {
return unload(sender, plugin) && getPluginFile(plugin).delete(); return unload(sender, plugin) && getPluginFile(plugin).delete();
} }
@ -96,7 +96,7 @@ public class PluginsManager {
* - 插件 * - 插件
* @return 是否成功 * @return 是否成功
*/ */
public boolean deletePlugin(final Plugin plugin) { public boolean deletePlugin(Plugin plugin) {
return deletePlugin(Bukkit.getConsoleSender(), plugin); return deletePlugin(Bukkit.getConsoleSender(), plugin);
} }
@ -106,7 +106,7 @@ public class PluginsManager {
* @param plugin * @param plugin
* - 插件 * - 插件
*/ */
public void disable(final Plugin plugin) { public void disable(Plugin plugin) {
if ((plugin != null) && (plugin.isEnabled())) { if ((plugin != null) && (plugin.isEnabled())) {
Bukkit.getPluginManager().disablePlugin(plugin); Bukkit.getPluginManager().disablePlugin(plugin);
} }
@ -116,7 +116,7 @@ public class PluginsManager {
* 关闭所有插件 * 关闭所有插件
*/ */
public void disableAll() { public void disableAll() {
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (!isIgnored(plugin)) { if (!isIgnored(plugin)) {
disable(plugin); disable(plugin);
} }
@ -129,7 +129,7 @@ public class PluginsManager {
* @param plugin * @param plugin
* - 插件 * - 插件
*/ */
public void enable(final Plugin plugin) { public void enable(Plugin plugin) {
if ((plugin != null) && (!plugin.isEnabled())) { if ((plugin != null) && (!plugin.isEnabled())) {
Bukkit.getPluginManager().enablePlugin(plugin); Bukkit.getPluginManager().enablePlugin(plugin);
} }
@ -139,7 +139,7 @@ public class PluginsManager {
* 启用所有插件 * 启用所有插件
*/ */
public void enableAll() { public void enableAll() {
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (!isIgnored(plugin)) { if (!isIgnored(plugin)) {
enable(plugin); enable(plugin);
} }
@ -155,8 +155,9 @@ public class PluginsManager {
* - 插件 * - 插件
* @return 是否成功 * @return 是否成功
*/ */
public boolean fullDeletePlugin(final CommandSender sender, final Plugin plugin) { public boolean fullDeletePlugin(CommandSender sender, Plugin plugin) {
return unload(sender, plugin) && getPluginFile(plugin).delete() && FileUtil.deleteDir(sender, plugin.getDataFolder()); return unload(sender, plugin) && getPluginFile(plugin).delete()
&& FileKit.deleteDir(sender, plugin.getDataFolder());
} }
/** /**
@ -166,7 +167,7 @@ public class PluginsManager {
* - 插件 * - 插件
* @return 格式化的插件名称 * @return 格式化的插件名称
*/ */
public String getFormattedName(final Plugin plugin) { public String getFormattedName(Plugin plugin) {
return getFormattedName(plugin, false); return getFormattedName(plugin, false);
} }
@ -179,8 +180,8 @@ public class PluginsManager {
* - 是否包括版本 * - 是否包括版本
* @return 格式化的插件名称 * @return 格式化的插件名称
*/ */
public String getFormattedName(final Plugin plugin, final boolean includeVersions) { public String getFormattedName(Plugin plugin, boolean includeVersions) {
final ChatColor color = plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED; ChatColor color = plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED;
String pluginName = color + plugin.getName(); String pluginName = color + plugin.getName();
if (includeVersions) { if (includeVersions) {
pluginName = pluginName + " (" + getVersion(plugin) + ")"; pluginName = pluginName + " (" + getVersion(plugin) + ")";
@ -195,7 +196,7 @@ public class PluginsManager {
* - 名称 * - 名称
* @return 插件 * @return 插件
*/ */
public Plugin getPluginByName(final String name) { public Plugin getPluginByName(String name) {
return Bukkit.getPluginManager().getPlugin(name); return Bukkit.getPluginManager().getPlugin(name);
} }
@ -206,7 +207,7 @@ public class PluginsManager {
* - 名称 * - 名称
* @return 插件 * @return 插件
*/ */
public Plugin getPluginByName(final String[] args, final int start) { public Plugin getPluginByName(String[] args, int start) {
return getPluginByName(StrKit.consolidateStrings(args, start)); return getPluginByName(StrKit.consolidateStrings(args, start));
} }
@ -217,24 +218,24 @@ public class PluginsManager {
* - 插件 * - 插件
* @return 插件的绝对路径 * @return 插件的绝对路径
*/ */
public File getPluginFile(final Plugin plugin) { public File getPluginFile(Plugin plugin) {
File file = null; File file = null;
final ClassLoader cl = plugin.getClass().getClassLoader(); ClassLoader cl = plugin.getClass().getClassLoader();
if ((cl instanceof URLClassLoader)) { if ((cl instanceof URLClassLoader)) {
@SuppressWarnings("resource") @SuppressWarnings("resource")
final URLClassLoader ucl = (URLClassLoader) cl; URLClassLoader ucl = (URLClassLoader) cl;
final URL url = ucl.getURLs()[0]; URL url = ucl.getURLs()[0];
try { try {
file = new File(URLDecoder.decode(url.getFile(), "UTF-8")); file = new File(URLDecoder.decode(url.getFile(), "UTF-8"));
} catch (final UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
} }
} }
return file; return file;
} }
public List<String> getPluginNames(final boolean fullName) { public List<String> getPluginNames(boolean fullName) {
final List<String> plugins = new ArrayList<>(); List<String> plugins = new ArrayList<>();
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
plugins.add(fullName ? plugin.getDescription().getFullName() : plugin.getName()); plugins.add(fullName ? plugin.getDescription().getFullName() : plugin.getName());
} }
return plugins; return plugins;
@ -247,11 +248,9 @@ public class PluginsManager {
* - 插件名称 * - 插件名称
* @return 插件版本 * @return 插件版本
*/ */
public String getPluginVersion(final String name) { public String getPluginVersion(String name) {
final Plugin plugin = getPluginByName(name); Plugin plugin = getPluginByName(name);
if ((plugin != null) && (plugin.getDescription() != null)) { if ((plugin != null) && (plugin.getDescription() != null)) { return getVersion(plugin); }
return getVersion(plugin);
}
return null; return null;
} }
@ -262,23 +261,21 @@ public class PluginsManager {
* - 插件 * - 插件
* @return 插件命令 * @return 插件命令
*/ */
public String getUsages(final Plugin plugin) { public String getUsages(Plugin plugin) {
final List<String> parsedCommands = new ArrayList<>(); List<String> parsedCommands = new ArrayList<>();
final Map<String, Map<String, Object>> commands = plugin.getDescription().getCommands(); Map<String, Map<String, Object>> commands = plugin.getDescription().getCommands();
if (commands != null) { if (commands != null) {
final Iterator<Entry<String, Map<String, Object>>> commandsIt = commands.entrySet().iterator(); Iterator<Entry<String, Map<String, Object>>> commandsIt = commands.entrySet().iterator();
while (commandsIt.hasNext()) { while (commandsIt.hasNext()) {
final Entry<String, Map<String, Object>> thisEntry = commandsIt.next(); Entry<String, Map<String, Object>> thisEntry = commandsIt.next();
if (thisEntry != null) { if (thisEntry != null) {
parsedCommands.add(thisEntry.getKey()); parsedCommands.add(thisEntry.getKey());
} }
} }
} }
if (parsedCommands.isEmpty()) { if (parsedCommands.isEmpty()) { return null; }
return null;
}
return Joiner.on(", ").join(parsedCommands); return Joiner.on(", ").join(parsedCommands);
} }
@ -289,7 +286,7 @@ public class PluginsManager {
* - 插件 * - 插件
* @return 是否 * @return 是否
*/ */
public boolean isIgnored(final Plugin plugin) { public boolean isIgnored(Plugin plugin) {
return isIgnored(plugin.getName()); return isIgnored(plugin.getName());
} }
@ -300,11 +297,9 @@ public class PluginsManager {
* - 插件名称 * - 插件名称
* @return 是否 * @return 是否
*/ */
public boolean isIgnored(final String plugin) { public boolean isIgnored(String plugin) {
for (final String name : ignoreList) { for (String name : ignoreList) {
if (name.equalsIgnoreCase(plugin)) { if (name.equalsIgnoreCase(plugin)) { return true; }
return true;
}
} }
return false; return false;
} }
@ -318,17 +313,17 @@ public class PluginsManager {
* - 插件文件 * - 插件文件
* @return 是否成功 * @return 是否成功
*/ */
public boolean load(final CommandSender sender, final File pluginFile) { public boolean load(CommandSender sender, File pluginFile) {
Plugin target = null; Plugin target = null;
final String name = pluginFile.getName(); String name = pluginFile.getName();
try { try {
try { try {
target = Bukkit.getPluginManager().loadPlugin(pluginFile); target = Bukkit.getPluginManager().loadPlugin(pluginFile);
} catch (final UnsupportedClassVersionError e) { } catch (UnsupportedClassVersionError e) {
sender.sendMessage("§4异常: §c" + e.getMessage()); sender.sendMessage("§4异常: §c" + e.getMessage());
sender.sendMessage("§c服务器或JAVA的版本低于插件: " + name + " 所需要的版本!!"); sender.sendMessage("§c服务器或JAVA的版本低于插件: " + name + " 所需要的版本!!");
return false; return false;
} catch (final InvalidPluginException e) { } catch (InvalidPluginException e) {
if (e.getMessage().equalsIgnoreCase("Plugin already initialized!")) { if (e.getMessage().equalsIgnoreCase("Plugin already initialized!")) {
sender.sendMessage("§4异常: §c" + e.getMessage()); sender.sendMessage("§4异常: §c" + e.getMessage());
sender.sendMessage("§4插件: §c" + name + " 已载入到服务器!"); sender.sendMessage("§4插件: §c" + name + " 已载入到服务器!");
@ -339,7 +334,7 @@ public class PluginsManager {
sender.sendMessage("§4文件: §c" + name + " 不是一个可载入的插件!"); sender.sendMessage("§4文件: §c" + name + " 不是一个可载入的插件!");
sender.sendMessage("§4注意: §cMOD服重载插件3次以上需重启服务器"); sender.sendMessage("§4注意: §cMOD服重载插件3次以上需重启服务器");
return false; return false;
} catch (final UnknownDependencyException e) { } catch (UnknownDependencyException e) {
sender.sendMessage("§4异常: §c服务器未安装必须依赖: " + e.getMessage()); sender.sendMessage("§4异常: §c服务器未安装必须依赖: " + e.getMessage());
sender.sendMessage("§4插件: §c" + name + " 载入失败 缺少部分依赖项目!"); sender.sendMessage("§4插件: §c" + name + " 载入失败 缺少部分依赖项目!");
return false; return false;
@ -352,7 +347,7 @@ public class PluginsManager {
Bukkit.getPluginManager().enablePlugin(target); Bukkit.getPluginManager().enablePlugin(target);
sender.sendMessage("§6载入: §a插件 §b" + target.getName() + " §a版本 §d" + getVersion(target) + " §a已成功载入到服务器!"); sender.sendMessage("§6载入: §a插件 §b" + target.getName() + " §a版本 §d" + getVersion(target) + " §a已成功载入到服务器!");
return true; return true;
} catch (final Throwable e) { } catch (Throwable e) {
sender.sendMessage("§4错误: §c" + e.getClass().getName() + ": " + e.getMessage()); sender.sendMessage("§4错误: §c" + e.getClass().getName() + ": " + e.getMessage());
sender.sendMessage("§4异常: §c具体信息请查看后台异常堆栈!"); sender.sendMessage("§4异常: §c具体信息请查看后台异常堆栈!");
e.printStackTrace(); e.printStackTrace();
@ -370,7 +365,7 @@ public class PluginsManager {
* - 插件名称 * - 插件名称
* @return 是否成功 * @return 是否成功
*/ */
public boolean load(CommandSender sender, final String name) { public boolean load(CommandSender sender, String name) {
String filename = name; String filename = name;
if (sender == null) { if (sender == null) {
sender = Bukkit.getConsoleSender(); sender = Bukkit.getConsoleSender();
@ -378,8 +373,8 @@ public class PluginsManager {
if (!name.endsWith(".jar")) { if (!name.endsWith(".jar")) {
filename = name + ".jar"; filename = name + ".jar";
} }
final File pluginDir = new File("plugins"); File pluginDir = new File("plugins");
final File updateDir = new File(pluginDir, "update"); File updateDir = new File(pluginDir, "update");
if (!pluginDir.isDirectory()) { if (!pluginDir.isDirectory()) {
sender.sendMessage("§6载入: §c插件目录不存在或IO错误!"); sender.sendMessage("§6载入: §c插件目录不存在或IO错误!");
return false; return false;
@ -389,15 +384,15 @@ public class PluginsManager {
if (!pluginFile.isFile() && !new File(updateDir, filename).isFile()) { if (!pluginFile.isFile() && !new File(updateDir, filename).isFile()) {
pluginFile = null; pluginFile = null;
for (final File file : pluginDir.listFiles()) { for (File file : pluginDir.listFiles()) {
if (file.getName().endsWith(".jar")) { if (file.getName().endsWith(".jar")) {
try { try {
final PluginDescriptionFile desc = main.getPluginLoader().getPluginDescription(file); PluginDescriptionFile desc = main.getPluginLoader().getPluginDescription(file);
if (desc.getName().equalsIgnoreCase(name)) { if (desc.getName().equalsIgnoreCase(name)) {
pluginFile = file; pluginFile = file;
break; break;
} }
} catch (final InvalidDescriptionException e) { } catch (InvalidDescriptionException e) {
} }
} }
} }
@ -416,7 +411,7 @@ public class PluginsManager {
* - 插件名称 * - 插件名称
* @return 是否成功 * @return 是否成功
*/ */
public boolean load(final File pluginFile) { public boolean load(File pluginFile) {
return load(Bukkit.getConsoleSender(), pluginFile); return load(Bukkit.getConsoleSender(), pluginFile);
} }
@ -427,7 +422,7 @@ public class PluginsManager {
* - 插件名称 * - 插件名称
* @return 是否成功 * @return 是否成功
*/ */
public boolean load(final String name) { public boolean load(String name) {
return load(Bukkit.getConsoleSender(), name); return load(Bukkit.getConsoleSender(), name);
} }
@ -440,10 +435,8 @@ public class PluginsManager {
* - 插件 * - 插件
* @return 是否成功 * @return 是否成功
*/ */
public boolean reload(final CommandSender sender, final Plugin plugin) { public boolean reload(CommandSender sender, Plugin plugin) {
if (plugin != null) { if (plugin != null) { return unload(sender, plugin) && load(sender, plugin.getName()); }
return unload(sender, plugin) && load(sender, plugin.getName());
}
return false; return false;
} }
@ -456,10 +449,8 @@ public class PluginsManager {
* - 插件 * - 插件
* @return 是否成功 * @return 是否成功
*/ */
public boolean reload(final CommandSender sender, final String name) { public boolean reload(CommandSender sender, String name) {
if (name != null) { if (name != null) { return unload(sender, name) && load(sender, name); }
return unload(sender, name) && load(sender, name);
}
return false; return false;
} }
@ -470,7 +461,7 @@ public class PluginsManager {
* - 插件 * - 插件
* @return 是否成功 * @return 是否成功
*/ */
public boolean reload(final Plugin plugin) { public boolean reload(Plugin plugin) {
return reload(Bukkit.getConsoleSender(), plugin); return reload(Bukkit.getConsoleSender(), plugin);
} }
@ -478,7 +469,7 @@ public class PluginsManager {
* 重载所有插件 * 重载所有插件
*/ */
public void reloadAll() { public void reloadAll() {
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (!isIgnored(plugin)) { if (!isIgnored(plugin)) {
unload(plugin); unload(plugin);
} }
@ -489,14 +480,14 @@ public class PluginsManager {
/** /**
* 重载所有插件 * 重载所有插件
*/ */
public void reloadAll(final CommandSender sender) { public void reloadAll(CommandSender sender) {
final Plugin[] plist = Bukkit.getPluginManager().getPlugins(); Plugin[] plist = Bukkit.getPluginManager().getPlugins();
for (final Plugin plugin : plist) { for (Plugin plugin : plist) {
if (!isIgnored(plugin)) { if (!isIgnored(plugin)) {
unload(sender, plugin); unload(sender, plugin);
} }
} }
for (final Plugin plugin : plist) { for (Plugin plugin : plist) {
if (!isIgnored(plugin)) { if (!isIgnored(plugin)) {
load(sender, plugin.getName()); load(sender, plugin.getName());
} }
@ -510,7 +501,7 @@ public class PluginsManager {
* - 插件名称 * - 插件名称
* @return 是否成功 * @return 是否成功
*/ */
public boolean removeIgnore(final String name) { public boolean removeIgnore(String name) {
return ignoreList.remove(name); return ignoreList.remove(name);
} }
@ -523,7 +514,7 @@ public class PluginsManager {
* - 插件 * - 插件
* @return 是否成功 * @return 是否成功
*/ */
public boolean unload(final CommandSender sender, final Plugin plugin) { public boolean unload(CommandSender sender, Plugin plugin) {
return unload(sender, plugin.getName()); return unload(sender, plugin.getName());
} }
@ -537,47 +528,47 @@ public class PluginsManager {
* @return 是否成功 * @return 是否成功
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public boolean unload(CommandSender sender, final String name) { public boolean unload(CommandSender sender, String name) {
if (sender == null) { if (sender == null) {
sender = Bukkit.getConsoleSender(); sender = Bukkit.getConsoleSender();
} }
final PluginManager pluginManager = Bukkit.getPluginManager(); PluginManager pluginManager = Bukkit.getPluginManager();
SimpleCommandMap commandMap = null; SimpleCommandMap commandMap = null;
List<Plugin> plugins = null; List<Plugin> plugins = null;
Map<String, Plugin> lookupNames = null; Map<String, Plugin> lookupNames = null;
Map<String, Command> knownCommands = null; Map<String, Command> knownCommands = null;
// final Map<Pattern, JavaPluginLoader> fileAssociations = null; // Map<Pattern, JavaPluginLoader> fileAssociations = null;
if (pluginManager == null) { if (pluginManager == null) {
sender.sendMessage("§4异常: §c插件管理类反射获取失败!"); sender.sendMessage("§4异常: §c插件管理类反射获取失败!");
return false; return false;
} }
try { try {
final Field pluginsField = pluginManager.getClass().getDeclaredField("plugins"); Field pluginsField = pluginManager.getClass().getDeclaredField("plugins");
pluginsField.setAccessible(true); pluginsField.setAccessible(true);
plugins = (List<Plugin>) pluginsField.get(pluginManager); plugins = (List<Plugin>) pluginsField.get(pluginManager);
final Field lookupNamesField = pluginManager.getClass().getDeclaredField("lookupNames"); Field lookupNamesField = pluginManager.getClass().getDeclaredField("lookupNames");
lookupNamesField.setAccessible(true); lookupNamesField.setAccessible(true);
lookupNames = (Map<String, Plugin>) lookupNamesField.get(pluginManager); lookupNames = (Map<String, Plugin>) lookupNamesField.get(pluginManager);
final Field commandMapField = pluginManager.getClass().getDeclaredField("commandMap"); Field commandMapField = pluginManager.getClass().getDeclaredField("commandMap");
commandMapField.setAccessible(true); commandMapField.setAccessible(true);
commandMap = (SimpleCommandMap) commandMapField.get(pluginManager); commandMap = (SimpleCommandMap) commandMapField.get(pluginManager);
final Field knownCommandsField = commandMap.getClass().getDeclaredField("knownCommands"); Field knownCommandsField = commandMap.getClass().getDeclaredField("knownCommands");
knownCommandsField.setAccessible(true); knownCommandsField.setAccessible(true);
knownCommands = (Map<String, Command>) knownCommandsField.get(commandMap); knownCommands = (Map<String, Command>) knownCommandsField.get(commandMap);
// final Field fileAssociationsField = pluginManager.getClass().getDeclaredField("fileAssociations"); // Field fileAssociationsField = pluginManager.getClass().getDeclaredField("fileAssociations");
// fileAssociationsField.setAccessible(true); // fileAssociationsField.setAccessible(true);
// fileAssociations = (Map<Pattern, JavaPluginLoader>) fileAssociationsField.get(pluginManager); // fileAssociations = (Map<Pattern, JavaPluginLoader>) fileAssociationsField.get(pluginManager);
} catch (final Exception e) { } catch (Exception e) {
sender.sendMessage("§4异常: §c" + e.getMessage() + " 插件 §b" + name + " §c卸载失败!"); sender.sendMessage("§4异常: §c" + e.getMessage() + " 插件 §b" + name + " §c卸载失败!");
return false; return false;
} }
String pluginVersion = ""; String pluginVersion = "";
for (final Plugin next : pluginManager.getPlugins()) { for (Plugin next : pluginManager.getPlugins()) {
if (next.getName().equals(name)) { if (next.getName().equals(name)) {
pluginManager.disablePlugin(next); pluginManager.disablePlugin(next);
if ((plugins != null) && (plugins.contains(next))) { if ((plugins != null) && (plugins.contains(next))) {
@ -591,10 +582,10 @@ public class PluginsManager {
sender.sendMessage("§6卸载: §a从插件查找列表删除 §b" + name + " §a的实例!"); sender.sendMessage("§6卸载: §a从插件查找列表删除 §b" + name + " §a的实例!");
} }
for (final Iterator<Map.Entry<String, Command>> it = knownCommands.entrySet().iterator(); it.hasNext();) { for (Iterator<Map.Entry<String, Command>> it = knownCommands.entrySet().iterator(); it.hasNext();) {
final Map.Entry<String, Command> entry = it.next(); Map.Entry<String, Command> entry = it.next();
if ((entry.getValue() instanceof PluginCommand)) { if ((entry.getValue() instanceof PluginCommand)) {
final PluginCommand command = (PluginCommand) entry.getValue(); PluginCommand command = (PluginCommand) entry.getValue();
if (command.getPlugin() == next) { if (command.getPlugin() == next) {
command.unregister(commandMap); command.unregister(commandMap);
it.remove(); it.remove();
@ -603,31 +594,31 @@ public class PluginsManager {
} }
// try { // try {
// if (fileAssociations != null) { // if (fileAssociations != null) {
// for (final Entry<Pattern, JavaPluginLoader> entry : fileAssociations.entrySet()) { // for (Entry<Pattern, JavaPluginLoader> entry : fileAssociations.entrySet()) {
// final Matcher match = entry.getKey().matcher(getPluginFile(next).getName()); // Matcher match = entry.getKey().matcher(getPluginFile(next).getName());
// if (match.find()) { // if (match.find()) {
// PluginLoader pluginLoader = entry.getValue(); // PluginLoader pluginLoader = entry.getValue();
// if (pluginLoader instanceof YumPluginLoader) { // if (pluginLoader instanceof YumPluginLoader) {
// pluginLoader = ((YumPluginLoader) pluginLoader).internal_loader; // pluginLoader = ((YumPluginLoader) pluginLoader).internal_loader;
// } // }
// final Field loadersField = pluginLoader.getClass().getDeclaredField("loaders"); // Field loadersField = pluginLoader.getClass().getDeclaredField("loaders");
// loadersField.setAccessible(true); // loadersField.setAccessible(true);
// final Map<String, URLClassLoader> loaders = (Map<String, URLClassLoader>) loadersField.get(pluginLoader); // Map<String, URLClassLoader> loaders = (Map<String, URLClassLoader>) loadersField.get(pluginLoader);
// for (final Entry<String, URLClassLoader> entry2 : loaders.entrySet()) { // for (Entry<String, URLClassLoader> entry2 : loaders.entrySet()) {
// Reflect.on(entry2.getValue()).set("pluginInit", null).set("plugin", null); // Reflect.on(entry2.getValue()).set("pluginInit", null).set("plugin", null);
// } // }
// sender.sendMessage("§6卸载: §a移除插件 §b" + name + " §a的类实例缓存!"); // sender.sendMessage("§6卸载: §a移除插件 §b" + name + " §a的类实例缓存!");
// } // }
// } // }
// } // }
// } catch (final Exception e) { // } catch (Exception e) {
// e.printStackTrace(); // e.printStackTrace();
// } // }
sender.sendMessage("§6卸载: §a注销插件 §b" + name + " §a的所有命令!"); sender.sendMessage("§6卸载: §a注销插件 §b" + name + " §a的所有命令!");
final ClassLoader cl = next.getClass().getClassLoader(); ClassLoader cl = next.getClass().getClassLoader();
try { try {
((URLClassLoader) cl).close(); ((URLClassLoader) cl).close();
} catch (final IOException ex) { } catch (IOException ex) {
} }
System.gc(); System.gc();
} }
@ -646,7 +637,7 @@ public class PluginsManager {
* - 卸载插件 * - 卸载插件
* @return 是否成功 * @return 是否成功
*/ */
public boolean unload(final Plugin plugin) { public boolean unload(Plugin plugin) {
return unload(Bukkit.getConsoleSender(), plugin); return unload(Bukkit.getConsoleSender(), plugin);
} }
@ -655,7 +646,7 @@ public class PluginsManager {
* *
* @return 是否成功 * @return 是否成功
*/ */
public boolean upgrade(final CommandSender sender) { public boolean upgrade(CommandSender sender) {
sender.sendMessage("§6升级: §a开始升级 服务器更新 目录下的所有插件!"); sender.sendMessage("§6升级: §a开始升级 服务器更新 目录下的所有插件!");
return upgrade(sender, null, null); return upgrade(sender, null, null);
} }
@ -669,9 +660,9 @@ public class PluginsManager {
* - 更新目录 * - 更新目录
* @return 是否成功 * @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; boolean result = false;
final PluginLoader loader = main.getPluginLoader(); PluginLoader loader = main.getPluginLoader();
File updateDirectory; File updateDirectory;
if (directory == null || !directory.isDirectory()) { if (directory == null || !directory.isDirectory()) {
updateDirectory = Bukkit.getServer().getUpdateFolderFile(); updateDirectory = Bukkit.getServer().getUpdateFolderFile();
@ -691,23 +682,23 @@ public class PluginsManager {
sender.sendMessage("§4异常: §c文件夹 §d" + updateDirectory.getName() + " §c权限不足或IO错误!"); sender.sendMessage("§4异常: §c文件夹 §d" + updateDirectory.getName() + " §c权限不足或IO错误!");
return false; return false;
} }
final File[] plugins = updateDirectory.listFiles(); File[] plugins = updateDirectory.listFiles();
if (plugins.length == 0) { if (plugins.length == 0) {
sender.sendMessage("§6升级: §d更新文件夹未找到插件!"); sender.sendMessage("§6升级: §d更新文件夹未找到插件!");
return false; return false;
} }
for (final File file : updateDirectory.listFiles()) { for (File file : updateDirectory.listFiles()) {
if (file.isDirectory()) { if (file.isDirectory()) {
continue; continue;
} }
PluginDescriptionFile description = null; PluginDescriptionFile description = null;
try { try {
description = loader.getPluginDescription(file); description = loader.getPluginDescription(file);
final String name = description.getName(); String name = description.getName();
if (plugin != null && !name.equals(plugin.getName())) { if (plugin != null && !name.equals(plugin.getName())) {
continue; continue;
} }
final Plugin oldplugin = Bukkit.getPluginManager().getPlugin(name); Plugin oldplugin = Bukkit.getPluginManager().getPlugin(name);
result = true; result = true;
File dest = null; File dest = null;
if (!unload(sender, name)) { if (!unload(sender, name)) {
@ -715,7 +706,8 @@ public class PluginsManager {
dest = new File(Bukkit.getUpdateFolderFile().getParentFile(), File.separatorChar + file.getName()); dest = new File(Bukkit.getUpdateFolderFile().getParentFile(), File.separatorChar + file.getName());
} else { } else {
if (oldplugin != null) { 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插件!"); sender.sendMessage("§6升级: §a开始升级 §b" + name + " §a插件!");
} }
@ -723,7 +715,7 @@ public class PluginsManager {
file.renameTo(dest); file.renameTo(dest);
} }
load(sender, name); load(sender, name);
} catch (final InvalidDescriptionException e) { } catch (InvalidDescriptionException e) {
sender.sendMessage("§4异常: §c" + e.getMessage()); sender.sendMessage("§4异常: §c" + e.getMessage());
sender.sendMessage("§4文件: §c" + file.getName() + " 的plugin.yml文件存在错误!"); sender.sendMessage("§4文件: §c" + file.getName() + " 的plugin.yml文件存在错误!");
} }
@ -740,7 +732,7 @@ public class PluginsManager {
* *
* @return 是否成功 * @return 是否成功
*/ */
public boolean upgrade(final CommandSender sender, final Plugin plugin) { public boolean upgrade(CommandSender sender, Plugin plugin) {
return upgrade(sender, null, plugin); return upgrade(sender, null, plugin);
} }
@ -749,7 +741,7 @@ public class PluginsManager {
* *
* @return 是否成功 * @return 是否成功
*/ */
public boolean upgrade(final File directory) { public boolean upgrade(File directory) {
Bukkit.getConsoleSender().sendMessage("§6升级: §a开始升级 §d" + directory.getName() + " §a目录下的所有插件!"); Bukkit.getConsoleSender().sendMessage("§6升级: §a开始升级 §d" + directory.getName() + " §a目录下的所有插件!");
return upgrade(Bukkit.getConsoleSender(), directory, null); return upgrade(Bukkit.getConsoleSender(), directory, null);
} }

View File

@ -14,7 +14,6 @@ import org.bukkit.command.CommandSender;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.JSONValue; import org.json.simple.JSONValue;
import cn.citycraft.PluginHelper.kit.StrKit;
import pw.yumc.Yum.models.PluginInfo; import pw.yumc.Yum.models.PluginInfo;
import pw.yumc.Yum.models.RepoCache; import pw.yumc.Yum.models.RepoCache;
import pw.yumc.Yum.models.RepoSerialization.PackageInfo; import pw.yumc.Yum.models.RepoSerialization.PackageInfo;
@ -35,30 +34,24 @@ public class RepositoryManager {
org.bukkit.plugin.Plugin main; org.bukkit.plugin.Plugin main;
RepoCache repocache; RepoCache repocache;
public RepositoryManager(final org.bukkit.plugin.Plugin plugin) { public RepositoryManager(org.bukkit.plugin.Plugin plugin) {
this.main = plugin; this.main = plugin;
repocache = new RepoCache(); repocache = new RepoCache();
} }
public boolean addPackage(final CommandSender sender, final String urlstring) { public boolean addPackage(CommandSender sender, String urlstring) {
final String json = HttpKit.get(urlstring); String json = HttpKit.get(urlstring);
if (json == null || json.isEmpty()) { if (json == null || json.isEmpty()) { return false; }
return false; PackageInfo pkg = jsonToPackage(json);
} if (pkg == null) { return false; }
final PackageInfo pkg = jsonToPackage(json);
if (pkg == null) {
return false;
}
updatePackage(sender, pkg); updatePackage(sender, pkg);
return true; return true;
} }
public boolean addRepositories(final CommandSender sender, final String urlstring) { public boolean addRepositories(CommandSender sender, String urlstring) {
final String url = handerRepoUrl(urlstring); String url = handerRepoUrl(urlstring);
final Repositories repo = repocache.addRepo(url); Repositories repo = repocache.addRepo(url);
if (repo == null) { if (repo == null) { return false; }
return false;
}
return updateRepositories(sender, repo); return updateRepositories(sender, repo);
} }
@ -66,56 +59,57 @@ public class RepositoryManager {
repocache.getPlugins().clear(); repocache.getPlugins().clear();
} }
public boolean delRepositories(final CommandSender sender, final String urlstring) { public boolean delRepositories(CommandSender sender, String urlstring) {
return repocache.removeRepo(handerRepoUrl(urlstring)); return repocache.removeRepo(handerRepoUrl(urlstring));
} }
public List<PluginInfo> getAllPlugin() { public List<PluginInfo> getAllPlugin() {
final List<PluginInfo> li = new ArrayList<>(); List<PluginInfo> li = new ArrayList<>();
for (final Entry<String, PluginInfo> plugin : repocache.getPlugins().entrySet()) { for (Entry<String, PluginInfo> plugin : repocache.getPlugins().entrySet()) {
li.add(plugin.getValue()); li.add(plugin.getValue());
} }
return li; return li;
} }
public List<String> getAllPluginName() { public List<String> getAllPluginName() {
final List<String> li = new ArrayList<>(); List<String> li = new ArrayList<>();
for (final Entry<String, PluginInfo> plugin : repocache.getPlugins().entrySet()) { for (Entry<String, PluginInfo> plugin : repocache.getPlugins().entrySet()) {
li.add(plugin.getValue().name); li.add(plugin.getValue().name);
} }
return li; return li;
} }
public List<String> getAllPluginsInfo() { public List<String> getAllPluginsInfo() {
final List<String> li = new ArrayList<>(); List<String> li = new ArrayList<>();
li.add("§d仓库名称 §a插件名称 §e插件描述"); li.add("§d仓库名称 §a插件名称 §e插件描述");
for (final Entry<String, PluginInfo> pi : repocache.getPlugins().entrySet()) { for (Entry<String, PluginInfo> pi : repocache.getPlugins().entrySet()) {
final Plugin plugin = pi.getValue().plugin; Plugin plugin = pi.getValue().plugin;
li.add(String.format("§d%s §a%s §6- §e%s", pi.getValue().repo, pi.getValue().name, plugin.description)); li.add(String.format("§d%s §a%s §6- §e%s", pi.getValue().repo, pi.getValue().name, plugin.description));
if (plugin.tags != null) { if (plugin.tags != null) {
li.add(" §b┗Tags §c标签 §a版本 §e类型"); li.add(" §b┗Tags §c标签 §a版本 §e类型");
final List<TagInfo> taglist = plugin.tags; List<TagInfo> taglist = plugin.tags;
for (int i = 0; i < taglist.size(); i++) { for (int i = 0; i < taglist.size(); i++) {
final TagInfo tag = taglist.get(i); 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)); 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; return li;
} }
public PluginInfo getPlugin(final String name) { public PluginInfo getPlugin(String name) {
for (final Entry<String, PluginInfo> plugin : repocache.getPlugins().entrySet()) { for (Entry<String, PluginInfo> plugin : repocache.getPlugins().entrySet()) {
if (plugin.getValue().name.equalsIgnoreCase(name)) { if (plugin.getValue().name.equalsIgnoreCase(name)) { return plugin.getValue(); }
return plugin.getValue();
}
} }
return null; return null;
} }
public List<PluginInfo> getPluginInfo(final String name) { public List<PluginInfo> getPluginInfo(String name) {
final List<PluginInfo> li = new ArrayList<>(); List<PluginInfo> li = new ArrayList<>();
for (final Entry<String, PluginInfo> plugin : repocache.getPlugins().entrySet()) { for (Entry<String, PluginInfo> plugin : repocache.getPlugins().entrySet()) {
if (plugin.getValue().name.equalsIgnoreCase(name)) { if (plugin.getValue().name.equalsIgnoreCase(name)) {
li.add(plugin.getValue()); li.add(plugin.getValue());
} }
@ -123,7 +117,7 @@ public class RepositoryManager {
return li; return li;
} }
public PluginInfo getPluginInfo(final String groupId, final String artifactId) { public PluginInfo getPluginInfo(String groupId, String artifactId) {
return repocache.getPlugins().get(groupId + "." + artifactId); return repocache.getPlugins().get(groupId + "." + artifactId);
} }
@ -135,7 +129,7 @@ public class RepositoryManager {
return repocache; return repocache;
} }
public Repositories getRepoCache(final String urlstring) { public Repositories getRepoCache(String urlstring) {
return repocache.getRepos().get(handerRepoUrl(urlstring)); return repocache.getRepos().get(handerRepoUrl(urlstring));
} }
@ -143,28 +137,26 @@ public class RepositoryManager {
return repocache.getRepos(); return repocache.getRepos();
} }
public boolean getRepositories(final CommandSender sender, final String urlstring) { public boolean getRepositories(CommandSender sender, String urlstring) {
final int urllength = urlstring.length(); int urllength = urlstring.length();
final String url = urlstring.substring(0, urlstring.endsWith("/") ? urllength - 1 : urllength); String url = urlstring.substring(0, urlstring.endsWith("/") ? urllength - 1 : urllength);
handerRepoUrl(url); handerRepoUrl(url);
final Repositories repo = repocache.addRepo(urlstring); Repositories repo = repocache.addRepo(urlstring);
if (repo == null) { if (repo == null) { return false; }
return false;
}
return updateRepositories(sender, repo); return updateRepositories(sender, repo);
} }
public PackageInfo jsonToPackage(final String json) { public PackageInfo jsonToPackage(String json) {
return new PackageInfo((JSONObject) JSONValue.parse(json)); return new PackageInfo((JSONObject) JSONValue.parse(json));
} }
public void updatePackage(final CommandSender sender, final PackageInfo pkg) { public void updatePackage(CommandSender sender, PackageInfo pkg) {
for (final Plugin plugin : pkg.plugins) { for (Plugin plugin : pkg.plugins) {
final PluginInfo pi = new PluginInfo(); PluginInfo pi = new PluginInfo();
pi.name = StrKit.getNotNull(plugin.name, plugin.artifactId); pi.name = getNotNull(plugin.name, plugin.artifactId);
pi.branch = StrKit.getNotNull(plugin.branch, "master"); pi.branch = getNotNull(plugin.branch, "master");
pi.pom = StrKit.getNotNull(plugin.pom, pkg.pom); pi.pom = getNotNull(plugin.pom, pkg.pom);
pi.url = StrKit.getNotNull(plugin.url, pkg.url); pi.url = getNotNull(plugin.url, pkg.url);
pi.type = plugin.type != null ? plugin.type : pkg.type; pi.type = plugin.type != null ? plugin.type : pkg.type;
pi.type = pi.type != null ? pi.type : URLType.Maven; pi.type = pi.type != null ? pi.type : URLType.Maven;
pi.plugin = plugin; pi.plugin = plugin;
@ -174,15 +166,19 @@ public class RepositoryManager {
sender.sendMessage("§6仓库: §e" + pkg.name + " §a更新成功!"); 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(); repocache.getPlugins().clear();
if (repocache.getRepos().isEmpty()) { if (repocache.getRepos().isEmpty()) {
repocache.addRepo("http://data.yumc.pw/yumcenter/repo.info"); repocache.addRepo("http://data.yumc.pw/yumcenter/repo.info");
} }
final Iterator<Entry<String, Repositories>> keys = repocache.getRepos().entrySet().iterator(); Iterator<Entry<String, Repositories>> keys = repocache.getRepos().entrySet().iterator();
while (keys.hasNext()) { while (keys.hasNext()) {
final Entry<String, Repositories> string = keys.next(); Entry<String, Repositories> string = keys.next();
final Repositories repo = repocache.getRepo(string.getKey()); Repositories repo = repocache.getRepo(string.getKey());
if (updateRepositories(sender, repo)) { if (updateRepositories(sender, repo)) {
sender.sendMessage("§6源: §e" + repo.name + " §a更新成功!"); sender.sendMessage("§6源: §e" + repo.name + " §a更新成功!");
} else { } else {
@ -193,7 +189,7 @@ public class RepositoryManager {
return true; return true;
} }
public boolean updateRepositories(CommandSender sender, final Repositories repocenter) { public boolean updateRepositories(CommandSender sender, Repositories repocenter) {
if (sender == null) { if (sender == null) {
sender = Bukkit.getConsoleSender(); sender = Bukkit.getConsoleSender();
} }
@ -201,14 +197,14 @@ public class RepositoryManager {
sender.sendMessage(String.format("§6[§bYum§6] 源 %s 数据为空或列表为空!", repocenter.name)); sender.sendMessage(String.format("§6[§bYum§6] 源 %s 数据为空或列表为空!", repocenter.name));
return false; return false;
} }
for (final Repository repo : repocenter.repos) { for (Repository repo : repocenter.repos) {
addPackage(sender, repo.url); addPackage(sender, repo.url);
} }
return true; return true;
} }
private String handerRepoUrl(String url) { private String handerRepoUrl(String url) {
final int urllength = url.length(); int urllength = url.length();
url = url.substring(0, url.endsWith("/") ? urllength - 1 : urllength); url = url.substring(0, url.endsWith("/") ? urllength - 1 : urllength);
if (!url.startsWith("http://")) { if (!url.startsWith("http://")) {
url = "http://" + url; url = "http://" + url;

View File

@ -27,7 +27,7 @@ public class BukkitDev implements Serializable {
public String md5; public String md5;
public String releaseType; public String releaseType;
public Files(final JSONObject obj) { public Files(JSONObject obj) {
projectId = Integer.parseInt(obj.get("projectId").toString()); projectId = Integer.parseInt(obj.get("projectId").toString());
name = obj.get("name").toString(); name = obj.get("name").toString();
fileUrl = obj.get("fileUrl").toString(); fileUrl = obj.get("fileUrl").toString();
@ -38,12 +38,10 @@ public class BukkitDev implements Serializable {
releaseType = obj.get("releaseType").toString(); releaseType = obj.get("releaseType").toString();
} }
public static List<Files> parseList(final String json) { public static List<Files> parseList(String json) {
if (StrKit.isBlank(json) || json.equals("[]")) { if (StrKit.isBlank(json) || json.equals("[]")) { return Collections.emptyList(); }
return Collections.emptyList(); List<Files> temp = new ArrayList<>();
} JSONArray ja = (JSONArray) JSONValue.parse(json);
final List<Files> temp = new ArrayList<>();
final JSONArray ja = (JSONArray) JSONValue.parse(json);
for (int i = 0; i < ja.size(); i++) { for (int i = 0; i < ja.size(); i++) {
temp.add(new Files((JSONObject) ja.get(i))); temp.add(new Files((JSONObject) ja.get(i)));
} }
@ -58,19 +56,17 @@ public class BukkitDev implements Serializable {
public String slug; public String slug;
public String stage; public String stage;
public Projects(final JSONObject obj) { public Projects(JSONObject obj) {
id = Integer.parseInt(obj.get("id").toString()); id = Integer.parseInt(obj.get("id").toString());
name = obj.get("name").toString(); name = obj.get("name").toString();
slug = obj.get("slug").toString(); slug = obj.get("slug").toString();
stage = obj.get("stage").toString(); stage = obj.get("stage").toString();
} }
public static List<Projects> parseList(final String json) { public static List<Projects> parseList(String json) {
if (StrKit.isBlank(json) || json.equals("[]")) { if (StrKit.isBlank(json) || json.equals("[]")) { return Collections.emptyList(); }
return Collections.emptyList(); List<Projects> temp = new ArrayList<>();
} JSONArray ja = (JSONArray) JSONValue.parse(json);
final List<Projects> temp = new ArrayList<>();
final JSONArray ja = (JSONArray) JSONValue.parse(json);
for (int i = 0; i < ja.size(); i++) { for (int i = 0; i < ja.size(); i++) {
temp.add(new Projects((JSONObject) ja.get(i))); temp.add(new Projects((JSONObject) ja.get(i)));
} }

View File

@ -2,10 +2,12 @@ package pw.yumc.Yum.models;
import java.io.Serializable; import java.io.Serializable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import cn.citycraft.PluginHelper.utils.IOUtil;
import pw.yumc.Yum.models.RepoSerialization.Plugin; import pw.yumc.Yum.models.RepoSerialization.Plugin;
import pw.yumc.Yum.models.RepoSerialization.TagInfo; import pw.yumc.Yum.models.RepoSerialization.TagInfo;
import pw.yumc.Yum.models.RepoSerialization.URLType; import pw.yumc.Yum.models.RepoSerialization.URLType;
@ -17,7 +19,7 @@ public class PluginInfo implements Serializable {
static { static {
try { try {
NMSVersion = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; NMSVersion = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
} catch (final Exception e) { } catch (Exception e) {
Log.warning("服务器NMS解析失败: " + Bukkit.getServer().getClass().getPackage().getName()); Log.warning("服务器NMS解析失败: " + Bukkit.getServer().getClass().getPackage().getName());
NMSVersion = "NONMS"; NMSVersion = "NONMS";
} }
@ -53,7 +55,7 @@ public class PluginInfo implements Serializable {
* 版本 * 版本
* @return 下载直链 * @return 下载直链
*/ */
public String getDirectUrl(final String version) { public String getDirectUrl(String version) {
return url.replace("[version]", version); return url.replace("[version]", version);
} }
@ -73,7 +75,7 @@ public class PluginInfo implements Serializable {
* 插件版本 * 插件版本
* @return 文件名称 * @return 文件名称
*/ */
public String getFileName(final String version) { public String getFileName(String version) {
return String.format("%1$s-%2$s.jar", plugin.artifactId, version); return String.format("%1$s-%2$s.jar", plugin.artifactId, version);
} }
@ -86,29 +88,30 @@ public class PluginInfo implements Serializable {
* - 需要更新的版本 * - 需要更新的版本
* @return 更新地址 * @return 更新地址
*/ */
public String getMavenUrl(final String 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); 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; String ver = version;
if (ver == null) { if (ver == null) {
if (plugin.tags != null) { if (plugin.tags != null) {
Log.debug("发现存在TAG标签 开始检索: " + NMSVersion); Log.debug("发现存在TAG标签 开始检索: " + NMSVersion);
for (final TagInfo tagInfo : plugin.tags) { for (TagInfo tagInfo : plugin.tags) {
if (tagInfo.tag.equalsIgnoreCase(NMSVersion)) { if (tagInfo.tag.equalsIgnoreCase(NMSVersion)) {
sender.sendMessage("§6版本: §b从Tag标签中获取 §e" + NMSVersion + " §b的最新版本..."); sender.sendMessage("§6版本: §b从Tag标签中获取 §e" + NMSVersion + " §b的最新版本...");
ver = tagInfo.version; ver = tagInfo.version;
if (tagInfo.type == URLType.DirectUrl) { if (tagInfo.type == URLType.DirectUrl) { return tagInfo.url; }
return tagInfo.url;
}
break; break;
} }
} }
} else if (pom != null && !pom.isEmpty()) { } else if (pom != null && !pom.isEmpty()) {
pom = pom.replace("[name]", name).replace("[branch]", branch); pom = pom.replace("[name]", name).replace("[branch]", branch);
sender.sendMessage("§6版本: §b尝试从在线POM文件获取最新版本..."); sender.sendMessage("§6版本: §b尝试从在线POM文件获取最新版本...");
ver = IOUtil.getXMLTag(pom, "version", null); ver = getXMLTag(pom, "version", null);
if (ver != null) { if (ver != null) {
sender.sendMessage("§6版本: §a成功获取到最新版本 §e" + ver + " §a..."); sender.sendMessage("§6版本: §a成功获取到最新版本 §e" + ver + " §a...");
} }
@ -127,4 +130,26 @@ public class PluginInfo implements Serializable {
return null; 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;
}
} }

View File

@ -10,33 +10,29 @@ import java.util.Map.Entry;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.JSONValue; import org.json.simple.JSONValue;
import cn.citycraft.PluginHelper.utils.IOUtil;
import pw.yumc.Yum.models.RepoSerialization.Repositories; import pw.yumc.Yum.models.RepoSerialization.Repositories;
import pw.yumc.YumCore.bukkit.Log; import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.kit.HttpKit;
public class RepoCache implements Serializable { public class RepoCache implements Serializable {
Map<String, PluginInfo> plugins = new HashMap<>(); Map<String, PluginInfo> plugins = new HashMap<>();
Map<String, Repositories> repos = new HashMap<>(); Map<String, Repositories> repos = new HashMap<>();
public void addPlugins(final String name, final PluginInfo info) { public void addPlugins(String name, PluginInfo info) {
plugins.put(name, info); plugins.put(name, info);
} }
public Repositories addRepo(final String repo) { public Repositories addRepo(String repo) {
if (repos.containsKey(repo) || repo.isEmpty()) { if (repos.containsKey(repo) || repo.isEmpty()) { return null; }
return null; Repositories reposes = getRepo(repo);
} if (reposes == null) { return null; }
final Repositories reposes = getRepo(repo);
if (reposes == null) {
return null;
}
repos.put(repo, reposes); repos.put(repo, reposes);
return reposes; return reposes;
} }
public List<String> getAllRepoInfo() { public List<String> getAllRepoInfo() {
final List<String> repoinfo = new ArrayList<>(); List<String> repoinfo = new ArrayList<>();
for (final Entry<String, Repositories> repo : repos.entrySet()) { for (Entry<String, Repositories> repo : repos.entrySet()) {
repoinfo.add(String.format("§d仓库: §e%s §6- §3%s", repo.getValue().name, repo.getKey())); repoinfo.add(String.format("§d仓库: §e%s §6- §3%s", repo.getValue().name, repo.getKey()));
} }
return repoinfo; return repoinfo;
@ -46,13 +42,13 @@ public class RepoCache implements Serializable {
return plugins; return plugins;
} }
public Repositories getRepo(final String repo) { public Repositories getRepo(String repo) {
final String json = IOUtil.getData(repo); String json = HttpKit.get(repo);
if (json == null || json.isEmpty()) { if (json == null || json.isEmpty()) {
Log.console("§c源地址获取数据为空 §b" + repo); Log.console("§c源地址获取数据为空 §b" + repo);
return null; return null;
} }
final Repositories reposes = new Repositories((JSONObject) JSONValue.parse(json)); Repositories reposes = new Repositories((JSONObject) JSONValue.parse(json));
if (reposes.repos.isEmpty()) { if (reposes.repos.isEmpty()) {
Log.console("§c源地址解析Json为空 §b" + repo); Log.console("§c源地址解析Json为空 §b" + repo);
return null; return null;
@ -64,10 +60,8 @@ public class RepoCache implements Serializable {
return repos; return repos;
} }
public boolean removeRepo(final String repo) { public boolean removeRepo(String repo) {
if (repo.isEmpty() || !repos.containsKey(repo)) { if (repo.isEmpty() || !repos.containsKey(repo)) { return false; }
return false;
}
repos.remove(repo); repos.remove(repo);
return true; return true;
} }

View File

@ -20,12 +20,10 @@ import org.json.simple.JSONValue;
*/ */
public class RepoSerialization { public class RepoSerialization {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <E> List<E> parse(final String json, final Class<?> clazz) { public static <E> List<E> parse(String json, Class<?> clazz) {
if (json == null || "null".equals(json) || json.isEmpty()) { if (json == null || "null".equals(json) || json.isEmpty()) { return null; }
return null; List<E> temp = new ArrayList<>();
} JSONArray ja = (JSONArray) JSONValue.parse(json);
final List<E> temp = new ArrayList<>();
final JSONArray ja = (JSONArray) JSONValue.parse(json);
for (int i = 0; i < ja.size(); i++) { for (int i = 0; i < ja.size(); i++) {
try { try {
temp.add((E) clazz.getConstructor(JSONObject.class).newInstance((JSONObject) ja.get(i))); temp.add((E) clazz.getConstructor(JSONObject.class).newInstance((JSONObject) ja.get(i)));
@ -43,12 +41,12 @@ public class RepoSerialization {
public String url; public String url;
public URLType type; public URLType type;
public PackageInfo(final JSONObject obj) { public PackageInfo(JSONObject obj) {
name = String.valueOf(obj.get("name")); name = String.valueOf(obj.get("name"));
plugins = Plugin.parseList(String.valueOf(obj.get("plugins"))); plugins = Plugin.parseList(String.valueOf(obj.get("plugins")));
pom = String.valueOf(obj.get("pom")); pom = String.valueOf(obj.get("pom"));
url = String.valueOf(obj.get("url")); 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()); type = tt == null ? null : URLType.valueOf(tt.toString());
} }
} }
@ -65,7 +63,7 @@ public class RepoSerialization {
public String version; public String version;
public URLType type; public URLType type;
public Plugin(final JSONObject obj) { public Plugin(JSONObject obj) {
artifactId = String.valueOf(obj.get("artifactId")); artifactId = String.valueOf(obj.get("artifactId"));
branch = String.valueOf(obj.get("branch")); branch = String.valueOf(obj.get("branch"));
description = String.valueOf(obj.get("description")); description = String.valueOf(obj.get("description"));
@ -75,11 +73,11 @@ public class RepoSerialization {
pom = String.valueOf(obj.get("pom")); pom = String.valueOf(obj.get("pom"));
tags = TagInfo.parseList(String.valueOf(obj.get("tags"))); tags = TagInfo.parseList(String.valueOf(obj.get("tags")));
version = String.valueOf(obj.get("version")); 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()); type = tt == null ? null : URLType.valueOf(tt.toString());
} }
public static List<Plugin> parseList(final String json) { public static List<Plugin> parseList(String json) {
return parse(json, Plugin.class); return parse(json, Plugin.class);
} }
} }
@ -88,7 +86,7 @@ public class RepoSerialization {
public String name; public String name;
public List<Repository> repos; public List<Repository> repos;
public Repositories(final JSONObject obj) { public Repositories(JSONObject obj) {
name = String.valueOf(obj.get("name")); name = String.valueOf(obj.get("name"));
repos = Repository.parseList(String.valueOf(obj.get("repos"))); repos = Repository.parseList(String.valueOf(obj.get("repos")));
} }
@ -99,14 +97,14 @@ public class RepoSerialization {
public URLType type; public URLType type;
public String url; public String url;
public Repository(final JSONObject obj) { public Repository(JSONObject obj) {
id = String.valueOf(obj.get("id")); 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()); type = tt == null ? null : URLType.valueOf(tt.toString());
url = String.valueOf(obj.get("url")); url = String.valueOf(obj.get("url"));
} }
public static List<Repository> parseList(final String json) { public static List<Repository> parseList(String json) {
return parse(json, Repository.class); return parse(json, Repository.class);
} }
} }
@ -117,15 +115,15 @@ public class RepoSerialization {
public URLType type; public URLType type;
public String url; public String url;
public TagInfo(final JSONObject obj) { public TagInfo(JSONObject obj) {
tag = String.valueOf(obj.get("tag")); tag = String.valueOf(obj.get("tag"));
version = String.valueOf(obj.get("version")); 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()); type = tt == null ? null : URLType.valueOf(tt.toString());
url = String.valueOf(obj.get("url")); url = String.valueOf(obj.get("url"));
} }
public static List<TagInfo> parseList(final String json) { public static List<TagInfo> parseList(String json) {
return parse(json, TagInfo.class); return parse(json, TagInfo.class);
} }
} }

View File

@ -1,13 +1,16 @@
package pw.yumc.Yum.runnables; package pw.yumc.Yum.runnables;
import java.lang.Thread.State; import java.lang.Thread.State;
import java.lang.reflect.Method;
import java.util.TimerTask; import java.util.TimerTask;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import cn.citycraft.PluginHelper.kit.ServerKit;
import pw.yumc.YumCore.bukkit.Log; import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.bukkit.compatible.C;
import pw.yumc.YumCore.kit.PKit; import pw.yumc.YumCore.kit.PKit;
import pw.yumc.YumCore.plugin.protocollib.PacketKit;
/** /**
* 线程安全检查任务 * 线程安全检查任务
@ -16,16 +19,25 @@ import pw.yumc.YumCore.kit.PKit;
* @author * @author
*/ */
public class MainThreadCheckTask extends TimerTask { public class MainThreadCheckTask extends TimerTask {
private final String prefix = "§6[§bYum §a线程管理§6] "; private static Method tickMethod;
private final String warnPNet = "§6插件 §b%s §c在主线程进行网络操作 §4服务器处于停止状态..."; private String prefix = "§6[§bYum §a线程管理§6] ";
private final String warnPIO = "§6插件 §b%s §c在主线程进行IO操作 §4服务器处于停止状态..."; private String warnPNet = "§6插件 §b%s §c在主线程进行网络操作 §4服务器处于停止状态...";
private final String warnNet = "§c主线程存在网络操作 §4服务器处于停止状态..."; private String warnPIO = "§6插件 §b%s §c在主线程进行IO操作 §4服务器处于停止状态...";
private final String warnIO = "§c主线程存在IO操作 §4服务器处于停止状态..."; private String warnNet = "§c主线程存在网络操作 §4服务器处于停止状态...";
private final String deliver = "§c服务器处于停止状态 已超过 %s 秒 激活心跳 防止线程关闭..."; private String warnIO = "§c主线程存在IO操作 §4服务器处于停止状态...";
private String deliver = "§c服务器处于停止状态 已超过 %s 秒 激活心跳 防止线程关闭...";
private int stopTime = 0; 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; this.mainThread = mainThread;
} }
@ -37,8 +49,8 @@ public class MainThreadCheckTask extends TimerTask {
if (mainThread.getState() == State.RUNNABLE) { if (mainThread.getState() == State.RUNNABLE) {
// Based on this post we have to check the top element of the stack // 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 // https://stackoverflow.com/questions/20891386/how-to-detect-thread-being-blocked-by-io
final StackTraceElement[] stackTrace = mainThread.getStackTrace(); StackTraceElement[] stackTrace = mainThread.getStackTrace();
final StackTraceElement topElement = stackTrace[0]; StackTraceElement topElement = stackTrace[0];
if (topElement.isNativeMethod()) { if (topElement.isNativeMethod()) {
// Socket/SQL (connect) - java.net.DualStackPlainSocketImpl.connect0 // Socket/SQL (connect) - java.net.DualStackPlainSocketImpl.connect0
// Socket/SQL (read) - java.net.SocketInputStream.socketRead0 // Socket/SQL (read) - java.net.SocketInputStream.socketRead0
@ -46,7 +58,7 @@ public class MainThreadCheckTask extends TimerTask {
if (isElementEqual(topElement, "java.net.DualStackPlainSocketImpl", "connect0") if (isElementEqual(topElement, "java.net.DualStackPlainSocketImpl", "connect0")
|| isElementEqual(topElement, "java.net.SocketInputStream", "socketRead0") || isElementEqual(topElement, "java.net.SocketInputStream", "socketRead0")
|| isElementEqual(topElement, "java.net.SocketOutputStream", "socketWrite0")) { || isElementEqual(topElement, "java.net.SocketOutputStream", "socketWrite0")) {
final Plugin plugin = PKit.getOperatePlugin(stackTrace); Plugin plugin = PKit.getOperatePlugin(stackTrace);
if (plugin != null) { if (plugin != null) {
Log.console(prefix + warnPNet, plugin.getName()); Log.console(prefix + warnPNet, plugin.getName());
} else { } else {
@ -56,8 +68,9 @@ public class MainThreadCheckTask extends TimerTask {
} }
// File (in) - java.io.FileInputStream.readBytes // File (in) - java.io.FileInputStream.readBytes
// File (out) - java.io.FileOutputStream.writeBytes // File (out) - java.io.FileOutputStream.writeBytes
else if (isElementEqual(topElement, "java.io.FileInputStream", "readBytes") || isElementEqual(topElement, "java.io.FileOutputStream", "writeBytes")) { else if (isElementEqual(topElement, "java.io.FileInputStream", "readBytes")
final Plugin plugin = PKit.getOperatePlugin(stackTrace); || isElementEqual(topElement, "java.io.FileOutputStream", "writeBytes")) {
Plugin plugin = PKit.getOperatePlugin(stackTrace);
if (plugin != null) { if (plugin != null) {
Log.console(prefix + warnPIO, plugin.getName()); Log.console(prefix + warnPIO, plugin.getName());
} else { } 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); return traceElement.getClassName().equals(className) && traceElement.getMethodName().equals(methodName);
} }
@ -81,7 +94,23 @@ public class MainThreadCheckTask extends TimerTask {
stopTime += 5; stopTime += 5;
if (stopTime >= 45) { if (stopTime >= 45) {
Log.console(prefix + deliver, stopTime); 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) {
} }
} }
} }