ChestShop-3/com/Acrobot/Breeze/Configuration/Configuration.java

89 lines
2.7 KiB
Java
Raw Normal View History

2012-11-23 20:59:12 +01:00
package com.Acrobot.Breeze.Configuration;
2012-11-23 21:00:35 +01:00
import org.bukkit.ChatColor;
2012-11-23 20:59:12 +01:00
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
2013-01-24 22:35:28 +01:00
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
2012-11-23 20:59:12 +01:00
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
2012-11-23 21:00:35 +01:00
* A class which can be used to make configs easier to load
*
2012-11-23 20:59:12 +01:00
* @author Acrobot
*/
public class Configuration {
2012-11-23 21:00:35 +01:00
/**
* Loads a YAML-formatted file into a class and modifies the file if some of class's fields are missing
*
* @param file File to load
* @param clazz Class to modify
*/
public static void pairFileAndClass(File file, Class clazz) {
2012-11-23 20:59:12 +01:00
FileConfiguration config = YamlConfiguration.loadConfiguration(file);
try {
2012-11-23 21:00:35 +01:00
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
2012-11-23 20:59:12 +01:00
for (Field field : clazz.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers()) || !Modifier.isPublic(field.getModifiers())) {
2012-11-23 20:59:12 +01:00
continue;
}
String path = field.getName();
try {
2012-11-23 21:00:35 +01:00
if (path.toLowerCase().replace("_", "").startsWith("newline")) {
continue;
}
2012-11-23 20:59:12 +01:00
if (config.isSet(path)) {
2012-11-23 21:00:35 +01:00
field.set(null, ValueParser.parseToJava(config.get(path)));
2012-11-23 20:59:12 +01:00
} else {
2012-11-23 21:00:35 +01:00
writer.write('\n' + FieldParser.parse(field));
if (clazz.getDeclaredField("NEWLINE_" + path) != null) {
writer.write('\n');
}
2012-11-23 20:59:12 +01:00
}
2012-11-23 21:00:35 +01:00
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
continue;
2012-11-23 20:59:12 +01:00
}
}
2012-11-23 21:00:35 +01:00
writer.close();
2012-11-23 20:59:12 +01:00
} catch (IOException e) {
e.printStackTrace();
}
}
2012-11-23 21:00:35 +01:00
/**
* Converts a java value to config-compatible value
*
* @param value Value to parse
* @return Parsed output
*/
public static String parseToConfig(Object value) {
return ValueParser.parseToYAML(value);
2012-11-23 20:59:12 +01:00
}
2012-11-23 21:00:35 +01:00
/**
* Colourises a string (using '&' character)
2012-11-29 20:28:16 +01:00
*
2012-11-23 21:00:35 +01:00
* @param string String to colourise
* @return Colourised string
*/
public static String getColoured(String string) {
return ChatColor.translateAlternateColorCodes('&', string);
2012-11-23 20:59:12 +01:00
}
}