use pluginhelper and add versionchecker...

This commit is contained in:
502647092 2015-09-02 12:06:40 +08:00
parent 22676fdf8e
commit fb898dbfa0
7 changed files with 186 additions and 381 deletions

View File

@ -1,31 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<classpath> <classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java"> <classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes> <attributes>
<attribute name="optional" value="true"/> <attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"> <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes> <attributes>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java"> <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes> <attributes>
<attribute name="optional" value="true"/> <attribute name="maven.pomderived" value="true"/>
<attribute name="maven.pomderived" value="true"/> </attributes>
</attributes> </classpathentry>
</classpathentry> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"> <attributes>
<attributes> <attribute name="maven.pomderived" value="true"/>
<attribute name="maven.pomderived" value="true"/> </attributes>
</attributes> </classpathentry>
</classpathentry> <classpathentry kind="src" output="target/test-classes" path="src/test/java">
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"> <attributes>
<attributes> <attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="output" path="target/classes"/> <classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
</classpath> <attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

31
pom.xml
View File

@ -23,6 +23,27 @@
<target>1.7</target> <target>1.7</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<configuration>
<minimizeJar>true</minimizeJar>
<artifactSet>
<includes>
<include>cn.citycraft:PluginHelper</include>
</includes>
</artifactSet>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>
<repositories> <repositories>
@ -30,6 +51,10 @@
<id>spigot-repo</id> <id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url> <url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository> </repository>
<repository>
<id>citycraft-repo</id>
<url>http://ci.citycraft.cn:8800/jenkins/plugin/repository/everything/</url>
</repository>
</repositories> </repositories>
<dependencies> <dependencies>
<dependency> <dependency>
@ -38,6 +63,12 @@
<type>jar</type> <type>jar</type>
<version>1.8.3-R0.1-SNAPSHOT</version> <version>1.8.3-R0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency>
<groupId>cn.citycraft</groupId>
<artifactId>PluginHelper</artifactId>
<type>jar</type>
<version>1.0</version>
</dependency>
</dependencies> </dependencies>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -6,8 +6,9 @@ package cn.citycraft.Yum;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import cn.citycraft.Yum.commands.CommandHandler; import cn.citycraft.Yum.commands.CommandHandler;
import cn.citycraft.Yum.config.FileConfig;
import cn.citycraft.Yum.manager.YumManager; import cn.citycraft.Yum.manager.YumManager;
import cn.citycraft.config.FileConfig;
import cn.citycraft.utils.VersionChecker;
/** /**
* MC插件仓库 * MC插件仓库
@ -19,8 +20,9 @@ public class Yum extends JavaPlugin {
public FileConfig config; public FileConfig config;
@Override @Override
public void onLoad() { public void onDisable() {
config = new FileConfig(this, "config.yml"); YumManager.repo.cacheToJson(config);
config.save();
} }
@Override @Override
@ -30,12 +32,12 @@ public class Yum extends JavaPlugin {
this.getCommand("yum").setTabCompleter(cmdhandler); this.getCommand("yum").setTabCompleter(cmdhandler);
yumgr = new YumManager(this); yumgr = new YumManager(this);
YumManager.repo.jsonToCache(config); YumManager.repo.jsonToCache(config);
new VersionChecker(this);
} }
@Override @Override
public void onDisable() { public void onLoad() {
YumManager.repo.cacheToJson(config); config = new FileConfig(this, "config.yml");
config.save();
} }
} }

View File

@ -1,198 +0,0 @@
package cn.citycraft.Yum.config;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.logging.Logger;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.file.YamlConstructor;
import org.bukkit.configuration.file.YamlRepresenter;
import org.bukkit.plugin.Plugin;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.representer.Representer;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
/**
* An implementation of {@link Configuration} which saves all files in Yaml.
* Note that this
* implementation is not synchronized.
*/
public class FileConfig extends YamlConfiguration {
protected File file;
protected Logger loger;
protected Plugin plugin;
protected final DumperOptions yamlOptions = new DumperOptions();
protected final Representer yamlRepresenter = new YamlRepresenter();
protected final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
private FileConfig(File file) {
Validate.notNull(file, "File cannot be null");
this.file = file;
loger = Bukkit.getLogger();
init(file);
}
private FileConfig(InputStream stream) {
loger = Bukkit.getLogger();
init(stream);
}
public FileConfig(Plugin plugin, File file) {
Validate.notNull(file, "File cannot be null");
Validate.notNull(plugin, "Plugin cannot be null");
this.plugin = plugin;
this.file = file;
loger = plugin.getLogger();
check(file);
init(file);
}
public FileConfig(Plugin plugin, String filename) {
this(plugin, new File(plugin.getDataFolder(), filename));
}
private void check(File file) {
String filename = file.getName();
InputStream stream = plugin.getResource(filename);
try {
if (!file.exists()) {
file.getParentFile().mkdirs();
if (stream == null) {
file.createNewFile();
loger.info("配置文件 " + filename + " 不存在 创建新文件...");
} else {
plugin.saveResource(filename, true);
loger.info("配置文件 " + filename + " 不存在 从插件释放...");
}
} else {
if (stream == null) {
return;
}
FileConfig newcfg = new FileConfig(stream);
FileConfig oldcfg = new FileConfig(file);
String newver = newcfg.getString("version");
String oldver = oldcfg.getString("version");
if (newver != null && newver != oldver) {
loger.warning("配置文件: " + filename + " 版本 " + oldver + " 过低 正在升级到 " + newver + " ...");
try {
oldcfg.save(new File(file.getParent(), filename + ".backup"));
loger.warning("配置文件: " + filename + " 已备份为 " + filename + ".backup !");
} catch (IOException e) {
loger.warning("配置文件: " + filename + "备份失败!");
}
plugin.saveResource(filename, true);
loger.info("配置文件: " + filename + "升级成功!");
}
}
} catch (IOException e) {
loger.info("配置文件 " + filename + " 创建失败...");
}
}
private void init(File file) {
Validate.notNull(file, "File cannot be null");
FileInputStream stream;
try {
stream = new FileInputStream(file);
init(stream);
} catch (FileNotFoundException e) {
loger.info("配置文件 " + file.getName() + " 不存在...");
}
}
private void init(InputStream stream) {
Validate.notNull(stream, "Stream cannot be null");
try {
this.load(new InputStreamReader(stream, Charsets.UTF_8));
} catch (IOException ex) {
loger.info("配置文件 " + file.getName() + " 读取错误...");
} catch (InvalidConfigurationException ex) {
loger.info("配置文件 " + file.getName() + " 格式错误...");
}
}
@Override
public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException {
Validate.notNull(file, "File cannot be null");
final FileInputStream stream = new FileInputStream(file);
load(new InputStreamReader(stream, Charsets.UTF_8));
}
@Override
public void load(Reader reader) throws IOException, InvalidConfigurationException {
BufferedReader input = (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
try {
String line;
while ((line = input.readLine()) != null) {
builder.append(line);
builder.append('\n');
}
} finally {
input.close();
}
loadFromString(builder.toString());
}
public void reload() {
init(file);
}
public void save() {
if (file == null) {
loger.info("未定义配置文件路径 保存失败!");
}
try {
this.save(file);
} catch (IOException e) {
loger.info("配置文件 " + file.getName() + " 保存错误...");
e.printStackTrace();
}
}
@Override
public void save(File file) throws IOException {
Validate.notNull(file, "File cannot be null");
Files.createParentDirs(file);
String data = saveToString();
Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8);
try {
writer.write(data);
} finally {
writer.close();
}
}
@Override
public String saveToString() {
yamlOptions.setIndent(options().indent());
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
String header = buildHeader();
String dump = yaml.dump(getValues(false));
if (dump.equals(BLANK_CONFIG)) {
dump = "";
}
return header + dump;
}
}

