Why is this happening?

Discussion in 'Plugin Development' started by boss86741, Mar 26, 2013.

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

    boss86741

    I am pretty new to date/time oriented plugins.

    I made a tempbanning plugin.

    Code:
    20:09:10 [INFO] boss86741 issued server command: /tempban boss86741 1d
    20:09:10 [INFO] Player boss86741 was banned by boss86741 for 1364342950704.
    20:09:19 [WARNING] [Enjin Minecraft Plugin] Enjin Minecraft plugin was updated to version 2.4.2. Please restart your server.
    20:10:12 [INFO] boss86741[/127.0.0.1:54854] logged in with entity id 614 at ([survivaworld] 573.1667839059104, 79.0, 750.3881112328812)
    20:10:24 [INFO] boss86741 issued server command: /gm 1

    You can probably see that I wrote 1d aka 1day but it said player boss86741 was banned by boss86741 for 1364342950704.


    The plugin has 4 classes.

    Main class:
    Code:
    package com.boss86741.plugins.CustomBans;
     
    import java.io.File;
     
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.player.PlayerLoginEvent;
    import org.bukkit.plugin.java.JavaPlugin;
     
    import com.boss86741.plugins.CustomBans.commands.BanExecutor;
    import com.boss86741.plugins.CustomBans.util.ListStore;
     
    public class CustomBans extends JavaPlugin {
        public ListStore bannedPlayers;
       
        BanExecutor b = new BanExecutor(this);   
     
        public String target = b.getTarget();
       
        @EventHandler
        public boolean onPlayerLogin(PlayerLoginEvent event) {
            String player = event.getPlayer().getName();
            Player pl = event.getPlayer();
            if (bannedPlayers.contains(player)) {
                pl.kickPlayer("You were banned for " + b);
                return true;
            }
        return false;
        }
       
        @Override
        public void onEnable() {
           
            String pluginFolder = this.getDataFolder().getAbsolutePath();
           
            (new File(pluginFolder)).mkdirs();
           
            this.bannedPlayers = new ListStore(new File(pluginFolder + File.separator + "bannedPlayers.yml"));
           
            this.bannedPlayers.load();
           
            getLogger().info("Ban Tracker Version 1.0!");
            getLogger().warning("This version is custom made!");
           
            this.getCommand("tempban").setExecutor(new BanExecutor(this));
        }
       
        @Override
        public void onDisable() {
            this.bannedPlayers.save();
        }
     
        public void setBanTimeout(long banTimestamp) throws InterruptedException {
            getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable()
            {
              public void run() {
                bannedPlayers.remove(target);
              }
            }, banTimestamp*20);
        }
    }
    
    BanExecutor
    Code:
    package com.boss86741.plugins.CustomBans.commands;
     
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
     
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.entity.Player;
     
    import com.boss86741.plugins.CustomBans.CustomBans;
     
    public class BanExecutor implements CommandExecutor {
        DateUtil dateUtil = new DateUtil();
       
        static Player player = null;
       
        public CustomBans plugin;
       
        public BanExecutor(CustomBans plugin) {
            this.plugin = plugin;
        }
       
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        Date date = new Date();
        String d = "1 Day";
        String target;
        long banTimestamp = 0;
       
        @Override
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
            if(cmd.getName().equalsIgnoreCase("tempban")) {
                if (sender instanceof Player) {
                    player = (Player) sender;
                }
                    if (player == null) {
                        sender.sendMessage(ChatColor.RED + "Can't be used from the console.");
                    } else {
                        if (args.length <= 1) {
                            sender.sendMessage(ChatColor.RED + "Not enough arguments! Try /tempban <player> <number_of_days>");
                            return true;
                        } else {
                            if (player.hasPermission("custombans.admin.tempban")) {
                                String plName = player.getName();
                               
                                target = args[0];
                                Player target1 = plugin.getServer().getPlayer(args[0]);
                               
                                try {
                                    banTimestamp = DateUtil.parseDateDiff(args[1], true);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                               
                                try {
                                    plugin.setBanTimeout(banTimestamp);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                plugin.bannedPlayers.add(target);
                               
                                if (target != null) {
                                    target1.kickPlayer("You were banned by " + plName + " for " + banTimestamp + ".");
                                    Bukkit.getServer().broadcastMessage(ChatColor.GOLD + "Player " + ChatColor.RED + target + ChatColor.GOLD + " was banned by " + ChatColor.RED + plName + ChatColor.GOLD + " for " + banTimestamp + ".");
                                }
                        }
                    }
                }
            return true;
            }
        return false;
        }
       
        public String getTarget() {
            return target;
        }
       
        public long getTimeBanned() {
            return banTimestamp;
        }
    }
    
    ListStore
    Code:
    package com.boss86741.plugins.CustomBans.util;
     
    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;
     
    import org.bukkit.ChatColor;
    import org.bukkit.command.CommandSender;
     
    import com.boss86741.plugins.CustomBans.CustomBans;
    import com.boss86741.plugins.CustomBans.commands.BanExecutor;
     
    public class ListStore {
        private File storageFile;
       
        private ArrayList<String> values;
     
        private CustomBans plugin;
       
        public ListStore(CustomBans plugin) {
            this.plugin = plugin;
        }
     
        BanExecutor b = new BanExecutor(plugin);   
     
        public String target = b.getTarget();
       
        CommandSender sender;
        public void error() {
            sender.sendMessage(ChatColor.GREEN + "This person is not banned!");
        }
       
        public ListStore(File file) {
            this.storageFile = file;
            this.values = new ArrayList<String>();
           
            if (this.storageFile.exists() == false) {
                try {
                    this.storageFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        public void load() {
            try {
                DataInputStream input = new DataInputStream(new FileInputStream(this.storageFile));
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
               
                String line, value;
               
                while ((line = reader.readLine()) != null) {
                    if (this.values.contains(line) == false) {
                        this.values.add(line);
                    }
                }
               
                reader.close();
                input.close();
               
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public void save() {
            try {
                FileWriter stream = new FileWriter(this.storageFile);
                BufferedWriter out = new BufferedWriter(stream);
               
                for (String value : this.values) {
                    out.write(value);
                    out.newLine();
                }
               
                out.close();
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
       
        public boolean contains (String target) {
            return this.values.contains(target);
        }
       
        public boolean add(String value) {
            if (this.contains(value) == false) {
                this.values.add(value);
            return true;
            }
        return false;
        }
       
        public void remove(String target) {
            if (this.contains(target) == true) {
                this.values.remove(target);
            } else {
                error();
            }
        }
       
        public ArrayList<String> getValues() {
            return this.values;
        }
    }
    
    DateUtil
    Code:
    package com.boss86741.plugins.CustomBans.commands;
     
    import java.util.*;
    import java.util.logging.Logger;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
     
     
    public class DateUtil
    {
        DateUtil()
        {
        }
        private final static Logger logger = Logger.getLogger("Minecraft");
        private final static Pattern INVALIDFILECHARS = Pattern.compile("[^a-z0-9]");
        private final static Pattern INVALIDCHARS = Pattern.compile("[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]");
     
        //Used to clean file names before saving to disk
        public static String sanitizeFileName(final String name)
        {
            return safeString(name);
        }
     
        //Used to clean strings/names before saving as filenames/permissions
        public static String safeString(final String string)
        {
            return INVALIDFILECHARS.matcher(string.toLowerCase(Locale.ENGLISH)).replaceAll("_");
        }
     
        //Less restrictive string sanitizing, when not used as perm or filename
        public static String sanitizeString(final String string)
        {
            return INVALIDCHARS.matcher(string).replaceAll("");
        }
     
        public static String formatDateDiff(long date)
        {
            Calendar c = new GregorianCalendar();
            c.setTimeInMillis(date);
            Calendar now = new GregorianCalendar();
            return DateUtil.formatDateDiff(now, c);
        }
     
        public static String formatDateDiff(Calendar fromDate, Calendar toDate)
        {
            boolean future = false;
            if (toDate.equals(fromDate))
            {
                return ("now");
            }
            if (toDate.after(fromDate))
            {
                future = true;
            }
     
            StringBuilder sb = new StringBuilder();
            int[] types = new int[]
            {
                Calendar.YEAR,
                Calendar.MONTH,
                Calendar.DAY_OF_MONTH,
                Calendar.HOUR_OF_DAY,
                Calendar.MINUTE,
                Calendar.SECOND
            };
            String[] names = new String[]
            {
                ("year"),
                ("years"),
                ("month"),
                ("months"),
                ("day"),
                ("days"),
                ("hour"),
                ("hours"),
                ("minute"),
                ("minutes"),
                ("second"),
                ("seconds")
            };
            int accuracy = 0;
            for (int i = 0; i < types.length; i++)
            {
                if (accuracy > 2)
                {
                    break;
                }
                int diff = dateDiff(types[i], fromDate, toDate, future);
                if (diff > 0)
                {
                    accuracy++;
                    sb.append(" ").append(diff).append(" ").append(names[i * 2 + (diff > 1 ? 1 : 0)]);
                }
            }
            if (sb.length() == 0)
            {
                return "now";
            }
            return sb.toString().trim();
        }
     
        private static int dateDiff(int type, Calendar fromDate, Calendar toDate, boolean future)
        {
            int diff = 0;
            long savedDate = fromDate.getTimeInMillis();
            while ((future && !fromDate.after(toDate)) || (!future && !fromDate.before(toDate)))
            {
                savedDate = fromDate.getTimeInMillis();
                fromDate.add(type, future ? 1 : -1);
                diff++;
            }
            diff--;
            fromDate.setTimeInMillis(savedDate);
            return diff;
        }
     
        public static long parseDateDiff(String time, boolean future) throws Exception
        {
            Pattern timePattern = Pattern.compile(
                    "(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?"
                    + "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?"
                    + "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?"
                    + "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?"
                    + "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?"
                    + "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?"
                    + "(?:([0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE);
            Matcher m = timePattern.matcher(time);
            int years = 0;
            int months = 0;
            int weeks = 0;
            int days = 0;
            int hours = 0;
            int minutes = 0;
            int seconds = 0;
            Calendar c = new GregorianCalendar();
            if (years > 0)
            {
                c.add(Calendar.YEAR, years * (future ? 1 : -1));
            }
            if (months > 0)
            {
                c.add(Calendar.MONTH, months * (future ? 1 : -1));
            }
            if (weeks > 0)
            {
                c.add(Calendar.WEEK_OF_YEAR, weeks * (future ? 1 : -1));
            }
            if (days > 0)
            {
                c.add(Calendar.DAY_OF_MONTH, days * (future ? 1 : -1));
            }
            if (hours > 0)
            {
                c.add(Calendar.HOUR_OF_DAY, hours * (future ? 1 : -1));
            }
            if (minutes > 0)
            {
                c.add(Calendar.MINUTE, minutes * (future ? 1 : -1));
            }
            if (seconds > 0)
            {
                c.add(Calendar.SECOND, seconds * (future ? 1 : -1));
            }
     
            Calendar max = new GregorianCalendar();
            max.add(Calendar.YEAR, 10);
            if (c.after(max))
            {
                return max.getTimeInMillis();
            }
            return c.getTimeInMillis();
        }
    
     
  2. Offline

    Technius

    In PlayerLoginEvent, you should set the result to DENY instead of kicking the player.
     
  3. Offline

    boss86741

    ?
     
  4. Offline

    Tirelessly

    Do not use a scheduler for this. Use a map String name,long unbanTime
     
  5. Offline

    Technius

    Code:
    //Something like this?
    event.disallow(Result.KICK_BANNED, "Your message here");
     
    //Or this
    event.setResult(Result.KICK_BANNED);
    event.setKickMessage("Your message here");
    
    Oh, and what Tirelessly said.
     
  6. Offline

    boss86741

    How does that work?

    Sorry for my derpiness, I am new to this type of plugin coding :)
     
  7. Offline

    seemethere

  8. Offline

    boss86741

  9. Offline

    Technius

    Code:
    //Create your map
    //You might want to keep this as a variable somewhere
    HashMap<String, Long> map = new HashMap<String,Long>();
     
    //To add a value
    map.put("playeryouwanttoban", timeinmillisecondswhentheywillbeunbanned);
     
    //To remove a value
    map.remove("playeryouwanttounban");
     
    //To check if a value exists
    map.containsKey("playerthatmightbebanned");
    
    More can be found in Oracle's Java tutorials.
     
  10. Offline

    seemethere

    boss86741
    The best thing to do would be to store the time they were banned in a map in the Long data type.

    Next in OnPlayerLogin you get the current time in Millis and see if the difference between the
    stored time and the current time is bigger than the custom ban time you have set.

    If it isn't you do a event.disallow("Whatever you want to say");

    If it is you remove them from the map.

    And that's how you do temporary bans.
     
  11. Offline

    Technius

    It's better to store the time when they will be unbanned in the map so that you only have to have one map.
     
  12. Offline

    seemethere

    Technius
    You only need one map in mine
    Map<String, Long> timesTheyWereBanned
     
  13. Offline

    Tirelessly

    But then you can only have one ban time instead of a different ban time for everyone.
     
  14. Offline

    seemethere

    Tirelessly

    True, I've recently been working on a ban on death type plugin and I forgot that people want to be able to use more than 1 time xD

    Forgive my narrow-mindedness
     
Thread Status:
Not open for further replies.

Share This Page