[TUT] Custom YAML configurations with comments

Discussion in 'Resources' started by Log-out, Apr 20, 2013.

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

    Log-out

    Hello everyone. I was working on my plugin when I worked out that i need to create few configuration files and write to them. I had to add comments dynamically, but it isn't possible with Bukkit FileConfiguration. So i made this simple "cheat" that will allow you to use FileConfiguration and multiple comments and headers.

    SimpleConfigManager.java - basic methods for configurations

    Code:JAVA
    1. import java.io.BufferedReader;
    2. import java.io.BufferedReader;
    3. import java.io.BufferedWriter;
    4. import java.io.ByteArrayInputStream;
    5. import java.io.File;
    6. import java.io.FileOutputStream;
    7. import java.io.FileReader;
    8. import java.io.FileWriter;
    9. import java.io.IOException;
    10. import java.io.InputStream;
    11. import java.io.OutputStream;
    12. import java.nio.charset.Charset;
    13.  
    14. import org.bukkit.plugin.java.JavaPlugin;
    15.  
    16. public class SimpleConfigManager {
    17.  
    18. private JavaPlugin plugin;
    19.  
    20. /*
    21.   * Manage custom configurations and files
    22.   */
    23. public SimpleConfigManager(JavaPlugin plugin) {
    24. this.plugin = plugin;
    25. }
    26.  
    27. /*
    28.   * Get new configuration with header
    29.   * @param filePath - Path to file
    30.   * @return - New SimpleConfig
    31.   */
    32. public SimpleConfig getNewConfig(String filePath, String[] header) {
    33.  
    34. File file = this.getConfigFile(filePath);
    35.  
    36. if(!file.exists()) {
    37. this.prepareFile(filePath);
    38.  
    39. if(header != null && header.length != 0) {
    40. this.setHeader(file, header);
    41. }
    42.  
    43. }
    44.  
    45. SimpleConfig config = new SimpleConfig(this.getConfigContent(filePath), file, this.getCommentsNum(file), plugin);
    46. return config;
    47.  
    48. }
    49.  
    50. /*
    51.   * Get new configuration
    52.   * @param filePath - Path to file
    53.   * @return - New SimpleConfig
    54.   */
    55. public SimpleConfig getNewConfig(String filePath) {
    56. return this.getNewConfig(filePath, null);
    57. }
    58.  
    59. /*
    60.   * Get configuration file from string
    61.   * @param file - File path
    62.   * @return - New file object
    63.   */
    64. private File getConfigFile(String file) {
    65.  
    66. if(file.isEmpty() || file == null) {
    67. return null;
    68. }
    69.  
    70. File configFile;
    71.  
    72. if(file.contains("/")) {
    73.  
    74. if(file.startsWith("/")) {
    75. configFile = new File(plugin.getDataFolder() + file.replace("/", File.separator));
    76. } else {
    77. configFile = new File(plugin.getDataFolder() + File.separator + file.replace("/", File.separator));
    78. }
    79.  
    80. } else {
    81. configFile = new File(plugin.getDataFolder(), file);
    82. }
    83.  
    84. return configFile;
    85.  
    86. }
    87.  
    88. /*
    89.   * Create new file for config and copy resource into it
    90.   * @param file - Path to file
    91.   * @param resource - Resource to copy
    92.   */
    93. public void prepareFile(String filePath, String resource) {
    94.  
    95. File file = this.getConfigFile(filePath);
    96.  
    97. if(file.exists()) {
    98. return;
    99. }
    100.  
    101. try {
    102. file.getParentFile().mkdirs();
    103. file.createNewFile();
    104.  
    105. if(!resource.isEmpty() && resource != null) {
    106. this.copyResource(plugin.getResource(resource), file);
    107. }
    108.  
    109. } catch (IOException e) {
    110. e.printStackTrace();
    111. }
    112.  
    113. }
    114.  
    115. /*
    116.   * Create new file for config without resource
    117.   * @param file - File to create
    118.   */
    119. public void prepareFile(String filePath) {
    120. this.prepareFile(filePath, null);
    121. }
    122.  
    123. /*
    124.   * Adds header block to config
    125.   * @param file - Config file
    126.   * @param header - Header lines
    127.   */
    128. public void setHeader(File file, String[] header) {
    129.  
    130. if(!file.exists()) {
    131. return;
    132. }
    133.  
    134. try {
    135. String currentLine;
    136. StringBuilder config = new StringBuilder("");
    137. BufferedReader reader = new BufferedReader(new FileReader(file));
    138.  
    139. while((currentLine = reader.readLine()) != null) {
    140. config.append(currentLine + "\n");
    141. }
    142.  
    143. reader.close();
    144. config.append("# +----------------------------------------------------+ #\n");
    145.  
    146. for(String line : header) {
    147.  
    148. if(line.length() > 50) {
    149. continue;
    150. }
    151.  
    152. int lenght = (50 - line.length()) / 2;
    153. StringBuilder finalLine = new StringBuilder(line);
    154.  
    155. for(int i = 0; i < lenght; i++) {
    156. finalLine.append(" ");
    157. finalLine.reverse();
    158. finalLine.append(" ");
    159. finalLine.reverse();
    160. }
    161.  
    162. if(line.length() % 2 != 0) {
    163. finalLine.append(" ");
    164. }
    165.  
    166. config.append("# < " + finalLine.toString() + " > #\n");
    167.  
    168. }
    169.  
    170. config.append("# +----------------------------------------------------+ #");
    171.  
    172. BufferedWriter writer = new BufferedWriter(new FileWriter(file));
    173. writer.write(this.prepareConfigString(config.toString()));
    174. writer.flush();
    175. writer.close();
    176.  
    177. } catch (IOException e) {
    178. e.printStackTrace();
    179. }
    180.  
    181. }
    182.  
    183. /*
    184.   * Read file and make comments SnakeYAML friendly
    185.   * @param filePath - Path to file
    186.   * @return - File as Input Stream
    187.   */
    188. public InputStream getConfigContent(File file) {
    189.  
    190. if(!file.exists()) {
    191. return null;
    192. }
    193.  
    194. try {
    195. int commentNum = 0;
    196.  
    197. String addLine;
    198. String currentLine;
    199. String pluginName = this.getPluginName();
    200.  
    201. StringBuilder whole = new StringBuilder("");
    202. BufferedReader reader = new BufferedReader(new FileReader(file));
    203.  
    204. while((currentLine = reader.readLine()) != null) {
    205.  
    206. if(currentLine.startsWith("#")) {
    207. addLine = currentLine.replaceFirst("#", pluginName + "_COMMENT_" + commentNum + ":");
    208. whole.append(addLine + "\n");
    209. commentNum++;
    210.  
    211. } else {
    212. whole.append(currentLine + "\n");
    213. }
    214.  
    215. }
    216.  
    217. String config = whole.toString();
    218. InputStream configStream = new ByteArrayInputStream(config.getBytes(Charset.forName("UTF-8")));
    219.  
    220. reader.close();
    221. return configStream;
    222.  
    223. } catch (IOException e) {
    224. e.printStackTrace();
    225. return null;
    226. }
    227.  
    228. }
    229.  
    230. /*
    231.   * Get comments from file
    232.   * @param file - File
    233.   * @return - Comments number
    234.   */
    235. private int getCommentsNum(File file) {
    236.  
    237. if(!file.exists()) {
    238. return 0;
    239. }
    240.  
    241. try {
    242. int comments = 0;
    243. String currentLine;
    244.  
    245. BufferedReader reader = new BufferedReader(new FileReader(file));
    246.  
    247. while((currentLine = reader.readLine()) != null) {
    248.  
    249. if(currentLine.startsWith("#")) {
    250. comments++;
    251. }
    252.  
    253. }
    254.  
    255. reader.close();
    256. return comments;
    257.  
    258. } catch (IOException e) {
    259. e.printStackTrace();
    260. return 0;
    261. }
    262.  
    263. }
    264.  
    265. /*
    266.   * Get config content from file
    267.   * @param filePath - Path to file
    268.   * @return - readied file
    269.   */
    270. public InputStream getConfigContent(String filePath) {
    271. return this.getConfigContent(this.getConfigFile(filePath));
    272. }
    273.  
    274.  
    275. private String prepareConfigString(String configString) {
    276.  
    277. int lastLine = 0;
    278. int headerLine = 0;
    279.  
    280. String[] lines = configString.split("\n");
    281. StringBuilder config = new StringBuilder("");
    282.  
    283. for(String line : lines) {
    284.  
    285. if(line.startsWith(this.getPluginName() + "_COMMENT")) {
    286. String comment = "#" + line.trim().substring(line.indexOf(":") + 1);
    287.  
    288. if(comment.startsWith("# +-")) {
    289.  
    290. /*
    291.   * If header line = 0 then it is
    292.   * header start, if it's equal
    293.   * to 1 it's the end of header
    294.   */
    295.  
    296. if(headerLine == 0) {
    297. config.append(comment + "\n");
    298.  
    299. lastLine = 0;
    300. headerLine = 1;
    301.  
    302. } else if(headerLine == 1) {
    303. config.append(comment + "\n\n");
    304.  
    305. lastLine = 0;
    306. headerLine = 0;
    307.  
    308. }
    309.  
    310. } else {
    311.  
    312. /*
    313.   * Last line = 0 - Comment
    314.   * Last line = 1 - Normal path
    315.   */
    316.  
    317. String normalComment;
    318.  
    319. if(comment.startsWith("# ' ")) {
    320. normalComment = comment.substring(0, comment.length() - 1).replaceFirst("# ' ", "# ");
    321. } else {
    322. normalComment = comment;
    323. }
    324.  
    325. if(lastLine == 0) {
    326. config.append(normalComment + "\n");
    327. } else if(lastLine == 1) {
    328. config.append("\n" + normalComment + "\n");
    329. }
    330.  
    331. lastLine = 0;
    332.  
    333. }
    334.  
    335. } else {
    336. config.append(line + "\n");
    337. lastLine = 1;
    338. }
    339.  
    340. }
    341.  
    342. return config.toString();
    343.  
    344. }
    345.  
    346.  
    347. /*
    348.   * Saves configuration to file
    349.   * @param configString - Config string
    350.   * @param file - Config file
    351.   */
    352. public void saveConfig(String configString, File file) {
    353. String configuration = this.prepareConfigString(configString);
    354.  
    355. try {
    356. BufferedWriter writer = new BufferedWriter(new FileWriter(file));
    357. writer.write(configuration);
    358. writer.flush();
    359. writer.close();
    360.  
    361. } catch (IOException e) {
    362. e.printStackTrace();
    363. }
    364.  
    365. }
    366.  
    367. public String getPluginName() {
    368. return plugin.getDescription().getName();
    369. }
    370.  
    371. /*
    372.   * Copy resource from Input Stream to file
    373.   * @param resource - Resource from .jar
    374.   * @param file - File to write
    375.   */
    376. private void copyResource(InputStream resource, File file) {
    377.  
    378. try {
    379. OutputStream out = new FileOutputStream(file);
    380.  
    381. int lenght;
    382. byte[] buf = new byte[1024];
    383.  
    384. while((lenght = resource.read(buf)) > 0){
    385. out.write(buf, 0, lenght);
    386. }
    387.  
    388. out.close();
    389. resource.close();
    390.  
    391. } catch (Exception e) {
    392. e.printStackTrace();
    393. }
    394.  
    395. }
    396.  
    397. }


    SimpleConfig.java - class that corresponds for configuration
    Code:JAVA
    1. import java.io.File;
    2. import java.io.InputStream;
    3. import java.util.List;
    4. import java.util.Set;
    5.  
    6. import org.bukkit.configuration.ConfigurationSection;
    7. import org.bukkit.configuration.file.FileConfiguration;
    8. import org.bukkit.configuration.file.YamlConfiguration;
    9. import org.bukkit.plugin.java.JavaPlugin;
    10.  
    11. public class SimpleConfig {
    12. private int comments;
    13. private SimpleConfigManager manager;
    14.  
    15. private File file;
    16. private FileConfiguration config;
    17.  
    18. public SimpleConfig(InputStream configStream, File configFile, int comments, JavaPlugin plugin) {
    19. this.comments = comments;
    20. this.manager = new SimpleConfigManager(plugin);
    21.  
    22. this.file = configFile;
    23. this.config = YamlConfiguration.loadConfiguration(configStream);
    24. }
    25.  
    26. public Object get(String path) {
    27. return this.config.get(path);
    28. }
    29.  
    30. public Object get(String path, Object def) {
    31. return this.config.get(path, def);
    32. }
    33.  
    34. public String getString(String path) {
    35. return this.config.getString(path);
    36. }
    37.  
    38. public String getString(String path, String def) {
    39. return this.config.getString(path, def);
    40. }
    41.  
    42. public int getInt(String path) {
    43. return this.config.getInt(path);
    44. }
    45.  
    46. public int getInt(String path, int def) {
    47. return this.config.getInt(path, def);
    48. }
    49.  
    50. public boolean getBoolean(String path) {
    51. return this.config.getBoolean(path);
    52. }
    53.  
    54. public boolean getBoolean(String path, boolean def) {
    55. return this.config.getBoolean(path, def);
    56. }
    57.  
    58. public void createSection(String path) {
    59. this.config.createSection(path);
    60. }
    61.  
    62. public ConfigurationSection getConfigurationSection(String path) {
    63. return this.config.getConfigurationSection(path);
    64. }
    65.  
    66. public double getDouble(String path) {
    67. return this.config.getDouble(path);
    68. }
    69.  
    70. public double getDouble(String path, double def) {
    71. return this.config.getDouble(path, def);
    72. }
    73.  
    74. public List<?> getList(String path) {
    75. return this.config.getList(path);
    76. }
    77.  
    78. public List<?> getList(String path, List<?> def) {
    79. return this.config.getList(path, def);
    80. }
    81.  
    82. public boolean contains(String path) {
    83. return this.config.contains(path);
    84. }
    85.  
    86. public void removeKey(String path) {
    87. this.config.set(path, null);
    88. }
    89.  
    90. public void set(String path, Object value) {
    91. this.config.set(path, value);
    92. }
    93.  
    94. public void set(String path, Object value, String comment) {
    95. if(!this.config.contains(path)) {
    96. this.config.set(manager.getPluginName() + "_COMMENT_" + comments, " " + comment);
    97. comments++;
    98. }
    99.  
    100. this.config.set(path, value);
    101.  
    102. }
    103.  
    104. public void set(String path, Object value, String[] comment) {
    105.  
    106. for(String comm : comment) {
    107.  
    108. if(!this.config.contains(path)) {
    109. this.config.set(manager.getPluginName() + "_COMMENT_" + comments, " " + comm);
    110. comments++;
    111. }
    112.  
    113. }
    114.  
    115. this.config.set(path, value);
    116.  
    117. }
    118.  
    119. public void setHeader(String[] header) {
    120. manager.setHeader(this.file, header);
    121. this.comments = header.length + 2;
    122. this.reloadConfig();
    123. }
    124.  
    125. public void reloadConfig() {
    126. this.config = YamlConfiguration.loadConfiguration(manager.getConfigContent(file));
    127. }
    128.  
    129. public void saveConfig() {
    130. String config = this.config.saveToString();
    131. manager.saveConfig(config, this.file);
    132.  
    133. }
    134.  
    135. public Set<String> getKeys() {
    136. return this.config.getKeys(false);
    137. }
    138.  
    139. }

    Now when we have our two classes we can start ! Here is a small example:
    Code:JAVA
    1. import org.bukkit.plugin.java.JavaPlugin;
    2.  
    3. public class CLASS_NAME extends JavaPlugin {
    4.  
    5. public SimpleConfigManager manager;
    6.  
    7. public SimpleConfig config;
    8. public SimpleConfig messages;
    9.  
    10. public void onDisable() {
    11.  
    12. }
    13.  
    14. public void onEnable() {
    15.  
    16. String[] comments = {"Multiple lines", "Of nice comments", "Are supported !"};
    17. String[] header = {"This is super simple", "And highly customizable", "new and fresh SimpleConfig !"};
    18.  
    19. this.manager = new SimpleConfigManager(this);
    20.  
    21. this.config = manager.getNewConfig("config.yml", header);
    22. this.messages = manager.getNewConfig("misc/messages.yml");
    23.  
    24. this.config.set("path1", "value1", comments);
    25. this.config.set("path2", "value2", "This is second comment !");
    26. this.config.saveConfig();
    27.  
    28. }
    29.  
    30. }

    Code from above will give us 2 files - one in folder misc (messages.yml, it's empty) and second in main plugin directory - config.yml - which will look like this :
    Code:
    # +----------------------------------------------------+
    # <                This is super simple                >
    # <              And highly customizable               >
    # <            new and fresh SimpleConfig !            >
    # +----------------------------------------------------+
    
    # Multiple lines
    # Of nice comments
    # Are supported !
    path1: value1
    
    # This is second comment !
    path2: value2
    And that's it ! I hope you'll find this useful. You can add as many methods in SimpleConfig as you wish, no limits. If you use this code in your plugin I'll be really happy if you give me a credit. I'm sorry for my English but I'm from Poland so please forgive my any mistakes. This is my first tutorial so if you find any errors please tell me and i'll fix them :)
     
  2. Super, że jest wsparcie dla komentarzy ;)
    Thx :D
     
  3. Offline

    ziimzy

    Hi got this error!

    Code:
     Error occurred while enabling PotionEffects v1.0 (Is it up to date?)
    java.lang.NullPointerException
        at me.Ziimzy.youtube.SimpleConfigManager.prepareFile(SimpleConfigManager.java:106)
        at me.Ziimzy.youtube.SimpleConfigManager.prepareFile(SimpleConfigManager.java:121)
        at me.Ziimzy.youtube.SimpleConfigManager.getNewConfig(SimpleConfigManager.java:38)
        at me.Ziimzy.youtube.PotionEffectsMain.onEnable(PotionEffectsMain.java:41)
        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:217)
        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:457)
        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:381)
        at org.bukkit.craftbukkit.v1_5_R3.CraftServer.loadPlugin(CraftServer.java:282)
        at org.bukkit.craftbukkit.v1_5_R3.CraftServer.enablePlugins(CraftServer.java:264)
        at org.bukkit.craftbukkit.v1_5_R3.CraftServer.reload(CraftServer.java:605)
        at org.bukkit.Bukkit.reload(Bukkit.java:185)
        at org.bukkit.command.defaults.ReloadCommand.execute(ReloadCommand.java:23)
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:189)
        at org.bukkit.craftbukkit.v1_5_R3.CraftServer.dispatchCommand(CraftServer.java:523)
        at org.bukkit.craftbukkit.v1_5_R3.CraftServer.dispatchServerCommand(CraftServer.java:512)
        at net.minecraft.server.v1_5_R3.DedicatedServer.an(DedicatedServer.java:262)
        at net.minecraft.server.v1_5_R3.DedicatedServer.r(DedicatedServer.java:227)
        at net.minecraft.server.v1_5_R3.MinecraftServer.q(MinecraftServer.java:477)
        at net.minecraft.server.v1_5_R3.MinecraftServer.run(MinecraftServer.java:410)
        at net.minecraft.server.v1_5_R3.ThreadServerApplication.run(SourceFile:573)
     
  4. Offline

    Log-out

    ziimzy Paste your main class
     
  5. Offline

    ziimzy

    heres my main:
    Code:
    package me.Ziimzy.youtube;
     
    import java.util.logging.Logger;
     
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.PluginDescriptionFile;
    import org.bukkit.plugin.java.JavaPlugin;
    import org.bukkit.potion.PotionEffect;
    import org.bukkit.potion.PotionEffectType;
     
     
    public class PotionEffectsMain extends JavaPlugin {
       
    public final Logger logger = Logger.getLogger("Minecraft");
       
        public static PotionEffectsMain plugin;
       
        public SimpleConfigManager manager;
       
        public SimpleConfig config;
        public SimpleConfig messages;
       
        @Override
        public void onDisable() {
            PluginDescriptionFile pdfFile = this.getDescription();
            this.logger.info(pdfFile.getName() + " has been Disabled.");
        }
       
       
        @Override
        public void onEnable() {
            String[] comments = {"Multiple lines", "Of nice comments", "Are supported !"};
            String[] header = {"This is super simple", "And highly customizable", "new and fresh SimpleConfig !"};
     
            this.manager = new SimpleConfigManager(this);
     
            this.config = manager.getNewConfig("config.yml", header);
            this.messages = manager.getNewConfig("misc/messages.yml");
     
            this.config.set("path1", "value1", comments);
            this.config.set("path2", "value2", "This is second comment !");
            this.config.saveConfig();
            PluginDescriptionFile pdfFile = this.getDescription();
            this.logger.info(pdfFile.getName() + " Version" + pdfFile.getVersion() + " has been Enabled.");
            Bukkit.getServer().getPluginManager().registerEvents(new PotionEffectsListener(this), this);
           
        }
       
     
        public boolean onCommand(final CommandSender sender, Command cmd, String commandLabel, String[] args){
           
            if (cmd.getName().equalsIgnoreCase("potionlist")){
                if(sender.hasPermission("potioneffect.list")){
                if(args.length == 0){
                sender.sendMessage("PotionEffects List Pg 1");
                }
                if(args.length == 1){
                    if(args[0].equalsIgnoreCase("1")){
                        sender.sendMessage("PotionEffects List Pg 1");
                        }
                    if(args[0].equalsIgnoreCase("2")){
                    sender.sendMessage("PotionEffects List Pg 2");
                    }
                    if(args[0].equalsIgnoreCase("3")){
                        sender.sendMessage("PotionEffects List Pg 3");
                        }
                    if(args[0].equalsIgnoreCase("4")){
                        sender.sendMessage("PotionEffects List Pg 4");
                        }
                    if(args[0].equalsIgnoreCase("5")){
                        sender.sendMessage("PotionEffects List Pg 5");
                        }else{
                        return false;
                    }
                }
                }
            }
           
            if (cmd.getName().equalsIgnoreCase("potioneffect") || cmd.getName().equalsIgnoreCase("potione"))
            {
                if (!(sender instanceof Player))
                {
                    if (args.length != 4)
                    {
                        sender.sendMessage("Console usage: /"+cmd.getName()+" <username> <potioneffect> <timeinticks> <level>");
                    } else {
                        Integer potiontime;
                        Integer potionlevel;
                        Player target = Bukkit.getServer().getPlayer(args[0]);
                        try{
                        potiontime = Integer.parseInt(args[2]);
                        potionlevel = Integer.parseInt(args[3]);
                        target.addPotionEffect(new PotionEffect(PotionEffectType.getByName(args[1]), potiontime*20, potionlevel));
                        sender.sendMessage("Gave " + args[0]+" a " + args[1] + " potion effect for " + args[2] + " at a level of " + args[3] + "!");
                    } catch (Exception e) {
                        target.sendMessage(ChatColor.DARK_RED + "Level and time must me numbers. /"+cmd.getName()+" <username> <potioneffect> <seconds> <level>");
                    }
                    }
     
                   
                }
                if (sender instanceof Player)
                {
                    if(sender.hasPermission("potioneffect.maincommand")){
                    if (args.length != 4)
                    {
                        sender.sendMessage(ChatColor.DARK_RED + "Usage: /"+cmd.getName()+" <username> <potioneffect> <seconds> <level>");
                    } else {
                        Integer potiontime;
                        Integer potionlevel;
                        try{
                        potiontime = Integer.parseInt(args[2]);
                        potionlevel = Integer.parseInt(args[3]);
                        if (Bukkit.getServer().getPlayer(args[0]) != null) {
                            Player target = Bukkit.getServer().getPlayer(args[0]);
                                String senderofcmd = ((Player)sender).getName();
                                String targetusername = target.getName();
                                target.addPotionEffect(new PotionEffect(PotionEffectType.getByName(args[1]), potiontime*20, potionlevel));
                                if(this.getConfig().getBoolean("message.reciever") == true && this.getConfig().getBoolean("message.sendername") == true){
                                    target.sendMessage(ChatColor.GREEN + "You got a potion effect of " + args[1] + " Lvl "+ args[3] + " for " + args[2] + " seconds from " + senderofcmd);
                                }else if(this.getConfig().getBoolean("message.reciever") == true){
                                    target.sendMessage(ChatColor.GREEN + "You got a potion effect of " + args[1] + " Lvl "+ args[3] + " for " + args[2] + " seconds!");
                                }
                                if(this.getConfig().getBoolean("message.sender") == true){
                                    sender.sendMessage(ChatColor.GREEN + "You gave a potion effect of " + args[1] + " Lvl "+ args[3] + " to " + targetusername + " for " + args[2] + " seconds!");
                                }
     
                            } else {
                                sender.sendMessage(ChatColor.DARK_RED + "Player not found!");
                            }
                    } catch (Exception e) {
                        Player target = Bukkit.getServer().getPlayer(args[0]);
                        if (Bukkit.getServer().getPlayer(args[0]) != null) {
                        target.sendMessage(ChatColor.DARK_RED + "The level and time must me integers.");
                        target.sendMessage(ChatColor.DARK_RED + "The potion name may be wrong! Type " + ChatColor.LIGHT_PURPLE + "/potionlist  " + ChatColor.DARK_RED + "for help.");
                    }else{
                        sender.sendMessage(ChatColor.DARK_RED + "Player not found! And your doing it wrong!");
                    }
                    }
                    }
     
                }else {
                    sender.sendMessage(ChatColor.RED +" You don't have permission to do that!");
                }
                }
            }
            return false;
        }
       
    }
    
    and the line that gets errors:

    38: this.prepareFile(filePath);
    106: if(!resource.isEmpty() && resource != null) {
    121: this.prepareFile(filePath, null);

    and in potioneffectmain its:

    41: this.config = manager.getNewConfig("config.yml", header);

    hope this helps. hanks so much btw if this works it is amazing!
     
  6. Offline

    beastman3226

    Beautiful work of configuration editting.

    Changing out all my outdated an non-functioning code and replacing it with yours immediately.
     
  7. I am having the same problem as Ziimzy, I have not modified any of your code, but I get the same error as provided by Ziimzy. I tried both 1.5.2-R1.0 Craftbukkit and 1.6.2-R0.1. I would really like to see a solution to this as your method would be awesome to use!

    Okay, so I went through your code, and there was a simple fix:

    In SimpleConfigManager, at line 105, you should be checking for isn't null before isn't empty, as if it is null, checking for isn't null causes a NullPointerException.

    Code:JAVA
    1. if(resource != null && !resource.isEmpty()) {
    2. this.copyResource(plugin.getResource(resource), file);
    3. }


    Now the next problem, I'll have a go at looking for a solution for, but I'll describe it so others can help too (I would like it solved as soon as possible and I am not the best suited for debugging someone's code given my lack of experience so far in making plug-ins).

    Okay, so the problem is that all comments are formatted thusly:

    Code:
    Natives Vs:
      ' Pioneers_COMMENT_0': +----------------------------------------------------+
      ' Pioneers_COMMENT_1': <                This is super simple                >
      ' Pioneers_COMMENT_2': <              And highly customizable              >
      ' Pioneers_COMMENT_3': <            new and fresh SimpleConfig !            >
      ' Pioneers_COMMENT_4': +----------------------------------------------------+
      ' Pioneers_COMMENT_5': ' Multiple lines'
      ' Pioneers_COMMENT_6': ' Of nice comments'
      ' Pioneers_COMMENT_7': ' Are supported !'
      ' Pioneers_COMMENT_8': ' This is second comment !'
    path1: value1
    path2: value2
    
    Rather than it looking as you have shown in the original post.

    Okay, so I know this post will make a triple post, but I thought I might as well, considering how much it has helped me in the last however long since the last post:

    I have added a few features to SimpleConfig that I consider absolutely necessary. Now I did cheat; I used already existing resources within the Bukkit MemorySection(.java), however I feel it was justified as these functions now serve all custom Yaml files. I have only added all the variable specific list functions, however, I think it is only fair that I provide it and save other people the hassle (if you use lists often the getList() available in SimpleConfig is a bit of a pain). So without further ado, the rather useful but not so incredible (on my part in the way of contribution) code (incorporated into the SimpleConfig class already provided, hopefully to lessen hassle even further):

    Code:JAVA
    1. import java.io.File;
    2. import java.io.InputStream;
    3. import java.util.ArrayList;
    4. import java.util.List;
    5. import java.util.Map;
    6. import java.util.Set;
    7.  
    8. import org.bukkit.configuration.ConfigurationSection;
    9. import org.bukkit.configuration.file.FileConfiguration;
    10. import org.bukkit.configuration.file.YamlConfiguration;
    11. import com.github.samthepsychoticleprechaun.NativesVsPioneers.NativesVsPioneers;
    12.  
    13. public class SimpleConfig {
    14. private int comments;
    15. private SimpleConfigManager manager;
    16.  
    17. private File file;
    18. private FileConfiguration config;
    19.  
    20. public SimpleConfig(InputStream configStream, File configFile, int comments, NativesVsPioneers plugin) {
    21. this.comments = comments;
    22. this.manager = new SimpleConfigManager(plugin);
    23.  
    24. this.file = configFile;
    25. this.config = YamlConfiguration.loadConfiguration(configStream);
    26. }
    27.  
    28. public Object get(String path) {
    29. return this.config.get(path);
    30. }
    31.  
    32. public Object get(String path, Object def) {
    33. return this.config.get(path, def);
    34. }
    35.  
    36. public String getString(String path) {
    37. return this.config.getString(path);
    38. }
    39.  
    40. public String getString(String path, String def) {
    41. return this.config.getString(path, def);
    42. }
    43.  
    44. public int getInt(String path) {
    45. return this.config.getInt(path);
    46. }
    47.  
    48. public int getInt(String path, int def) {
    49. return this.config.getInt(path, def);
    50. }
    51.  
    52. public boolean getBoolean(String path) {
    53. return this.config.getBoolean(path);
    54. }
    55.  
    56. public boolean getBoolean(String path, boolean def) {
    57. return this.config.getBoolean(path, def);
    58. }
    59.  
    60. public void createSection(String path) {
    61. this.config.createSection(path);
    62. }
    63.  
    64. public ConfigurationSection getConfigurationSection(String path) {
    65. return this.config.getConfigurationSection(path);
    66. }
    67.  
    68. public double getDouble(String path) {
    69. return this.config.getDouble(path);
    70. }
    71.  
    72. public double getDouble(String path, double def) {
    73. return this.config.getDouble(path, def);
    74. }
    75.  
    76. public List<?> getList(String path) {
    77. return this.config.getList(path);
    78. }
    79.  
    80. public List<?> getList(String path, List<?> def) {
    81. return this.config.getList(path, def);
    82. }
    83.  
    84. public List<String> getStringList(String path) {
    85.  
    86. List<?> list = getList(path);
    87.  
    88. if (list == null) {
    89.  
    90. return new ArrayList<String>(0);
    91.  
    92. }
    93.  
    94. List<String> result = new ArrayList<String>();
    95.  
    96. for (Object object : list) {
    97.  
    98. if ((object instanceof String) || (isPrimitiveWrapper(object))) {
    99.  
    100. result.add(String.valueOf(object));
    101. }
    102.  
    103. }
    104.  
    105. return result;
    106.  
    107. }
    108.  
    109. public List<Integer> getIntegerList(String path) {
    110.  
    111. List<?> list = getList(path);
    112.  
    113. if (list == null) {
    114.  
    115. return new ArrayList<Integer>(0);
    116.  
    117. }
    118.  
    119. List<Integer> result = new ArrayList<Integer>();
    120.  
    121. for (Object object : list) {
    122.  
    123. if (object instanceof Integer) {
    124.  
    125. result.add((Integer) object);
    126.  
    127. } else if (object instanceof String) {
    128.  
    129. try {
    130.  
    131. result.add(Integer.valueOf((String) object));
    132.  
    133. } catch (Exception ex) {
    134.  
    135. }
    136.  
    137. } else if (object instanceof Character) {
    138.  
    139. result.add((int) ((Character) object).charValue());
    140.  
    141. } else if (object instanceof Number) {
    142.  
    143. result.add(((Number) object).intValue());
    144.  
    145. }
    146.  
    147. }
    148.  
    149. return result;
    150.  
    151. }
    152.  
    153. public List<Boolean> getBooleanList(String path) {
    154.  
    155. List<?> list = getList(path);
    156.  
    157. if (list == null) {
    158.  
    159. return new ArrayList<Boolean>(0);
    160.  
    161. }
    162.  
    163.  
    164. List<Boolean> result = new ArrayList<Boolean>();
    165.  
    166. for (Object object : list) {
    167.  
    168. if (object instanceof Boolean) {
    169.  
    170. result.add((Boolean) object);
    171.  
    172. } else if (object instanceof String) {
    173.  
    174. if (Boolean.TRUE.toString().equals(object)) {
    175.  
    176. result.add(true);
    177.  
    178. } else if (Boolean.FALSE.toString().equals(object)) {
    179.  
    180. result.add(false);
    181.  
    182. }
    183.  
    184. }
    185.  
    186. }
    187.  
    188. return result;
    189.  
    190. }
    191.  
    192.  
    193. public List<Double> getDoubleList(String path) {
    194.  
    195. List<?> list = getList(path);
    196.  
    197.  
    198. if (list == null) {
    199.  
    200. return new ArrayList<Double>(0);
    201.  
    202. }
    203.  
    204. List<Double> result = new ArrayList<Double>();
    205.  
    206. for (Object object : list) {
    207.  
    208. if (object instanceof Double) {
    209.  
    210. result.add((Double) object);
    211.  
    212. } else if (object instanceof String) {
    213.  
    214. try {
    215.  
    216. result.add(Double.valueOf((String) object));
    217.  
    218. } catch (Exception ex) {
    219.  
    220. }
    221.  
    222. } else if (object instanceof Character) {
    223.  
    224. result.add((double) ((Character) object).charValue());
    225.  
    226. } else if (object instanceof Number) {
    227.  
    228. result.add(((Number) object).doubleValue());
    229.  
    230. }
    231.  
    232. }
    233.  
    234. return result;
    235.  
    236. }
    237.  
    238. public List<Float> getFloatList(String path) {
    239.  
    240. List<?> list = getList(path);
    241.  
    242. if (list == null) {
    243.  
    244. return new ArrayList<Float>(0);
    245.  
    246. }
    247.  
    248. List<Float> result = new ArrayList<Float>();
    249.  
    250. for (Object object : list) {
    251.  
    252. if (object instanceof Float) {
    253.  
    254.  
    255. result.add((Float) object);
    256.  
    257. } else if (object instanceof String) {
    258.  
    259. try {
    260.  
    261. result.add(Float.valueOf((String) object));
    262.  
    263. } catch (Exception ex) {
    264.  
    265. }
    266.  
    267. } else if (object instanceof Character) {
    268.  
    269. result.add((float) ((Character) object).charValue());
    270.  
    271. } else if (object instanceof Number) {
    272.  
    273. result.add(((Number) object).floatValue());
    274.  
    275. }
    276.  
    277. }
    278.  
    279. return result;
    280.  
    281. }
    282.  
    283. public List<Long> getLongList(String path) {
    284.  
    285. List<?> list = getList(path);
    286.  
    287. if (list == null) {
    288.  
    289. return new ArrayList<Long>(0);
    290.  
    291. }
    292.  
    293. List<Long> result = new ArrayList<Long>();
    294.  
    295. for (Object object : list) {
    296.  
    297. if (object instanceof Long) {
    298.  
    299. result.add((Long) object);
    300.  
    301. } else if (object instanceof String) {
    302.  
    303. try {
    304.  
    305. result.add(Long.valueOf((String) object));
    306.  
    307. } catch (Exception ex) {
    308.  
    309. }
    310.  
    311. } else if (object instanceof Character) {
    312.  
    313. result.add((long) ((Character) object).charValue());
    314.  
    315. } else if (object instanceof Number) {
    316.  
    317. result.add(((Number) object).longValue());
    318.  
    319. }
    320.  
    321. }
    322.  
    323. return result;
    324.  
    325. }
    326.  
    327. public List<Byte> getByteList(String path) {
    328.  
    329. List<?> list = getList(path);
    330.  
    331. if (list == null) {
    332.  
    333. return new ArrayList<Byte>(0);
    334.  
    335. }
    336.  
    337. List<Byte> result = new ArrayList<Byte>();
    338.  
    339. for (Object object : list) {
    340.  
    341. if (object instanceof Byte) {
    342.  
    343. result.add((Byte) object);
    344.  
    345. } else if (object instanceof String) {
    346.  
    347. try {
    348.  
    349. result.add(Byte.valueOf((String) object));
    350.  
    351. } catch (Exception ex) {
    352.  
    353. }
    354.  
    355. } else if (object instanceof Character) {
    356.  
    357. result.add((byte) ((Character) object).charValue());
    358.  
    359. } else if (object instanceof Number) {
    360.  
    361. result.add(((Number) object).byteValue());
    362.  
    363. }
    364.  
    365. }
    366.  
    367. return result;
    368.  
    369. }
    370.  
    371. public List<Character> getCharacterList(String path) {
    372.  
    373. List<?> list = getList(path);
    374.  
    375. if (list == null) {
    376.  
    377. return new ArrayList<Character>(0);
    378.  
    379. }
    380.  
    381. List<Character> result = new ArrayList<Character>();
    382.  
    383. for (Object object : list) {
    384.  
    385. if (object instanceof Character) {
    386.  
    387.  
    388. result.add((Character) object);
    389.  
    390. } else if (object instanceof String) {
    391.  
    392. String str = (String) object;
    393.  
    394.  
    395. if (str.length() == 1) {
    396.  
    397. result.add(str.charAt(0));
    398.  
    399. }
    400.  
    401. } else if (object instanceof Number) {
    402.  
    403. result.add((char) ((Number) object).intValue());
    404.  
    405. }
    406.  
    407. }
    408.  
    409. return result;
    410.  
    411. }
    412.  
    413. public List<Short> getShortList(String path) {
    414.  
    415. List<?> list = getList(path);
    416.  
    417. if (list == null) {
    418.  
    419. return new ArrayList<Short>(0);
    420.  
    421. }
    422.  
    423. List<Short> result = new ArrayList<Short>();
    424.  
    425. for (Object object : list) {
    426.  
    427. if (object instanceof Short) {
    428.  
    429. result.add((Short) object);
    430.  
    431. } else if (object instanceof String) {
    432.  
    433. try {
    434.  
    435. result.add(Short.valueOf((String) object));
    436.  
    437. } catch (Exception ex) {
    438.  
    439. }
    440.  
    441. } else if (object instanceof Character) {
    442.  
    443. result.add((short) ((Character) object).charValue());
    444.  
    445. } else if (object instanceof Number) {
    446.  
    447. result.add(((Number) object).shortValue());
    448.  
    449. }
    450.  
    451. }
    452.  
    453. return result;
    454.  
    455. }
    456.  
    457. public List<Map<?, ?>> getMapList(String path) {
    458.  
    459. List<?> list = getList(path);
    460.  
    461. List<Map<?, ?>> result = new ArrayList<Map<?, ?>>();
    462.  
    463. if (list == null) {
    464.  
    465. return result;
    466.  
    467. }
    468.  
    469. for (Object object : list) {
    470.  
    471. if (object instanceof Map) {
    472.  
    473. result.add((Map<?, ?>) object);
    474.  
    475. }
    476.  
    477. }
    478.  
    479. return result;
    480.  
    481. }
    482.  
    483.  
    484.  
    485. public boolean contains(String path) {
    486. return this.config.contains(path);
    487. }
    488.  
    489. public void removeKey(String path) {
    490. this.config.set(path, null);
    491. }
    492.  
    493. public void set(String path, Object value) {
    494. this.config.set(path, value);
    495. }
    496.  
    497. public void set(String path, Object value, String comment) {
    498. if(!this.config.contains(path)) {
    499. this.config.set(manager.getPluginName() + "_COMMENT_" + comments, " " + comment);
    500. comments++;
    501. }
    502.  
    503. this.config.set(path, value);
    504.  
    505. }
    506.  
    507. public void set(String path, Object value, String[] comment) {
    508.  
    509. for(String comm : comment) {
    510.  
    511. if(!this.config.contains(path)) {
    512. this.config.set(manager.getPluginName() + "_COMMENT_" + comments, " " + comm);
    513. comments++;
    514. }
    515.  
    516. }
    517.  
    518. this.config.set(path, value);
    519.  
    520. }
    521.  
    522. public void setHeader(String[] header) {
    523. manager.setHeader(this.file, header);
    524. this.comments = header.length + 2;
    525. this.reloadConfig();
    526. }
    527.  
    528. public void reloadConfig() {
    529. this.config = YamlConfiguration.loadConfiguration(manager.getConfigContent(file));
    530. }
    531.  
    532. public void saveConfig() {
    533. String config = this.config.saveToString();
    534. manager.saveConfig(config, this.file);
    535.  
    536. }
    537.  
    538. public Set<String> getKeys() {
    539. return this.config.getKeys(false);
    540. }
    541.  
    542. protected boolean isPrimitiveWrapper(Object input) {
    543.  
    544. return input instanceof Integer || input instanceof Boolean ||
    545. input instanceof Character || input instanceof Byte ||
    546. input instanceof Short || input instanceof Double ||
    547. input instanceof Long || input instanceof Float;
    548.  
    549. }
    550.  
    551. }


    Edit: Okay so formatting isn't great, but I have no idea how (or if) that is a resolvable issue.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 1, 2016
  8. Offline

    ToastHelmi

    what is when i have a path like

    Zombie.test

    and i want the commend only above "zombie" and than one above "tes"
     
  9. So, you want something like this:

    Code:
    //Comment Here
    Zombie:
      //Comment Here
      test:
    If so, as of right now, I personally cannot get comments to work in the system provided by Log-out as I have the problems that I stated in one of the above posts I made.

    However, should the issue I mentioned be resolved, I don't know whether what you ask is possible but I guess you could try something like:

    Code:JAVA
    1. this.config.set("Zombie", "value1", <Comments Above Zombie>);
    2. this.config.set("Zombie.test", "Actual Value", <Comments Above Test>);


    With the presumption that by adding a further path to Zombie, "Value1" will be overwritten.
     
  10. Offline

    Gopaintman

    Well I noticed with this is that, every-time the plugin initializes, the configs are overwritten. Anyways to have this not happen?
     
  11. Offline

    IDragonfire

  12. Gopaintman The configs need not be overwritten if you do it right, and using saveConfig() does not remove anything added in a previous server run as the data is collected and put into your SimpleConfig instance when you load the file (creating the file if it does not exist) and unless you remove or add bits, when you saveConfig() on the instance it will not edit any information in the file.

    Example:
    Code:JAVA
    1. List<String> list = factionData.getStringList("Faction_List");
    2. if(list == null) {
    3. factionData.set("Faction_List", "<empty>");
    4. factionData.saveConfig();
    5. }
    6. list = playerData.getStringList("Player_List");
    7. if(list == null) {
    8. playerData.set("Player_List", "<empty>");
    9. playerData.saveConfig();
    10. }
    11. list = companyData.getStringList("Company_List");
    12. if(list == null) {
    13. companyData.set("Company_List", "<empty>");
    14. companyData.saveConfig();
    15. }


    I run this whenever a my plug-in I'm working on starts up. This checks to make sure that the files have got a necessary list path for my plug-in, if the list is null (i.e. path doesn't exist) then it will create the necessary path. This does not overwrite the list, however, when I use saveConfig() at any point in my plug-in.

    Edit: Perhaps you are just referring to the example provided by Log-out? If so, that is a basic example of what this can do, and is not really the way that you should create and add paths to a file.
     
  13. Offline

    Log-out

    First off I'm really sorry that I haven't answered your question (Thanks to SamThePsychoticLeprechaun for doing it for me). I've been working at few big projects and haven't got time for plugin development and somethin less funny - my PC broke down. If everything will go fine, i'll have new PC about week from now and I'll start writing this tutorial / library from scratch. Hope you'll still use it :)
     
  14. Offline

    eveninglight

    Code:
    [SEVERE] Error occurred while enabling Customlogin vB2.0.0 (Is it up to date?)
    java.lang.NullPointerException
        at com.webs.lexucraft.Customlogin.config.YAMLConfigManager.getConfigFile(YAMLConfigManager.java:85)
        at com.webs.lexucraft.Customlogin.config.YAMLConfigManager.getNewConfig(YAMLConfigManager.java:32)
        at com.webs.lexucraft.Customlogin.config.Configurations.createSettings(Configurations.java:26)
        at com.webs.lexucraft.Customlogin.Customlogin.onEnable(Customlogin.java:28)
        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:217)
        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:457)
        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:381)
        at org.bukkit.craftbukkit.v1_6_R2.CraftServer.loadPlugin(CraftServer.java:282)
        at org.bukkit.craftbukkit.v1_6_R2.CraftServer.enablePlugins(CraftServer.java:264)
        at net.minecraft.server.v1_6_R2.MinecraftServer.l(MinecraftServer.java:313)
        at net.minecraft.server.v1_6_R2.MinecraftServer.f(MinecraftServer.java:290)
        at net.minecraft.server.v1_6_R2.MinecraftServer.a(MinecraftServer.java:250)
        at net.minecraft.server.v1_6_R2.DedicatedServer.init(DedicatedServer.java:151)
        at net.minecraft.server.v1_6_R2.MinecraftServer.run(MinecraftServer.java:391)
        at net.minecraft.server.v1_6_R2.ThreadServerApplication.run(SourceFile:582)
     
  15. eveninglight You can't just give an error message and expect help. You must give a message describing your plight, and provide the classes and methods referenced by the error message you have provided.

    To determine which classes you need to post, look at the error message, where the package is yours (i.e. com.webs.lexucraft.Customlogin.*****) you can determine the class (i.e. YAMLConfigManager) and even further the method that is the issue and the line of the method (i.e. getConfigFile at line 85 of YAMLConfigManager.java).

    In this case as you are calling getFileConfig for the NullPointerException (as called by getNewConfig) it suggests to me that the String filepath that you are passing to getNewConfig is null, you should check for it and have your code print something if the filePath parameter is being passed with a value of null.
     
  16. Offline

    xxNightlordx

    Nice. This will definitely be useful for future plugin :)
     
  17. Offline

    Solivero

    Thanks a lot for this. I was just about to give up getting comments in to my config, but this sure did the trick. :D
     
  18. Hey man, out of interest, are you still looking to revise the code for this? I would love to make use of your comment system, it has so much potential!
     
  19. Offline

    NoChanceSD

    I know this is kind of old... but i just started using it recently. Everything seems to work except that when comments are to long(i guess that's why) they get split into 2 lines, but the second line doesn't have an "#" and some letters disappear. Anyone had this problem or knows how to fix it?
     
  20. Offline

    DrMedia

    instead of the comment being {"This is a really super super super super super super long comment"}, put {"This is a really super", "super super super super super long comment"}
     
  21. Offline

    NoChanceSD

    DrMedia Thanks, but i know that, it's just that it's not really that long and i don't see any reason for it not to work in the code. Maybe it's some limitation on YamlConfiguration?
     
  22. Offline

    DrMedia

  23. Offline

    Joserex65

    But this code resets the config on every plugin startup. How can I solve this?
     
Thread Status:
Not open for further replies.

Share This Page