Trying to finish my plugin

Discussion in 'Plugin Development' started by cocoson, May 8, 2012.

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

    cocoson

    hello my name is cocoson and i have about 5 years total with development and started to get into java about a week back. My friend runs a minecraft bukkit server so i said hell i will try to make a plugin for it, well i got most of the code done just having a little problem.

    i cant seem to get it to read from a file
    what i'm trying to do is get a name from the file and show that the name is in the file and make it so the command will notify them that they are in the file alrdy.

    this is the code that i use to write and read,
    Code:
    package me.cocoson.CRules;
     
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
     
    public class CRulesPlayers {
     
        static File AcceptedList;
        private static ArrayList<String> Values;
     
        public CRulesPlayers(File file){
            CRulesPlayers.AcceptedList = file;
            CRulesPlayers.Values = new ArrayList<String>();
     
            if (CRulesPlayers.AcceptedList.exists() == false){
                try{
                    CRulesPlayers.AcceptedList.createNewFile();
                }catch (IOException e) {
                    System.err.println("Error: " + e.getMessage());
                }
            }
     
        }
     
        static void load(){
            try{
                DataInputStream input = new DataInputStream(new FileInputStream(AcceptedList));
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
         
                String line;
         
                while ((line = reader.readLine()) != null){
                    if (CRulesPlayers.contains(line) == false){
                        CRulesPlayers.Values.add(line);
                    }
             
                }
         
                reader.close();
                input.close();
            }catch (Exception e) {
                System.err.println("Error: " + e.getMessage());
            }
        }
     
        static void save(){
            try{
                FileWriter stream = new FileWriter(AcceptedList);
                BufferedWriter out = new BufferedWriter(stream);
         
                for (String value : CRulesPlayers.Values){
                    out.write(value);
                    out.newLine();
            }
         
                out.close();
                stream.close();
         
            }catch (IOException e) {
                System.err.println("Error: " + e.getMessage());
            }
        }
     
        static boolean contains(String value){
            return Values.contains(value);
        }
     
        static void add(String value){
            if (contains(value) == false){
                Values.add(value);
            }
        }
     
        public ArrayList<String> getNames(){
            return CRulesPlayers.Values;
        }
     
    }
    Command Executor
    Code:
    package me.cocoson.CRules;
     
    import java.util.List;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
     
    public class CRulesExecutor implements CommandExecutor {
     
        private CRules plugin;
        public CRulesExecutor(CRules plugin) {
            this.plugin = plugin;
        }
     
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String commandLabel,String[] args) {
            Player player = (Player)sender;
            if (commandLabel.equalsIgnoreCase("CRules")){
                List<String> rules = plugin.getConfig().getStringList("Rules");
                for (String rule : rules){
                    sender.sendMessage(rule.replaceAll("&([a-f0-9])", ChatColor.COLOR_CHAR + "$1"));
             
                }
             
            }else if(commandLabel.equalsIgnoreCase("CAccept")){
                    if (sender instanceof Player){
                    if (args.length == 0){
                    if (CRules.players.contains(player.getName())){
                        sender.sendMessage(CRules.AcceptedAllReady.replaceAll("&([a-f0-9])",
                        ChatColor.COLOR_CHAR + "$1")); 
                    }else{
                        if (CRules.readed.contains(sender)){
                            CRulesPlayers.add(player.getName());
                            CRulesPlayers.load();
                            sender.sendMessage(CRules.Accepted.replaceAll("&([a-f0-9])", ChatColor.COLOR_CHAR + "$1"));
                            CRulesPlayers.save();
                    }
                }
                    System.out.println("[CRules] Player: "+player.getName()+" Has accepted the rules!");
                    if(CRules.NotifyOPs == true){
                            if (player.isOp()){
                                    player.sendMessage(ChatColor.GOLD+"[CRules] "+ChatColor.GREEN+"Player: "+player.getName()+
                                    " has accepted the rules!");
                         
                            }
                        }
                }else{
                    sender.sendMessage(CRules.ReadRules.replaceAll("&([a-f0-9])", ChatColor.COLOR_CHAR + "S1"));
         
                        }
                    }
                }
            return true;
        }
    }
    
    Main
    Code:
    package me.cocoson.CRules;
     
    import java.io.File;
    import java.util.ArrayList;
    import java.util.logging.Logger;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.entity.Player;
    import org.bukkit.plugin.PluginManager;
    import org.bukkit.plugin.java.JavaPlugin;
     
    public class CRules extends JavaPlugin  {
       
        Logger log = Logger.getLogger("Minecraft");
       
        public static CRules plugin;
        protected CRulesPlayers AcceptedPlayers;
        private CRulesExecutor CRExecutor;
        private FileConfiguration config;
        public static ArrayList<String> players = new ArrayList<String>();
        public static ArrayList<String> rules = new ArrayList<String>();
        public static ArrayList<Player> readed = new ArrayList<Player>();
        public static String OnJoin,Accepted,ReadRules,AcceptedAllReady,CantBuild,CantMove,CantChat,CmdRules,CmdAccept,NotifyUserMsg;
        public static boolean NotifyOPs,NotifyUser,BuildBeforeAccept,ChatBeforeAccept,MoveBeforeAccept,CmdBlock;
       
        public void onDisable (){
            log.info("[CRules] is now unLoaded");
        }
     
       
        public void onEnable (){
            PluginManager pm = getServer().getPluginManager();
            log.info("[CRules] is now Loaded");
            CRExecutor = new CRulesExecutor(this);
           
            getCommand("CRules").setExecutor(CRExecutor);
            getCommand("CAccept").setExecutor(CRExecutor);
            pm.registerEvents(new CRulesListener(this), this);
           
            String pluginFolder = this.getDataFolder().getAbsolutePath();
           
            (new File(pluginFolder)).mkdirs();
           
            this.AcceptedPlayers = new CRulesPlayers(new File(pluginFolder + File.separator + "players-accepted.txt"));
           
            CRulesPlayers.load();
           
           
            getConfig().options().copyDefaults(true);
            saveConfig();
            config = getConfig();
            OnJoin = config.getString("OnJoin", "You have to accept the rules by doing /crules and /caccept");
            Accepted = config.getString("Accepted","You have succesfully accepted the rules!");
            ReadRules = config.getString("ReadRules","You must read the rules!");
            AcceptedAllReady = config.getString("AcceptedAllReady","You have allready accepted the rules!");
            CantBuild = config.getString("CantBuild","You can't build till you accept the rules!");
            CantMove = config.getString("CantMove","You can't move till you accept the rules!");
            CantChat = config.getString("CantChat","You cant Chat with other players untill you accept the rules!");
            CmdRules = config.getString("CmdRules","/crules");
            CmdAccept = config.getString("CmdAccept","/caccept");
            NotifyUserMsg = config.getString("NotifyUserMsg","You have to accept the rules! Use /crules and then /caccept!");
            NotifyOPs = config.getBoolean("NotifyOps", true);
            NotifyUser = config.getBoolean("NotifyUser", true);
            BuildBeforeAccept = config.getBoolean("BuildBeforeAccept", false);
            ChatBeforeAccept = config.getBoolean(" ChatBeforeAccept", false);
            MoveBeforeAccept = config.getBoolean("MoveBeforeAccept", false);
            CmdBlock = config.getBoolean("BlockCommandsBeforeAccept", true);
           
            saveConfig();
            CRulesPlayers.load();
            CRulesPlayers.save();
           
        }
    }
    
    Listener Class
    Code:
    package me.cocoson.CRules;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.block.BlockBreakEvent;
    import org.bukkit.event.block.BlockPlaceEvent;
    import org.bukkit.event.player.PlayerCommandPreprocessEvent;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.event.player.PlayerMoveEvent;
    
    public class CRulesListener implements Listener{
        
        public static CRules plugin;
        
        public CRulesListener(CRules instance) {
            plugin = instance;
        }
        
        @EventHandler
        public void onPlayerJoin(PlayerJoinEvent event){
            if(CRules.NotifyUser == true){
                final Player player = event.getPlayer();
                
                Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(new CRules(), new Runnable() {
                    public void run() {
                        player.sendMessage(CRules.NotifyUserMsg.replaceAll("&([a-f0-9])", ChatColor.COLOR_CHAR + "$1"));
                    }
                    
                }, 10L);
            }
    
        }
        
        @EventHandler
        public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event){
                Player player = event.getPlayer();
                String cmd = event.getMessage();
                String[] args = event.getMessage().split(" ");
                String[] command = CRules.CmdRules.split(" ");
                
            if(cmd.equalsIgnoreCase(CRules.CmdRules)){
                if(!(CRules.readed.contains(player))){
                    CRules.readed.add(player);    
                }
                
            }else{
                if(!args[0].equalsIgnoreCase(command[0]) && CRules.CmdBlock && !args[0].equalsIgnoreCase("/CAccept") && !CRules.players.contains(event.getPlayer().getName())){
                    player.sendMessage(CRules.ReadRules.replaceAll("&([a-f0-9])", ChatColor.COLOR_CHAR + "$1"));
                    event.setCancelled(true);
                }
            }
        }
        @EventHandler
        public void onBlockPlace(BlockPlaceEvent event) {
            Player player = event.getPlayer();
            if(CRules.BuildBeforeAccept == false){
                if (CRules.players.contains(player.getName())){
            }else{
                event.setCancelled(true);
                player.sendMessage(CRules.CantBuild.replaceAll("&([a-f0-9])", ChatColor.COLOR_CHAR + "$1"));
                }
            }
        }
        @EventHandler
        public void onBlockBreak(BlockBreakEvent event){
            Player player = event.getPlayer();
            if(CRules.BuildBeforeAccept == false){
                if (CRules.players.contains(player.getName())){
                }else{
                    event.setCancelled(true);
                    player.sendMessage(CRules.CantBuild.replaceAll("&([a-f0-9])", ChatColor.COLOR_CHAR + "$1"));
                }
            }
        }
        @EventHandler
        public void onPlayerMove(PlayerMoveEvent event){
            if((!CRules.players.contains(event.getPlayer().getName()))&& (CRules.MoveBeforeAccept == false)){
                event.setCancelled(true);
            }
        }
    
    }
    
    maybe some one can help me figure out why its not reading from file.
     
  2. Offline

    Nitnelave

    Do you get any errors? or does it simply not read the file?
     
  3. Offline

    MCForger

    seeing the main will be helpful.
     
  4. Offline

    Darksonn

    First 2 things about style that i just want to point out.
    Dont use boolean == false to see if a boolean is false instead do !boolean (Note the !)

    All variables should start with a lower case letter, including class variables.


    Now i looked at your code and i cant see where CRulesPlayers is used in your command executor, so could we see the main class please. Also if theres any exceptions in the console i would like to see those too!
     
  5. Offline

    cocoson

    ok the main is now in the first post at the bottom

    Nitnelave
    no errors at all

    Darksonn
    the main is in the top post now
     
  6. Offline

    ZachBora

    Instead of a static file, you should keep a list or an array of string or players.
     
  7. Offline

    Darksonn

    I think that static variables should always be final.
     
  8. Offline

    ZachBora

    Yeah seriously, what's with all those static variables in your plugin class... It's not like the class needs to be loaded more than once! It's a memory leak if you create multiple instances of your plugin class.
     
  9. Offline

    cocoson

    lol i'm new to java was just trying to make the plugin work before i went in and fixed all the memory leaks and little errors
     
  10. Offline

    Darksonn

    Maybe by the way can i see all remaining classes of your plugin? Ill fix your plugin after getting all files from it. (And comment why i edited something)
     
  11. Offline

    cocoson

    there u go just added the last class to the main post
     
  12. Offline

    Darksonn

    Finished the plugin (<Edit by Moderator: Redacted mediafire url>
     
    Last edited by a moderator: Nov 10, 2016
  13. Offline

    cocoson

    thanks i will study and make sure to use ur notes when making other plugins
     
  14. They can be used for easier access expecially because you shouldn't have more instances of a plugin.
     
  15. Offline

    ZachBora

    This is one of the reasons to remove the /reload command. Static variables.
     
  16. Offline

    colony88

    [quote uid=3521 name="Darksonn" post=1115426]Finished the plugin (<Edit by Moderator: Redacted mediafire url>
    Could I get a copy of the plugin too? I need to know how to read/write thing to a flatfile and the mediafire page won't let me download...

    EDIT: nvm, it was a problem with my firewall
     
    Last edited by a moderator: Nov 10, 2016
  17. My plugin works just fine after reload with all global variables as static :}

    Well, every plugin should make it's own reload command to safely reload the settings and other stuff anyway... but it would be nice if the bukkit API added something easy :}
     
  18. Offline

    LucasEmanuel

    Oh wow dear god! As they said above dont use static classes or methods in an OOP. Static objects in an OOP is the work of the devil.

    Learn to use gets and sets.
     
  19. LucasEmanuel
    That's like racism. =) Statics are there for a reason, they're useful when used right.

    Also you're kinda mixing up stuff, getters and setters are used to process data and store it in private variables as opposed to using public variables, those are unrelated to static.
     
  20. Offline

    cocoson

    lol like i said i'm new to java still learning it and from Darksonn fix's in the code i will learn even more still a long way off from finishing the plugin but now i know that Static variables aren't the best way of going about it but also they can be useful.
     
  21. Offline

    Darksonn

    If you ever have aproblem again, pm me and ill do what i can to help! Also i dont know what the error was but after my cleanup it worked as a charm.
     
Thread Status:
Not open for further replies.

Share This Page