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

@ -11,12 +11,6 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
@ -27,5 +21,16 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<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>
</configuration>
</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>
</build>
<repositories>
@ -30,6 +51,10 @@
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>citycraft-repo</id>
<url>http://ci.citycraft.cn:8800/jenkins/plugin/repository/everything/</url>
</repository>
</repositories>
<dependencies>
<dependency>
@ -38,6 +63,12 @@
<type>jar</type>
<version>1.8.3-R0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>cn.citycraft</groupId>
<artifactId>PluginHelper</artifactId>
<type>jar</type>
<version>1.0</version>
</dependency>
</dependencies>
<properties>
<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 cn.citycraft.Yum.commands.CommandHandler;
import cn.citycraft.Yum.config.FileConfig;
import cn.citycraft.Yum.manager.YumManager;
import cn.citycraft.config.FileConfig;
import cn.citycraft.utils.VersionChecker;
/**
* MC插件仓库
@ -19,8 +20,9 @@ public class Yum extends JavaPlugin {
public FileConfig config;
@Override
public void onLoad() {
config = new FileConfig(this, "config.yml");
public void onDisable() {
YumManager.repo.cacheToJson(config);
config.save();
}
@Override
@ -30,12 +32,12 @@ public class Yum extends JavaPlugin {
this.getCommand("yum").setTabCompleter(cmdhandler);
yumgr = new YumManager(this);
YumManager.repo.jsonToCache(config);
new VersionChecker(this);
}
@Override
public void onDisable() {
YumManager.repo.cacheToJson(config);
config.save();
public void onLoad() {
config = new FileConfig(this, "config.yml");
}
}

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

@ -48,29 +48,16 @@ public class DownloadManager {
private String getPer(int per) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 11; i++) {
if (per > i) {
for (int i = 0; i < 11; i++)
if (per > i)
sb.append("==");
} else if (per == i) {
else if (per == i)
sb.append("> ");
} else {
else
sb.append(" ");
}
}
return sb.toString();
}
/**
* 从网络下载文件
*
* @param urlstring
* - 下载地址
* @return 是否成功
*/
public boolean run(String urlstring) {
return run(null, urlstring);
}
/**
* 从网络下载文件
*
@ -120,9 +107,8 @@ public class DownloadManager {
public boolean run(CommandSender sender, URL url, File file) {
BufferedInputStream in = null;
FileOutputStream fout = null;
if (sender == null) {
if (sender == null)
sender = Bukkit.getConsoleSender();
}
try {
sender.sendMessage("§6开始下载: §3" + getFileName(url));
sender.sendMessage("§6下载地址: §3" + url.toString());
@ -138,9 +124,8 @@ public class DownloadManager {
file.getParentFile().mkdirs();
sender.sendMessage("§6创建新目录: §d" + file.getParentFile().getAbsolutePath());
}
if (file.exists()) {
if (file.exists())
file.delete();
}
file.createNewFile();
sender.sendMessage("§6创建新文件: §d" + file.getAbsolutePath());
fout = new FileOutputStream(file);
@ -152,13 +137,12 @@ public class DownloadManager {
downloaded += count;
fout.write(data, 0, count);
int percent = (int) (downloaded * 100L / fileLength);
if (percent % 10 == 0) {
if (percent % 10 == 0)
if (fileLength < 102400 || System.currentTimeMillis() - time > 1000) {
sender.sendMessage(String.format("§6已下载: §a" + getPer(percent / 10) + " %s%%", percent));
time = System.currentTimeMillis();
}
}
}
sender.sendMessage("§6文件: §a " + file.getName() + " 下载完成!");
return true;
} catch (Exception ex) {
@ -167,15 +151,26 @@ public class DownloadManager {
return false;
} finally {
try {
if (in != null) {
if (in != null)
in.close();
if (fout != null)
fout.close();
}
} catch (Exception ex) {
}
}
}
/**
* 从网络下载文件
*
* @param urlstring
* - 下载地址
* @return 是否成功
*/
public boolean run(String urlstring) {
return run(null, urlstring);
}
/**
* 从网络下载文件
*

View File

@ -23,10 +23,10 @@ import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.UnknownDependencyException;
import cn.citycraft.Yum.utils.StringUtil;
import com.google.common.base.Joiner;
import cn.citycraft.Yum.utils.StringUtil;
/**
* 插件管理类
*
@ -70,21 +70,18 @@ public class PluginsManager {
* - 插件
*/
public void disable(Plugin plugin) {
if ((plugin.isEnabled()) && (plugin != null)) {
if ((plugin != null) && (plugin.isEnabled()))
Bukkit.getPluginManager().disablePlugin(plugin);
}
}
/**
* 关闭所有插件
*/
public void disableAll() {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (!isIgnored(plugin)) {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins())
if (!isIgnored(plugin))
disable(plugin);
}
}
}
/**
* 启用插件
@ -93,21 +90,18 @@ public class PluginsManager {
* - 插件
*/
public void enable(Plugin plugin) {
if ((!plugin.isEnabled()) && (plugin != null)) {
if ((plugin != null) && (!plugin.isEnabled()))
Bukkit.getPluginManager().enablePlugin(plugin);
}
}
/**
* 启用所有插件
*/
public void enableAll() {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (!isIgnored(plugin)) {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins())
if (!isIgnored(plugin))
enable(plugin);
}
}
}
/**
* 获得格式化的插件名称
@ -132,9 +126,8 @@ public class PluginsManager {
public String getFormattedName(Plugin plugin, boolean includeVersions) {
ChatColor color = plugin.isEnabled() ? ChatColor.GREEN : ChatColor.RED;
String pluginName = color + plugin.getName();
if (includeVersions) {
if (includeVersions)
pluginName = pluginName + " (" + plugin.getDescription().getVersion() + ")";
}
return pluginName;
}
@ -181,9 +174,8 @@ public class PluginsManager {
public List<String> getPluginNames(boolean fullName) {
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());
}
return plugins;
}
@ -217,11 +209,10 @@ public class PluginsManager {
Iterator<Entry<String, Map<String, Object>>> commandsIt = commands.entrySet().iterator();
while (commandsIt.hasNext()) {
Entry<String, Map<String, Object>> thisEntry = commandsIt.next();
if (thisEntry != null) {
if (thisEntry != null)
parsedCommands.add(thisEntry.getKey());
}
}
}
if (parsedCommands.isEmpty())
return null;
return Joiner.on(", ").join(parsedCommands);
@ -246,10 +237,9 @@ public class PluginsManager {
* @return 是否
*/
public boolean isIgnored(String plugin) {
for (String name : new ArrayList<String>()) {
for (String name : new ArrayList<String>())
if (name.equalsIgnoreCase(plugin))
return true;
}
return false;
}
@ -265,12 +255,10 @@ public class PluginsManager {
public boolean load(CommandSender sender, String name) {
Plugin target = null;
String filename = null;
if (sender == null) {
if (sender == null)
sender = Bukkit.getConsoleSender();
}
if (!name.endsWith(".jar")) {
if (!name.endsWith(".jar"))
filename = name + ".jar";
}
File pluginDir = new File("plugins");
File updateDir = new File(pluginDir, "update");
if (!pluginDir.isDirectory()) {
@ -282,8 +270,8 @@ public class PluginsManager {
if (!pluginFile.isFile() && !new File(updateDir, filename).isFile()) {
pluginFile = null;
for (File file : pluginDir.listFiles()) {
if (file.getName().endsWith(".jar")) {
for (File file : pluginDir.listFiles())
if (file.getName().endsWith(".jar"))
try {
PluginDescriptionFile desc = main.getPluginLoader().getPluginDescription(file);
if (desc.getName().equalsIgnoreCase(name)) {
@ -292,8 +280,6 @@ public class PluginsManager {
}
} catch (InvalidDescriptionException e) {
}
}
}
if (pluginFile == null) {
sender.sendMessage("§6载入: §c在插件目录和更新目录均未找到 " + name + " 插件 请确认文件是否存在!");
return false;
@ -359,23 +345,19 @@ public class PluginsManager {
/**
* 重载所有插件
*/
public void reloadAll(CommandSender sender) {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (!isIgnored(plugin)) {
reload(sender, plugin);
}
}
public void reloadAll() {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins())
if (!isIgnored(plugin))
reload(plugin);
}
/**
* 重载所有插件
*/
public void reloadAll() {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (!isIgnored(plugin)) {
reload(plugin);
}
}
public void reloadAll(CommandSender sender) {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins())
if (!isIgnored(plugin))
reload(sender, plugin);
}
/**
@ -390,15 +372,17 @@ public class PluginsManager {
@SuppressWarnings("unchecked")
public boolean unload(CommandSender sender, Plugin plugin) {
String name = plugin.getName();
if (sender == null) {
if (sender == null)
sender = Bukkit.getConsoleSender();
}
PluginManager pluginManager = Bukkit.getPluginManager();
SimpleCommandMap commandMap = null;
List<Plugin> plugins = null;
Map<String, Plugin> lookupNames = null;
Map<String, Command> knownCommands = null;
if (pluginManager != null) {
if (pluginManager == null) {
sender.sendMessage("§4异常: §c插件管理类为Null!");
return false;
}
try {
Field pluginsField = pluginManager.getClass().getDeclaredField("plugins");
pluginsField.setAccessible(true);
@ -419,8 +403,7 @@ public class PluginsManager {
sender.sendMessage("§4异常: §c" + e.getMessage() + " 插件 " + name + " 卸载失败!");
return false;
}
}
for (Plugin next : pluginManager.getPlugins()) {
for (Plugin next : pluginManager.getPlugins())
if (next.getName().equals(name)) {
pluginManager.disablePlugin(next);
if ((plugins != null) && (plugins.contains(next))) {
@ -447,7 +430,6 @@ public class PluginsManager {
sender.sendMessage("§6卸载: §a注销插件 " + name + " 的所有命令!");
}
}
}
sender.sendMessage("§6卸载: §a插件 " + name + " 已成功卸载!");
return true;
}

View File

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