Config Keeps resetting to default and perms are being overridden by config

Discussion in 'Plugin Development' started by Vidsify, Mar 8, 2015.

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

    Vidsify

    Hello,

    I'm not sure why but each time you do a command ingame to change the config it resets and removes all the comments. When this happens it also overrides some permissions which give players, depending what one they have, an exp multiplier. I'm not sure why this is happening.

    Here's my code: https://github.com/Vidsify/DoubleYourExperience

    Any help will be much appreciated
     
  2. @Vidsify Please post all relevant classes with the code tags. It'd be a lot easier to look at the classes rather than going on GitHub.
     
  3. Offline

    Vidsify

    @CodePlaysMinecraft Here you go

    Config.yml:

    Code:
    # Welcome to Durexp Config File
    # Here you will find the default config settings feel free to change them to suit your liking! :)
    # If you have any problems please create a ticket:
    # http://dev.bukkit.org/bukkit-plugins/double-your-experience/tickets/
    #
    # Multiplier: 2.0
    #     # This will allow you to set a server wide Multiplier
    #     # This number is ignored if EnablePermMultiplier = true
    # EnablePermMultiplier: false
    #     # true = Instead of one server-wide-"Multiplier",
    #     # there will be a different "Multiplier" for each permission node that you create.
    #     # Give this permission node to a player or a group: (max = 10.0)
    #     # doubleurexp.multiplier.<number>
    # AutoUpdate: True
    #     # true = automatically update this plugin when a new version is released.
    #     # false = ignore updates
    # Enable: true
    #     # true = enable plugin
    #     # false = disable plugin
    #     # in-game command:
    #     # /durexp toggle
    # CheckForSpawner: true
    #     # Enables/disables the check for mob spawners.
    #     # true = check for nearby mob spawners before giving bonus experience.
    #     # false = do not check for nearby mob spawners: just give out bonus xp.
    # CheckRadius: 40
    #     # The radius that the plugin will check if the "CheckForSpawner" option is enabled,
    #     # could be used to prevent mass farming. <---We don't want that now!
    # DaysToEnable:
    #     # This is a list of the days that are enabled,
    #     # shown is the different ways you can write the date,
    #     # the plugin will detect them all!!!
    Multiplier: 2.0
    EnablePermMultiplier: false
    AutoUpdate: True
    Enable: true
    CheckForSpawner: true
    CheckRadius: 40
    DaysToEnable:
    - Monday
    - tuesday
    - wed
    - thursday
    - frida
    - sat
    - SundAy
    plugin.yml:

    Code:
    name: Durexp
    main: me.vidsify.durexp.DurexpPlugin
    version: 1.2.6.1
    website: http://dev.bukkit.org/bukkit-plugins/double-your-experience/
    description: Doubles players experience levels depending on what permissions they have!
    author: Vidsify
    authors: [Europia79, stevesmithjr]
    depend: [Vault]
    softdepend: []
    commands:
        durexp:
            description: All Durexp commands.
    permissions:
      doubleurexp.use:
        default: op
      doubleurexp.allow:
        default: false
    DurexpExecutor.java is in a package called commands

    Code:
    package me.vidsify.durexp.commands;
    
    import me.vidsify.durexp.DurexpPlugin;
    import me.vidsify.durexp.Perm;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    
    /**
    *
    * @author Vidsify
    */
    public class DurexpExecutor implements CommandExecutor {
    
        DurexpPlugin plugin;
    
        public DurexpExecutor(DurexpPlugin reference) {
            this.plugin = reference;
        }
    
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
            if (!sender.hasPermission(Perm.ADMIN)) {
                sender.sendMessage(ChatColor.GOLD + "[DurEXP]" + ChatColor.RED + "You do not have permission for this command!");
                return true;
            }
            if (args.length == 0) {
                sender.sendMessage(ChatColor.GOLD + "[DurEXP]" + ChatColor.RED + "Use /durexp help, for more information");
            } // Help Command
            else if (args[0].equalsIgnoreCase("help")) {
                return help(sender);
            } //Multipler Command
            else if (args[0].equalsIgnoreCase("multiplier")) {
                return multiplier(sender, args);
            } //Toggle Command
            else if (args[0].equalsIgnoreCase("toggle")) {
                return toggle(sender);
            } //Update Command
            else if (args[0].equalsIgnoreCase("update")) {
                return update(sender);
            } else {
                sender.sendMessage(ChatColor.GOLD + "[DUREXP]" + ChatColor.RED + " Invalid command");
            }
            return true;
        }
      
        public boolean help(CommandSender sender) {
            sender.sendMessage(ChatColor.GOLD + "================" + ChatColor.DARK_PURPLE + " DoubleXP By Vidsify " + ChatColor.GOLD + "================");
            sender.sendMessage(ChatColor.GOLD + "/durexp help" + ChatColor.RED + " - Displays this help menu");
            sender.sendMessage(ChatColor.GOLD + "/durexp toggle" + ChatColor.RED + " - Toggles this plugin on or off");
            sender.sendMessage(ChatColor.GOLD + "/durexp multiplier <amount>" + ChatColor.RED + " - Amount xp is multiplied by, e.g. 2 is double");
            sender.sendMessage(ChatColor.GOLD + "=====================================================");
            return true;
        }
      
        public boolean multiplier(CommandSender sender, String[] args) {
            if (args.length < 2) {
                sender.sendMessage(ChatColor.GOLD + "[DurEXP]" + ChatColor.RED + " You must specify a number!");
                return false;
            }
            if (plugin.isDouble(args[1])) {
                plugin.getConfig().set("Multiplier", Double.valueOf(Double.parseDouble(args[1])));
                sender.sendMessage(ChatColor.GOLD + "[DurEXP]" + ChatColor.RED + "Multiplier set to: " + args[1]);
                plugin.saveConfig();
            } else {
                sender.sendMessage(ChatColor.GOLD + "[DurEXP]" + ChatColor.RED + " Only enter a number!");
            }
            return true;
        }
    
        public boolean toggle(CommandSender sender) {
            if (plugin.getConfig().getBoolean("Enable")) {
                plugin.getConfig().set("Enable", Boolean.valueOf(false));
                sender.sendMessage(ChatColor.GOLD + "[DurEXP]" + ChatColor.RED + " Plugin disabled!");
            } else {
                plugin.getConfig().set("Enable", Boolean.valueOf(true));
                sender.sendMessage(ChatColor.GOLD + "[DurEXP]" + ChatColor.GREEN + " Plugin enabled!");
            }
            return true;
        }
    
        public boolean update(CommandSender sender) {
            if (plugin.getConfig().getBoolean("AutoUpdate")) {
                plugin.getConfig().set("AutoUpdate", Boolean.valueOf(false));
                sender.sendMessage(ChatColor.GOLD + "[DurEXP]" + ChatColor.RED + " AutoUpdate Disabled!");
            } else {
                plugin.getConfig().set("AutoUpdate", Boolean.valueOf(true));
                sender.sendMessage(ChatColor.GOLD + "[DurEXP]" + ChatColor.GREEN + " AutoUpdate Enabled!");
            }
            plugin.saveConfig();
            return true;
        }
    
    }
    PlayerExpListener.java is in a package called listeners:

    Code:
    package me.vidsify.durexp.listeners;
    
    import java.util.Calendar;
    import java.util.List;
    import me.vidsify.durexp.DurexpPlugin;
    import me.vidsify.durexp.Perm;
    import org.bukkit.Material;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.PlayerExpChangeEvent;
    
    /**
    *
    * @author Vidsify
    */
    public class PlayerExpListener implements Listener {
    
        DurexpPlugin plugin;
    
        public PlayerExpListener(DurexpPlugin reference) {
            this.plugin = reference;
        }
    
        @EventHandler
        public void onExpChange(PlayerExpChangeEvent e) {
            Calendar mydate = Calendar.getInstance();
            int dow = mydate.get(7);
            Boolean alreadyDone = Boolean.valueOf(false);
            List<String> EnabledDays = plugin.getConfig().getStringList("DaysToEnable");
            int radius = plugin.getConfig().getInt("CheckRadius");
            for (String Day : EnabledDays) {
                int currentDay = 0;
                if (Day.toLowerCase().contains("mon")) {
                    currentDay = 2;
                } else if (Day.toLowerCase().contains("tue")) {
                    currentDay = 3;
                } else if (Day.toLowerCase().contains("wed")) {
                    currentDay = 4;
                } else if (Day.toLowerCase().contains("thu")) {
                    currentDay = 5;
                } else if (Day.toLowerCase().contains("fri")) {
                    currentDay = 6;
                } else if (Day.toLowerCase().contains("sat")) {
                    currentDay = 7;
                } else if (Day.toLowerCase().contains("sun")) {
                    currentDay = 1;
                }
                if ((dow == currentDay) && (!alreadyDone.booleanValue())
                        && (plugin.getConfig().getBoolean("Enable"))) {
                    if (plugin.getConfig().getBoolean("CheckForSpawner")) {
                        if (!plugin.isLocationNearBlock(e.getPlayer().getLocation(), Material.MOB_SPAWNER, radius)) {
                            alreadyDone = Boolean.valueOf(true);
                            Player player = e.getPlayer();
                            int originalAmount = e.getAmount();
                            int newAmount = originalAmount;
                            if (plugin.getConfig().getBoolean("EnablePermMultiplier")) {
                                boolean found = false;
                                for (float temp = 0.0F; temp <= 10.0F; temp = (float) (temp + 0.1D)) {
                                    if (!player.isOp() && player.hasPermission(Perm.MULTIPLIER + temp)) {
                                        newAmount = (int) (originalAmount * temp);
                                        found = true;
                                    }
                                }
                                if ((!found)
                                        && (player.hasPermission(Perm.ALLOW))) {
                                    newAmount = (int) (originalAmount * plugin.getConfig().getDouble("Multiplier"));
                                }
                            } else if (player.hasPermission(Perm.ALLOW)) {
                                newAmount = (int) (originalAmount * plugin.getConfig().getDouble("Multiplier"));
                            }
                            e.setAmount(newAmount);
                        }
                    } else {
                        alreadyDone = Boolean.valueOf(true);
                        Player player = e.getPlayer();
                        int originalAmount = e.getAmount();
                        int newAmount = originalAmount;
                        if (plugin.getConfig().getBoolean("EnablePermMultiplier")) {
                            boolean found = false;
                            for (float temp = 0.0F; temp <= 10.0F; temp = (float) (temp + 0.1D)) {
                                if (!player.isOp() && player.hasPermission(Perm.MULTIPLIER + temp)) {
                                    newAmount = (int) (originalAmount * temp);
                                    found = true;
                                }
                            }
                            if ((!found)
                                    && (player.hasPermission(Perm.ALLOW))) {
                                newAmount = (int) (originalAmount * plugin.getConfig().getDouble("Multiplier"));
                            }
                        } else if (player.hasPermission(Perm.ALLOW)) {
                            newAmount = (int) (originalAmount * plugin.getConfig().getDouble("Multiplier"));
                        }
                        e.setAmount(newAmount);
                    }
                }
            }
        }
    
    }
    DurexpPlugin.java is the main class:

    Code:
    package me.vidsify.durexp;
    
    import me.vidsify.durexp.commands.DurexpExecutor;
    import me.vidsify.durexp.gravity.Updater;
    import me.vidsify.durexp.listeners.PlayerExpListener;
    
    import net.milkbowl.vault.chat.Chat;
    import net.milkbowl.vault.economy.Economy;
    import net.milkbowl.vault.permission.Permission;
    
    import org.bukkit.Location;
    import org.bukkit.Material;
    import org.bukkit.block.Block;
    import org.bukkit.event.Listener;
    import org.bukkit.plugin.PluginDescriptionFile;
    import org.bukkit.plugin.RegisteredServiceProvider;
    import org.bukkit.plugin.java.JavaPlugin;
    
    /**
    *
    * @author Vidsify
    */
    public class DurexpPlugin extends JavaPlugin implements Listener {
      
        public Permission permission;
        public Economy economy;
        public Chat chat;
        private static final int bukkitId = 80039;
    
        @Override
        public void onEnable() {
            saveDefaultConfig();
            loadConfiguration();
            PluginDescriptionFile pdffile = getDescription();
            getServer().getPluginManager().registerEvents(new PlayerExpListener(this), this);
            getCommand("durexp").setExecutor(new DurexpExecutor(this));
          
            //AutoUpdater
            if (getConfig().getBoolean("AutoUpdate", false)) {
                Updater localUpdater = new Updater(this, bukkitId, getFile(), Updater.UpdateType.DEFAULT, true);
            } else {
                getLogger().info("AutoUpdate is turned off.");
            }
          
            //Load Vault
            setupPermissions();
            setupEconomy();
            setupChat();
          
            getLogger().info("Linked to Vault!");
            getLogger().info("by Vidsify");
            getLogger().info("" + pdffile.getVersion() + " has been enabled()");
        }
    
        @Override
        public void onDisable() {
            saveConfig();
        }
    
        public void loadConfiguration() {
        }
      
        private boolean setupPermissions() {
            RegisteredServiceProvider<Permission> permissionProvider = getServer()
                    .getServicesManager().getRegistration(
                            net.milkbowl.vault.permission.Permission.class);
            if (permissionProvider != null) {
                permission = permissionProvider.getProvider();
            }
            return (permission != null);
        }
    
        private boolean setupChat() {
            RegisteredServiceProvider<Chat> chatProvider = getServer()
                    .getServicesManager().getRegistration(
                            net.milkbowl.vault.chat.Chat.class);
            if (chatProvider != null) {
                chat = chatProvider.getProvider();
            }
    
            return (chat != null);
        }
    
        private boolean setupEconomy() {
            RegisteredServiceProvider<Economy> economyProvider = getServer()
                    .getServicesManager().getRegistration(
                            net.milkbowl.vault.economy.Economy.class);
            if (economyProvider != null) {
                economy = economyProvider.getProvider();
            }
    
            return (economy != null);
        }
      
        @SuppressWarnings("deprecation")
        public boolean isLocationNearBlock(Location loc, Material type, int radius) {
          
            int x1 = loc.getBlockX() - radius;
            int y1 = loc.getBlockY() - radius;
            int z1 = loc.getBlockZ() - radius;
          
            int x2 = loc.getBlockX() + radius;
            int y2 = loc.getBlockY() + radius;
            int z2 = loc.getBlockZ() + radius;
          
            for (int x = x1; x <= x2; x++) {
                for (int y = y1; y <= y2; y++) {
                    for (int z = z1; z <= z2; z++) {
                        Block block = loc.getWorld().getBlockAt(x, y, z);
                        if (block.getType() == type) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    
        public boolean isDouble(String input) {
            try {
                Double.parseDouble(input);
                return true;
            } catch (NumberFormatException e) {
            }
            return false;
        }
    }
    perm.java:

    Code:
    package me.vidsify.durexp;
    
    /**
    *
    * @author Nikolai
    */
    public abstract class Perm {
      
        public static final String ALLOW = "doubleurexp.allow";
        public static final String ADMIN = "doubleurexp.use";
        public static final String MULTIPLIER = "doubleurexp.multiplier.";
      
    }
    There is also Gravity's autoupdater which I haven't posted here
     
  4. Offline

    Vidsify

  5. Offline

    drew6017

    Hum... For a starters, this plugin is very inefficient. In the on command method, you can just use if{} statements to catch the command. You don't have to use if else, and I would also return false if the command has not been found so that the player at least gets something. Second, I would put your perms in a enum. Third, you don't have to load the configuration in the onEnable method. Fourth, you have to check to see if the config file exists before saving it because when you save it, if you don't it overrides the existing file(causing your problem). Other than that, good job!
    Code:
            File file = new File(getDataFolder(), "config.yml");
            if(!file.exists()) {
                saveDefaultConfig();
            }
     
  6. Offline

    Vidsify

Thread Status:
Not open for further replies.

Share This Page