How to call an int from config?

Discussion in 'Plugin Development' started by Turtlegasm, Aug 12, 2012.

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

    Turtlegasm

    This is really annoying me because I can't get it to work...I have this in my main class"
    Code:java
    1.  
    2. public void onEnable(){
    3.  
    4. FileConfiguration config = getConfig();
    5. config.addDefault("LCooldown", 5);
    6. config.options().copyDefaults(true);
    7. saveConfig();
    8.  

    I need to call the LCooldown int to my listener class for a cooldown I have set.
    Right now it has this:
    Code:java
    1.  
    2. public int COOLDOWN_TIME = 5;
    3.  

    I want it to be something like this:
    Code:java
    1.  
    2. public int COOLDOWN_TIME = (getConfig().getInt("LCooldown"));
    3.  

    But that doesn't work even when I extend javaplugin in my listener class
    (which i'm pretty sure I'm not supposed to do)
    I have been through javadocs, wiki etc. and am still stuck can anyone help?
     
  2. Offline

    dark navi

    It may be the way you are loading defaults. The (somewhat dirty) what I load defaults is like so:
    Code:
    getConfig().getInt("LCooldown", 5);
    Also, depending on when you are declaring / initializing COOLDOWN_TIME, it may not have set the defaults yet.
     
    Turtlegasm likes this.
  3. Offline

    Turtlegasm

    I tried
    Code:
    public final int COOLDOWN_TIME = getConfig().getInt("LCooldown", 5);
    I don't know why but it still doesn't work...I will post error log?
    Code:
    09:45:55 [SEVERE] Error occurred while enabling Cheese v1.2.1 (Is it up to date?
    )
    java.lang.IllegalArgumentException: File cannot be null
            at org.apache.commons.lang.Validate.notNull(Validate.java:203)
            at org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(Yam
    lConfiguration.java:170)
            at org.bukkit.plugin.java.JavaPlugin.reloadConfig(JavaPlugin.java:117)
            at org.bukkit.plugin.java.JavaPlugin.getConfig(JavaPlugin.java:111)
            at com.github.Turtlegasm.CheeseListener.<init>(CheeseListener.java:21)
            at com.github.Turtlegasm.Cheese.onEnable(Cheese.java:21)
            at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:217)
            at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader
    .java:365)
            at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManage
    r.java:381)
            at org.bukkit.craftbukkit.CraftServer.loadPlugin(CraftServer.java:265)
            at org.bukkit.craftbukkit.CraftServer.enablePlugins(CraftServer.java:247
    )
            at org.bukkit.craftbukkit.CraftServer.reload(CraftServer.java:567)
            at org.bukkit.Bukkit.reload(Bukkit.java:183)
            at org.bukkit.command.defaults.ReloadCommand.execute(ReloadCommand.java:
    21)
            at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:16
    8)
            at org.bukkit.craftbukkit.CraftServer.dispatchCommand(CraftServer.java:4
    92)
            at org.bukkit.craftbukkit.CraftServer.dispatchServerCommand(CraftServer.
    java:488)
            at net.minecraft.server.DedicatedServer.ah(DedicatedServer.java:248)
            at net.minecraft.server.DedicatedServer.q(DedicatedServer.java:213)
            at net.minecraft.server.MinecraftServer.p(MinecraftServer.java:476)
            at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:408)
    Cheese:21:mgr.registerEvents(new CheeseListener(), this);
    (error goes away when i set int to 5)
    CheeseListener:21:public int COOLDOWN_TIME = getConfig().getInt("LCooldown", 5);
     
  4. Offline

    dark navi

    That's because you're initializing that variable before you load your config.
     
    Turtlegasm likes this.
  5. Offline

    Turtlegasm

    But I set it to final so shouldn't it load last then?
     
  6. Offline

    dark navi

    Try declaring it as final, and then initializing it after you have set your config in your onEnable.
     
    Turtlegasm likes this.
  7. Offline

    Turtlegasm

    I don't know how to, I'm setting it as a final int but it's in a different class so I'm not sure what's happening because it's still initializing before the config isn't null
     
  8. Offline

    dark navi

    How are you accessing getConfig in your listener class?
     
    Turtlegasm likes this.
  9. Offline

    Turtlegasm

    I'm not :|
    I'm thinking maybe I could do this:
    Main class(Cheese.java)
    Code:
        public void onEnable(){
     
            FileConfiguration config = getConfig();
            config.addDefault("LCooldown", 5);
            config.options().copyDefaults(true);
            saveConfig();
           
        PluginManager mgr = this.getServer().getPluginManager();
        mgr.registerEvents(new CheeseListener(), this);
       
        }
        public final int CDTIME= getConfig().getInt("LCooldown", 5);
        
    Listener:
    Code:
    private int COOLDOWN_TIME = Cheese.CDTIME;
    But Cannot make a static reference to the non-static field Cheese.CDTIME
    Unless i make it
    Code:
    public final static int CDTIME= getConfig().getInt("LCooldown", 5);
    But then
    Code:
    Cannot make a static reference to the non-static method getConfig() from the type JavaPlugin
    :(
     
  10. Offline

    dark navi

    Is there a reason you need it to be final?
     
    Turtlegasm likes this.
  11. Offline

    Turtlegasm

    So it initializes after the config? I thought :|

    I can see why it won't work but I don't know how to make it work

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

    dark navi

    So the way I would do it is set it up like so:
    Code:
    //Declare publicly
    public int COOLDOWN_TIME;
    FileConfiguration config;
     
    public void onEnable()
    {
        //Initialize in order
        this.config = getConfig();
        this.COOLDOWN_TIME = this.config.getInt("COOLDOWN_TIME", 5);
    }
    Then in your listener you'll need to have a reference of your main plugin, in which you can access the cooldown time like so:
    Code:
    plugin.COOLDOWN_TIME
     
    Turtlegasm likes this.
  13. Offline

    lordaragos

    ^^ The above idea is correct. Just have your listener/event handler kind of branch off your main class. and then have the listener/event handler bring it all in on its side

    Code:
    public static Main plugin;
    public ServerEventHandler(Main instance){
        plugin = instance; 
    }
    then you should be able to pull

    Code:
    plugin.getConfig()
    or
    Code:
    #foobar initialized as something from either config or a constant
    plugin.foobar
    just fine.

    EDIT:
    just remember to have it on both sides:
    Code:
    public final ServerEventHandler eventhandler = new ServerEventHandler(this);
     
    Turtlegasm likes this.
  14. Offline

    Turtlegasm

    I did all that but I still have
    Code:
    public int COOLDOWN_TIME = Cheese.COOLDOWN_TIME;
    telling me that it is static and that the declaration thing in my main class is not

    I can't understand this...This is what I've got:
    Code:java
    1.  
    2. package com.github.Turtlegasm;
    3.  
    4. import java.util.HashMap;
    5. import java.util.logging.Logger;
    6.  
    7. import org.bukkit.ChatColor;
    8. import org.bukkit.Material;
    9. import org.bukkit.configuration.file.FileConfiguration;
    10. import org.bukkit.entity.Player;
    11. import org.bukkit.event.EventHandler;
    12. import org.bukkit.event.Listener;
    13. import org.bukkit.event.block.Action;
    14. import org.bukkit.event.block.BlockPlaceEvent;
    15. import org.bukkit.event.player.PlayerInteractEvent;
    16. import org.bukkit.plugin.java.JavaPlugin;
    17.  
    18. public class CheeseListener extends JavaPlugin implements Listener {
    19.  
    20. FileConfiguration config;
    21.  
    22. Logger log = Logger.getLogger("Minecraft");
    23.  
    24. public int COOLDOWN_TIME = Cheese.plugin.config.getInt("COOLDOWN_TIME", 5);
    25. private HashMap<String, Long> COOLDOWN = new HashMap<String, Long>();
    26.  
    27.  
    28.  
    29. @EventHandler
    30. public void onPlayerInteractEvent(PlayerInteractEvent evt)
    31. {
    32. if(evt.getPlayer().getItemInHand().getTypeId() == Material.GOLD_HOE.getId())
    33. {
    34. Player p = evt.getPlayer();
    35. if (COOLDOWN.containsKey(p.getName()))
    36. {
    37. long diff = (System.currentTimeMillis() - COOLDOWN.get(p.getName())) / 1000;
    38. if (diff < COOLDOWN_TIME)
    39. {
    40. p.sendMessage(ChatColor.DARK_AQUA+ "You must wait " + (COOLDOWN_TIME - diff) + " seconds before you can do that again!");
    41. return;
    42. }
    43. }
    44. evt.getPlayer().getWorld().strikeLightning(evt.getPlayer().getTargetBlock(null, 200).getLocation());
    45. System.out.print(evt.getPlayer().getName()+ " struck lightning");
    46. COOLDOWN.put(p.getName(), System.currentTimeMillis());
    47. }
    48.  

    In my listener class
    This is my main
    Code:java
    1.  
    2. package com.github.Turtlegasm;
    3. import org.bukkit.ChatColor;
    4. import org.bukkit.command.Command;
    5. import org.bukkit.command.CommandSender;
    6. import org.bukkit.configuration.file.FileConfiguration;
    7. import org.bukkit.craftbukkit.Main;
    8. import org.bukkit.plugin.PluginManager;
    9. import org.bukkit.plugin.java.JavaPlugin;
    10. public class Cheese extends JavaPlugin
    11. {
    12.  
    13.  
    14. //Declare publicly
    15. public int COOLDOWN_TIME;
    16. FileConfiguration config;
    17.  
    18. public void onEnable(){
    19. FileConfiguration config = getConfig();
    20. config.addDefault("LCooldown", 5);
    21. config.options().copyDefaults(true);
    22. saveConfig();
    23.  
    24. PluginManager mgr = this.getServer().getPluginManager();
    25. mgr.registerEvents(new CheeseListener(), this);
    26.  
    27. //Initialize in order
    28. this.config = getConfig();
    29. this.COOLDOWN_TIME = this.config.getInt("COOLDOWN_TIME", 5);
    30. }
    31. public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
    32. if(cmd.getName().equalsIgnoreCase("cheese")){ // If the player typed /basic then do the following...
    33. sender.sendMessage(ChatColor.BOLD + "Turtlegasm's Cheese+Lightning Hoe bukkit plugin v1.2.1 12/8/12");
    34. return true;
    35. } //If this has happened the function will break and return true. if this hasn't happened the a value of false will be returned.
    36. return false;
    37. }
    38. public static Main plugin;
    39. public Cheese (Main instance){
    40. plugin = instance;
    41. }
    42. }
    43.  

    The only error is
    public int COOLDOWN_TIME = Cheese.plugin.config.getInt("COOLDOWN_TIME", 5);
    config cannot be resolved or is not a field
    even though i have
    FileConfiguration config;
    3 lines above

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

    dark navi

    That's because when you create your listener you actually have to pass it a reference to your main class. It doesn't automatically know what "Cheese" is.
     
    Turtlegasm likes this.
  16. Offline

    Turtlegasm

    I don't understand...In past I don't remember stuff like this :| How would I pass it a reference?
     
  17. Offline

    dark navi

    Here is what I have for your main:
    Code:
    package com.github.Turtlegasm;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.craftbukkit.Main;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.java.JavaPlugin;
    public class Cheese extends JavaPlugin
    {
     
     
    //Declare publicly
    public int COOLDOWN_TIME;
    FileConfiguration config;
     
    public void onEnable(){
        FileConfiguration config = getConfig();
        config.addDefault("LCooldown", 5);
        config.options().copyDefaults(true);
        saveConfig();
     
        PluginManager mgr = this.getServer().getPluginManager();
        mgr.registerEvents(new CheeseListener(this), this);
     
      //Initialize in order
      this.config = getConfig();
      this.COOLDOWN_TIME = this.config.getInt("COOLDOWN_TIME", 5);
    }
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
        if(cmd.getName().equalsIgnoreCase("cheese")){ // If the player typed /basic then do the following...
            sender.sendMessage(ChatColor.BOLD + "Turtlegasm's Cheese+Lightning Hoe bukkit plugin v1.2.1 12/8/12");
            return true;
        } //If this has happened the function will break and return true. if this hasn't happened the a value of false will be returned.
            return false;
        }
    }
    
    Here is what I have for your listener:
    Code:
    ackage com.github.Turtlegasm;
     
    import java.util.HashMap;
    import java.util.logging.Logger;
     
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.Action;
    import org.bukkit.event.block.BlockPlaceEvent;
    import org.bukkit.event.player.PlayerInteractEvent;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class CheeseListener implements Listener  {
     
     
    Logger log = Logger.getLogger("Minecraft");
     
    public int COOLDOWN_TIME;
    private HashMap<String, Long> COOLDOWN = new HashMap<String, Long>();
    Cheese plugin;
     
    public CheeseListener(Cheese instance)
    {
        this.plugin = instance;
        this.COOLDOWN_TIME = this.plugin.COOLDOWNTIME;
    }
     
    @EventHandler
    public void onPlayerInteractEvent(PlayerInteractEvent evt)
    {
        if(evt.getPlayer().getItemInHand().getTypeId() == Material.GOLD_HOE.getId())
        {
            Player p = evt.getPlayer();
            if (COOLDOWN.containsKey(p.getName()))
            {
                long diff = (System.currentTimeMillis() - COOLDOWN.get(p.getName())) / 1000;
                if (diff < COOLDOWN_TIME)
                {
                    p.sendMessage(ChatColor.DARK_AQUA+ "You must wait " + (COOLDOWN_TIME - diff) + " seconds before you can do that again!");
                    return;
                }
            }
            evt.getPlayer().getWorld().strikeLightning(evt.getPlayer().getTargetBlock(null, 200).getLocation());
            System.out.print(evt.getPlayer().getName()+ " struck lightning");
            COOLDOWN.put(p.getName(), System.currentTimeMillis());
        }
    
    There may be some syntax stuff, as I did it in notepad. :p

    Notes:
    • Added initializer to CheeseListener that takes a Cheese
    • Added local variable to CheeseListener for your local copy of COOLDOWN_TIME
     
    Turtlegasm likes this.
  18. Offline

    lordaragos

    I would not actually do
    Code:
    FileConfiguration config;
    because it might wipe out the default [plugin_name]/config.yml path. Just call a getConfig() to get access to the config.yml
     
    Turtlegasm likes this.
  19. Offline

    dark navi

    What? How would making a variable wipe out an existing file?

    Edit: I am assuming you're talking about loading the defaults, in which you may be correct. Like I said, I usually do a rough and dirty way of just passing the get method the default value.
     
    Turtlegasm likes this.
  20. Offline

    Turtlegasm

    There's no errors or anything but I think COOLDOWN_TIME is returning null because you can spam lightning ingame. I also fixed the default to be COOLDOWN_TIME so it's not that


    EDIT: I added System.out.println(COOLDOWN_TIME); and it outputs 5...weird
     
  21. Offline

    lordaragos

    EDIT: ^^ at that point, its no longer a config issue Turtle

    Well I actually never initialize my config variable. I think you might have to save config with config.save("where/config/goes.yml") if you do....I always just do
    Code:
    this.getConfig().options().copyDefaults(true)
    //and
    this.saveConfig()
    this.saveDefaultConfig() //just for safety at this point ._.
     
    Turtlegasm likes this.
  22. Offline

    dark navi

    I'd use some debuging to console to see what the current values are set to.
     
    Turtlegasm likes this.
  23. Offline

    Jogy34

    that wouldn't wipe out the existing config file. It wouldn't actually do much at all since you would just be storing the config into a variable.

    what I would suggest doing is in your listener constructor just do this:
    Code:
    public cheeseListener(Cheese plugin)
    {
        this.COOLDOWNTIME = plugin.getConfig().getInt("LCooldown", 5);
    }
    to that first point. You would only ever have to do something like that if you are making a custom .yml file, otherwise just use the built in bukkit method for saving the config files.
    To the second part, as from what I've seen most people do something like that if not the same exact thing.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 27, 2016
    Turtlegasm and lordaragos like this.
  24. Offline

    Turtlegasm

    Good idea but now even when I change the config.yml from my /plugins/cheese directory to 2 then it is still on a 5 second cooldown
    EDIT:Nevermind my fault made a small error this works fine! Thanks everyone :)
     
  25. Offline

    lordaragos

    sorry, I'm referencing "this" under "Main" or "plugin"
     
    Turtlegasm likes this.
  26. Offline

    Jogy34

    the ', 5' part is what it defaults to if the the value you retrieved is null. You don't have to have it there but in my opinion it is a good safety precaution.
     
Thread Status:
Not open for further replies.

Share This Page