1
0
mirror of https://e.coding.net/circlecloud/YumCore.git synced 2024-12-24 06:58:51 +00:00

feat: 更新优化配置文件类

Signed-off-by: 502647092 <admin@yumc.pw>
This commit is contained in:
502647092 2016-08-29 10:31:04 +08:00
parent 5d994fbb27
commit b967cf82bd
10 changed files with 181 additions and 194 deletions

View File

@ -18,6 +18,7 @@ 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.error.YAMLException;
@ -25,14 +26,27 @@ import org.yaml.snakeyaml.representer.Representer;
import com.google.common.io.Files;
import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.bukkit.P;
/**
* 抽象配置文件
*
* @since 2016年3月12日 下午4:46:45
* @author
*/
public class AbstractConfig extends YamlConfiguration {
public static final Charset UTF_8 = Charset.forName("UTF-8");
public abstract class AbstractConfig extends YamlConfiguration {
private static final String CONTENT_NOT_BE_NULL = "内容不能为 null";
private static final String TOP_KEY_MUST_BE_MAP = "顶层键值必须是Map.";
protected static final Charset UTF_8 = Charset.forName("UTF-8");
protected static final String FILE_NOT_BE_NULL = "文件不能为 NULL";
protected static final String CREATE_NEW_CONFIG = "配置: 创建新的文件 %s ...";
protected static final String newLine = "\n";
protected static Plugin plugin = P.instance;
protected final DumperOptions yamlOptions = new DumperOptions();
protected final Representer yamlRepresenter = new YamlRepresenter();
protected final Yaml yamlz = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
@ -41,7 +55,7 @@ public class AbstractConfig extends YamlConfiguration {
@Override
public void load(final File file) throws FileNotFoundException, IOException, InvalidConfigurationException {
Validate.notNull(file, "文件不能为null");
Validate.notNull(file, FILE_NOT_BE_NULL);
final FileInputStream stream = new FileInputStream(file);
load(new InputStreamReader(stream, UTF_8));
}
@ -54,7 +68,7 @@ public class AbstractConfig extends YamlConfiguration {
String line;
while ((line = input.readLine()) != null) {
builder.append(line);
builder.append('\n');
builder.append(newLine);
}
} finally {
input.close();
@ -64,14 +78,14 @@ public class AbstractConfig extends YamlConfiguration {
@Override
public void loadFromString(final String contents) throws InvalidConfigurationException {
Validate.notNull(contents, "内容不能为 null");
Validate.notNull(contents, CONTENT_NOT_BE_NULL);
Map<?, ?> input;
try {
input = (Map<?, ?>) yamlz.load(contents);
} catch (final YAMLException e) {
throw new InvalidConfigurationException(e);
} catch (final ClassCastException e) {
throw new InvalidConfigurationException("顶层键值必须是Map.");
throw new InvalidConfigurationException(TOP_KEY_MUST_BE_MAP);
}
final String header = parseHeader(contents);
if (header.length() > 0) {
@ -84,10 +98,11 @@ public class AbstractConfig extends YamlConfiguration {
@Override
public void save(final File file) throws IOException {
Validate.notNull(file, "文件不得为 null");
Validate.notNull(file, FILE_NOT_BE_NULL);
Files.createParentDirs(file);
if (!file.exists()) {
file.createNewFile();
Log.info(String.format(CREATE_NEW_CONFIG, file.toPath()));
}
final Writer writer = new OutputStreamWriter(new FileOutputStream(file), UTF_8);
try {

View File

@ -16,18 +16,27 @@ import pw.yumc.YumCore.bukkit.Log;
* @author
*/
public abstract class AbstractInjectConfig {
private static final String DATA_FORMAT_ERROR = "配置节点 {0} 数据类型不匹配 应该为: {1} 但实际为: {2}!";
private static final String INJECT_ERROR = "自动注入配置错误!";
private static final String DATE_PARSE_ERROR = "配置节点 {0} 日期解析失败 格式应该为: {1} 但输入值为: {2}!";
private static final String PATH_NOT_FOUND = "配置节点 %s 丢失!";
private static final String DATA_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final SimpleDateFormat df = new SimpleDateFormat(DATA_FORMAT);
private ConfigurationSection config;
/**
* 注入配置数据
*/
public void inject() {
public void inject(final ConfigurationSection config) {
this.config = config;
for (final Field field : getClass().getDeclaredFields()) {
if (Modifier.isTransient(field.getModifiers()) || field.getType().isPrimitive()) {
continue;
}
final ConfigNode node = field.getAnnotation(ConfigNode.class);
String path = field.getName();
if (node != null && !node.path().isEmpty()) {
path = node.path();
if (node != null && !node.value().isEmpty()) {
path = node.value();
}
field.setAccessible(true);
setField(path, field);
@ -45,35 +54,37 @@ public abstract class AbstractInjectConfig {
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
protected boolean commonParse(final ConfigurationSection config, final String path, final Field field) throws IllegalArgumentException, IllegalAccessException {
final String typeName = field.getType().getName();
switch (typeName) {
case "java.util.Date":
final String format = "yyyy-MM-dd HH:mm:ss";
final String value = config.getString(path);
try {
field.set(this, new SimpleDateFormat(format).parse(value));
} catch (final ParseException e) {
final Object[] obj = new Object[] { path, format, value };
Log.log(Level.INFO, "配置节点 {0} 日期解析失败 格式应该为: {1} 但输入值为: {2}!", obj);
protected void setField(final String path, final Field field) {
Object value = config.get(path);
final Default def = field.getAnnotation(Default.class);
if (value == null) {
if (def != null) {
value = def.value();
} else if (field.getAnnotation(Nullable.class) == null) {
Log.warning(String.format(PATH_NOT_FOUND, path));
return;
}
return true;
case "java.util.List":
field.set(this, config.getList(path));
return true;
default:
return false;
}
try {
final String typeName = field.getType().getName();
switch (typeName) {
case "java.util.Date":
try {
value = df.parse((String) value);
} catch (final ParseException e) {
final Object[] obj = new Object[] { path, DATA_FORMAT, value };
Log.log(Level.INFO, DATE_PARSE_ERROR, obj);
}
case "java.util.List":
value = config.getList(path);
default:
}
field.set(this, value);
} catch (final IllegalArgumentException ex) {
final Object[] obj = new Object[] { path, field.getType().getName(), value.getClass().getName() };
Log.log(Level.INFO, DATA_FORMAT_ERROR, obj);
} catch (final IllegalAccessException ex) {
Log.log(Level.SEVERE, INJECT_ERROR, ex);
}
}
/**
* 设置字段数据
*
* @param path
* 配置路径
* @param field
* 字段
* @throws IllegalArgumentException
*/
protected abstract void setField(final String path, final Field field) throws IllegalArgumentException;
}

View File

@ -26,8 +26,6 @@ public class CommentConfig extends AbstractConfig {
protected static final int commentSplitWidth = 90;
protected static final String newLine = "\n";
private static String[] split(final String string, final int partLength) {
final String[] array = new String[string.length() / partLength + 1];
for (int i = 0; i < array.length; i++) {

View File

@ -7,23 +7,17 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specializes a non-default path for config node
* 配置节点路径
*/
@Target(ElementType.FIELD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface ConfigNode {
/**
* @return 是否允许为空
*/
boolean notNull() default false;
/**
* Defines the path to the node if it has another as the variable name.
* Every indention is separated with an dot ('.')
* 定义配置文件路径节点路径.
* 通常用于配置节点 ('.')
*
* @return the path to the node
* @return 节点路径
*/
String path() default "";
String value();
}

View File

@ -0,0 +1,23 @@
package pw.yumc.YumCore.config;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 配置默认值
*
* @author
* @since 2016年8月24日 下午10:41:55
*/
@Target(ElementType.FIELD)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Default {
/**
* @return 默认值
*/
String value();
}

View File

@ -11,17 +11,14 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import org.apache.commons.lang.Validate;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import pw.yumc.YumCore.bukkit.Log;
import pw.yumc.YumCore.bukkit.P;
/**
* 一个继承于 {@link YamlConfiguration} 的配置文件类
@ -33,20 +30,34 @@ import pw.yumc.YumCore.bukkit.P;
*/
@SuppressWarnings({ "unchecked" })
public class FileConfig extends AbstractConfig {
protected static String CHECK_FIELD = "Version";
protected static String PLUGINHELPER = "PluginHelper";
protected static Plugin plugin = P.instance;
protected static final String VERSION = "Version";
private static final char ALT_COLOR_CHAR = '&';
private static final String DEFAULT = "config.yml";
private static final String DATA_FORMANT = "yyyyMMddHHmmss";
private static final String CONFIG_BACKUP = "配置: %s 已备份为 %s !";
private static final String CONFIG_UPDATED = "配置: %s 升级成功 版本 %S !";
private static final String CONFIG_OVERRIDE = "配置: %s 将覆盖原有字段数据...";
private static final String CONFIG_READ_ERROR = "配置: %s 读取错误...";
private static final String CONFIG_SAVE_ERROR = "配置: %s 保存错误...";
private static final String CONFIG_UPDATE_WARN = "配置: %s 版本 %s 过低 正在升级到 %s ...";
private static final String CONFIG_CREATE_ERROR = "配置: %s 创建失败...";
private static final String CONFIG_FORMAT_ERROR = "配置: %s 格式错误...";
private static final String CONFIG_BACKUP_ERROR = "配置: %s 备份失败 异常: %s !";
private static final String CONFIG_BACKUP_AND_RESET = "配置: %s 格式错误 已备份为 %s 并恢复默认配置!";
private static final String CONFIG_NOT_FOUND_IN_JAR = "配置: 从插件内部未找到预置的 %s 文件!";
private static final String CONFIG_READ_COMMENT_ERROR = "配置: 读取文件注释信息失败!";
private static final String STREAM_NOT_BE_NULL = "数据流不能为 NULL";
protected Logger loger = P.getLogger();
protected File file;
private CommentConfig commentConfig;
/**
* 实例化空的配置文件
* 实例化默认配置文件
*/
public FileConfig() {
this("config.yml");
this(DEFAULT);
}
/**
@ -56,7 +67,7 @@ public class FileConfig extends AbstractConfig {
* 配置文件名称
*/
public FileConfig(final File file) {
Validate.notNull(file, "文件不能为 null");
Validate.notNull(file, FILE_NOT_BE_NULL);
this.file = file;
init(file);
}
@ -233,7 +244,7 @@ public class FileConfig extends AbstractConfig {
return null;
}
for (int i = 0; i < cfgmsg.size(); i++) {
cfgmsg.set(i, ChatColor.translateAlternateColorCodes('&', cfgmsg.get(i)));
cfgmsg.set(i, ChatColor.translateAlternateColorCodes(ALT_COLOR_CHAR, cfgmsg.get(i)));
}
return cfgmsg;
}
@ -255,7 +266,7 @@ public class FileConfig extends AbstractConfig {
commentConfig = new CommentConfig();
commentConfig.loadFromString(contents);
} catch (final Exception e) {
Log.debug("读取配置文件注释信息失败!");
Log.debug(CONFIG_READ_COMMENT_ERROR);
commentConfig = null;
}
super.loadFromString(contents);
@ -317,7 +328,7 @@ public class FileConfig extends AbstractConfig {
this.save(file);
return true;
} catch (final IOException e) {
loger.warning("配置 " + file.getName() + " 保存错误...");
Log.warning(String.format(CONFIG_SAVE_ERROR, file.getName()));
e.printStackTrace();
return false;
}
@ -325,7 +336,7 @@ public class FileConfig extends AbstractConfig {
@Override
public void save(final File file) throws IOException {
Validate.notNull(file, "文件不得为 null");
Validate.notNull(file, FILE_NOT_BE_NULL);
if (commentConfig != null) {
data = commentConfig.saveToString();
} else {
@ -353,8 +364,8 @@ public class FileConfig extends AbstractConfig {
* @throws IOException
*/
private boolean needUpdate(final FileConfig newcfg, final FileConfig oldcfg) throws IOException {
final String newver = newcfg.getString(CHECK_FIELD);
return newver != null && !newver.equalsIgnoreCase(oldcfg.getString(CHECK_FIELD));
final String newver = newcfg.getString(VERSION);
return newver != null && !newver.equalsIgnoreCase(oldcfg.getString(VERSION));
}
/**
@ -367,18 +378,17 @@ public class FileConfig extends AbstractConfig {
final InputStream filestream = plugin.getResource(file.getName());
final String errFileName = this.getErrName(filename);
file.renameTo(new File(file.getParent(), errFileName));
loger.warning(String.format("错误的配置文件: %s 已备份为 %s !", filename, errFileName));
if (filestream == null) {
file.createNewFile();
} else {
plugin.saveResource(filename, true);
}
loger.warning("从插件内部读取并保存正确的配置文件...");
} catch (final IOException ex) {
loger.warning("从插件内部获取或保存配置文件时出错: " + ex.getMessage());
Log.warning(String.format(CONFIG_BACKUP_AND_RESET, filename, errFileName));
} catch (final IOException | IllegalArgumentException e) {
throw new IllegalArgumentException(e);
}
} else {
loger.warning("从插件内部未找到预置的 " + (file != null ? file.getName() : "") + " 配置文件!");
Log.warning(String.format(CONFIG_NOT_FOUND_IN_JAR, file != null ? file.getName() : ""));
}
}
@ -388,9 +398,9 @@ public class FileConfig extends AbstractConfig {
final String newCfgName = this.getBakName(filename);
final File newcfg = new File(file.getParent(), newCfgName);
oldcfg.save(newcfg);
loger.warning(String.format("配置: %s 已备份为 %s !", filename, newCfgName));
Log.warning(String.format(CONFIG_BACKUP, filename, newCfgName));
} catch (final IOException e) {
loger.warning(String.format("配置: %s 备份失败 异常: %s !", filename, e.getMessage()));
Log.warning(String.format(CONFIG_BACKUP_ERROR, filename, e.getMessage()));
}
}
@ -408,10 +418,8 @@ public class FileConfig extends AbstractConfig {
file.getParentFile().mkdirs();
if (stream == null) {
file.createNewFile();
loger.info("配置 " + filename + " 不存在 创建新文件...");
} else {
plugin.saveResource(filename, true);
loger.info("配置 " + filename + " 不存在 从插件释放...");
}
} else {
if (stream == null) {
@ -425,16 +433,16 @@ public class FileConfig extends AbstractConfig {
}
}
} catch (final IOException e) {
loger.warning("配置 " + filename + " 创建失败...");
Log.warning(String.format(CONFIG_CREATE_ERROR, filename));
}
}
protected String getBakName(final String cfgname) {
return cfgname + "." + getStringDate("yyyyMMddHHmmss") + ".bak";
return cfgname + "." + getStringDate(DATA_FORMANT) + ".bak";
}
protected String getErrName(final String cfgname) {
return cfgname + "." + getStringDate("yyyyMMddHHmmss") + ".err";
return cfgname + "." + getStringDate(DATA_FORMANT) + ".err";
}
/**
@ -456,13 +464,12 @@ public class FileConfig extends AbstractConfig {
* @return FileConfig
*/
protected FileConfig init(final File file) {
Validate.notNull(file, "文件不能为 null");
Validate.notNull(file, FILE_NOT_BE_NULL);
FileInputStream stream;
try {
stream = new FileInputStream(file);
init(stream);
} catch (final FileNotFoundException e) {
loger.warning("配置 " + file.getName() + " 不存在...");
}
return this;
}
@ -475,21 +482,21 @@ public class FileConfig extends AbstractConfig {
* @return FileConfig
*/
protected FileConfig init(final InputStream stream) {
Validate.notNull(stream, "数据流不能为 null");
Validate.notNull(stream, STREAM_NOT_BE_NULL);
try {
this.load(new InputStreamReader(stream, UTF_8));
} catch (final InvalidConfigurationException | IllegalArgumentException ex) {
if (file == null) {
throw new RuntimeException("数据流转换格式时发生错误...", ex);
throw new IllegalArgumentException(ex);
}
loger.warning("配置 " + file.getName() + " 格式错误...");
loger.warning(ex.getMessage());
Log.warning(String.format(CONFIG_FORMAT_ERROR, file.getName()));
Log.warning(ex.getMessage());
saveFromJar();
} catch (final IOException ex) {
if (file == null) {
throw new RuntimeException("数据流读取时发生错误...", ex);
throw new IllegalStateException(ex);
}
loger.warning("配置 " + file.getName() + " 读取错误...");
Log.warning(String.format(CONFIG_READ_ERROR, file.getName()));
}
return this;
}
@ -517,22 +524,22 @@ public class FileConfig extends AbstractConfig {
*/
protected FileConfig updateConfig(final FileConfig newCfg, final FileConfig oldCfg, final boolean force) {
final String filename = oldCfg.getConfigName();
final String newver = newCfg.getString(CHECK_FIELD);
final String oldver = oldCfg.getString(CHECK_FIELD);
final String newver = newCfg.getString(VERSION);
final String oldver = oldCfg.getString(VERSION);
final Set<String> oldConfigKeys = oldCfg.getKeys(true);
loger.warning("配置: " + filename + " 版本 " + oldver + " 过低 正在升级到 " + newver + " ...");
Log.warning(String.format(CONFIG_UPDATE_WARN, filename, oldver, newver));
// 保留版本字段 不更新
oldConfigKeys.remove("Version");
oldConfigKeys.remove(VERSION);
// 强制更新 去除新版本存在的字段
if (force) {
loger.warning("配置: " + filename + " 将覆盖原有字段数据...");
Log.warning(String.format(CONFIG_OVERRIDE, filename));
oldConfigKeys.removeAll(newCfg.getKeys(true));
}
// 复制旧的数据
for (final String string : oldConfigKeys) {
newCfg.set(string, oldCfg.get(string));
}
loger.info("配置: " + filename + " 升级成功 版本 " + newver + " !");
Log.info(String.format(CONFIG_UPDATED, filename, newver));
return newCfg;
}
}

View File

@ -1,10 +1,6 @@
package pw.yumc.YumCore.config;
import java.io.File;
import java.lang.reflect.Field;
import java.util.logging.Level;
import pw.yumc.YumCore.bukkit.Log;
/**
* 配置自动载入类
@ -16,18 +12,20 @@ public abstract class InjectConfig extends AbstractInjectConfig {
protected FileConfig config;
public InjectConfig() {
config = new FileConfig();
inject();
this(new FileConfig());
}
public InjectConfig(final File file) {
config = new FileConfig(file);
inject();
this(new FileConfig(file));
}
public InjectConfig(final FileConfig config) {
this.config = config;
inject(config);
}
public InjectConfig(final String name) {
config = new FileConfig(name);
inject();
this(new FileConfig(name));
}
/**
@ -44,41 +42,6 @@ public abstract class InjectConfig extends AbstractInjectConfig {
*/
public void reload() {
config.reload();
inject();
}
/**
* 设置字段数据
*
* @param path
* 配置路径
* @param field
* 字段
* @throws IllegalArgumentException
*/
@Override
protected void setField(final String path, final Field field) throws IllegalArgumentException {
final String realPath = path.replace("_", ".");
if (config.isSet(realPath)) {
final Object value = config.get(realPath);
try {
if (!commonParse(config, realPath, field)) {
if (config.isString(realPath)) {
field.set(this, config.getMessage(realPath));
} else if (config.isList(realPath)) {
field.set(this, config.getMessageList(realPath));
} else {
field.set(this, value);
}
}
} catch (final IllegalArgumentException ex) {
final Object[] obj = new Object[] { realPath, field.getType().getName(), value.getClass().getName() };
Log.log(Level.INFO, "配置节点 {0} 数据类型不匹配 应该为: {1} 但实际为: {2}!", obj);
} catch (final IllegalAccessException ex) {
Log.log(Level.SEVERE, "自动注入配置错误!", ex);
}
} else if (field.getAnnotation(Nullable.class) == null) {
Log.warning(String.format("配置节点 %s 丢失!", realPath));
}
inject(config);
}
}

View File

@ -1,12 +1,7 @@
package pw.yumc.YumCore.config;
import java.lang.reflect.Field;
import java.util.logging.Level;
import org.bukkit.configuration.ConfigurationSection;
import pw.yumc.YumCore.bukkit.Log;
/**
* 配置自动载入类
*
@ -14,47 +9,15 @@ import pw.yumc.YumCore.bukkit.Log;
* @author
*/
public class InjectConfigurationSection extends AbstractInjectConfig {
protected ConfigurationSection config;
public InjectConfigurationSection(final ConfigurationSection config) {
this.config = config;
inject();
inject(config);
}
/**
* 重载配置文件
*/
public void reload(final ConfigurationSection config) {
this.config = config;
inject();
}
/**
* 设置字段数据
*
* @param path
* 配置路径
* @param field
* 字段
* @throws IllegalArgumentException
*/
@Override
protected void setField(final String path, final Field field) throws IllegalArgumentException {
final String realPath = path.replace("_", ".");
if (config.isSet(realPath)) {
final Object value = config.get(realPath);
try {
if (!commonParse(config, realPath, field)) {
field.set(this, value);
}
} catch (final IllegalArgumentException ex) {
final Object[] obj = new Object[] { realPath, field.getType().getName(), value.getClass().getName() };
Log.log(Level.INFO, "配置节点 {0} 数据类型不匹配 应该为: {1} 但实际为: {2}!", obj);
} catch (final IllegalAccessException ex) {
Log.log(Level.SEVERE, "自动注入配置错误!", ex);
}
} else if (field.getAnnotation(Nullable.class) == null) {
Log.warning(String.format("配置节点 %s 丢失!", realPath));
}
inject(config);
}
}

View File

@ -21,8 +21,20 @@ public class PlayerConfig extends FileConfig {
* @param player
* 玩家
*/
public PlayerConfig(final File dir, final Player player) {
this(plugin.getDataFolder(), player.getName());
}
/**
* 获得玩家配置(保存在 指定 文件夹)
*
* @param plugin
* 插件
* @param playername
* 玩家名称
*/
public PlayerConfig(final File dir, final String playername) {
super(new File(dir, CONFIG_FOLDER + File.separatorChar + playername + ".yml"));
super(new File(dir, String.format("%s%s%s.yml", CONFIG_FOLDER, File.separatorChar, playername)));
}
/**
@ -46,6 +58,6 @@ public class PlayerConfig extends FileConfig {
* 玩家
*/
public PlayerConfig(final String playername) {
super(new File(plugin.getDataFolder(), CONFIG_FOLDER + File.separatorChar + playername + ".yml"));
this(plugin.getDataFolder(), playername);
}
}

View File

@ -8,11 +8,10 @@ import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import com.google.common.base.Charsets;
import pw.yumc.YumCore.bukkit.Log;
/**
* 远程配置文件类
@ -21,11 +20,13 @@ import com.google.common.base.Charsets;
* @author
*/
public class RemoteConfig extends FileConfig {
protected static String REMOTEFILECENTER = "http://data.yumc.pw/config/";
private static String fromYumc = "配置 %s 来自 YUMC 数据中心...";
private static String createError = "尝试从 YUMC 数据中心下载 %s 失败 部分功能可能无法使用...";
private static String updateError = "尝试从 YUMC 数据中心更新配置文件 %s 失败 部分数据可能已过时...";
private static final String PLUGINHELPER = "PluginHelper";
private static final String fromYumc = "配置 %s 来自 YUMC 数据中心...";
private static final String createError = "尝试从 YUMC 数据中心下载 %s 失败 部分功能可能无法使用...";
private static final String updateError = "尝试从 YUMC 数据中心更新配置文件 %s 失败 部分数据可能已过时...";
public RemoteConfig(final String filename) {
this(filename, REMOTEFILECENTER + filename);
@ -36,26 +37,26 @@ public class RemoteConfig extends FileConfig {
}
public RemoteConfig(final String filename, final String url, final boolean force) {
file = new File(Bukkit.getUpdateFolderFile().getParentFile(), PLUGINHELPER + File.separator + filename);
file = new File(plugin.getDataFolder().getParentFile(), PLUGINHELPER + File.separator + filename);
if (!file.exists()) {
try {
// 尝试从YUMC下载配置文件
Files.copy(new URL(url).openStream(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
loger.info(String.format(fromYumc, filename));
Log.info(String.format(fromYumc, filename));
} catch (final IOException e) {
loger.warning(String.format(createError, filename));
Log.warning(String.format(createError, filename));
}
} else {
final FileConfig oldcfg = new FileConfig(file);
final FileConfig newcfg = getFileConfig(url);
final String newver = newcfg.getString(CHECK_FIELD);
final String oldver = oldcfg.getString(CHECK_FIELD);
final String newver = newcfg.getString(VERSION);
final String oldver = oldcfg.getString(VERSION);
if (newver != null && !newver.equals(oldver)) {
try {
file.renameTo(new File(Bukkit.getUpdateFolderFile().getParentFile(), PLUGINHELPER + File.separator + getBakName(filename)));
file.renameTo(new File(plugin.getDataFolder().getParentFile(), PLUGINHELPER + File.separator + getBakName(filename)));
updateConfig(newcfg, oldcfg, force).save(file);
} catch (final IOException e) {
loger.warning(String.format(updateError, filename));
Log.warning(String.format(updateError, filename));
}
}
}
@ -72,7 +73,7 @@ public class RemoteConfig extends FileConfig {
public static FileConfig getFileConfig(final String url) {
final FileConfig config = new FileConfig();
try {
final BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream(), Charsets.UTF_8));
final BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream(), UTF_8));
config.load(br);
br.close();
} catch (final Exception e) {
@ -94,7 +95,7 @@ public class RemoteConfig extends FileConfig {
public static String getYamlTag(final String url, final String tag, final String def) {
String result = def;
try {
final BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream(), Charsets.UTF_8));
final BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream(), UTF_8));
final FileConfiguration config = YamlConfiguration.loadConfiguration(br);
br.close();
result = config.getString(tag);