View File

@ -12,7 +12,7 @@ import org.bukkit.plugin.Plugin;
/** /**
* 下载管理类 * 下载管理类
* *
* @author 蒋天蓓 * @author 蒋天蓓
* 2015年8月21日下午6:08:09 * 2015年8月21日下午6:08:09
*/ */
@ -25,7 +25,7 @@ public class DownloadManager {
/** /**
* 从地址获得文件名称 * 从地址获得文件名称
* *
* @param url * @param url
* - 地址 * - 地址
* @return 文件名称 * @return 文件名称
@ -37,7 +37,7 @@ public class DownloadManager {
/** /**
* 从地址获得文件名称 * 从地址获得文件名称
* *
* @param url * @param url
* - 地址 * - 地址
* @return 文件名称 * @return 文件名称
@ -48,32 +48,19 @@ public class DownloadManager {
private String getPer(int per) { private String getPer(int per) {
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("==");
} else if (per == i) { else if (per == i)
sb.append("> "); sb.append("> ");
} else { else
sb.append(" "); sb.append(" ");
}
}
return sb.toString(); return sb.toString();
} }
/** /**
* 从网络下载文件 * 从网络下载文件
* *
* @param urlstring
* - 下载地址
* @return 是否成功
*/
public boolean run(String urlstring) {
return run(null, urlstring);
}
/**
* 从网络下载文件
*
* @param sender * @param sender
* - 命令发送者 * - 命令发送者
* @param urlstring * @param urlstring
@ -86,7 +73,7 @@ public class DownloadManager {
/** /**
* 从网络下载文件 * 从网络下载文件
* *
* @param sender * @param sender
* - 命令发送者 * - 命令发送者
* @param urlstring * @param urlstring
@ -108,7 +95,7 @@ public class DownloadManager {
/** /**
* 从网络下载文件 * 从网络下载文件
* *
* @param sender * @param sender
* - 命令发送者 * - 命令发送者
* @param url * @param url
@ -120,9 +107,8 @@ public class DownloadManager {
public boolean run(CommandSender sender, URL url, File file) { public boolean run(CommandSender sender, URL url, File file) {
BufferedInputStream in = null; BufferedInputStream in = null;
FileOutputStream fout = null; FileOutputStream fout = null;
if (sender == null) { if (sender == null)
sender = Bukkit.getConsoleSender(); sender = Bukkit.getConsoleSender();
}
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());
@ -138,9 +124,8 @@ public class DownloadManager {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
sender.sendMessage("§6创建新目录: §d" + file.getParentFile().getAbsolutePath()); sender.sendMessage("§6创建新目录: §d" + file.getParentFile().getAbsolutePath());
} }
if (file.exists()) { if (file.exists())
file.delete(); file.delete();
}
file.createNewFile(); file.createNewFile();
sender.sendMessage("§6创建新文件: §d" + file.getAbsolutePath()); sender.sendMessage("§6创建新文件: §d" + file.getAbsolutePath());
fout = new FileOutputStream(file); fout = new FileOutputStream(file);
@ -152,12 +137,11 @@ public class DownloadManager {
downloaded += count; downloaded += count;
fout.write(data, 0, count); fout.write(data, 0, count);
int percent = (int) (downloaded * 100L / fileLength); int percent = (int) (downloaded * 100L / fileLength);
if (percent % 10 == 0) { if (percent % 10 == 0)
if (fileLength < 102400 || System.currentTimeMillis() - time > 1000) { if (fileLength < 102400 || System.currentTimeMillis() - time > 1000) {
sender.sendMessage(String.format("§6已下载: §a" + getPer(percent / 10) + " %s%%", percent)); sender.sendMessage(String.format("§6已下载: §a" + getPer(percent / 10) + " %s%%", percent));
time = System.currentTimeMillis(); time = System.currentTimeMillis();
} }
}
} }
sender.sendMessage("§6文件: §a " + file.getName() + " 下载完成!"); sender.sendMessage("§6文件: §a " + file.getName() + " 下载完成!");
return true; return true;
@ -167,10 +151,10 @@ public class DownloadManager {
return false; return false;
} finally { } finally {
try { try {
if (in != null) { if (in != null)
in.close(); in.close();
if (fout != null)
fout.close(); fout.close();
}
} catch (Exception ex) { } catch (Exception ex) {
} }
} }
@ -178,7 +162,18 @@ public class DownloadManager {
/** /**
* 从网络下载文件 * 从网络下载文件
* *
* @param urlstring
* - 下载地址
* @return 是否成功
*/
public boolean run(String urlstring) {
return run(null, urlstring);
}
/**
* 从网络下载文件
*
* @param urlstring * @param urlstring
* - 下载地址 * - 下载地址
* @param file * @param file
@ -191,7 +186,7 @@ public class DownloadManager {
/** /**
* 从网络下载文件 * 从网络下载文件
* *
* @param url * @param url
* - 下载地址 * - 下载地址
* @param file * @param file

View File

@ -23,10 +23,10 @@ import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.UnknownDependencyException; import org.bukkit.plugin.UnknownDependencyException;
import cn.citycraft.Yum.utils.StringUtil;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import cn.citycraft.Yum.utils.StringUtil;
/** /**
* 插件管理类 * 插件管理类
* *
@ -41,7 +41,7 @@ public class PluginsManager {
/** /**
* 删除插件 * 删除插件
* *
* @param sender * @param sender
* - 命令发送者 * - 命令发送者
* @param plugin * @param plugin
@ -54,7 +54,7 @@ public class PluginsManager {
/** /**
* 删除插件 * 删除插件
* *
* @param plugin * @param plugin
* - 插件 * - 插件
* @return 是否成功 * @return 是否成功
@ -65,53 +65,47 @@ public class PluginsManager {
/** /**
* 关闭插件 * 关闭插件
* *
* @param plugin * @param plugin
* - 插件 * - 插件
*/ */
public void disable(Plugin plugin) { public void disable(Plugin plugin) {
if ((plugin.isEnabled()) && (plugin != null)) { if ((plugin != null) && (plugin.isEnabled()))
Bukkit.getPluginManager().disablePlugin(plugin); Bukkit.getPluginManager().disablePlugin(plugin);
}
} }
/** /**
* 关闭所有插件 * 关闭所有插件
*/ */
public void disableAll() { public void disableAll() {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (Plugin plugin : Bukkit.getPluginManager().getPlugins())
if (!isIgnored(plugin)) { if (!isIgnored(plugin))
disable(plugin); disable(plugin);
}
}
} }
/** /**
* 启用插件 * 启用插件
* *
* @param plugin * @param plugin
* - 插件 * - 插件
*/ */
public void enable(Plugin plugin) { public void enable(Plugin plugin) {
if ((!plugin.isEnabled()) && (plugin != null)) { if ((plugin != null) && (!plugin.isEnabled()))
Bukkit.getPluginManager().enablePlugin(plugin); Bukkit.getPluginManager().enablePlugin(plugin);
}
} }
/** /**
* 启用所有插件 * 启用所有插件
*/ */
public void enableAll() { public void enableAll() {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (Plugin plugin : Bukkit.getPluginManager().getPlugins())
if (!isIgnored(plugin)) { if (!isIgnored(plugin))
enable(plugin); enable(plugin);
}
}
} }
/** /**
* 获得格式化的插件名称 * 获得格式化的插件名称
* *
* @param plugin * @param plugin
* - 插件 * - 插件
* @return 格式化的插件名称 * @return 格式化的插件名称
@ -122,7 +116,7 @@ public class PluginsManager {
/** /**
* 获得格式化的插件名称(可带版本) * 获得格式化的插件名称(可带版本)
* *
* @param plugin * @param plugin
* - 插件 * - 插件
* @param includeVersions * @param includeVersions
@ -132,15 +126,14 @@ public class PluginsManager {
public String getFormattedName(Plugin plugin, boolean includeVersions) { public String getFormattedName(Plugin plugin, boolean includeVersions) {
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 + " (" + plugin.getDescription().getVersion() + ")"; pluginName = pluginName + " (" + plugin.getDescription().getVersion() + ")";
}
return pluginName; return pluginName;
} }
/** /**
* 通过名称获得插件 * 通过名称获得插件
* *
* @param name * @param name
* - 名称 * - 名称
* @return 插件 * @return 插件
@ -151,7 +144,7 @@ public class PluginsManager {
/** /**
* 通过名称获得插件(处理带空格的插件) * 通过名称获得插件(处理带空格的插件)
* *
* @param name * @param name
* - 名称 * - 名称
* @return 插件 * @return 插件
@ -162,7 +155,7 @@ public class PluginsManager {
/** /**
* 获得插件绝对路径 * 获得插件绝对路径
* *
* @param plugin * @param plugin
* - 插件 * - 插件
* @return 插件的绝对路径 * @return 插件的绝对路径
@ -181,15 +174,14 @@ public class PluginsManager {
public List<String> getPluginNames(boolean fullName) { public List<String> getPluginNames(boolean fullName) {
List<String> plugins = new ArrayList<String>(); List<String> plugins = new ArrayList<String>();
for (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;
} }
/** /**
* 获得插件版本 * 获得插件版本
* *
* @param name * @param name
* - 插件名称 * - 插件名称
* @return 插件版本 * @return 插件版本
@ -203,7 +195,7 @@ public class PluginsManager {
/** /**
* 获得插件命令 * 获得插件命令
* *
* @param plugin * @param plugin
* - 插件 * - 插件
* @return 插件命令 * @return 插件命令
@ -217,9 +209,8 @@ public class PluginsManager {
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()) {
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())
@ -229,7 +220,7 @@ public class PluginsManager {
/** /**
* 判断插件是否在忽略列表 * 判断插件是否在忽略列表
* *
* @param plugin * @param plugin
* - 插件 * - 插件
* @return 是否 * @return 是否
@ -240,22 +231,21 @@ public class PluginsManager {
/** /**
* 判断插件是否在忽略列表 * 判断插件是否在忽略列表
* *
* @param plugin * @param plugin
* - 插件名称 * - 插件名称
* @return 是否 * @return 是否
*/ */
public boolean isIgnored(String plugin) { public boolean isIgnored(String plugin) {
for (String name : new ArrayList<String>()) { for (String name : new ArrayList<String>())
if (name.equalsIgnoreCase(plugin)) if (name.equalsIgnoreCase(plugin))
return true; return true;
}
return false; return false;
} }
/** /**
* 载入插件 * 载入插件
* *
* @param sender * @param sender
* - 命令发送者 * - 命令发送者
* @param name * @param name
@ -265,12 +255,10 @@ public class PluginsManager {
public boolean load(CommandSender sender, String name) { public boolean load(CommandSender sender, String name) {
Plugin target = null; Plugin target = null;
String filename = null; String filename = null;
if (sender == null) { if (sender == null)
sender = Bukkit.getConsoleSender(); sender = Bukkit.getConsoleSender();
} if (!name.endsWith(".jar"))
if (!name.endsWith(".jar")) {
filename = name + ".jar"; filename = name + ".jar";
}
File pluginDir = new File("plugins"); File pluginDir = new File("plugins");
File updateDir = new File(pluginDir, "update"); File updateDir = new File(pluginDir, "update");
if (!pluginDir.isDirectory()) { if (!pluginDir.isDirectory()) {
@ -282,8 +270,8 @@ public class PluginsManager {
if (!pluginFile.isFile() && !new File(updateDir, filename).isFile()) { if (!pluginFile.isFile() && !new File(updateDir, filename).isFile()) {
pluginFile = null; pluginFile = null;
for (File file : pluginDir.listFiles()) { for (File file : pluginDir.listFiles())
if (file.getName().endsWith(".jar")) { if (file.getName().endsWith(".jar"))
try { try {
PluginDescriptionFile desc = main.getPluginLoader().getPluginDescription(file); PluginDescriptionFile desc = main.getPluginLoader().getPluginDescription(file);
if (desc.getName().equalsIgnoreCase(name)) { if (desc.getName().equalsIgnoreCase(name)) {
@ -292,8 +280,6 @@ public class PluginsManager {
} }
} catch (InvalidDescriptionException e) { } catch (InvalidDescriptionException e) {
} }
}
}
if (pluginFile == null) { if (pluginFile == null) {
sender.sendMessage("§6载入: §c在插件目录和更新目录均未找到 " + name + " 插件 请确认文件是否存在!"); sender.sendMessage("§6载入: §c在插件目录和更新目录均未找到 " + name + " 插件 请确认文件是否存在!");
return false; return false;
@ -332,7 +318,7 @@ public class PluginsManager {
/** /**
* 删除重载插件 * 删除重载插件
* *
* @param sender * @param sender
* - 命令发送者 * - 命令发送者
* @param plugin * @param plugin
@ -347,7 +333,7 @@ public class PluginsManager {
/** /**
* 重载插件 * 重载插件
* *
* @param plugin * @param plugin
* - 插件 * - 插件
* @return 是否成功 * @return 是否成功
@ -359,28 +345,24 @@ public class PluginsManager {
/** /**
* 重载所有插件 * 重载所有插件
*/ */
public void reloadAll(CommandSender sender) { public void reloadAll() {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (Plugin plugin : Bukkit.getPluginManager().getPlugins())
if (!isIgnored(plugin)) { if (!isIgnored(plugin))
reload(sender, plugin); reload(plugin);
}
}
} }
/** /**
* 重载所有插件 * 重载所有插件
*/ */
public void reloadAll() { public void reloadAll(CommandSender sender) {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (Plugin plugin : Bukkit.getPluginManager().getPlugins())
if (!isIgnored(plugin)) { if (!isIgnored(plugin))
reload(plugin); reload(sender, plugin);
}
}
} }
/** /**
* 卸载插件 * 卸载插件
* *
* @param sender * @param sender
* - 命令发送者 * - 命令发送者
* @param plugin * @param plugin
@ -390,37 +372,38 @@ public class PluginsManager {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public boolean unload(CommandSender sender, Plugin plugin) { public boolean unload(CommandSender sender, Plugin plugin) {
String name = plugin.getName(); String name = plugin.getName();
if (sender == null) { if (sender == null)
sender = Bukkit.getConsoleSender(); sender = Bukkit.getConsoleSender();
}
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;
if (pluginManager != null) { if (pluginManager == null) {
try { sender.sendMessage("§4异常: §c插件管理类为Null!");
Field pluginsField = pluginManager.getClass().getDeclaredField("plugins"); return false;
pluginsField.setAccessible(true);
plugins = (List<Plugin>) pluginsField.get(pluginManager);
Field lookupNamesField = pluginManager.getClass().getDeclaredField("lookupNames");
lookupNamesField.setAccessible(true);
lookupNames = (Map<String, Plugin>) lookupNamesField.get(pluginManager);
Field commandMapField = pluginManager.getClass().getDeclaredField("commandMap");
commandMapField.setAccessible(true);
commandMap = (SimpleCommandMap) commandMapField.get(pluginManager);
Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands");
knownCommandsField.setAccessible(true);
knownCommands = (Map<String, Command>) knownCommandsField.get(commandMap);
} catch (Exception e) {
sender.sendMessage("§4异常: §c" + e.getMessage() + " 插件 " + name + " 卸载失败!");
return false;
}
} }
for (Plugin next : pluginManager.getPlugins()) { try {
Field pluginsField = pluginManager.getClass().getDeclaredField("plugins");
pluginsField.setAccessible(true);
plugins = (List<Plugin>) pluginsField.get(pluginManager);
Field lookupNamesField = pluginManager.getClass().getDeclaredField("lookupNames");
lookupNamesField.setAccessible(true);
lookupNames = (Map<String, Plugin>) lookupNamesField.get(pluginManager);
Field commandMapField = pluginManager.getClass().getDeclaredField("commandMap");
commandMapField.setAccessible(true);
commandMap = (SimpleCommandMap) commandMapField.get(pluginManager);
Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands");
knownCommandsField.setAccessible(true);
knownCommands = (Map<String, Command>) knownCommandsField.get(commandMap);
} catch (Exception e) {
sender.sendMessage("§4异常: §c" + e.getMessage() + " 插件 " + name + " 卸载失败!");
return false;
}
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))) {
@ -447,14 +430,13 @@ public class PluginsManager {
sender.sendMessage("§6卸载: §a注销插件 " + name + " 的所有命令!"); sender.sendMessage("§6卸载: §a注销插件 " + name + " 的所有命令!");
} }
} }
}
sender.sendMessage("§6卸载: §a插件 " + name + " 已成功卸载!"); sender.sendMessage("§6卸载: §a插件 " + name + " 已成功卸载!");
return true; return true;
} }
/** /**
* 卸载插件 * 卸载插件
* *
* @param plugin * @param plugin
* - 卸载插件 * - 卸载插件
* @return 是否成功 * @return 是否成功

View File

@ -39,7 +39,7 @@ public abstract class SQLHelper {
/** /**
* 初始化连接信息 * 初始化连接信息
* *
* @param username * @param username
* - 用户名 * - 用户名
* @param password * @param password
@ -75,12 +75,10 @@ public abstract class SQLHelper {
if (!dbConnection()) if (!dbConnection())
return false; return false;
String kv = ""; String kv = "";
for (Entry<String, String> kvs : fields.entrySet()) { for (Entry<String, String> kvs : fields.entrySet())
kv += "`" + kvs.getKey() + "` " + kvs.getValue() + " NOT NULL , "; kv += "`" + kvs.getKey() + "` " + kvs.getValue() + " NOT NULL , ";
}
kv = kv.substring(0, kv.length() - 2);// 根据String的索引提取子串 kv = kv.substring(0, kv.length() - 2);// 根据String的索引提取子串
String sql = "CREATE TABLE `" + tableName + "` ( " + kv + (Conditions == "" ? "" : " , " + Conditions) String sql = "CREATE TABLE `" + tableName + "` ( " + kv + (Conditions == "" ? "" : " , " + Conditions) + " ) ENGINE = InnoDB DEFAULT CHARSET=UTF8";
+ " ) ENGINE = InnoDB DEFAULT CHARSET=UTF8";
try { try {
PreparedStatement state = dbconn.prepareStatement(sql); PreparedStatement state = dbconn.prepareStatement(sql);
state.executeUpdate(); state.executeUpdate();
@ -139,9 +137,8 @@ public abstract class SQLHelper {
return false; return false;
String selCondition = ""; String selCondition = "";
if (selConditions != null && !selConditions.isEmpty()) { if (selConditions != null && !selConditions.isEmpty()) {
for (Entry<String, String> kvs : selConditions.entrySet()) { for (Entry<String, String> kvs : selConditions.entrySet())
selCondition += kvs.getKey() + "='" + kvs.getValue() + "', "; selCondition += kvs.getKey() + "='" + kvs.getValue() + "', ";
}
selCondition = " WHERE " + selCondition.substring(0, selCondition.length() - 2);// 根据String的索引提取子串 selCondition = " WHERE " + selCondition.substring(0, selCondition.length() - 2);// 根据String的索引提取子串
} }
String sql = "DELETE FROM `" + tableName + "` " + selCondition; String sql = "DELETE FROM `" + tableName + "` " + selCondition;
@ -171,9 +168,8 @@ public abstract class SQLHelper {
return false; return false;
String selCondition = ""; String selCondition = "";
if (selConditions != null && !selConditions.isEmpty()) { if (selConditions != null && !selConditions.isEmpty()) {
for (Entry<String, String> kvs : selConditions.entrySet()) { for (Entry<String, String> kvs : selConditions.entrySet())
selCondition += kvs.getKey() + "='" + kvs.getValue() + "', "; selCondition += kvs.getKey() + "='" + kvs.getValue() + "', ";
}
selCondition = " WHERE " + selCondition.substring(0, selCondition.length() - 2);// 根据String的索引提取子串 selCondition = " WHERE " + selCondition.substring(0, selCondition.length() - 2);// 根据String的索引提取子串
} }
String sql = "SELECT * FROM " + tableName + selCondition; String sql = "SELECT * FROM " + tableName + selCondition;
@ -231,18 +227,14 @@ public abstract class SQLHelper {
* 选择条件 * 选择条件
* @return 一个含有map的List列表 * @return 一个含有map的List列表
*/ */
@SuppressWarnings({ @SuppressWarnings({ "rawtypes", "unchecked" })
"rawtypes",
"unchecked"
})
public List dbSelect(String tableName, List<String> fields, String selCondition) { public List dbSelect(String tableName, List<String> fields, String selCondition) {
if (!dbConnection()) if (!dbConnection())
return null; return null;
List mapInList = new ArrayList(); List mapInList = new ArrayList();
String selFields = ""; String selFields = "";
for (int i = 0; i < fields.size(); ++i) { for (int i = 0; i < fields.size(); ++i)
selFields += fields.get(i) + ", "; selFields += fields.get(i) + ", ";
}
String selFieldsTem = selFields.substring(0, selFields.length() - 2);// 根据String的索引提取子串 String selFieldsTem = selFields.substring(0, selFields.length() - 2);// 根据String的索引提取子串
String sql = "SELECT " + selFieldsTem + " FROM `" + tableName + "`" + selCondition == "" ? "" : " WHERE " + selCondition; String sql = "SELECT " + selFieldsTem + " FROM `" + tableName + "`" + selCondition == "" ? "" : " WHERE " + selCondition;
try { try {
@ -255,9 +247,8 @@ public abstract class SQLHelper {
} }
while (dbresult.next()) { while (dbresult.next()) {
Map selResult = new HashMap(); Map selResult = new HashMap();
for (String col : fields) { for (String col : fields)
selResult.put(col, dbresult.getString(col)); selResult.put(col, dbresult.getString(col));
}
mapInList.add(selResult); mapInList.add(selResult);
} }
} catch (Exception e) { } catch (Exception e) {
@ -284,9 +275,8 @@ public abstract class SQLHelper {
String selFieldsTem = fields; String selFieldsTem = fields;
String selCondition = ""; String selCondition = "";
if (selConditions != null && !selConditions.isEmpty()) { if (selConditions != null && !selConditions.isEmpty()) {
for (Entry<String, String> kvs : selConditions.entrySet()) { for (Entry<String, String> kvs : selConditions.entrySet())
selCondition += kvs.getKey() + "='" + kvs.getValue() + "', "; selCondition += kvs.getKey() + "='" + kvs.getValue() + "', ";
}
selCondition = " WHERE " + selCondition.substring(0, selCondition.length() - 2);// 根据String的索引提取子串 selCondition = " WHERE " + selCondition.substring(0, selCondition.length() - 2);// 根据String的索引提取子串
} }
String sql = "SELECT " + selFieldsTem + " FROM " + tableName + selCondition + " limit 1"; String sql = "SELECT " + selFieldsTem + " FROM " + tableName + selCondition + " limit 1";
@ -308,9 +298,7 @@ public abstract class SQLHelper {
* @param reCount * @param reCount
* @return bool值成功返回true失败返回false * @return bool值成功返回true失败返回false
*/ */
@SuppressWarnings({ @SuppressWarnings({ "rawtypes" })
"rawtypes"
})
public boolean dbUpdate(String tabName, HashMap reCount, String upCondition) { public boolean dbUpdate(String tabName, HashMap reCount, String upCondition) {
if (!dbConnection()) if (!dbConnection())
return false; return false;
@ -402,24 +390,24 @@ public abstract class SQLHelper {
print("执行SQL文件: " + file.getName() + " ..."); print("执行SQL文件: " + file.getName() + " ...");
br = new BufferedReader(new FileReader(file)); br = new BufferedReader(new FileReader(file));
state = dbconn.createStatement(); state = dbconn.createStatement();
while ((sql = br.readLine()) != null) { while ((sql = br.readLine()) != null)
if (sql != "") { if (sql != "")
try { try {
state.executeUpdate(sql); state.executeUpdate(sql);
} catch (Exception e) { } catch (Exception e) {
print("数据库操作出错: " + e.getMessage()); print("数据库操作出错: " + e.getMessage());
print("SQL语句: " + sql); print("SQL语句: " + sql);
} }
}
}
return true; return true;
} catch (Exception e) { } catch (Exception e) {
print("执行SQL文件 " + file.getName() + "出错: " + e.getMessage()); print("执行SQL文件 " + file.getName() + "出错: " + e.getMessage());
return false; return false;
} finally { } finally {
try { try {
state.close(); if (state != null)
br.close(); state.close();
if (br != null)
br.close();
} catch (Exception e) { } catch (Exception e) {
} }
} }