[Lib] SuperEasyConfig v1.2 - Based off of codename_Bs awesome EasyConfig v2.1

Discussion in 'Resources' started by MrFigg, Sep 13, 2012.

Thread Status:
Not open for further replies.
  1. Offline

    MrFigg

    Hey people. I saw and really liked codename_Bs EasyConfig but I needed a bit more functionality, so I made this. Thought I'd share. Btw, the 'Super' in SuperEasyConfig doesn't mean this is any easier to use then codename_Bs EasyConfig, it just has a few more capabilities.

    The Classes:
    ConfigObject.java
    Code:JAVA
    1. import java.lang.reflect.Field;
    2. import java.lang.reflect.Modifier;
    3. import java.lang.reflect.ParameterizedType;
    4. import java.lang.reflect.Type;
    5. import java.util.ArrayList;
    6. import java.util.HashMap;
    7. import java.util.List;
    8. import java.util.Map;
    9. import java.util.Set;
    10.  
    11. import org.bukkit.Bukkit;
    12. import org.bukkit.Location;
    13. import org.bukkit.World;
    14. import org.bukkit.configuration.ConfigurationSection;
    15. import org.bukkit.util.Vector;
    16. import org.json.simple.JSONObject;
    17. import org.json.simple.parser.JSONParser;
    18.  
    19. /*
    20. * SuperEasyConfig - ConfigObject
    21. *
    22. * Based off of codename_Bs EasyConfig v2.1
    23. * which was inspired by md_5
    24. *
    25. * An even awesomer super-duper-lazy Config lib!
    26. *
    27. * This program is distributed in the hope that it will be useful,
    28. * but WITHOUT ANY WARRANTY; without even the implied warranty of
    29. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    30. *
    31. * @author MrFigg
    32. * @version 1.2
    33. */
    34.  
    35. public abstract class ConfigObject {
    36.  
    37. /*
    38.   * loading and saving
    39.   */
    40.  
    41. protected void onLoad(ConfigurationSection cs) throws Exception {
    42. for(Field field : getClass().getDeclaredFields()) {
    43. String path = field.getName().replaceAll("_", ".");
    44. if(doSkip(field)) {
    45. // Do nothing
    46. } else if(cs.isSet(path)) {
    47. field.set(this, loadObject(field, cs, path));
    48. } else {
    49. cs.set(path, saveObject(field.get(this), field, cs, path));
    50. }
    51. }
    52. }
    53.  
    54. protected void onSave(ConfigurationSection cs) throws Exception {
    55. for(Field field : getClass().getDeclaredFields()) {
    56. String path = field.getName().replaceAll("_", ".");
    57. if(doSkip(field)) {
    58. // Do nothing
    59. } else {
    60. cs.set(path, saveObject(field.get(this), field, cs, path));
    61. }
    62. }
    63. }
    64.  
    65. protected Object loadObject(Field field, ConfigurationSection cs, String path) throws Exception {
    66. return loadObject(field, cs, path, 0);
    67. }
    68.  
    69. protected Object saveObject(Object obj, Field field, ConfigurationSection cs, String path) throws Exception {
    70. return saveObject(obj, field, cs, path, 0);
    71. }
    72.  
    73. @SuppressWarnings("rawtypes")
    74. protected Object loadObject(Field field, ConfigurationSection cs, String path, int depth) throws Exception {
    75. Class clazz = getClassAtDepth(field.getGenericType(), depth);
    76. if(ConfigObject.class.isAssignableFrom(clazz)&&isConfigurationSection(cs.get(path))) {
    77. return getConfigObject(clazz, cs.getConfigurationSection(path));
    78. } else if(Location.class.isAssignableFrom(clazz)&&isJSON(cs.get(path))) {
    79. return getLocation((String) cs.get(path));
    80. } else if(Vector.class.isAssignableFrom(clazz)&&isJSON(cs.get(path))) {
    81. return getVector((String) cs.get(path));
    82. } else if(Map.class.isAssignableFrom(clazz)&&isConfigurationSection(cs.get(path))) {
    83. return getMap(field, cs.getConfigurationSection(path), path, depth);
    84. } else if(clazz.isEnum()&&isString(cs.get(path))) {
    85. return getEnum(clazz, (String) cs.get(path));
    86. } else if(List.class.isAssignableFrom(clazz)&&isConfigurationSection(cs.get(path))) {
    87. Class subClazz = getClassAtDepth(field.getGenericType(), depth+1);
    88. if(ConfigObject.class.isAssignableFrom(subClazz)||Location.class.isAssignableFrom(subClazz)||Vector.class.isAssignableFrom(subClazz)||Map.class.isAssignableFrom(subClazz)||List.class.isAssignableFrom(subClazz)||subClazz.isEnum()) {
    89. return getList(field, cs.getConfigurationSection(path), path, depth);
    90. } else {
    91. return cs.get(path);
    92. }
    93. } else {
    94. return cs.get(path);
    95. }
    96. }
    97.  
    98. @SuppressWarnings("rawtypes")
    99. protected Object saveObject(Object obj, Field field, ConfigurationSection cs, String path, int depth) throws Exception {
    100. Class clazz = getClassAtDepth(field.getGenericType(), depth);
    101. if(ConfigObject.class.isAssignableFrom(clazz)&&isConfigObject(obj)) {
    102. return getConfigObject((ConfigObject) obj, path, cs);
    103. } else if(Location.class.isAssignableFrom(clazz)&&isLocation(obj)) {
    104. return getLocation((Location) obj);
    105. } else if(Vector.class.isAssignableFrom(clazz)&&isVector(obj)) {
    106. return getVector((Vector) obj);
    107. } else if(Map.class.isAssignableFrom(clazz)&&isMap(obj)) {
    108. return getMap((Map) obj, field, cs, path, depth);
    109. } else if(clazz.isEnum()&&isEnum(clazz, obj)) {
    110. return getEnum((Enum) obj);
    111. } else if(List.class.isAssignableFrom(clazz)&&isList(obj)) {
    112. Class subClazz = getClassAtDepth(field.getGenericType(), depth+1);
    113. if(ConfigObject.class.isAssignableFrom(subClazz)||Location.class.isAssignableFrom(subClazz)||Vector.class.isAssignableFrom(subClazz)||Map.class.isAssignableFrom(subClazz)||List.class.isAssignableFrom(subClazz)||subClazz.isEnum()) {
    114. return getList((List) obj, field, cs, path, depth);
    115. } else {
    116. return obj;
    117. }
    118. } else {
    119. return obj;
    120. }
    121. }
    122.  
    123. /*
    124.   * class detection
    125.   */
    126.  
    127. @SuppressWarnings("rawtypes")
    128. protected Class getClassAtDepth(Type type, int depth) throws Exception {
    129. if(depth<=0) {
    130. String className = type.toString();
    131. if(className.length()>=6&&className.substring(0, 6).equalsIgnoreCase("class ")) {
    132. className = className.substring(6);
    133. }
    134. if(className.indexOf("<")>=0) {
    135. className = className.substring(0, className.indexOf("<"));
    136. }
    137. try {
    138. return Class.forName(className);
    139. } catch(ClassNotFoundException ex) {
    140. // ugly fix for primitive data types
    141. if(className.equalsIgnoreCase("byte")) return Byte.class;
    142. if(className.equalsIgnoreCase("short")) return Short.class;
    143. if(className.equalsIgnoreCase("int")) return Integer.class;
    144. if(className.equalsIgnoreCase("long")) return Long.class;
    145. if(className.equalsIgnoreCase("float")) return Float.class;
    146. if(className.equalsIgnoreCase("double")) return Double.class;
    147. if(className.equalsIgnoreCase("char")) return Character.class;
    148. if(className.equalsIgnoreCase("boolean")) return Boolean.class;
    149. throw ex;
    150. }
    151. }
    152. depth--;
    153. ParameterizedType pType = (ParameterizedType) type;
    154. Type[] typeArgs = pType.getActualTypeArguments();
    155. return getClassAtDepth(typeArgs[typeArgs.length-1], depth);
    156. }
    157.  
    158. protected boolean isString(Object obj) {
    159. if(obj instanceof String) {
    160. return true;
    161. }
    162. return false;
    163. }
    164.  
    165. protected boolean isConfigurationSection(Object o) {
    166. try {
    167. return (ConfigurationSection) o != null;
    168. } catch (Exception e) {
    169. return false;
    170. }
    171. }
    172.  
    173. protected boolean isJSON(Object obj) {
    174. try {
    175. if(obj instanceof String) {
    176. String str = (String) obj;
    177. if(str.startsWith("{")) {
    178. return new JSONParser().parse(str) != null;
    179. }
    180. }
    181. return false;
    182. } catch (Exception e) {
    183. return false;
    184. }
    185. }
    186.  
    187. protected boolean isConfigObject(Object obj) {
    188. try {
    189. return (ConfigObject) obj != null;
    190. } catch (Exception e) {
    191. return false;
    192. }
    193. }
    194.  
    195. protected boolean isLocation(Object obj) {
    196. try {
    197. return (Location) obj != null;
    198. } catch (Exception e) {
    199. return false;
    200. }
    201. }
    202.  
    203. protected boolean isVector(Object obj) {
    204. try {
    205. return (Vector) obj != null;
    206. } catch (Exception e) {
    207. return false;
    208. }
    209. }
    210.  
    211. @SuppressWarnings("rawtypes")
    212. protected boolean isMap(Object obj) {
    213. try {
    214. return (Map) obj != null;
    215. } catch (Exception e) {
    216. return false;
    217. }
    218. }
    219.  
    220. @SuppressWarnings("rawtypes")
    221. protected boolean isList(Object obj) {
    222. try {
    223. return (List) obj != null;
    224. } catch(Exception e) {
    225. return false;
    226. }
    227. }
    228.  
    229. @SuppressWarnings("rawtypes")
    230. protected boolean isEnum(Class clazz, Object obj) {
    231. if(!clazz.isEnum()) return false;
    232. for(Object constant : clazz.getEnumConstants()) {
    233. if(constant.equals(obj)) {
    234. return true;
    235. }
    236. }
    237. return false;
    238. }
    239.  
    240. /*
    241.   * loading conversion
    242.   */
    243.  
    244. @SuppressWarnings("rawtypes")
    245. protected ConfigObject getConfigObject(Class clazz, ConfigurationSection cs) throws Exception {
    246. ConfigObject obj = (ConfigObject) clazz.newInstance();
    247. obj.onLoad(cs);
    248. return obj;
    249. }
    250.  
    251. protected Location getLocation(String json) throws Exception {
    252. JSONObject data = (JSONObject) new JSONParser().parse(json);
    253. // world
    254. World world = Bukkit.getWorld((String) data.get("world"));
    255. // x, y, z
    256. double x = Double.parseDouble((String) data.get("x"));
    257. double y = Double.parseDouble((String) data.get("y"));
    258. double z = Double.parseDouble((String) data.get("z"));
    259. // pitch, yaw
    260. float pitch = Float.parseFloat((String) data.get("pitch"));
    261. float yaw = Float.parseFloat((String) data.get("yaw"));
    262. // generate Location
    263. Location loc = new Location(world, x, y, z);
    264. loc.setPitch(pitch);
    265. loc.setYaw(yaw);
    266. return loc;
    267. }
    268.  
    269. protected Vector getVector(String json) throws Exception {
    270. JSONObject data = (JSONObject) new JSONParser().parse(json);
    271. // x, y, z
    272. double x = Double.parseDouble((String) data.get("x"));
    273. double y = Double.parseDouble((String) data.get("y"));
    274. double z = Double.parseDouble((String) data.get("z"));
    275. // generate Vector
    276. return new Vector(x, y, z);
    277. }
    278.  
    279. @SuppressWarnings({ "rawtypes", "unchecked" })
    280. protected Map getMap(Field field, ConfigurationSection cs, String path, int depth) throws Exception {
    281. depth++;
    282. Set<String> keys = cs.getKeys(false);
    283. Map map = new HashMap();
    284. if(keys != null && keys.size() > 0) {
    285. for(String key : keys) {
    286. Object in = cs.get(key);
    287. in = loadObject(field, cs, key, depth);
    288. map.put(key, in);
    289. }
    290. }
    291. return map;
    292. }
    293.  
    294. @SuppressWarnings({ "rawtypes", "unchecked" })
    295. protected List getList(Field field, ConfigurationSection cs, String path, int depth) throws Exception {
    296. depth++;
    297. int listSize = cs.getKeys(false).size();
    298. String key = path;
    299. if(key.lastIndexOf(".")>=0) {
    300. key = key.substring(key.lastIndexOf("."));
    301. }
    302. List list = new ArrayList();
    303. if(listSize > 0) {
    304. int loaded = 0;
    305. int i = 0;
    306. while(loaded<listSize) {
    307. if(cs.isSet(key+i)) {
    308. Object in = cs.get(key+i);
    309. in = loadObject(field, cs, key+i, depth);
    310. list.add(in);
    311. loaded++;
    312. }
    313. i++;
    314. // ugly overflow guard... should only be needed if config was manually edited very badly
    315. if(i>(listSize*3)) loaded = listSize;
    316. }
    317. }
    318. return list;
    319. }
    320.  
    321. @SuppressWarnings("rawtypes")
    322. protected Enum getEnum(Class clazz, String string) throws Exception {
    323. if(!clazz.isEnum()) throw new Exception("Class "+clazz.getName()+" is not an enum.");
    324. for(Object constant : clazz.getEnumConstants()) {
    325. if(((Enum) constant).toString().equals(string)) {
    326. return (Enum) constant;
    327. }
    328. }
    329. throw new Exception("String "+string+" not a valid enum constant for "+clazz.getName());
    330. }
    331.  
    332. /*
    333.   * saving conversion
    334.   */
    335.  
    336. protected ConfigurationSection getConfigObject(ConfigObject obj, String path, ConfigurationSection cs) throws Exception {
    337. ConfigurationSection subCS = cs.createSection(path);
    338. obj.onSave(subCS);
    339. return subCS;
    340. }
    341.  
    342. protected String getLocation(Location loc) {
    343. String ret = "{";
    344. ret += "\"world\":\""+loc.getWorld().getName()+"\"";
    345. ret += ",\"x\":\""+loc.getX()+"\"";
    346. ret += ",\"y\":\""+loc.getY()+"\"";
    347. ret += ",\"z\":\""+loc.getZ()+"\"";
    348. ret += ",\"pitch\":\""+loc.getPitch()+"\"";
    349. ret += ",\"yaw\":\""+loc.getYaw()+"\"";
    350. ret += "}";
    351. if(!isJSON(ret)) return getLocationJSON(loc);
    352. try {
    353. getLocation(ret);
    354. } catch(Exception ex) {
    355. return getLocationJSON(loc);
    356. }
    357. return ret;
    358. }
    359.  
    360. @SuppressWarnings("unchecked")
    361. protected String getLocationJSON(Location loc) {
    362. JSONObject data = new JSONObject();
    363. // world
    364. data.put("world", loc.getWorld().getName());
    365. // x, y, z
    366. data.put("x", String.valueOf(loc.getX()));
    367. data.put("y", String.valueOf(loc.getY()));
    368. data.put("z", String.valueOf(loc.getZ()));
    369. // pitch, yaw
    370. data.put("pitch", String.valueOf(loc.getPitch()));
    371. data.put("yaw", String.valueOf(loc.getYaw()));
    372. return data.toJSONString();
    373. }
    374.  
    375. protected String getVector(Vector vec) {
    376. String ret = "{";
    377. ret += "\"x\":\""+vec.getX()+"\"";
    378. ret += ",\"y\":\""+vec.getY()+"\"";
    379. ret += ",\"z\":\""+vec.getZ()+"\"";
    380. ret += "}";
    381. if(!isJSON(ret)) return getVectorJSON(vec);
    382. try {
    383. getVector(ret);
    384. } catch(Exception ex) {
    385. return getVectorJSON(vec);
    386. }
    387. return ret;
    388. }
    389.  
    390. @SuppressWarnings("unchecked")
    391. protected String getVectorJSON(Vector vec) {
    392. JSONObject data = new JSONObject();
    393. // x, y, z
    394. data.put("x", String.valueOf(vec.getX()));
    395. data.put("y", String.valueOf(vec.getY()));
    396. data.put("z", String.valueOf(vec.getZ()));
    397. return data.toJSONString();
    398. }
    399.  
    400. @SuppressWarnings({ "rawtypes", "unchecked" })
    401. protected ConfigurationSection getMap(Map map, Field field, ConfigurationSection cs, String path, int depth) throws Exception {
    402. depth++;
    403. ConfigurationSection subCS = cs.createSection(path);
    404. Set<String> keys = map.keySet();
    405. if(keys != null && keys.size() > 0) {
    406. for(String key : keys) {
    407. Object out = map.get(key);
    408. out = saveObject(out, field, cs, path+"."+key, depth);
    409. subCS.set(key, out);
    410. }
    411. }
    412. return subCS;
    413. }
    414.  
    415. @SuppressWarnings("rawtypes")
    416. protected ConfigurationSection getList(List list, Field field, ConfigurationSection cs, String path, int depth) throws Exception {
    417. depth++;
    418. ConfigurationSection subCS = cs.createSection(path);
    419. String key = path;
    420. if(key.lastIndexOf(".")>=0) {
    421. key = key.substring(key.lastIndexOf("."));
    422. }
    423. if(list != null && list.size() > 0) {
    424. for(int i = 0; i < list.size(); i++) {
    425. Object out = list.get(i);
    426. out = saveObject(out, field, cs, path+"."+key+(i+1), depth);
    427. subCS.set(key+(i+1), out);
    428. }
    429. }
    430. return subCS;
    431. }
    432.  
    433. @SuppressWarnings("rawtypes")
    434. protected String getEnum(Enum enumObj) {
    435. return enumObj.toString();
    436. }
    437.  
    438. /*
    439.   * utility
    440.   */
    441.  
    442. protected boolean doSkip(Field field) {
    443. return Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()) || Modifier.isPrivate(field.getModifiers());
    444. }
    445. }
    Config.java
    Code:JAVA
    1. import java.io.BufferedWriter;
    2. import java.io.File;
    3. import java.io.FileWriter;
    4. import java.io.IOException;
    5. import java.io.Writer;
    6. import org.bukkit.configuration.InvalidConfigurationException;
    7. import org.bukkit.configuration.file.YamlConfiguration;
    8.  
    9. /*
    10. * SuperEasyConfig - Config
    11. *
    12. * Based off of codename_Bs EasyConfig v2.1
    13. * which was inspired by md_5
    14. *
    15. * An even awesomer super-duper-lazy Config lib!
    16. *
    17. * This program is distributed in the hope that it will be useful,
    18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
    19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    20. *
    21. * @author MrFigg
    22. * @version 1.2
    23. */
    24.  
    25. public abstract class Config extends ConfigObject {
    26. protected transient File CONFIG_FILE = null;
    27. protected transient String CONFIG_HEADER = null;
    28.  
    29. public Config() {
    30. CONFIG_HEADER = null;
    31. }
    32.  
    33. public Config load(File file) throws InvalidConfigurationException {
    34. if(file==null) throw new InvalidConfigurationException(new NullPointerException());
    35. if(!file.exists()) throw new InvalidConfigurationException(new IOException("File doesn't exist"));
    36. CONFIG_FILE = file;
    37. return reload();
    38. }
    39.  
    40. public Config reload() throws InvalidConfigurationException {
    41. if(CONFIG_FILE==null) throw new InvalidConfigurationException(new NullPointerException());
    42. if(!CONFIG_FILE.exists()) throw new InvalidConfigurationException(new IOException("File doesn't exist"));
    43. YamlConfiguration yamlConfig = YamlConfiguration.loadConfiguration(CONFIG_FILE);
    44. try {
    45. onLoad(yamlConfig);
    46. yamlConfig.save(CONFIG_FILE);
    47. } catch(Exception ex) {
    48. throw new InvalidConfigurationException(ex);
    49. }
    50. return this;
    51. }
    52.  
    53. public Config save(File file) throws InvalidConfigurationException {
    54. if(file==null) throw new InvalidConfigurationException(new NullPointerException());
    55. CONFIG_FILE = file;
    56. return save();
    57. }
    58.  
    59. public Config save() throws InvalidConfigurationException {
    60. if(CONFIG_FILE==null) throw new InvalidConfigurationException(new NullPointerException());
    61. if(!CONFIG_FILE.exists()) {
    62. try {
    63. if(CONFIG_FILE.getParentFile() != null) CONFIG_FILE.getParentFile().mkdirs();
    64. CONFIG_FILE.createNewFile();
    65. if(CONFIG_HEADER!=null) {
    66. Writer newConfig = new BufferedWriter(new FileWriter(CONFIG_FILE));
    67. for(String line : CONFIG_HEADER.split("\n")) {
    68. newConfig.write("# "+line+"\n");
    69. }
    70. newConfig.close();
    71. }
    72. } catch(Exception ex) {
    73. throw new InvalidConfigurationException(ex);
    74. }
    75. }
    76. YamlConfiguration yamlConfig = YamlConfiguration.loadConfiguration(CONFIG_FILE);
    77. try {
    78. onSave(yamlConfig);
    79. yamlConfig.save(CONFIG_FILE);
    80. } catch(Exception ex) {
    81. throw new InvalidConfigurationException(ex);
    82. }
    83. return this;
    84. }
    85.  
    86. public Config init(File file) throws InvalidConfigurationException {
    87. if(file==null) throw new InvalidConfigurationException(new NullPointerException());
    88. CONFIG_FILE = file;
    89. return init();
    90. }
    91.  
    92. public Config init() throws InvalidConfigurationException {
    93. if(CONFIG_FILE==null) throw new InvalidConfigurationException(new NullPointerException());
    94. if(CONFIG_FILE.exists()) return reload();
    95. else return save();
    96. }
    97. }



    Usage:
    First copy ConfigObject.java and Config.java to any package in your project. It doesn't really matter where, but I'd recommend creating a Config sub-package. Add a proper package declaration at the top of each file and they're good to go.

    Next you'll need to make your first config. Create a new class that extends Config. Add any fields you want the same way as the examples in the next post. For the rest of this post I'll be using the Basic Example below.

    Now it's finally time to use your config. This is harder to explain, so first I'll give you an example plugin;
    Code:JAVA
    1. public class ExamplePlugin extends JavaPlugin {
    2. public BasicExampleConfig config; // variable where we're going to store the config
    3.  
    4. @Override
    5. public void onEnable() {
    6. try {
    7. config = new BasicExampleConfig(this); // create config
    8. config.init(); // load config file if it exists, create it if it doesn't
    9. } catch(Exception ex) {
    10. getLogger().log(Level.SEVERE, "FAILED TO LOAD CONFIG!!!", ex);
    11. getServer().getPluginManager().disablePlugin(this);
    12. return;
    13. }
    14. }
    15.  
    16. @Override
    17. public void onDisable() {
    18. config.save(); // save the config
    19. }
    20.  
    21. @Override
    22. public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    23. sender.sendMessage("Example String: "+config.example_string);
    24. }
    25. }


    I'll expand on this later, but that should be enough to start with.
     
  2. Offline

    MrFigg

    Basic Example:
    BasicExampleConfig.java
    Code:JAVA
    1. public class BasicExampleConfig extends Config {
    2.  
    3. public BasicExampleConfig(Plugin plugin) {
    4. CONFIG_FILE = new File(plugin.getDataFolder(), "config.yml");
    5. CONFIG_HEADER = "Basic Example Configuration File";
    6. }
    7.  
    8. public String example_string = "Example";
    9. public Vector example_vector = new Vector(5, 65, 5);
    10. public boolean example_boolean = true;
    11. }

    Code:
    # Basic Example Configuration File
     
    example:
      string: Example
      vector: '{"x":"5.0","y":"65.0","z":"5.0"}'
      boolean: true

    Advanced Example:
    ExampleConfig.java
    Code:JAVA
    1. public class ExampleConfig extends Config {
    2.  
    3. public ExampleConfig(Plugin plugin) {
    4. CONFIG_FILE = new File(plugin.getDataFolder(), "config.yml");
    5. CONFIG_HEADER = "Example Configuration File";
    6. CONFIG_HEADER += "\n\nOhhh look more than one line!";
    7.  
    8. HashMap<String, String> subMapOne = new HashMap<String, String>();
    9. subMapOne.put("akey1", "avalue1");
    10. subMapOne.put("akey2", "avalue2");
    11. example_nestedmap.put("map1", subMapOne);
    12.  
    13. HashMap<String, String> subMapTwo = new HashMap<String, String>();
    14. subMapTwo.put("bkey1", "bvalue1");
    15. subMapTwo.put("bkey2", "bvalue2");
    16. example_nestedmap.put("map2", subMapTwo);
    17. }
    18.  
    19. public String example_string = "Example";
    20. public Vector example_vector = new Vector(5, 65, 5);
    21. public HashMap<String, HashMap<String, String>> example_nestedmap = new HashMap<String, HashMap<String, String>>();
    22. public ArrayList<Team> example_teams = new ArrayList<Team>(){{add(new Team("Red")); add(new Team("Blue")); add(new Team("Green"));}};
    23. public ArrayList<Material> example_banned = new ArrayList<Material>(){{add(Material.BEDROCK); add(Material.WEB);}};
    24. }
    Team.java
    Code:JAVA
    1. public class Team extends ConfigObject {
    2.  
    3. public Team(String name) {
    4. this.name = name;
    5. }
    6.  
    7. public String name = null;
    8. public ArrayList<String> members = new ArrayList<String>();
    9. public int secretsfound = 0;
    10. }

    Code:
    # Example Configuration File
    #
    # Ohhh look more than one line!
     
    example:
      string: Example
      vector: '{"x":"5.0","y":"65.0","z":"5.0"}'
      nestedmap:
        map2:
          bkey1: bvalue1
          bkey2: bvalue2
        map1:
          akey2: avalue2
          akey1: avalue1
      teams:
        teams1:
          name: Red
          members: []
          secretsfound: 0
        teams2:
          name: Blue
          members: []
          secretsfound: 0
        teams3:
          name: Green
          members: []
          secretsfound: 0
      banned:
        banned1: BEDROCK
        banned2: WEB
     
    bigbeno37, Skyost and bobacadodl like this.
  3. Offline

    drampelt

    Hello, I am I having some difficulty with HashMaps.
    In my Configuration class I have
    Code:
    public HashMap<String, ConfigPlayer> players = new HashMap<String, ConfigPlayer>();
    
    The ConfigPlayer class is similar to your Team example, containing a String and a Boolean.
    It saves to the config file perfectly, however when loading it the HashMap is empty (other configuration values load fine). I'm probably doing something wrong, any help would be appreciated.
     
  4. Offline

    MrFigg

    drampelt Nope, it was a bug left from when I first converted codename_Bs EasyConfig and I missed something. Updated the first post to v1.2.
     
  5. Offline

    Icyene

    For the collections you should use double brace initialization. Its cleaner like that. Example:

    Code:Java
    1.  
    2. List<String> blah =newArrayList<String>(){{add("asdfa");add("bbb");}};
    3.  
     
  6. Offline

    MrFigg

    Thanks, didn't know about those. Added it to the ArrayLists in the advanced example, but left the HashMaps alone just to show both work.
     
  7. Offline

    Icyene

  8. Offline

    AstramG

    How would I use this, like making it so that my plugin only works in certain worlds defined in the config?
     
  9. Offline

    MrFigg

    AstramG It's pretty simple. Follow the guide in the first post and when you get to adding fields to your config add something like this;
    Code:
    public ArrayList<String> worlds = new ArrayList<String>(){{add(Bukkit.getWorlds().get(0).getName());}};
    Then when you need to check if a worlds is allowed just use something like this;
    Code:
    World world = // Get world from somewhere
    if(config.worlds.contains(world.getName())) {
        // World is allowed!
    } else {
        // World is not allowed!
    }
    Even though that didn't really have anything to do with SuperEasyConfig and was more a basic plugin question, I hope this helps.
     
  10. Offline

    fireball1725

    Hello MrFigg,
    I am hoping you might be able to help me with a slight problem I am getting.

    I created a configuration file that looks like this:

    Code:
    public class SignConfig extends Config {
        public SignConfig(Plugin plugin) {
            CONFIG_FILE = new File(plugin.getDataFolder(), "signs.yml");
        }
     
        public ArrayList<SignDetails> signs = new ArrayList<SignDetails>(){{ }};
    and created a class for SignDetails that looks like this
    Code:
    public class SignDetails extends ConfigObject{
    public SignDetails(String name) {
    this.name = name;
    }
     
    public String name = null;
    public Location location = null;
    }
    It works fine when loading, creates the yml file, and even works ok when I add objects to this file

    Here is my YML
    Code:
    signs:
      signs1:
        name: test
        location: '{"world":"world","x":"10.0","y":"66.0","z":"-11.0","pitch":"0.0","yaw":"0.0"}'
    However, when the server restarts I am getting an error that i cannot figure out

    Code:
    java.lang.InstantiationException: net.craftminecraft.bukkit.minearcadesuite.config.SignDetails
    17:57:21 [INFO] net.craftminecraft.bukkit.minearcadesuite.config.Config.reload(Config.java:50)
    17:57:21 [INFO] net.craftminecraft.bukkit.minearcadesuite.config.Config.init(Config.java:96)
    17:57:21 [INFO] net.craftminecraft.bukkit.minearcadesuite.MineArcadeSuite.loadConfig(MineArcadeSuite.java:34)
    17:57:21 [INFO] net.craftminecraft.bukkit.minearcadesuite.MineArcadeSuite.onEnable(MineArcadeSuite.java:27)
    17:57:21 [INFO] org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:217)
    17:57:21 [INFO] org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:457)
    17:57:21 [INFO] org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:381)
    17:57:21 [INFO] org.bukkit.craftbukkit.v1_5_R2.CraftServer.loadPlugin(CraftServer.java:282)
    17:57:21 [INFO] org.bukkit.craftbukkit.v1_5_R2.CraftServer.enablePlugins(CraftServer.java:264)
    17:57:21 [INFO] net.minecraft.server.v1_5_R2.MinecraftServer.j(MinecraftServer.java:301)
    17:57:21 [INFO] net.minecraft.server.v1_5_R2.MinecraftServer.e(MinecraftServer.java:280)
    17:57:21 [INFO] net.minecraft.server.v1_5_R2.MinecraftServer.a(MinecraftServer.java:240)
    17:57:21 [INFO] net.minecraft.server.v1_5_R2.DedicatedServer.init(DedicatedServer.java:150)
    17:57:21 [INFO] net.minecraft.server.v1_5_R2.MinecraftServer.run(MinecraftServer.java:379)
    17:57:21 [INFO] net.minecraft.server.v1_5_R2.ThreadServerApplication.run(SourceFile:573)
    
    Any help you might be able to provide with this error would be great.
    Thanks,
    FireBall
     
  11. Hello MrFrigg,
    I have provided some enhancements to your SuperEasyConfig as to make it support Guava Library's collections. https://gist.github.com/roblabla/5345274.
    Feel free to take it and use it.
     
  12. Offline

    Skyost

    Love it so much <3
     
  13. Offline

    Ultimate_n00b

    Oh my god, this is amazing. If only I had found this sooner.. I guess I'll have to use it on a different project.
     
  14. Offline

    JPG2000

    fireball1725 I know this was posted awhile ago, but if you update the post, could you more clearly state how to use it? Thanks!
     
  15. Offline

    Ultimate_n00b

    You make variables, and set them to values. A level (like when using a normal config you would do LevelOne.LevelTwo) is defined using a _. So if I had a variable:

    Code:
    String Something_To_Set = "A Word!";
    inside my class, it would put in the config:

    Code:
    Something:
      To:
        Set: A Word!
     
  16. Offline

    SacredWaste

    This is a really nice way for configuration, I was just wondering one thing though. I defined my configuration in my main plugin file, and I did what you shown to do. The only issue, is that I am trying to access it from another class in the same project, and I can't access it. Any ideas?
     
  17. Offline

    viper_monster

  18. Offline

    SacredWaste

Thread Status:
Not open for further replies.

Share This Page