[TUT] Bukkit's new FileConfiguration API! Create a YAML configuration!

Discussion in 'Resources' started by Windwaker, Oct 23, 2011.

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

    herghost

    How do I get the values from the config file in a different class?
     
  2. Offline

    Windwaker

    Code:java
    1. plugin.getConfig().getString(path);


    Of course there's more then just getString();
     
  3. Offline

    herghost

    Thanks WalkerCrouse

    Still havin issues though, plugin cannot be resolved? I have tried just getConfig() but no method.

    Code:
    package me.herghost.Fiery.functions;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    public class sqlFunctions {
       
         private String getString(String m) {
                return getString(m);
            }
    
            String user = plugin.getConfig().getString("settings.mysql.user");
            String pass = plugin.getConfig().getString("settings.mysql.pass");
            String url = "jdbc:mysql://localhost:3306/Fiery";
        //}
     
        public void create_table_users() throws SQLException
        {
            Connection conn = DriverManager.getConnection(url, user, pass);
            PreparedStatement sampleQueryStatement = conn.prepareStatement("CREATE TABLE IF NOT EXISTS users (p_id int NOT NULL AUTO_INCREMENT KEY, p_name varchar(255), p_ip varchar(255))");
            sampleQueryStatement.executeUpdate();
            sampleQueryStatement.close();
            conn.close();
        }
      
        public void create_table_userhomes() throws SQLException
        {
            Connection conn = DriverManager.getConnection(url, user, pass);
            PreparedStatement sampleQueryStatement = conn.prepareStatement("CREATE TABLE IF NOT EXISTS userhomes (world varchar(128), p_name varchar(255) not null, home_x varchar(500), home_y varchar(500), home_z varchar(500), world1 varchar(128), home1_x varchar(500), home1_y varchar(500), home1_z varchar(500), world2 varchar(128), home2_x varchar(500), home2_y varchar(500), home2_z varchar(500), primary key(p_name))");
            sampleQueryStatement.executeUpdate();
            sampleQueryStatement.close();
            conn.close();
        }
         
    }
    
     
  4. Offline

    Windwaker

    Declare a private instance of your plugin...
    Code:java
    1. private MyPlugin plugin;
     
  5. Offline

    herghost

    Null pointer exceptions :( I think the issue is that I am using enjikaka s code, not the one in the thread title. I will swap to that and see if it works. Thanks for your time :)

    Ok still having issues :(

    Console:

    Code:
    2011-11-20 23:30:37 [SEVERE] Error occurred while enabling Fiery v0.1 (Is it up to date?): null
    java.lang.NullPointerException
        at me.herghost.Fiery.functions.sqlFunctions.<init>(sqlFunctions.java:17)
        at me.herghost.Fiery.Fiery.onEnable(Fiery.java:48)
        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:183)
        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:957)
        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:280)
        at org.bukkit.craftbukkit.CraftServer.loadPlugin(CraftServer.java:176)
        at org.bukkit.craftbukkit.CraftServer.enablePlugins(CraftServer.java:159)
        at net.minecraft.server.MinecraftServer.t(MinecraftServer.java:337)
        at net.minecraft.server.MinecraftServer.a(MinecraftServer.java:324)
        at net.minecraft.server.MinecraftServer.init(MinecraftServer.java:161)
        at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:388)
        at net.minecraft.server.ThreadServerApplication.run(SourceFile:457)
    My main class
    Code:
    package me.herghost.Fiery;
    
    import java.sql.SQLException;
    import java.util.logging.Logger;
    
    import me.herghost.Fiery.commands.banCommand;
    import me.herghost.Fiery.commands.giveCommand;
    import me.herghost.Fiery.commands.homeCommand;
    import me.herghost.Fiery.commands.itemCommand;
    import me.herghost.Fiery.commands.kickCommand;
    import me.herghost.Fiery.commands.sethomeCommand;
    import me.herghost.Fiery.commands.spawnCommand;
    import me.herghost.Fiery.commands.unbanCommand;
    import me.herghost.Fiery.functions.sqlFunctions;
    
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.event.Event;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public class Fiery extends JavaPlugin {
    	Logger log = Logger.getLogger("Minecraft");
    
    	//The Listener
    	private final FieryPlayerListener playerListener = new FieryPlayerListener(this);	
    	//Config File
    	FileConfiguration config;
    	//OnEnable Methods
    	public void onEnable(){
    		//Send Message to Console
    		log.info("Fiery Plugin Enabled - Beta");
    		//Initialize config file
    		loadConfiguration();
    		//Create Tables
    		try
    			{
    			    sqlFunctions method = new sqlFunctions();
    	        	method.create_table_users();
    	        	method.create_table_userhomes();
    	        	log.info("Fiery Database Tables OK!");
    			}
    		catch
    			(SQLException e1)
    				{
    					log.info("Something Fucked Up");
    					e1.printStackTrace();
    	        	}
    		//register commands
    		this.getCommand("item").setExecutor(new itemCommand());
    		this.getCommand("give").setExecutor(new giveCommand());
    		this.getCommand("kick").setExecutor(new kickCommand());
    		this.getCommand("spawn").setExecutor(new spawnCommand());
    		this.getCommand("ban").setExecutor(new banCommand());
    		this.getCommand("unban").setExecutor(new unbanCommand());
    		this.getCommand("sethome").setExecutor(new sethomeCommand());
    		this.getCommand("home").setExecutor(new homeCommand());
    		//register listeners
    		PluginManager pm = this.getServer().getPluginManager();
    		pm.registerEvent(Event.Type.PLAYER_JOIN,playerListener, Event.Priority.Normal, this);
    	}
    	public void onDisable(){
    		log.info("Fiery Plugin Disabled - Goodbye!");
    	}
    	public void loadConfiguration()
    	{
    		getConfig().addDefault("settings.mysql.user", "mysql username");
    		getConfig().addDefault("settings.mysql.pass", "mysql password");
    		getConfig().options().copyDefaults(true);
            saveConfig();
        }
    
    }
    
    and finally, how I am trying to get the strings for the mysql data

    Code:
    package me.herghost.Fiery.functions;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    import me.herghost.Fiery.Fiery;
    
    
    
    public class sqlFunctions {
    	private Fiery plugin;
    	 String user = plugin.getConfig().getString("settings.mysql.user");
         String pass = plugin.getConfig().getString("settings.mysql.pass");
    	 String url = "jdbc:mysql://localhost:3306/Fiery";
    	public void create_table_users() throws SQLException
    	{
    		Connection conn = DriverManager.getConnection(url, user, pass);
    		PreparedStatement sampleQueryStatement = conn.prepareStatement("CREATE TABLE IF NOT EXISTS users (p_id int NOT NULL AUTO_INCREMENT KEY, p_name varchar(255), p_ip varchar(255))");
    		sampleQueryStatement.executeUpdate();
    		sampleQueryStatement.close();
    		conn.close();
    	}
    
    	public void create_table_userhomes() throws SQLException
    	{
    		Connection conn = DriverManager.getConnection(url, user, pass);
    		PreparedStatement sampleQueryStatement = conn.prepareStatement("CREATE TABLE IF NOT EXISTS userhomes (world varchar(128), p_name varchar(255) not null, home_x varchar(500), home_y varchar(500), home_z varchar(500), world1 varchar(128), home1_x varchar(500), home1_y varchar(500), home1_z varchar(500), world2 varchar(128), home2_x varchar(500), home2_y varchar(500), home2_z varchar(500), primary key(p_name))");
    		sampleQueryStatement.executeUpdate();
    		sampleQueryStatement.close();
    		conn.close();
    	}
    
    
    
    }
    
    Anyone spot whats up? No errors in eclipse.

    Thanks :)

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 20, 2016
  6. Offline

    Sagacious_Zed Bukkit Docs

    @herghost
    Since there is a little bug with one of the recent commits,
    You are required to have a default config.yml, even if it is empty.
     
  7. Offline

    herghost

    I have one in the same place as my plugin.yml. If I remove the stuff in the mySQL functions it loads fine.
     
  8. Offline

    Sagacious_Zed Bukkit Docs

    @herghost
    your local plugin variable has not been instantiated.

    asides from that, getConfig cannot be used in field initializers and static block initializers.
     
  9. Offline

    herghost

    Thanks, so what is the correct method of doing this?

    Edit: I have initialized the plugin, just not sure how to get the value from config.yml?

    Edit2: I now have this:

    Code:
    public class sqlFunctions
    {
    
    	public sqlFunctions(Fiery instance)
    	{
    		this.plugin = instance;
    	}
    	 Fiery plugin;
    	 String user = plugin.config.getString("settings.mysql.user");
    	 String pass = plugin.config.getString("settings.mysql.pass");
    	 String url = "jdbc:mysql://localhost:3306/Fiery";
    	public void create_table_users() throws SQLException
    	{
    		Connection conn = DriverManager.getConnection(url, user, pass);
    		PreparedStatement sampleQueryStatement = conn.prepareStatement("CREATE TABLE IF NOT EXISTS users (p_id int NOT NULL AUTO_INCREMENT KEY, p_name varchar(255), p_ip varchar(255))");
    		sampleQueryStatement.executeUpdate();
    		sampleQueryStatement.close();
    		conn.close();
    	}
    
    
    But still getting the same error, not going to have much hair left at this rate :p

    @Sagacious_Zed - Any other hints available?! Thanks for your time so far
     
  10. Offline

    Kohle

    Very helpful, thanks! Got it working right off. However, I am a little stuck... I am working on a command-on-join plugin, and I want the user to be forced to do a command on join. I have everything to work, but I want they amount of commands to vary, so say one person sets the config to have 1 commands, the minium, and another person has 10 commands, or 9, or something... how would I go about making it so it can vary? (I'm not going to reread that because I'm sure I repeated the same thing 10 times...)
     
    DrAgonmoray likes this.
  11. Offline

    Windwaker

    So to clarify, a player executes 'x' amount of command on join? And it can differ between players?

    If that's the case you could make a user field and set it to a number, and get that number on join...
    Code:
    users:
      wjcrouse913:
        commands: 2
     
  12. Offline

    Kohle

    I guess I didn't clarify... okay, here is how the config is set up:
    Code:
    Commands:
      commandOne: hi
      commandTwo: hi2
    
    It's like that because I specified it in the plugin, when creating the config. Well, what if the server admin wanted them to perform 3 commands? If they added
    Code:
    commandThree: hi3
    
    The plugin does not recognize that or anything, so how would I get it to?
     
    DrAgonmoray likes this.
  13. Offline

    Windwaker

    I think an easier solution would be to get a list of commands...
    Code:
    Commands:
      - hi
      - hi2
      - hi3
    Then they could just add commands to the list, you could get the list, and iterate through the list for each command :)
     
  14. Offline

    Kohle

    Okay, I've never done anything remotely close to this, so... how would I do this? I hope I'm not making you say "What an idiot..."
     
    DrAgonmoray likes this.
  15. Offline

    Windwaker

    See "Getting a List", "Setting a List", and "Adding to a List"
     
  16. Offline

    Kohle

    It resets the config when I stop/rerun the server... why is this? :eek:
     
  17. Offline

    Windwaker

    Err.. code?
     
  18. Offline

    Kohle

    Ahh, right. Fail.

    Okay, here's my main class (JoinCommand.class)
    Show Spoiler

    Code:Java
    1.  
    2. package me.kohle.JoinCommand;
    3.  
    4. import java.util.Arrays;
    5. import java.util.logging.Logger;
    6.  
    7. import org.bukkit.command.Command;
    8. import org.bukkit.command.CommandSender;
    9. import org.bukkit.entity.Player;
    10. import org.bukkit.event.Event.Priority;
    11. import org.bukkit.event.Event.Type;
    12. import org.bukkit.plugin.PluginManager;
    13. import org.bukkit.plugin.java.JavaPlugin;
    14.  
    15. public class JoinCommand extends JavaPlugin {
    16. public void loadConfiguration(){
    17. String[] list = {"hi", "hi2"};
    18. this.getConfig().set("Commands", Arrays.asList(list));
    19. //See "Creating you're defaults"
    20. this.getConfig().options().copyDefaults(true); // NOTE: You do not have to use "plugin." if the class extends the java plugin
    21. //Save the config whenever you manipulate it
    22. this.saveConfig();
    23. }
    24.  
    25. public PluginManager pm;
    26. private JoinCommandPlayerListener playerListener = new JoinCommandPlayerListener(this);
    27. Logger log = Logger.getLogger("Minecraft");
    28.  
    29. public void onEnable() {
    30. loadConfiguration();
    31. pm = getServer().getPluginManager();
    32. pluginInfo("enabled, with a configuration file!");
    33. pm.registerEvent(Type.PLAYER_JOIN, playerListener, Priority.High, this);
    34. }
    35. public void onDisable() {
    36. pluginInfo("disabled.");
    37. this.saveConfig();
    38. }
    39. public static void pluginInfo(String message) {
    40. String v = "1.0-i";
    41. System.out.println("[JoinCommand] Version " + v + " " + message);
    42. }
    43. public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
    44. Player player = (Player)sender;
    45. if(commandLabel.equalsIgnoreCase("hi")) {
    46. player.sendMessage("It works! Wow. I am... shocked.");
    47. return true;
    48. } else if(commandLabel.equalsIgnoreCase("hi2")) {
    49. player.sendMessage("Wow, another command works. I guess Kohle is good at this, eh?");
    50. return true;
    51. }
    52. return false;
    53. }
    54. }



    Now, here is my player listener class (JoinCommandPlayerListener.class)
    Show Spoiler

    Code:Java
    1.  
    2. package me.kohle.JoinCommand;
    3.  
    4. import java.util.List;
    5.  
    6. import org.bukkit.entity.Player;
    7. import org.bukkit.event.player.PlayerJoinEvent;
    8. import org.bukkit.event.player.PlayerListener;
    9.  
    10.  
    11.  
    12. public class JoinCommandPlayerListener extends PlayerListener {
    13. public JoinCommand plugin;
    14.  
    15.  
    16. public JoinCommandPlayerListener(JoinCommand instance) {
    17. plugin = instance;
    18. }
    19.  
    20. @Override
    21. public void onPlayerJoin(PlayerJoinEvent event) {
    22. Player player = event.getPlayer();
    23. //If the player is not present when the player joins:
    24. if(!(player == null)) {
    25. System.out.println("[JoinCommand] A non-player joined the server... what would do that?!");
    26. }
    27. @SuppressWarnings("unchecked")
    28. List<String> stuff = plugin.getConfig().getList("Commands", null);
    29. for (String s : stuff) {
    30. player.performCommand(s);
    31. }
    32. }
    33. }



    I have no idea why it's doing that!
     
  19. Offline

    Windwaker

    @Kohle
    I think this is the problem...
    Code:java
    1. this.getConfig().set("Commands", Arrays.asList(list));

    Should be...
    Code:java
    1. this.getConfig().addDefault("Commands", Arrays.asList(list));

    Because when you copyDefaults() you're copying nothing atm :eek:
     
  20. Offline

    Kohle

    What a fail... thanks! (I can't believe that got past me .__.)
     
  21. Offline

    Windwaker

    Happy to help :)
     
  22. Offline

    Icelaunche

    Its always the stupid errors that you cant ever find.... like forgetting a bracket or something :p
     
  23. Offline

    Kohle

    Exactly!
     
  24. Offline

    dakoslug

    What I'm trying to do is make a config file to change the kick message when non-ops are kicked.
    How will I do this?
     
  25. Offline

    w000rm

    I'm a noob @ this, and my mind is getting blown.
    How do I use the getConfig() method if my class does not extend JavaPlugin?
     
  26. Offline

    Windwaker

    Declare
    Code:java
    1. public myPlugin plugin

    And get the config with
    Code:java
    1. plugin.getConfig()
     
    nuclearcodes likes this.
  27. Offline

    Evangon

    Config noob here :/
    Code:
    08:10:22 [SEVERE] Could not load 'plugins\EVmin.jar' in folder 'plugins':
    java.lang.ExceptionInInitializerError
            at java.lang.Class.forName0(Native Method)
            at java.lang.Class.forName(Unknown Source)
            at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.j
    ava:170)
            at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.
    java:215)
            at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager
    .java:136)
            at org.bukkit.craftbukkit.CraftServer.loadPlugins(CraftServer.java:151)
            at org.bukkit.craftbukkit.CraftServer.<init>(CraftServer.java:127)
            at net.minecraft.server.ServerConfigurationManager.<init>(ServerConfigur
    ationManager.java:52)
            at net.minecraft.server.MinecraftServer.init(MinecraftServer.java:145)
            at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:393)
            at net.minecraft.server.ThreadServerApplication.run(SourceFile:457)
    Caused by: java.lang.NullPointerException
            at admin.command.<clinit>(command.java:30)
            ... 11 more
    
    public static List NoFake = config.getList("NoFake");
    public static List NoKick = config.getList("NoKick");
     
  28. Offline

    Ezzy

    Excuse me for being stupid but:
    How do I get the field itself NOT the value?

    EXAMPLE:
    Group:
    Crafter: 3
    Renovator: 4

    Is there a way I can get all the fields in 'Group'? then put them into an arraylist
     
  29. Offline

    DomovoiButler

    config.getConfigurationSection("Group").getKeys(true);
    i think, xD
     
  30. Offline

    Ezzy

    Yep that did it!
     
    WalkerCrouse likes this.
Thread Status:
Not open for further replies.

Share This Page