[Tutorial/Beginner] Making configs

Discussion in 'Resources' started by theguynextdoor, Dec 30, 2011.

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

    theguynextdoor

    The problem you are having is you have a Nullpointer Exception, because your plugin variable is null because you do not have constructor.
    Your executor should look like this at the start:
    Code:
    package me.cedi.setsunny;
     
    import org.bukkit.ChatColor;
    import org.bukkit.World;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.command.ConsoleCommandSender;
    import org.bukkit.entity.Player;
     
    public class SunCommandExecutor implements CommandExecutor{
    SetSunnyCore plugin;
     
    SunCommandExecutor(SetSunnyCore instance){
        plugin = instance;
    }
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    //onCommand(start)-------------------------------------------------
    if (sender instanceof ConsoleCommandSender == true){
    //If ConsoleCommandSender(start)-----------------------------------
     
    //If there are less than 1 arguments after "/sun"
    if(args.length < 1){
     
    sender.sendMessage("Not enough arguments.");
    sender.sendMessage("Correct usage is: /sun [world] [duration]");
     
    }
    Not part of the question, but
    Code:
    if (sender instanceof ConsoleCommandSender == true){
    Should be
    Code:
    if (sender instanceof ConsoleCommandSender){
    Then when registering the command in the main class
    Code:
    this.sunExecutor = new SunCommandExecutor(this);
    this.getCommand("sun").setExecutor(sunExecutor);
    Look at the source of my snowball plugin, i use config values alot in their. The main thing i see people doing wrong, or missing out is the constructor. But as requested, here is my main class for my snowball plugin:
    Code:
    package me.theguynextdoor.snowballnextdoor;
     
    import java.util.logging.Logger;
     
    import me.theguynextdoor.snowballnextdoor.commands.CritCommand;
    import me.theguynextdoor.snowballnextdoor.commands.HeadShotCommand;
    import me.theguynextdoor.snowballnextdoor.commands.IceCommand;
    import me.theguynextdoor.snowballnextdoor.commands.MissCommand;
    import me.theguynextdoor.snowballnextdoor.commands.MobDamageValue;
    import me.theguynextdoor.snowballnextdoor.commands.PlayerDamageValue;
    import me.theguynextdoor.snowballnextdoor.commands.SnowTilePlaceToggle;
    import me.theguynextdoor.snowballnextdoor.commands.SnowballDropToggle;
    import me.theguynextdoor.snowballnextdoor.commands.SnowmanDamage;
    import me.theguynextdoor.snowballnextdoor.listeners.SnowballBlockListener;
    import me.theguynextdoor.snowballnextdoor.listeners.SnowballEntityListener;
    import me.theguynextdoor.snowballnextdoor.listeners.SnowballPlayerListener;
     
    import org.bukkit.Bukkit;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class SnowBallNextDoor extends JavaPlugin {
     
        private final Logger log = Logger.getLogger("Minecraft");
        private final SnowballEntityListener entityListener = new SnowballEntityListener(this);
        private final SnowballPlayerListener playerListener = new SnowballPlayerListener(this);
        private final SnowballBlockListener blockListener = new SnowballBlockListener(this);
     
        @Override
        public void onDisable() {
            log.info(this.getDescription().getName() + " has been disabled");
        }
     
        @Override
        public void onEnable() {
     
            final FileConfiguration config = this.getConfig();
     
            config.options().header("The Server.PvP node: Set to true if PvP is enabled, and false if PvP is diabled.");
     
            config.addDefault("Server.PvP", true);
     
            config.addDefault("Toggle.Damage.PlayerDamage", true);
            config.addDefault("Toggle.Damage.MobDamage", true);
            config.addDefault("Toggle.Damage.SnowmanDamage", true);
     
            config.addDefault("Toggle.Snowball.PlaceOnRightClick", true);
            config.addDefault("Toggle.Snowball.SnowTileStacking", true);
            config.addDefault("Toggle.Snowball.PutEntityFiresOut", true);
            config.addDefault("Toggle.Snowball.WaterToIce", true);
     
            config.addDefault("Toggle.Drops.SnowballFromTiles", true);
     
            config.addDefault("Value.PlayerDamage", 2);
            config.addDefault("Value.MobDamage", 2);
            config.addDefault("Value.SnowmanDamage", 2);
     
            config.addDefault("Crit.Chance", true);
            config.addDefault("Crit.DamageExtra", true);
            config.addDefault("Crit.Toggle.Message", true);
     
            config.addDefault("Miss.Chance", true);
            config.addDefault("Miss.Toggle.Message", true);
     
            config.addDefault("Headshot.Toggle.HeadshotDamage", true);
            config.addDefault("Headshot.Toggle.HeadshotMessage", false);
            config.addDefault("Headshot.Value.HeadshotExtraDamageDealt", 1);
     
            config.options().copyDefaults(true);
            saveConfig();
     
            PluginManager pm = Bukkit.getServer().getPluginManager();
     
            pm.registerEvents(playerListener, this);
            pm.registerEvents(blockListener, this);
            pm.registerEvents(entityListener, this);
     
            getCommand("splayer").setExecutor(new PlayerDamageValue(this));
            getCommand("mob").setExecutor(new MobDamageValue(this));
            getCommand("snowman").setExecutor(new SnowmanDamage(this));
            getCommand("snowtile").setExecutor(new SnowTilePlaceToggle(this));
            getCommand("miss").setExecutor(new MissCommand(this));
            getCommand("crit").setExecutor(new CritCommand(this));
            getCommand("headshot").setExecutor(new HeadShotCommand(this));
            getCommand("snowice").setExecutor(new IceCommand(this));
            getCommand("snowball").setExecutor(new SnowballDropToggle(this));
     
            log.info(this.getDescription().getName() + " v" + getDescription().getVersion() + " has been enabled");
        }
    }
    And this is my listener:
    Code:
    package me.theguynextdoor.snowballnextdoor.listeners;
     
    import me.theguynextdoor.snowballnextdoor.SnowBallNextDoor;
    import me.theguynextdoor.snowballnextdoor.Util.Util;
     
    import org.bukkit.Bukkit;
    import org.bukkit.GameMode;
    import org.bukkit.entity.Entity;
    import org.bukkit.entity.LivingEntity;
    import org.bukkit.entity.Player;
    import org.bukkit.entity.Projectile;
    import org.bukkit.entity.Snowball;
    import org.bukkit.entity.Snowman;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.entity.EntityDamageByEntityEvent;
    import org.bukkit.event.entity.EntityDamageEvent;
    import org.bukkit.permissions.Permissible;
     
    public class SnowballEntityListener implements Listener {
        SnowBallNextDoor plugin;
     
        public SnowballEntityListener(SnowBallNextDoor instance) {
            plugin = instance;
        }
     
        private int damage;
     
        @EventHandler
        public void onEntityDamage(EntityDamageEvent e) {
            if (e instanceof EntityDamageByEntityEvent) {
                for (Player player : Bukkit.getServer().getOnlinePlayers()) {
                    if (player.hasPermission("snowball.use") || player.isOp()) {
                        Entity attacker = ((EntityDamageByEntityEvent) e).getDamager();
     
                        double crit = Math.random() * 20;
                        double dif = attacker.getLocation().getY() - e.getEntity().getLocation().getY() - 1.5;
     
                        if (attacker instanceof Snowball) {
                            Entity damaged = e.getEntity();
     
                            if (e.isCancelled()) {
                                e.setCancelled(false);
                            }
                            // Null check
                            if (damaged == null || ((Projectile) attacker).getShooter() == null) {
                                return;
                            }
                            // Snowman damage
                            if (((Snowball) attacker).getShooter() instanceof Snowman && plugin.getConfig().getBoolean("Toggle.Damage.SnowmanDamage")) {
                                damage = plugin.getConfig().getInt("Value.SnowmanDamage");
                            }
                            // Player damage
                            else if (damaged instanceof Player && plugin.getConfig().getBoolean("Toggle.Damage.PlayerDamage")) {
                                damage = plugin.getConfig().getInt("Value.PlayerDamage");
                            }
                            // Mob damage
                            else if (damaged instanceof LivingEntity && !(damaged instanceof Player) && plugin.getConfig().getBoolean("Toggle.Damage.MobDamage")) {
                                damage = plugin.getConfig().getInt("Value.MobDamage");
                            }
                            // Headshots
                            if (dif > 0.1 && dif < 0.5 && e.getEntity() instanceof Player && ((Player) damaged).getGameMode() != GameMode.CREATIVE) {
                                if (plugin.getConfig().getBoolean("Headshot.Toggle.HeadshotDamage")) {
                                    damage = damage + plugin.getConfig().getInt("Headshot.Value.HeadshotExtraDamageDealt");
                                    if (((Projectile) attacker).getShooter() == null) {
                                        return;
                                    }
                                    // Daze
                                    if (((Projectile) attacker).getShooter() instanceof Player) {
                                        if (((Permissible) ((Projectile) attacker).getShooter()).hasPermission("snowball.daze")) {
                                            if (Math.random() * 1000 >= 500) {
                                                Util.dazePlayer((Player) damaged);
                                            }
                                        }
                                    }
     
                                    if (plugin.getConfig().getBoolean("Headshot.Toggle.HeadshotMessage")) {
                                        if (damaged instanceof Player) {
     
                                            ((Player) damaged).sendMessage("Headshot from " + ((Player) ((Projectile) attacker).getShooter()).getDisplayName());
                                        }
                                        if (((Projectile) attacker).getShooter() instanceof Player) {
                                            ((Player) ((Projectile) attacker).getShooter()).sendMessage("Headshot dealt to " + ((Player) damaged).getDisplayName());
                                        }
                                    }
                                }
                            }
     
                            // Crit
                            if (((Snowball) attacker).getShooter() instanceof Player) {
                                if (crit >= 19) {
                                    if (plugin.getConfig().getBoolean("Crit.Chance")) {
                                        damage = damage + plugin.getConfig().getInt("Crit.DamageExtra");
                                        if (plugin.getConfig().getBoolean("Crit.Toggle.Message")) {
                                            ((Player) ((Projectile) attacker).getShooter()).sendMessage("Crit");
                                        }
                                    }
                                }
                                // Miss
                                else if (crit <= 1) {
                                    if (plugin.getConfig().getBoolean("Miss.Chance")) {
                                        damage = 0;
                                        if (plugin.getConfig().getBoolean("Miss.Toggle.Message")) {
                                            ((Player) ((Projectile) attacker).getShooter()).sendMessage("Miss");
                                        }
                                    }
                                }
                            }
     
                            // Put fires out on entities
                            if (damaged.getFireTicks() > 0) {
                                damaged.setFireTicks(0);
                            }
     
                            // Setting final damage
                            if (damaged instanceof Player) {
                                if (((Player) damaged).getHealth() > 20 || ((Player) damaged).getHealth() <= 0) {
                                    return;
                                }
                                if (plugin.getConfig().getBoolean("Server.PvP")) {
                                    e.setDamage(damage);
                                }
                                else {
                                    ((Player) damaged).setHealth(((Player) damaged).getHealth() - damage);
                                }
                            }
                            else {
                                e.setDamage(damage);
                            }
                        }
                    }
                }
            }
        }
    }
    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 22, 2016
    colony88 likes this.
  2. Offline

    wannezz

    Great tutorial! :)
     
  3. Offline

    lenis0012

    how can i use a boolean in a Listener?
    it makes the getConfig red -_-
     
  4. Offline

    theguynextdoor

  5. Offline

    TopGear93

    theguynextdoor is it possible to save hashmaps in this config type?
     
  6. Offline

    Theway2cool1

    I've done everything, as far as I can tell, according to instruction, and this thing still doesn't want to cooperate. Every time I try to get a boolean from the config, my console gets flooded with these messages:
    Code:
    08:05:57 [SEVERE] Could not pass event CreatureSpawnEvent to ServerProtect
    org.bukkit.event.EventException
            at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.ja
    va:304)
            at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.jav
    a:62)
            at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.j
    ava:477)
            at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.j
    ava:462)
            at org.bukkit.craftbukkit.event.CraftEventFactory.callCreatureSpawnEvent
    (CraftEventFactory.java:226)
            at net.minecraft.server.World.addEntity(World.java:887)
            at net.minecraft.server.SpawnerCreature.spawnEntities(SpawnerCreature.ja
    va:180)
            at net.minecraft.server.World.doTick(World.java:1735)
            at net.minecraft.server.MinecraftServer.w(MinecraftServer.java:546)
            at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:451)
            at net.minecraft.server.ThreadServerApplication.run(SourceFile:492)
    Caused by: java.lang.NullPointerException
            at com.gmail.thecotlsdragon98.ServerProtect.MobSpawnListener.MobSpawn(Mo
    bSpawnListener.java:21)
            at sun.reflect.GeneratedMethodAccessor14.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
            at java.lang.reflect.Method.invoke(Unknown Source)
            at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.ja
    va:302)
            ... 10 more
    Here is the onEnable() method from my main class:

    Code:
        public ServerProtect plugin;
        @Override
        public void onEnable()
        {
            getLogger().info("ServerProtect v1.1 enabled");
            PluginManager manager = this.getServer().getPluginManager();
            manager.registerEvents(new TNTListener(), this);
            manager.registerEvents(new FireBlockListener(), this);
            manager.registerEvents(new FireChargeListener(), this);
            manager.registerEvents(new FlintAndSteelListener(), this);
            manager.registerEvents(new BedrockBreakListener(), this);
            manager.registerEvents(new BedrockPlaceListener(), this);
            manager.registerEvents(new RedstoneListener(), this);
            manager.registerEvents(new LavaListener(), this);
            manager.registerEvents(new WaterListener(), this);
            manager.registerEvents(new UglyBlockListener(), this);
            manager.registerEvents(new BowAndArrowListener(), this);
            manager.registerEvents(new EggListener(), this);
            manager.registerEvents(new ExpBottleListener(), this);
            manager.registerEvents(new MobSpawnerListener(), this);
            manager.registerEvents(new ItemDropListener(), this);
            manager.registerEvents(new EnderPearlListener(), this);
            manager.registerEvents(new SnowballListener(), this);
            manager.registerEvents(new EnderEyeListener(), this);
            manager.registerEvents(new DispenserListener(), this);
            manager.registerEvents(new MobSpawnListener(plugin), this);
            FileConfiguration config = this.getConfig();
            config.addDefault("mob-spawning.disabled", false);
            config.options().copyDefaults(true);
            saveConfig();
        }
    And here is the class that is causing the issue:


    Code:
    package com.gmail.thecotlsdragon98.ServerProtect;
     
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.EventPriority;
    import org.bukkit.event.Listener;
    import org.bukkit.event.entity.CreatureSpawnEvent;
    import com.gmail.thecotlsdragon98.ServerProtect.ServerProtect;
     
    class MobSpawnListener extends ServerProtect implements Listener
    {
        ServerProtect plugin;
     
        public MobSpawnListener(ServerProtect instance) {
        plugin = instance;
        }
     
     
        @EventHandler()
        public void MobSpawn(CreatureSpawnEvent event)
        {
            if(plugin.getConfig().getBoolean("mob-spawning.disabled"))
            {
                event.setCancelled(true);
            }
        }
    }
     
  7. Offline

    theguynextdoor

    The problem is, in your main class you made a variable called plugin, never initialised it and then put in when you defined your listener. What you need to do is when you register the events for the class MobSpawnListener you want to do it like this.

    manager.registerEvents(new MobSpawnListener(this), this);

    or at the very least, at the top of your onEnable put:

    plugin = this;
     
  8. Offline

    Theway2cool1

    Hum. Eclipse told me to do manager.registerEvents(new MobSpawnListener(plugin), this);
    Maybe I should stop listening to Eclipse. Anyways, that fixed the issue, you're the first to actually help me figure out how to get a config working. You sir, are an awesome individual.
     
  9. Offline

    gamingod

    How do you add to a list?
     
  10. Offline

    theguynextdoor

    Off the top of my head, i believe you do something along the lines of

    Code:java
    1. List<String> list = config.getStringList("Path");
    2. list.add("Something");
    3. config.set("Path", list);
     
  11. Offline

    gamingod

    thanks

    theguynextdoor I tried changing "Something" to args[0] and it works but when I reload the server and do it, it replaces all the exiting info in the list

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

    theguynextdoor

    I finally got around to updating this little old post. Note how I now use images instead of code blocks. This is to prevent people just copying and pasting the code. At least this way they have to type is out and have a chance of remembering and understanding it a bit.
     
  13. Offline

    megasaad44

    theguynextdoor I'm having a problem with the getBoolean.

    I registered and made a constructor and all but i think the boolean thinks it's false or something... There are no errors
    Code:java
    1. if ((plugin.getConfig().getBoolean("PlaySmokeEFfect"))) {
    2. player.playEffect(player.getLocation(), Effect.SMOKE, 0);
    3. }

    Anything wrong with this?
     
  14. Offline

    theguynextdoor

    Looks fine to me. Add a message to ensure it is actually being called. Also ensure you have particle effects turned up from minimal in your video settings.
     
  15. Offline

    Nonam82

    Very nice and in-depth tutorial, much more helpful than the Configuration help page on the Bukkit wiki. Just wanted to say thanks! :)
     
  16. Offline

    megasaad44

    Is it just me or did you remove the photos from your dropbox? They aren't loading! D:
     
  17. Offline

    Neilnet

    EDIT: Removed. I fixed it. :)
     
  18. Offline

    zanda268

    I would like to point out that your note on not using getConfig() and instead storing it in a variable is wrong. You should always run getConfig to make sure you are getting a fresh version of the file. If a person would edit the config itself directly it would not show in your code if you saved it to a variable. The official API itself recommends not saving it to a variable.
     
  19. Offline

    theguynextdoor

    If you are referring to the variable used in the onEnable, because that is the only point I make a variable out of it (even then it is only a local variable), then the chances are the file is not going to chance in the few milliseconds it takes to do the config stuff in your onEnable. If you could link me to where it says in the API about not using a variable, then that would be good for I would like to take a read of it.

    If you look at the source code for getConfig(), then it will return the instance of 'newConfig', which is only loaded when it is null (i.e it is only loaded when you first call getConfig() (or reload config). It is not refreshed each time your call it.

    This is the code I see in the javadocs. newConfig is the instance you are retrieving. Note how it is not reloaded each time your call getConfig(), therefore it is not 'fresh' each time your get it.

    Code:
    public FileConfiguration getConfig() {
        if (newConfig == null) {
            reloadConfig();
        }
        return newConfig;
    }
       
    public void reloadConfig() {
        newConfig = YamlConfiguration.loadConfiguration(configFile);
       
        InputStream defConfigStream = getResource("config.yml");
        if (defConfigStream != null) {
            YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
       
            newConfig.setDefaults(defConfig);
        }
    }
       
    public void saveConfig() {
        try {
            getConfig().save(configFile);
        } catch (IOException ex) {
            logger.log(Level.SEVERE, "Could not save config to " + configFile, ex);
        }
    }
     
  20. Offline

    Vidsify

    theguynextdoor Is there away you can disable the plugin, if you wanted, within the config as I can't seem to find any tutorials on how to do i?
     
  21. Offline

    theguynextdoor

    You would create a boolean inside the config, then check in the onEnable whether that boolean is true and then do the appropriate actions to disable a plugin (I'll leave you do google/search for how to do that).
     
  22. Offline

    Vidsify

    theguynextdoor Ok thanks. I can't find anything on Google though nor can i find tutorials on youtube
     
  23. Offline

    theguynextdoor

    Not everything you need is going to be in the form of a tutorial. Especially on youtube. Youtube tutorials are alright, but they are often done by those whom are not always best suited to teaching. Some tutorials are alright on youtube, they teach some topics, without making too many mistakes, other tutorials are made by 12 year olds who have about maybe only a few months of programming experience, and now think they are amazing and deserve to teach. These people are wrong.

    You should consider looking in the javadocs for the BukkitAPI when finding the method to disable a plugin. Knowing what classes, and how to search the Java docs comes with practice. http://jd.bukkit.org/rb/apidocs/org/bukkit/plugin/PluginManager.html

    However if you also search around the forums, you will see threads about topics, these are easier found via a google search.
     
    Vidsify likes this.
Thread Status:
Not open for further replies.

Share This Page