diff --git a/plugin.yml b/plugin.yml index 749a23dc..0e3b9283 100644 --- a/plugin.yml +++ b/plugin.yml @@ -3,7 +3,7 @@ name: NoCheat author: Evenprime main: cc.co.evenprime.bukkit.nocheat.NoCheat -version: 1.12 +version: 1.12a softdepend: [ Permissions, CraftIRC ] diff --git a/src/cc/co/evenprime/bukkit/nocheat/ConfigurationException.java b/src/cc/co/evenprime/bukkit/nocheat/ConfigurationException.java index 56f6bbc0..5ab06c77 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/ConfigurationException.java +++ b/src/cc/co/evenprime/bukkit/nocheat/ConfigurationException.java @@ -2,12 +2,12 @@ package cc.co.evenprime.bukkit.nocheat; public class ConfigurationException extends Exception { - /** + /** * */ - private static final long serialVersionUID = -457634587532590464L; + private static final long serialVersionUID = -457634587532590464L; - public ConfigurationException(String message) { - super(message); - } + public ConfigurationException(String message) { + super(message); + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/CustomCommandSender.java b/src/cc/co/evenprime/bukkit/nocheat/CustomCommandSender.java index f39000bf..9f87d6cf 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/CustomCommandSender.java +++ b/src/cc/co/evenprime/bukkit/nocheat/CustomCommandSender.java @@ -42,8 +42,7 @@ public class CustomCommandSender implements CommandSender { } @Override - public PermissionAttachment addAttachment(Plugin plugin, String name, - boolean value) { + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { // Whatever it is, I don't care return null; } @@ -55,8 +54,7 @@ public class CustomCommandSender implements CommandSender { } @Override - public PermissionAttachment addAttachment(Plugin plugin, String name, - boolean value, int ticks) { + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { // Whatever it is, I don't care return null; } diff --git a/src/cc/co/evenprime/bukkit/nocheat/DataManager.java b/src/cc/co/evenprime/bukkit/nocheat/DataManager.java index 58577bfb..fe977fe4 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/DataManager.java +++ b/src/cc/co/evenprime/bukkit/nocheat/DataManager.java @@ -14,156 +14,154 @@ import cc.co.evenprime.bukkit.nocheat.data.NukeData; import cc.co.evenprime.bukkit.nocheat.data.PermissionData; import cc.co.evenprime.bukkit.nocheat.data.SpeedhackData; - public class DataManager { - // Store data between Events - private final Map playerData = new HashMap(); - - public DataManager() { } - - /** - * Go through the playerData HashMap and remove players that are no longer online - * from the map. This should be called in long, regular intervals (e.g. every 10 minutes) - * to keep the memory footprint of the plugin low - */ - public void cleanPlayerDataCollection() { - synchronized(playerData) { - Iterator> it = playerData.entrySet().iterator(); - while (it.hasNext()) { - Map.Entry pairs = (Map.Entry)it.next(); - if(!pairs.getKey().isOnline()) { - // Cancel all referenced tasks before removing the entry - cancelTasks(pairs.getValue()); + // Store data between Events + private final Map playerData = new HashMap(); + + public DataManager() {} + + /** + * Go through the playerData HashMap and remove players that are no longer + * online + * from the map. This should be called in long, regular intervals (e.g. + * every 10 minutes) + * to keep the memory footprint of the plugin low + */ + public void cleanPlayerDataCollection() { + synchronized(playerData) { + Iterator> it = playerData.entrySet().iterator(); + while(it.hasNext()) { + Map.Entry pairs = (Map.Entry) it.next(); + if(!pairs.getKey().isOnline()) { + // Cancel all referenced tasks before removing the entry + cancelTasks(pairs.getValue()); it.remove(); - } + } - } - } - } - + } + } + } - /** - * Main access to data that needs to be stored between different events. - * Always returns a NoCheatData object, because if there isn't one - * for the specified player, one will be created. - * - * @param p - * @return - */ - public NoCheatData getPlayerData(Player p) { - NoCheatData data = playerData.get(p); + /** + * Main access to data that needs to be stored between different events. + * Always returns a NoCheatData object, because if there isn't one + * for the specified player, one will be created. + * + * @param p + * @return + */ + private NoCheatData getPlayerData(final Player p) { + NoCheatData data = playerData.get(p); - if(data == null) { - synchronized(playerData) { - // If we have no data for the player, create some - data = new NoCheatData(); - playerData.put(p, data); - } - } + if(data == null) { + synchronized(playerData) { + // If we have no data for the player, create some + data = new NoCheatData(); + playerData.put(p, data); + } + } - return data; - } - - public AirbuildData getAirbuildData(Player p) { + return data; + } - NoCheatData data = getPlayerData(p); + public AirbuildData getAirbuildData(Player p) { - if(data.airbuild == null) { - data.airbuild = new AirbuildData(); - } + NoCheatData data = getPlayerData(p); - return data.airbuild; - } - - public MovingData getMovingData(final Player p) { + if(data.airbuild == null) { + data.airbuild = new AirbuildData(); + } - final NoCheatData data = getPlayerData(p); + return data.airbuild; + } - if(data.moving == null) { - data.moving = new MovingData(); - data.moving.teleportedTo = p.getLocation(); - } + public MovingData getMovingData(final Player p) { - return data.moving; - } - - public NukeData getNukeData(Player p) { + final NoCheatData data = getPlayerData(p); - NoCheatData data = getPlayerData(p); + if(data.moving == null) { + data.moving = new MovingData(); + } - if(data.nuke == null) { - data.nuke = new NukeData(); - } + return data.moving; + } - return data.nuke; - } - - public PermissionData getPermissionData(Player p) { + public NukeData getNukeData(Player p) { - NoCheatData data = getPlayerData(p); + NoCheatData data = getPlayerData(p); - if(data.permission == null) { - data.permission = new PermissionData(); - } + if(data.nuke == null) { + data.nuke = new NukeData(); + } - return data.permission; - } - - public SpeedhackData getSpeedhackData(Player p) { + return data.nuke; + } - NoCheatData data = getPlayerData(p); + public PermissionData getPermissionData(Player p) { - if(data.speedhack == null) { - data.speedhack = new SpeedhackData(); - } + NoCheatData data = getPlayerData(p); - return data.speedhack; - } - + if(data.permission == null) { + data.permission = new PermissionData(); + } + + return data.permission; + } + + public SpeedhackData getSpeedhackData(Player p) { + + NoCheatData data = getPlayerData(p); + + if(data.speedhack == null) { + data.speedhack = new SpeedhackData(); + } + + return data.speedhack; + } + + /** + * Go through the playerData HashMap and remove players that are no longer + * online + * from the map. This should be called in long, regular intervals (e.g. + * every 10 minutes) + * to keep the memory footprint of the plugin low + */ + public void cancelPlayerDataTasks() { + synchronized(playerData) { + Iterator> it = playerData.entrySet().iterator(); + while(it.hasNext()) { + cancelTasks(it.next().getValue()); + } + } + } + + private void cancelTasks(NoCheatData data) { - /** - * Go through the playerData HashMap and remove players that are no longer online - * from the map. This should be called in long, regular intervals (e.g. every 10 minutes) - * to keep the memory footprint of the plugin low - */ - public void cancelPlayerDataTasks() { - synchronized(playerData) { - Iterator> it = playerData.entrySet().iterator(); - while (it.hasNext()) { - cancelTasks(it.next().getValue()); - } - } - } - - private void cancelTasks(NoCheatData data) { - AirbuildData d = data.airbuild; - + if(d != null) { int id = d.summaryTask; - + if(id != -1) { Bukkit.getServer().getScheduler().cancelTask(id); - } - else { + } else { // To prevent accidentially creating a new one while cleaning up - d.summaryTask = 1; + d.summaryTask = 1; } } - + MovingData d2 = data.moving; - + if(d2 != null) { int id = d2.summaryTask; - + if(id != -1) { Bukkit.getServer().getScheduler().cancelTask(id); - } - else { + } else { // To prevent accidentially creating a new one while cleaning up - d2.summaryTask = 1; + d2.summaryTask = 1; } } - } + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/LogFileFormatter.java b/src/cc/co/evenprime/bukkit/nocheat/LogFileFormatter.java index 1b0d078d..fdb24b52 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/LogFileFormatter.java +++ b/src/cc/co/evenprime/bukkit/nocheat/LogFileFormatter.java @@ -7,6 +7,7 @@ import java.util.logging.Formatter; import java.util.logging.LogRecord; public class LogFileFormatter extends Formatter { + private final SimpleDateFormat date; public LogFileFormatter() { @@ -25,7 +26,7 @@ public class LogFileFormatter extends Formatter { builder.append(record.getMessage()); builder.append('\n'); - if (ex != null) { + if(ex != null) { StringWriter writer = new StringWriter(); ex.printStackTrace(new PrintWriter(writer)); builder.append(writer); @@ -33,5 +34,5 @@ public class LogFileFormatter extends Formatter { return builder.toString(); } - -} \ No newline at end of file + +} diff --git a/src/cc/co/evenprime/bukkit/nocheat/Main.java b/src/cc/co/evenprime/bukkit/nocheat/Main.java index fbfd9094..148ff65e 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/Main.java +++ b/src/cc/co/evenprime/bukkit/nocheat/Main.java @@ -4,12 +4,12 @@ import cc.co.evenprime.bukkit.nocheat.wizard.Wizard; public class Main { - /** - * @param args - */ - public static void main(String[] args) { + /** + * @param args + */ + public static void main(String[] args) { - Wizard w = new Wizard(); - w.setVisible(true); - } + Wizard w = new Wizard(); + w.setVisible(true); + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/NoCheat.java b/src/cc/co/evenprime/bukkit/nocheat/NoCheat.java index 30b985f9..10051251 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/NoCheat.java +++ b/src/cc/co/evenprime/bukkit/nocheat/NoCheat.java @@ -125,7 +125,7 @@ public class NoCheat extends JavaPlugin { try { dataManager.cancelPlayerDataTasks(); - + teardownCleanupTask(); teardownServerLagMeasureTask(); } catch(Exception e) { /* Can't do much in case of error here... */ @@ -323,7 +323,9 @@ public class NoCheat extends JavaPlugin { return false; if(useNewPermissionSystem) { - //System.out.println("New permissions system asked for " + PermissionData.permissionNames[permission] + " got " + player.hasPermission(PermissionData.permissionNames[permission])); + // System.out.println("New permissions system asked for " + + // PermissionData.permissionNames[permission] + " got " + + // player.hasPermission(PermissionData.permissionNames[permission])); return player.hasPermission(PermissionData.permissionNames[permission]); } diff --git a/src/cc/co/evenprime/bukkit/nocheat/actions/Action.java b/src/cc/co/evenprime/bukkit/nocheat/actions/Action.java index 002f1720..8f24861b 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/actions/Action.java +++ b/src/cc/co/evenprime/bukkit/nocheat/actions/Action.java @@ -3,18 +3,18 @@ package cc.co.evenprime.bukkit.nocheat.actions; /** * * @author Evenprime - * + * */ public abstract class Action { - public final int firstAfter; - public final boolean repeat; + public final int firstAfter; + public final boolean repeat; - public Action(int firstAfter, boolean repeat) { - this.firstAfter = firstAfter; - this.repeat = repeat; - } + public Action(int firstAfter, boolean repeat) { + this.firstAfter = firstAfter; + this.repeat = repeat; + } - public abstract String getName(); -} \ No newline at end of file + public abstract String getName(); +} diff --git a/src/cc/co/evenprime/bukkit/nocheat/actions/CancelAction.java b/src/cc/co/evenprime/bukkit/nocheat/actions/CancelAction.java index 2af5361d..eb8fcc54 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/actions/CancelAction.java +++ b/src/cc/co/evenprime/bukkit/nocheat/actions/CancelAction.java @@ -3,15 +3,17 @@ package cc.co.evenprime.bukkit.nocheat.actions; /** * * @author Evenprime - * + * */ public class CancelAction extends Action { - public final static CancelAction cancel = new CancelAction(); + public final static CancelAction cancel = new CancelAction(); - private CancelAction() { super(1, true); } + private CancelAction() { + super(1, true); + } - public String getName() { - return "cancel"; - } + public String getName() { + return "cancel"; + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/actions/CustomAction.java b/src/cc/co/evenprime/bukkit/nocheat/actions/CustomAction.java index d853ef63..8bfbcab6 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/actions/CustomAction.java +++ b/src/cc/co/evenprime/bukkit/nocheat/actions/CustomAction.java @@ -3,31 +3,29 @@ package cc.co.evenprime.bukkit.nocheat.actions; /** * * @author Evenprime - * + * */ public class CustomAction extends Action { - public final String command; + public final String command; - public CustomAction(int firstAfter, boolean repeat, String command) { - super(firstAfter, repeat); - this.command = command.trim(); - } + public CustomAction(int firstAfter, boolean repeat, String command) { + super(firstAfter, repeat); + this.command = command.trim(); + } - public String getName() { - return "custom"; - } - - public String getValue() { - if(firstAfter <= 1 && repeat) { - return command; - } - else if(repeat) { - return "["+firstAfter+"] "+ command; - } - else { - return "["+firstAfter+","+repeat+"] "+ command; - } - } + public String getName() { + return "custom"; + } + + public String getValue() { + if(firstAfter <= 1 && repeat) { + return command; + } else if(repeat) { + return "[" + firstAfter + "] " + command; + } else { + return "[" + firstAfter + "," + repeat + "] " + command; + } + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/actions/LogAction.java b/src/cc/co/evenprime/bukkit/nocheat/actions/LogAction.java index 98df05ea..97b30b1a 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/actions/LogAction.java +++ b/src/cc/co/evenprime/bukkit/nocheat/actions/LogAction.java @@ -3,33 +3,33 @@ package cc.co.evenprime.bukkit.nocheat.actions; /** * * @author Evenprime - * + * */ import java.util.logging.Level; public class LogAction extends Action { - public final Level level; + public final Level level; - public final static LogAction loglow = new LogAction(1, false, Level.INFO); - public final static LogAction logmed = new LogAction(1, false, Level.WARNING); - public final static LogAction loghigh = new LogAction(1, false, Level.SEVERE); + public final static LogAction loglow = new LogAction(1, false, Level.INFO); + public final static LogAction logmed = new LogAction(1, false, Level.WARNING); + public final static LogAction loghigh = new LogAction(1, false, Level.SEVERE); - public final static LogAction[] log = { loglow, logmed, loghigh }; + public final static LogAction[] log = {loglow, logmed, loghigh}; - private LogAction(int firstAfter, boolean repeat, Level level) { - super(firstAfter, repeat); - this.level = level; - } + private LogAction(int firstAfter, boolean repeat, Level level) { + super(firstAfter, repeat); + this.level = level; + } - public String getName() { - if(level.equals(Level.INFO)) - return "loglow"; - else if(level.equals(Level.WARNING)) - return "logmed"; - else if(level.equals(Level.SEVERE)) - return "loghigh"; - else - return ""; - } + public String getName() { + if(level.equals(Level.INFO)) + return "loglow"; + else if(level.equals(Level.WARNING)) + return "logmed"; + else if(level.equals(Level.SEVERE)) + return "loghigh"; + else + return ""; + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/checks/AirbuildCheck.java b/src/cc/co/evenprime/bukkit/nocheat/checks/AirbuildCheck.java index 489fc50c..d5218d0a 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/checks/AirbuildCheck.java +++ b/src/cc/co/evenprime/bukkit/nocheat/checks/AirbuildCheck.java @@ -20,130 +20,131 @@ import cc.co.evenprime.bukkit.nocheat.data.AirbuildData; import cc.co.evenprime.bukkit.nocheat.data.PermissionData; import cc.co.evenprime.bukkit.nocheat.listeners.AirbuildBlockListener; - /** - * Check if the player tries to place blocks in midair (which shouldn't be possible) + * Check if the player tries to place blocks in midair (which shouldn't be + * possible) * * @author Evenprime - * + * */ public class AirbuildCheck extends Check { - // How should airbuild violations be treated? - private Action actions[][]; + // How should airbuild violations be treated? + private Action actions[][]; - private int limits[]; + private int limits[]; - public AirbuildCheck(NoCheat plugin, NoCheatConfiguration config) { - super(plugin, "airbuild", PermissionData.PERMISSION_AIRBUILD, config); - } + public AirbuildCheck(NoCheat plugin, NoCheatConfiguration config) { + super(plugin, "airbuild", PermissionData.PERMISSION_AIRBUILD, config); + } - public void check(BlockPlaceEvent event) { + public void check(BlockPlaceEvent event) { - // Should we check at all? - if(skipCheck(event.getPlayer())) return; + // Should we check at all? + if(skipCheck(event.getPlayer())) + return; - // Are all 6 sides "air-blocks" -> cancel the event - if( event.getBlockAgainst().getType() == Material.AIR && event.getBlockPlaced().getType() != Material.AIR ) { - final AirbuildData data = plugin.getDataManager().getAirbuildData(event.getPlayer()); - final Player p = event.getPlayer(); + // Are all 6 sides "air-blocks" -> cancel the event + if(event.getBlockAgainst().getType() == Material.AIR && event.getBlockPlaced().getType() != Material.AIR) { + final AirbuildData data = plugin.getDataManager().getAirbuildData(event.getPlayer()); + final Player p = event.getPlayer(); - if(data.summaryTask == -1) { - Runnable r = new Runnable() { + if(data.summaryTask == -1) { + Runnable r = new Runnable() { - @Override - public void run() { - try { - summary(p, data); - // deleting its own reference - data.summaryTask = -1; - }catch(Exception e) {} - } - }; + @Override + public void run() { + try { + summary(p, data); + // deleting its own reference + data.summaryTask = -1; + } catch(Exception e) {} + } + }; - // Give a summary in 100 ticks ~ 1 second - data.summaryTask = plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, r, 100); - } + // Give a summary in 100 ticks ~ 1 second + data.summaryTask = plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, r, 100); + } - data.perFiveSeconds++; + data.perFiveSeconds++; - // which limit has been reached - for(int i = limits.length-1; i >= 0; i--) { - if(data.perFiveSeconds >= limits[i]) { - action(actions[i], event, data.perFiveSeconds - limits[i]+1); - break; - } - } - } - } + // which limit has been reached + for(int i = limits.length - 1; i >= 0; i--) { + if(data.perFiveSeconds >= limits[i]) { + action(actions[i], event, data.perFiveSeconds - limits[i] + 1); + break; + } + } + } + } - private void action(Action actions[], BlockPlaceEvent event, int violations) { + private void action(Action actions[], BlockPlaceEvent event, int violations) { - if(actions == null) return; + if(actions == null) + return; - // Execute actions in order - for(Action a : actions) { - if(a.firstAfter <= violations) { - if(a.firstAfter == violations || a.repeat) { - if(a instanceof LogAction) { - final Location l = event.getBlockPlaced().getLocation(); - String logMessage = "Airbuild: "+event.getPlayer().getName()+" tried to place block " + event.getBlockPlaced().getType() + " in the air at " + l.getBlockX() + "," + l.getBlockY() +"," + l.getBlockZ(); - plugin.log(((LogAction)a).level, logMessage); - } - else if(a instanceof CancelAction) { - event.setCancelled(true); - } - else if(a instanceof CustomAction) { - plugin.handleCustomAction((CustomAction)a, event.getPlayer()); - } - } - } - } - } + // Execute actions in order + for(Action a : actions) { + if(a.firstAfter <= violations) { + if(a.firstAfter == violations || a.repeat) { + if(a instanceof LogAction) { + final Location l = event.getBlockPlaced().getLocation(); + String logMessage = "Airbuild: " + event.getPlayer().getName() + " tried to place block " + event.getBlockPlaced().getType() + " in the air at " + l.getBlockX() + "," + l.getBlockY() + "," + l.getBlockZ(); + plugin.log(((LogAction) a).level, logMessage); + } else if(a instanceof CancelAction) { + event.setCancelled(true); + } else if(a instanceof CustomAction) { + plugin.handleCustomAction((CustomAction) a, event.getPlayer()); + } + } + } + } + } - private void summary(Player player, AirbuildData data) { + private void summary(Player player, AirbuildData data) { - // Give a summary according to the highest violation level we encountered in that second - for(int i = limits.length-1; i >= 0; i--) { - if(data.perFiveSeconds >= limits[i]) { - plugin.log(LogAction.log[i].level, "Airbuild summary: " +player.getName() + " total violations per 5 seconds: " + data.perFiveSeconds); - break; - } - } + // Give a summary according to the highest violation level we + // encountered in that second + for(int i = limits.length - 1; i >= 0; i--) { + if(data.perFiveSeconds >= limits[i]) { + plugin.log(LogAction.log[i].level, "Airbuild summary: " + player.getName() + " total violations per 5 seconds: " + data.perFiveSeconds); + break; + } + } - data.perFiveSeconds = 0; - } + data.perFiveSeconds = 0; + } - @Override - public void configure(NoCheatConfiguration config) { + @Override + public void configure(NoCheatConfiguration config) { - try { - limits = new int[3]; + try { + limits = new int[3]; - limits[0] = config.getIntegerValue("airbuild.limits.low"); - limits[1] = config.getIntegerValue("airbuild.limits.med"); - limits[2] = config.getIntegerValue("airbuild.limits.high"); + limits[0] = config.getIntegerValue("airbuild.limits.low"); + limits[1] = config.getIntegerValue("airbuild.limits.med"); + limits[2] = config.getIntegerValue("airbuild.limits.high"); - actions = new Action[3][]; + actions = new Action[3][]; - actions[0] = config.getActionValue("airbuild.action.low"); - actions[1] = config.getActionValue("airbuild.action.med"); - actions[2] = config.getActionValue("airbuild.action.high"); + actions[0] = config.getActionValue("airbuild.action.low"); + actions[1] = config.getActionValue("airbuild.action.med"); + actions[2] = config.getActionValue("airbuild.action.high"); - setActive(config.getBooleanValue("active.airbuild")); + setActive(config.getBooleanValue("active.airbuild")); - } catch (ConfigurationException e) { - setActive(false); - e.printStackTrace(); - } - } + } catch(ConfigurationException e) { + setActive(false); + e.printStackTrace(); + } + } - @Override - protected void registerListeners() { - PluginManager pm = Bukkit.getServer().getPluginManager(); + @Override + protected void registerListeners() { + PluginManager pm = Bukkit.getServer().getPluginManager(); - // Register listeners for airbuild check - pm.registerEvent(Event.Type.BLOCK_PLACE, new AirbuildBlockListener(this), Priority.Low, plugin); + // Register listeners for airbuild check + pm.registerEvent(Event.Type.BLOCK_PLACE, new AirbuildBlockListener(this), Priority.Low, plugin); - } + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/checks/BogusitemsCheck.java b/src/cc/co/evenprime/bukkit/nocheat/checks/BogusitemsCheck.java index 7679ba86..ffb77b36 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/checks/BogusitemsCheck.java +++ b/src/cc/co/evenprime/bukkit/nocheat/checks/BogusitemsCheck.java @@ -23,98 +23,101 @@ import cc.co.evenprime.bukkit.nocheat.listeners.BogusitemsPlayerListener; public class BogusitemsCheck extends Check { - public BogusitemsCheck(NoCheat plugin, NoCheatConfiguration config){ - super(plugin, "bogusitems", PermissionData.PERMISSION_BOGUSITEMS, config); - } + public BogusitemsCheck(NoCheat plugin, NoCheatConfiguration config) { + super(plugin, "bogusitems", PermissionData.PERMISSION_BOGUSITEMS, config); + } - public void check(PlayerPickupItemEvent event) { + public void check(PlayerPickupItemEvent event) { - // Should we check at all? - if(skipCheck(event.getPlayer())) return; + // Should we check at all? + if(skipCheck(event.getPlayer())) + return; - Item i = event.getItem(); - if(i != null) { - ItemStack s = i.getItemStack(); - if(s != null) { - if(s.getAmount() < 0) {// buggy item - event.getItem().remove(); - event.setCancelled(true); - plugin.log(Level.WARNING, event.getPlayer().getName() + " tried to pick up an invalid item. Item was removed."); + Item i = event.getItem(); + if(i != null) { + ItemStack s = i.getItemStack(); + if(s != null) { + if(s.getAmount() < 0) {// buggy item + event.getItem().remove(); + event.setCancelled(true); + plugin.log(Level.WARNING, event.getPlayer().getName() + " tried to pick up an invalid item. Item was removed."); - cleanPlayerInventory(event.getPlayer()); - } - } - } - } + cleanPlayerInventory(event.getPlayer()); + } + } + } + } - public void check(PlayerInteractEvent event) { + public void check(PlayerInteractEvent event) { - if(skipCheck(event.getPlayer())) return; + if(skipCheck(event.getPlayer())) + return; - if(event.hasItem() && event.getItem().getAmount() <= 0) {// buggy item - event.setCancelled(true); - plugin.log(Level.WARNING, event.getPlayer().getName() + " tried to use an invalid item. Item was removed."); - event.getPlayer().getInventory().remove(event.getItem()); + if(event.hasItem() && event.getItem().getAmount() <= 0) {// buggy item + event.setCancelled(true); + plugin.log(Level.WARNING, event.getPlayer().getName() + " tried to use an invalid item. Item was removed."); + event.getPlayer().getInventory().remove(event.getItem()); - cleanPlayerInventory(event.getPlayer()); - } - } + cleanPlayerInventory(event.getPlayer()); + } + } - public void check(PlayerDropItemEvent event) { + public void check(PlayerDropItemEvent event) { - if(skipCheck(event.getPlayer())) return; + if(skipCheck(event.getPlayer())) + return; - Item item = event.getItemDrop(); + Item item = event.getItemDrop(); - if(item.getItemStack() != null) { - ItemStack stack = item.getItemStack(); + if(item.getItemStack() != null) { + ItemStack stack = item.getItemStack(); - if(stack.getAmount() <= 0) { - plugin.log(Level.WARNING, event.getPlayer().getName() + " tried to drop an invalid item. Dropped item was changed to dirt."); - stack.setTypeId(3); // dirt - stack.setAmount(1); + if(stack.getAmount() <= 0) { + plugin.log(Level.WARNING, event.getPlayer().getName() + " tried to drop an invalid item. Dropped item was changed to dirt."); + stack.setTypeId(3); // dirt + stack.setAmount(1); - cleanPlayerInventory(event.getPlayer()); - } - } - } + cleanPlayerInventory(event.getPlayer()); + } + } + } - private void cleanPlayerInventory(Player player) { + private void cleanPlayerInventory(Player player) { - Inventory inv = player.getInventory(); + Inventory inv = player.getInventory(); - ItemStack stacks[] = inv.getContents(); + ItemStack stacks[] = inv.getContents(); - for(int i = 0; i < stacks.length; i++) { - if(stacks[i] != null && stacks[i].getAmount() <= 0) { - inv.clear(i); - plugin.log(Level.WARNING, "Removed invalid item from inventory of " + player.getName()); - } - } - } + for(int i = 0; i < stacks.length; i++) { + if(stacks[i] != null && stacks[i].getAmount() <= 0) { + inv.clear(i); + plugin.log(Level.WARNING, "Removed invalid item from inventory of " + player.getName()); + } + } + } - @Override - public void configure(NoCheatConfiguration config) { + @Override + public void configure(NoCheatConfiguration config) { - try { - setActive(config.getBooleanValue("active.bogusitems")); - } catch (ConfigurationException e) { - setActive(false); - e.printStackTrace(); - } - } + try { + setActive(config.getBooleanValue("active.bogusitems")); + } catch(ConfigurationException e) { + setActive(false); + e.printStackTrace(); + } + } - @Override - protected void registerListeners() { - PluginManager pm = Bukkit.getServer().getPluginManager(); + @Override + protected void registerListeners() { + PluginManager pm = Bukkit.getServer().getPluginManager(); - // Register listeners for itemdupe check - Listener bogusitemsPlayerListener = new BogusitemsPlayerListener(this); + // Register listeners for itemdupe check + Listener bogusitemsPlayerListener = new BogusitemsPlayerListener(this); - // Register listeners for itemdupe check - pm.registerEvent(Event.Type.PLAYER_PICKUP_ITEM, bogusitemsPlayerListener, Priority.Lowest, plugin); - pm.registerEvent(Event.Type.PLAYER_DROP_ITEM, bogusitemsPlayerListener, Priority.Lowest, plugin); - pm.registerEvent(Event.Type.PLAYER_INTERACT, bogusitemsPlayerListener, Priority.Lowest, plugin); + // Register listeners for itemdupe check + pm.registerEvent(Event.Type.PLAYER_PICKUP_ITEM, bogusitemsPlayerListener, Priority.Lowest, plugin); + pm.registerEvent(Event.Type.PLAYER_DROP_ITEM, bogusitemsPlayerListener, Priority.Lowest, plugin); + pm.registerEvent(Event.Type.PLAYER_INTERACT, bogusitemsPlayerListener, Priority.Lowest, plugin); - } + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/checks/Check.java b/src/cc/co/evenprime/bukkit/nocheat/checks/Check.java index 007c1e2f..a138d6c9 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/checks/Check.java +++ b/src/cc/co/evenprime/bukkit/nocheat/checks/Check.java @@ -1,6 +1,5 @@ package cc.co.evenprime.bukkit.nocheat.checks; - import org.bukkit.entity.Player; import cc.co.evenprime.bukkit.nocheat.ConfigurationException; @@ -8,64 +7,62 @@ import cc.co.evenprime.bukkit.nocheat.NoCheat; import cc.co.evenprime.bukkit.nocheat.config.NoCheatConfiguration; /** - * + * * @author Evenprime - * + * */ public abstract class Check { - private boolean active = false; - private boolean listenersRegistered = false; - private final int permission; - private final String name; - protected final NoCheat plugin; - - // Should OPs be checked if Permissions plugin is not available? - public boolean checkOPs; + private boolean active = false; + private boolean listenersRegistered = false; + private final int permission; + private final String name; + protected final NoCheat plugin; - protected Check(NoCheat plugin, String name, int permission, NoCheatConfiguration config) { - this.plugin = plugin; - this.permission = permission; - this.name = name; + // Should OPs be checked if Permissions plugin is not available? + public boolean checkOPs; - try { - checkOPs= config.getBooleanValue(name + ".checkops"); - } catch (ConfigurationException e) { - checkOPs = false; - } - - - configure(config); - } + protected Check(NoCheat plugin, String name, int permission, NoCheatConfiguration config) { + this.plugin = plugin; + this.permission = permission; + this.name = name; - public boolean skipCheck(Player player) { - // Should we check at all? - return !active || plugin.hasPermission(player, permission, checkOPs); - } - - protected abstract void configure(NoCheatConfiguration config); + try { + checkOPs = config.getBooleanValue(name + ".checkops"); + } catch(ConfigurationException e) { + checkOPs = false; + } - protected abstract void registerListeners(); + configure(config); + } - public boolean isActive() { - return active; - } + public boolean skipCheck(Player player) { + // Should we check at all? + return !active || plugin.hasPermission(player, permission, checkOPs); + } - protected void setActive(boolean active) { - synchronized(this) { - if(active && !listenersRegistered) { - listenersRegistered = true; - registerListeners(); - } - } + protected abstract void configure(NoCheatConfiguration config); - // There is no way to unregister listeners ... - this.active = active; - } + protected abstract void registerListeners(); - public String getName() { - return name; - } + public boolean isActive() { + return active; + } + protected void setActive(boolean active) { + synchronized(this) { + if(active && !listenersRegistered) { + listenersRegistered = true; + registerListeners(); + } + } + + // There is no way to unregister listeners ... + this.active = active; + } + + public String getName() { + return name; + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/checks/FlyingCheck.java b/src/cc/co/evenprime/bukkit/nocheat/checks/FlyingCheck.java index 53af1d24..5104ce5c 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/checks/FlyingCheck.java +++ b/src/cc/co/evenprime/bukkit/nocheat/checks/FlyingCheck.java @@ -1,109 +1,118 @@ package cc.co.evenprime.bukkit.nocheat.checks; - import org.bukkit.Location; import org.bukkit.entity.Player; import cc.co.evenprime.bukkit.nocheat.data.MovingData; /** - * Check if the player should be allowed to make that move, e.g. is he allowed to jump here or move that far in one step + * Check if the player should be allowed to make that move, e.g. is he allowed + * to jump here or move that far in one step * * @author Evenprime - * + * */ public class FlyingCheck { - public FlyingCheck() { } + public FlyingCheck() {} - // How many move events can a player have in air before he is expected to lose altitude (or eventually land somewhere) - private final static int jumpingLimit = 5; + // How many move events can a player have in air before he is expected to + // lose altitude (or eventually land somewhere) + private final static int jumpingLimit = 5; - // How high may a player get compared to his last location with ground contact - private final static double jumpHeight = 1.31D; + // How high may a player get compared to his last location with ground + // contact + private final static double jumpHeight = 1.31D; - // How much points should hovering attempts cause? - private final static double hoveringPunishment = 0.2D; - - // How high may a player move in one event on ground - private final static double stepHeight = 0.501D; + // How much points should hovering attempts cause? + private final static double hoveringPunishment = 0.2D; + // How high may a player move in one event on ground + private final static double stepHeight = 0.501D; - /** - * Calculate if and how much the player "failed" this check. The check should not - * modify any data - * - */ - public double check(final Player player, final Location from, final boolean fromOnGround, final Location to, final boolean toOnGround, final MovingData data) { + /** + * Calculate if and how much the player "failed" this check. The check + * should not + * modify any data + * + */ + public double check(final Player player, final Location from, final boolean fromOnGround, final Location to, final boolean toOnGround, final MovingData data) { - // How much higher did the player move than expected?? - double distanceAboveLimit = 0.0D; - - final double toY = to.getY(); - final double fromY = from.getY(); + // How much higher did the player move than expected?? + double distanceAboveLimit = 0.0D; - double limit = calculateVerticalLimit(data, fromOnGround) + jumpHeight; - - // Walk or start Jump - if(fromOnGround) - { - distanceAboveLimit = toY - Math.floor(fromY) - limit; - } - // Land or Fly/Fall - else - { - final Location l; + final double toY = to.getY(); + final double fromY = from.getY(); - if(data.setBackPoint == null) - l = from; - else - l = data.setBackPoint; + double limit = calculateVerticalLimit(data, fromOnGround) + jumpHeight; - if(data.jumpPhase > jumpingLimit) { - limit -= (data.jumpPhase-jumpingLimit) * 0.2D; - } + // Walk or start Jump + if(fromOnGround) { + distanceAboveLimit = toY - Math.floor(fromY) - limit; + } + // Land or Fly/Fall + else { + final Location l; - if(toOnGround) limit += stepHeight; + if(data.setBackPoint == null) + l = from; + else + l = data.setBackPoint; - distanceAboveLimit = toY - Math.floor(l.getY()) - limit; + if(data.jumpPhase > jumpingLimit) { + limit -= (data.jumpPhase - jumpingLimit) * 0.2D; + } - // Always give some bonus points in case of identical Y values in midair (hovering player) - if(fromY == toY && !toOnGround) { - distanceAboveLimit = Math.max(hoveringPunishment, distanceAboveLimit+hoveringPunishment); - } - } + if(toOnGround) + limit += stepHeight; - return distanceAboveLimit; - } + distanceAboveLimit = toY - Math.floor(l.getY()) - limit; - private double calculateVerticalLimit(final MovingData data, final boolean onGroundFrom) { + // Always give some bonus points in case of identical Y values in + // midair (hovering player) + if(fromY == toY && !toOnGround) { + distanceAboveLimit = Math.max(hoveringPunishment, distanceAboveLimit + hoveringPunishment); + } + } - // A halfway lag-resistant method of allowing vertical acceleration without allowing blatant cheating + return distanceAboveLimit; + } - // FACT: Minecraft server sends player "velocity" to the client and lets the client calculate the movement - // PROBLEM: There may be an arbitrary amount of other move events between the server sending the data - // and the client accepting it/reacting to it. The server can't know when the client starts to - // consider the sent "velocity" in its movement. - // SOLUTION: Give the client at least 10 events after sending "velocity" to actually use the velocity for - // its movement, plus additional events if the "velocity" was big and can cause longer flights + private double calculateVerticalLimit(final MovingData data, final boolean onGroundFrom) { - // The server sent the player a "velocity" packet a short time ago + // A halfway lag-resistant method of allowing vertical acceleration + // without allowing blatant cheating - // consume a counter for this client - if(data.vertFreedomCounter > 0) { - data.vertFreedomCounter--; - data.vertFreedom += data.maxYVelocity*2D; - data.maxYVelocity *= 0.90D; - } - - final double limit = data.vertFreedom; + // FACT: Minecraft server sends player "velocity" to the client and lets + // the client calculate the movement + // PROBLEM: There may be an arbitrary amount of other move events + // between the server sending the data + // and the client accepting it/reacting to it. The server can't know + // when the client starts to + // consider the sent "velocity" in its movement. + // SOLUTION: Give the client at least 10 events after sending "velocity" + // to actually use the velocity for + // its movement, plus additional events if the "velocity" was big and + // can cause longer flights - // If the event counter has been consumed, remove the vertical movement limit increase when landing the next time - if(onGroundFrom && data.vertFreedomCounter <= 0) { - data.vertFreedom = 0.0D; - } + // The server sent the player a "velocity" packet a short time ago + + // consume a counter for this client + if(data.vertFreedomCounter > 0) { + data.vertFreedomCounter--; + data.vertFreedom += data.maxYVelocity * 2D; + data.maxYVelocity *= 0.90D; + } + + final double limit = data.vertFreedom; + + // If the event counter has been consumed, remove the vertical movement + // limit increase when landing the next time + if(onGroundFrom && data.vertFreedomCounter <= 0) { + data.vertFreedom = 0.0D; + } + + return limit; + } - return limit; - } - } diff --git a/src/cc/co/evenprime/bukkit/nocheat/checks/MovingCheck.java b/src/cc/co/evenprime/bukkit/nocheat/checks/MovingCheck.java index 6450f261..4d8d9833 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/checks/MovingCheck.java +++ b/src/cc/co/evenprime/bukkit/nocheat/checks/MovingCheck.java @@ -1,4 +1,3 @@ - package cc.co.evenprime.bukkit.nocheat.checks; import java.util.Locale; @@ -27,10 +26,11 @@ import cc.co.evenprime.bukkit.nocheat.listeners.MovingPlayerListener; import cc.co.evenprime.bukkit.nocheat.listeners.MovingPlayerMonitor; /** - * Check if the player should be allowed to make that move, e.g. is he allowed to jump here or move that far in one step + * Check if the player should be allowed to make that move, e.g. is he allowed + * to jump here or move that far in one step * * @author Evenprime - * + * */ public class MovingCheck extends Check { @@ -42,33 +42,37 @@ public class MovingCheck extends Check { runningCheck = new RunningCheck(); } - private int ticksBeforeSummary; + private int ticksBeforeSummary; - public long statisticElapsedTimeNano = 0; + public long statisticElapsedTimeNano = 0; - public boolean allowFlying; - public boolean allowFakeSneak; - public boolean allowFastSwim; + public boolean allowFlying; + public boolean allowFakeSneak; + public boolean allowFastSwim; - public double stepWidth; - public double sneakWidth; - public double swimWidth; + public double stepWidth; + public double sneakWidth; + public double swimWidth; - private boolean waterElevators; + private boolean waterElevators; - private String logMessage; - private String summaryMessage; + private String logMessage; + private String summaryMessage; // How should moving violations be treated? - private Action actions[][]; + private Action actions[][]; - public long statisticTotalEvents = 1; // Prevent accidental division by 0 at some point + public long statisticTotalEvents = 1; // Prevent + // accidental + // division by + // 0 at some + // point - private boolean enforceTeleport; + private boolean enforceTeleport; private final MovingEventHelper helper; - private final FlyingCheck flyingCheck; - private final RunningCheck runningCheck; + private final FlyingCheck flyingCheck; + private final RunningCheck runningCheck; /** * The actual check. @@ -76,28 +80,29 @@ public class MovingCheck extends Check { * Second check if the player moved too far horizontally * Third check if the player moved too high vertically * Fourth treat any occured violations as configured + * * @param event */ - public Location check(Player player, Location from, Location to, - MovingData data) { + public Location check(Player player, Location from, Location to, MovingData data) { Location newToLocation = null; final long startTime = System.nanoTime(); /************* DECIDE WHICH CHECKS NEED TO BE RUN *************/ - final boolean flyCheck = !allowFlying && !plugin.hasPermission(player, PermissionData.PERMISSION_FLYING, checkOPs); + final boolean flyCheck = !allowFlying && !plugin.hasPermission(player, PermissionData.PERMISSION_FLYING, checkOPs); final boolean runCheck = true; /***************** REFINE EVENT DATA FOR CHECKS ***************/ if(flyCheck || runCheck) { - // In both cases it will be interesting to know the type of underground the player + // In both cases it will be interesting to know the type of + // underground the player // is in or goes to final int fromType = helper.isLocationOnGround(from.getWorld(), from.getX(), from.getY(), from.getZ(), waterElevators); - final int toType = helper.isLocationOnGround(to.getWorld(), to.getX(), to.getY(),to.getZ(), waterElevators); + final int toType = helper.isLocationOnGround(to.getWorld(), to.getX(), to.getY(), to.getZ(), waterElevators); final boolean fromOnGround = fromType != MovingEventHelper.NONSOLID; final boolean toOnGround = toType != MovingEventHelper.NONSOLID; @@ -109,16 +114,14 @@ public class MovingCheck extends Check { if(flyCheck) { result += Math.max(0D, flyingCheck.check(player, from, fromOnGround, to, toOnGround, data)); - } - else - { - // If players are allowed to fly, there's no need to remember the last location on ground + } else { + // If players are allowed to fly, there's no need to remember + // the last location on ground data.setBackPoint = from; } if(runCheck) { - result += Math.max(0D, runningCheck.check(from, to, - !allowFakeSneak && player.isSneaking(), !allowFastSwim && (fromType & toType & MovingEventHelper.LIQUID) > 0, data, this)); + result += Math.max(0D, runningCheck.check(from, to, !allowFakeSneak && player.isSneaking(), !allowFastSwim && (fromType & toType & MovingEventHelper.LIQUID) > 0, data, this)); } /********* HANDLE/COMBINE THE RESULTS OF THE CHECKS ***********/ @@ -128,22 +131,22 @@ public class MovingCheck extends Check { if(fromOnGround) { data.setBackPoint = from; data.jumpPhase = 0; - } - else if(result <= 0 && toOnGround) { + } else if(result <= 0 && toOnGround) { data.jumpPhase = 0; } if(result > 0) { // Increment violation counter data.violationLevel += result; - if(data.setBackPoint == null) data.setBackPoint = from; + if(data.setBackPoint == null) + data.setBackPoint = from; } if(result > 0 && data.violationLevel > 1) { setupSummaryTask(player, data); - int level = limitCheck(data.violationLevel-1); + int level = limitCheck(data.violationLevel - 1); data.violationsInARow[level]++; @@ -158,12 +161,13 @@ public class MovingCheck extends Check { statisticElapsedTimeNano += System.nanoTime() - startTime; statisticTotalEvents++; - return newToLocation; } /** - * Various corner cases that would cause this check to fail or require special treatment + * Various corner cases that would cause this check to fail or require + * special treatment + * * @param player * @param data * @param from @@ -172,34 +176,14 @@ public class MovingCheck extends Check { */ public boolean shouldBeApplied(final Player player, final MovingData data, final Location from, final Location to) { - if(player.isDead() || player.isInsideVehicle()) return false; - - if(data.wasTeleported) { - // Remember this location - data.teleportedTo = from.clone(); - data.wasTeleported = false; - data.jumpPhase = 0; - } - - if(data.teleportedTo != null && data.teleportedTo.getWorld().equals(from.getWorld())) { - // As long as the from-Location doesn't change, the player didn't accept the teleport - if(data.teleportedTo.distanceSquared(from) < 0.01D) { - // Event after Teleport ignored - return false; - } - else { - // The player finally accepted the teleport with the previous event - data.teleportedTo = null; - } - } - return true; } - /** - * Register a task with bukkit that will be run a short time from now, displaying how many + * Register a task with bukkit that will be run a short time from now, + * displaying how many * violations happened in that timeframe + * * @param p * @param data */ @@ -213,7 +197,7 @@ public class MovingCheck extends Check { try { if(data.highestLogLevel != null) { - String logString = String.format(summaryMessage, p.getName(), ticksBeforeSummary/20, data.violationsInARow[0], data.violationsInARow[1],data.violationsInARow[2]); + String logString = String.format(summaryMessage, p.getName(), ticksBeforeSummary / 20, data.violationsInARow[0], data.violationsInARow[1], data.violationsInARow[2]); plugin.log(data.highestLogLevel, logString); data.highestLogLevel = Level.ALL; @@ -224,8 +208,7 @@ public class MovingCheck extends Check { data.violationsInARow[0] = 0; data.violationsInARow[1] = 0; data.violationsInARow[2] = 0; - } - catch(Exception e) { } + } catch(Exception e) {} } }; @@ -235,7 +218,8 @@ public class MovingCheck extends Check { } /** - * Call this when a player got successfully teleported with the corresponding event to adjust stored + * Call this when a player got successfully teleported with the + * corresponding event to adjust stored * data to the new situation * * @param event @@ -244,32 +228,34 @@ public class MovingCheck extends Check { MovingData data = plugin.getDataManager().getMovingData(event.getPlayer()); - // We can enforce a teleport, if that flag is explicitly set (but I'd rather have other plugins + // We can enforce a teleport, if that flag is explicitly set (but I'd + // rather have other plugins // not arbitrarily cancel teleport events in the first place... - if(data.teleportInitializedByMe != null && event.isCancelled() && enforceTeleport && event.getTo().equals(data.teleportInitializedByMe)) { + if(data.teleportInitializedByMe != null && event.isCancelled() && enforceTeleport && event.getTo().equals(data.teleportInitializedByMe)) { event.setCancelled(false); data.teleportInitializedByMe = null; } if(!event.isCancelled()) { - data.wasTeleported = true; - data.setBackPoint = event.getTo().clone(); - //data.lastLocation = event.getTo().clone(); + data.setBackPoint = null; } - // reset anyway - if another plugin cancelled our teleport it's no use to try and be precise + // reset anyway - if another plugin cancelled our teleport it's no use + // to try and be precise data.jumpPhase = 0; } /** * Update the cached values for players velocity to be prepared to * give them additional movement freedom in their next move events + * * @param v * @param data */ public void updateVelocity(Vector v, MovingData data) { - // Compare the velocity vector to the existing movement freedom that we've from previous events + // Compare the velocity vector to the existing movement freedom that + // we've from previous events double tmp = (Math.abs(v.getX()) + Math.abs(v.getZ())) * 3D; if(tmp > data.horizFreedom) data.horizFreedom = tmp; @@ -282,58 +268,67 @@ public class MovingCheck extends Check { /** * Perform actions that were specified in the config file + * * @param event * @param action - * @return + * @return */ - private Location action( Player player, Location from, Location to, Action[] actions, int violations, MovingData data, MovingEventHelper helper) { - + private Location action(Player player, Location from, Location to, Action[] actions, int violations, MovingData data, MovingEventHelper helper) { Location newToLocation = null; - if(actions == null) return newToLocation; + if(actions == null) + return newToLocation; boolean cancelled = false; for(Action a : actions) { if(a.firstAfter <= violations) { if(a.firstAfter == violations || a.repeat) { - if(a instanceof LogAction) { + if(a instanceof LogAction) { // prepare log message if necessary - String log = String.format(Locale.US, logMessage, player.getName(), from.getWorld().getName(), to.getWorld().getName(), from.getX(), from.getY(), from.getZ(), to.getX(), to.getY(), to.getZ(), Math.abs(from.getX()-to.getX()),to.getY()-from.getY(), Math.abs(from.getZ()-to.getZ())); + String log = String.format(Locale.US, logMessage, player.getName(), from.getWorld().getName(), to.getWorld().getName(), from.getX(), from.getY(), from.getZ(), to.getX(), to.getY(), to.getZ(), Math.abs(from.getX() - to.getX()), to.getY() - from.getY(), Math.abs(from.getZ() - to.getZ())); - plugin.log(((LogAction)a).level, log); + plugin.log(((LogAction) a).level, log); - // Remember the highest log level we encountered to determine what level the summary log message should have - if(data.highestLogLevel == null) data.highestLogLevel = Level.ALL; - if(data.highestLogLevel.intValue() < ((LogAction)a).level.intValue()) data.highestLogLevel = ((LogAction)a).level; - } - else if(!cancelled && a instanceof CancelAction) { - // Make a modified copy of the setBackPoint to prevent other plugins from accidentally modifying it - // and keep the current pitch and yaw (setbacks "feel" better that way). Plus try to adapt the Y-coord + // Remember the highest log level we encountered to + // determine what level the summary log message should + // have + if(data.highestLogLevel == null) + data.highestLogLevel = Level.ALL; + if(data.highestLogLevel.intValue() < ((LogAction) a).level.intValue()) + data.highestLogLevel = ((LogAction) a).level; + } else if(!cancelled && a instanceof CancelAction) { + // Make a modified copy of the setBackPoint to prevent + // other plugins from accidentally modifying it + // and keep the current pitch and yaw (setbacks "feel" + // better that way). Plus try to adapt the Y-coord // to place the player close to ground double y = data.setBackPoint.getY(); - // search for the first solid block up to 5 blocks below the setbackpoint and teleport the player there + // search for the first solid block up to 5 blocks below + // the setbackpoint and teleport the player there int i = 0; for(; i < 20; i++) { - if(helper.isLocationOnGround(data.setBackPoint.getWorld(), data.setBackPoint.getX(), data.setBackPoint.getY() - 0.5*i, data.setBackPoint.getZ(), waterElevators) != MovingData.NONSOLID) { + if(helper.isLocationOnGround(data.setBackPoint.getWorld(), data.setBackPoint.getX(), data.setBackPoint.getY() - 0.5 * i, data.setBackPoint.getZ(), waterElevators) != MovingData.NONSOLID) { break; } - } - y -= 0.5*i; + } + y -= 0.5 * i; data.setBackPoint.setY(y); - // Remember the location we send the player to, to identify teleports that were started by us + // Remember the location we send the player to, to + // identify teleports that were started by us data.teleportInitializedByMe = new Location(data.setBackPoint.getWorld(), data.setBackPoint.getX(), y, data.setBackPoint.getZ(), to.getYaw(), to.getPitch()); newToLocation = data.teleportInitializedByMe; - cancelled = true; // just prevent us from treating more than one "cancel" action, which would make no sense - } - else if(a instanceof CustomAction) - plugin.handleCustomAction((CustomAction)a, player); + cancelled = true; // just prevent us from treating more + // than one "cancel" action, which + // would make no sense + } else if(a instanceof CustomAction) + plugin.handleCustomAction((CustomAction) a, player); } } } @@ -344,6 +339,7 @@ public class MovingCheck extends Check { /** * Check a value against an array of sorted values to find out * where it fits in + * * @param value * @param limits * @return @@ -352,10 +348,12 @@ public class MovingCheck extends Check { if(value > 0.0D) { if(value > 0.5D) { - if(value > 2.0D) + if(value > 2.0D) return 2; - return 1; } - return 0; } + return 1; + } + return 0; + } return -1; } @@ -371,19 +369,11 @@ public class MovingCheck extends Check { checkOPs = config.getBooleanValue("moving.checkops"); - logMessage = config.getStringValue("moving.logmessage"). - replace("[player]", "%1$s"). - replace("[world]", "%2$s"). - replace("[from]", "(%4$.1f, %5$.1f, %6$.1f)"). - replace("[to]", "(%7$.1f, %8$.1f, %9$.1f)"). - replace("[distance]", "(%10$.1f, %11$.1f, %12$.1f)"); + logMessage = config.getStringValue("moving.logmessage").replace("[player]", "%1$s").replace("[world]", "%2$s").replace("[from]", "(%4$.1f, %5$.1f, %6$.1f)").replace("[to]", "(%7$.1f, %8$.1f, %9$.1f)").replace("[distance]", "(%10$.1f, %11$.1f, %12$.1f)"); - summaryMessage = config.getStringValue("moving.summarymessage"). - replace("[timeframe]", "%2$d"). - replace("[player]", "%1$s"). - replace("[violations]", "(%3$d,%4$d,%5$d)"); + summaryMessage = config.getStringValue("moving.summarymessage").replace("[timeframe]", "%2$d").replace("[player]", "%1$s").replace("[violations]", "(%3$d,%4$d,%5$d)"); - ticksBeforeSummary = config.getIntegerValue("moving.summaryafter")*20; + ticksBeforeSummary = config.getIntegerValue("moving.summaryafter") * 20; actions = new Action[3][]; @@ -395,11 +385,11 @@ public class MovingCheck extends Check { enforceTeleport = config.getBooleanValue("moving.enforceteleport"); - stepWidth = ((double)config.getIntegerValue("moving.limits.walking")) /100D; - sneakWidth = ((double)config.getIntegerValue("moving.limits.sneaking"))/100D; - swimWidth = ((double)config.getIntegerValue("moving.limits.swimming"))/100D; + stepWidth = ((double) config.getIntegerValue("moving.limits.walking")) / 100D; + sneakWidth = ((double) config.getIntegerValue("moving.limits.sneaking")) / 100D; + swimWidth = ((double) config.getIntegerValue("moving.limits.swimming")) / 100D; - } catch (ConfigurationException e) { + } catch(ConfigurationException e) { setActive(false); e.printStackTrace(); } diff --git a/src/cc/co/evenprime/bukkit/nocheat/checks/MovingEventHelper.java b/src/cc/co/evenprime/bukkit/nocheat/checks/MovingEventHelper.java index 46531a57..a21fa4f9 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/checks/MovingEventHelper.java +++ b/src/cc/co/evenprime/bukkit/nocheat/checks/MovingEventHelper.java @@ -7,164 +7,160 @@ import org.bukkit.World; /** * A collection of stuff to process data of move events + * * @author Evenprime - * + * */ public class MovingEventHelper { - private final double magic = 0.30000001192092896D; - private final double magic2 = 0.69999998807907103D; - - // Block types that may need to be treated specially - public static final int NONSOLID = 0; // 0x00000000 - public static final int SOLID = 1; // 0x00000001 - public static final int LIQUID = 2; // 0x00000010 - public static final int LADDER = 4; // 0x00000100 - public static final int FENCE = 8; // 0x00001000 - - // Until I can think of a better way to determine if a block is solid or not, this is what I'll do - private final int types[] = new int[256]; + private final double magic = 0.30000001192092896D; + private final double magic2 = 0.69999998807907103D; - public MovingEventHelper() { - // Find and define properties of all blocks - for(int i = 0; i < types.length; i++) { - - // Everything is considered nonsolid at first - types[i] = NONSOLID; - - if(Block.byId[i] != null) { - if(Block.byId[i].material.isSolid()) { - // solid blocks like STONE, CAKE, TRAPDOORS - types[i] = SOLID; - } - else if(Block.byId[i].material.isLiquid()){ - // WATER, LAVA - types[i] = LIQUID; - } - } - } - - // Special types just for me - types[Material.LADDER.getId()]= LADDER | SOLID; - types[Material.FENCE.getId()]= FENCE | SOLID; - } - - /** - * Check if certain coordinates are considered "on ground" - * - * @param w The world the coordinates belong to - * @param values The coordinates [lowerX, higherX, Y, lowerZ, higherZ] to be checked - * @param l The precise location that was used for calculation of "values" - * @return - */ - public int isLocationOnGround(final World world, final double x, final double y, final double z, boolean waterElevatorsAllowed) { + // Block types that may need to be treated specially + public static final int NONSOLID = 0; // 0x00000000 + public static final int SOLID = 1; // 0x00000001 + public static final int LIQUID = 2; // 0x00000010 + public static final int LADDER = 4; // 0x00000100 + public static final int FENCE = 8; // 0x00001000 - final int lowerX = lowerBorder(x); - final int upperX = upperBorder(x); - final int Y = (int)Math.floor(y); - final int lowerZ = lowerBorder(z); - final int higherZ = upperBorder(z); + // Until I can think of a better way to determine if a block is solid or + // not, this is what I'll do + private final int types[] = new int[256]; + public MovingEventHelper() { + // Find and define properties of all blocks + for(int i = 0; i < types.length; i++) { - int result; + // Everything is considered nonsolid at first + types[i] = NONSOLID; - // check in what kind of block the player is standing "in" - result = types[world.getBlockTypeIdAt(lowerX, Y, lowerZ)] | types[world.getBlockTypeIdAt(upperX, Y, lowerZ)] | - types[world.getBlockTypeIdAt(lowerX, Y, higherZ)] | types[world.getBlockTypeIdAt(upperX, Y, higherZ)]; + if(Block.byId[i] != null) { + if(Block.byId[i].material.isSolid()) { + // solid blocks like STONE, CAKE, TRAPDOORS + types[i] = SOLID; + } else if(Block.byId[i].material.isLiquid()) { + // WATER, LAVA + types[i] = LIQUID; + } + } + } - if((result & SOLID) != 0) { - // return standing - return SOLID; - } - else if((result & LIQUID) != 0) { - // return swimming - return LIQUID; - } + // Special types just for me + types[Material.LADDER.getId()] = LADDER | SOLID; + types[Material.FENCE.getId()] = FENCE | SOLID; + } - // Check the four borders of the players hitbox for something he could be standing on - result = types[world.getBlockTypeIdAt(lowerX, Y-1, lowerZ)] | types[world.getBlockTypeIdAt(upperX, Y-1, lowerZ)] | - types[world.getBlockTypeIdAt(lowerX, Y-1, higherZ)] | types[world.getBlockTypeIdAt(upperX, Y-1, higherZ)]; + /** + * Check if certain coordinates are considered "on ground" + * + * @param w + * The world the coordinates belong to + * @param values + * The coordinates [lowerX, higherX, Y, lowerZ, higherZ] to be + * checked + * @param l + * The precise location that was used for calculation of "values" + * @return + */ + public int isLocationOnGround(final World world, final double x, final double y, final double z, boolean waterElevatorsAllowed) { - if((result & SOLID) != 0) { - // return standing - return SOLID; - } + final int lowerX = lowerBorder(x); + final int upperX = upperBorder(x); + final int Y = (int) Math.floor(y); + final int lowerZ = lowerBorder(z); + final int higherZ = upperBorder(z); + int result; - // check if his head is "stuck" in an block - result = types[world.getBlockTypeIdAt(lowerX, Y+1, lowerZ)] | types[world.getBlockTypeIdAt(upperX, Y+1, lowerZ)] | - types[world.getBlockTypeIdAt(lowerX, Y+1, higherZ)] | types[world.getBlockTypeIdAt(upperX, Y+1, higherZ)]; + // check in what kind of block the player is standing "in" + result = types[world.getBlockTypeIdAt(lowerX, Y, lowerZ)] | types[world.getBlockTypeIdAt(upperX, Y, lowerZ)] | types[world.getBlockTypeIdAt(lowerX, Y, higherZ)] | types[world.getBlockTypeIdAt(upperX, Y, higherZ)]; - if((result & SOLID) != 0) { - // return standing - return SOLID; - } - else if((result & LIQUID) != 0) { - // return swimming - return LIQUID; - } + if((result & SOLID) != 0) { + // return standing + return SOLID; + } else if((result & LIQUID) != 0) { + // return swimming + return LIQUID; + } - // Running on fences causes problems if not treated specially - result = types[world.getBlockTypeIdAt(lowerX, Y-2, lowerZ)] | types[world.getBlockTypeIdAt(upperX, Y-2, lowerZ)] | - types[world.getBlockTypeIdAt(lowerX, Y-2, higherZ)] | types[world.getBlockTypeIdAt(upperX, Y-2, higherZ)]; + // Check the four borders of the players hitbox for something he could + // be standing on + result = types[world.getBlockTypeIdAt(lowerX, Y - 1, lowerZ)] | types[world.getBlockTypeIdAt(upperX, Y - 1, lowerZ)] | types[world.getBlockTypeIdAt(lowerX, Y - 1, higherZ)] | types[world.getBlockTypeIdAt(upperX, Y - 1, higherZ)]; - if((result & FENCE) != 0) { - // return standing - return SOLID; - } + if((result & SOLID) != 0) { + // return standing + return SOLID; + } - // Water elevators - optional "feature" - if(waterElevatorsAllowed) { - result = types[world.getBlockTypeIdAt(lowerX+1, Y+1, lowerZ+1)] | - types[world.getBlockTypeIdAt(lowerX+1, Y , lowerZ+1)] | - types[world.getBlockTypeIdAt(lowerX, Y+1, lowerZ+1)] | - types[world.getBlockTypeIdAt(lowerX , Y , lowerZ+1)] | - types[world.getBlockTypeIdAt(lowerX+1, Y+1, lowerZ )] | - types[world.getBlockTypeIdAt(lowerX+1, Y , lowerZ )] ; + // check if his head is "stuck" in an block + result = types[world.getBlockTypeIdAt(lowerX, Y + 1, lowerZ)] | types[world.getBlockTypeIdAt(upperX, Y + 1, lowerZ)] | types[world.getBlockTypeIdAt(lowerX, Y + 1, higherZ)] | types[world.getBlockTypeIdAt(upperX, Y + 1, higherZ)]; - if((result & LIQUID) != 0) { - return SOLID; // Solid? Why that? Because that's closer to what the bug actually does than liquid - } - } - // If nothing matches, he is somewhere in the air - return NONSOLID; - } - - - - /** - * Personal Rounding function to determine if a player is still touching a block or not - * @param d1 - * @return - */ - private int lowerBorder(double d1) { + if((result & SOLID) != 0) { + // return standing + return SOLID; + } else if((result & LIQUID) != 0) { + // return swimming + return LIQUID; + } - double floor = Math.floor(d1); - double d4 = floor + magic; + // Running on fences causes problems if not treated specially + result = types[world.getBlockTypeIdAt(lowerX, Y - 2, lowerZ)] | types[world.getBlockTypeIdAt(upperX, Y - 2, lowerZ)] | types[world.getBlockTypeIdAt(lowerX, Y - 2, higherZ)] | types[world.getBlockTypeIdAt(upperX, Y - 2, higherZ)]; - if(d4 <= d1) - d4 = 0; - else - d4 = 1; + if((result & FENCE) != 0) { + // return standing + return SOLID; + } - return (int) (floor - d4); - } + // Water elevators - optional "feature" + if(waterElevatorsAllowed) { + result = types[world.getBlockTypeIdAt(lowerX + 1, Y + 1, lowerZ + 1)] | types[world.getBlockTypeIdAt(lowerX + 1, Y, lowerZ + 1)] | types[world.getBlockTypeIdAt(lowerX, Y + 1, lowerZ + 1)] | types[world.getBlockTypeIdAt(lowerX, Y, lowerZ + 1)] | types[world.getBlockTypeIdAt(lowerX + 1, Y + 1, lowerZ)] | types[world.getBlockTypeIdAt(lowerX + 1, Y, lowerZ)]; - /** - * Personal Rounding function to determine if a player is still touching a block or not - * @param d1 - * @return - */ - private int upperBorder(double d1) { + if((result & LIQUID) != 0) { + return SOLID; // Solid? Why that? Because that's closer to what + // the bug actually does than liquid + } + } + // If nothing matches, he is somewhere in the air + return NONSOLID; + } - double floor = Math.floor(d1); - double d4 = floor + magic2; + /** + * Personal Rounding function to determine if a player is still touching a + * block or not + * + * @param d1 + * @return + */ + private int lowerBorder(double d1) { - if(d4 < d1) - d4 = -1; - else - d4 = 0; + double floor = Math.floor(d1); + double d4 = floor + magic; - return (int) (floor - d4); - } + if(d4 <= d1) + d4 = 0; + else + d4 = 1; + + return (int) (floor - d4); + } + + /** + * Personal Rounding function to determine if a player is still touching a + * block or not + * + * @param d1 + * @return + */ + private int upperBorder(double d1) { + + double floor = Math.floor(d1); + double d4 = floor + magic2; + + if(d4 < d1) + d4 = -1; + else + d4 = 0; + + return (int) (floor - d4); + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/checks/NukeCheck.java b/src/cc/co/evenprime/bukkit/nocheat/checks/NukeCheck.java index 63afc066..b638baba 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/checks/NukeCheck.java +++ b/src/cc/co/evenprime/bukkit/nocheat/checks/NukeCheck.java @@ -20,102 +20,93 @@ import cc.co.evenprime.bukkit.nocheat.data.NukeData; import cc.co.evenprime.bukkit.nocheat.data.PermissionData; import cc.co.evenprime.bukkit.nocheat.listeners.NukeBlockListener; - public class NukeCheck extends Check { - private String kickMessage; - private String logMessage; - - private boolean limitReach; - - public NukeCheck(NoCheat plugin, NoCheatConfiguration config) { + private String kickMessage; + private String logMessage; - super(plugin, "nuke", PermissionData.PERMISSION_NUKE, config); + private boolean limitReach; - } + public NukeCheck(NoCheat plugin, NoCheatConfiguration config) { - @Override - protected void configure(NoCheatConfiguration config) { + super(plugin, "nuke", PermissionData.PERMISSION_NUKE, config); - - - try { - kickMessage = config.getStringValue("nuke.kickmessage"); - logMessage = config.getStringValue("nuke.logmessage"). - replace("[player]", "%1$s"); - - limitReach = config.getBooleanValue("nuke.limitreach"); - - setActive(config.getBooleanValue("active.nuke")); - } catch (ConfigurationException e) { - setActive(false); - e.printStackTrace(); - } - } + } - public void check(BlockBreakEvent event) { + @Override + protected void configure(NoCheatConfiguration config) { - if(skipCheck(event.getPlayer())) { - return; - } - - NukeData data = plugin.getDataManager().getNukeData(event.getPlayer()); - - Block block = event.getBlock(); + try { + kickMessage = config.getStringValue("nuke.kickmessage"); + logMessage = config.getStringValue("nuke.logmessage").replace("[player]", "%1$s"); - Location eyes = event.getPlayer().getEyeLocation(); - Vector direction = eyes.getDirection(); + limitReach = config.getBooleanValue("nuke.limitreach"); - // Because it's not very precise on very short distances, - // consider the length of the side of a block to be 2.0 instead of 1.0 - final double x1 = ((double)block.getX()) - eyes.getX() - 0.5; - final double y1 = ((double)block.getY()) - eyes.getY() - 0.5; - final double z1 = ((double)block.getZ()) - eyes.getZ() - 0.5; + setActive(config.getBooleanValue("active.nuke")); + } catch(ConfigurationException e) { + setActive(false); + e.printStackTrace(); + } + } - final double x2 = x1 + 2; - final double y2 = y1 + 2; - final double z2 = z1 + 2; + public void check(BlockBreakEvent event) { - double factor = new Vector(x1 + 1, y1 + 1, z1 + 1).length(); - - boolean tooFarAway = limitReach && factor > 4.85D; - - if(!tooFarAway && factor * direction.getX() >= x1 && factor * direction.getY() >= y1 && factor * direction.getZ() >= z1 && - factor * direction.getX() <= x2 && factor * direction.getY() <= y2 && factor * direction.getZ() <= z2) { - if(data.counter > 0) { - data.counter--; - } - } - else { - data.counter++; - event.setCancelled(true); - - if(data.counter > 10) { - - String log = String.format(Locale.US, logMessage, event.getPlayer().getName()); - - plugin.log(Level.SEVERE, log); - - event.getPlayer().kickPlayer(kickMessage); - data.counter = 0; // Reset to prevent problems on next login - } - } + if(skipCheck(event.getPlayer())) { + return; + } - - } + NukeData data = plugin.getDataManager().getNukeData(event.getPlayer()); + Block block = event.getBlock(); - @Override - protected void registerListeners() { - PluginManager pm = Bukkit.getServer().getPluginManager(); + Location eyes = event.getPlayer().getEyeLocation(); + Vector direction = eyes.getDirection(); - Listener blockListener = new NukeBlockListener(this); + // Because it's not very precise on very short distances, + // consider the length of the side of a block to be 2.0 instead of 1.0 + final double x1 = ((double) block.getX()) - eyes.getX() - 0.5; + final double y1 = ((double) block.getY()) - eyes.getY() - 0.5; + final double z1 = ((double) block.getZ()) - eyes.getZ() - 0.5; - // Register listeners for moving check - pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Priority.Lowest, plugin); - pm.registerEvent(Event.Type.BLOCK_DAMAGE, blockListener, Priority.Monitor, plugin); + final double x2 = x1 + 2; + final double y2 = y1 + 2; + final double z2 = z1 + 2; + double factor = new Vector(x1 + 1, y1 + 1, z1 + 1).length(); - } + boolean tooFarAway = limitReach && factor > 4.85D; + + if(!tooFarAway && factor * direction.getX() >= x1 && factor * direction.getY() >= y1 && factor * direction.getZ() >= z1 && factor * direction.getX() <= x2 && factor * direction.getY() <= y2 && factor * direction.getZ() <= z2) { + if(data.counter > 0) { + data.counter--; + } + } else { + data.counter++; + event.setCancelled(true); + + if(data.counter > 10) { + + String log = String.format(Locale.US, logMessage, event.getPlayer().getName()); + + plugin.log(Level.SEVERE, log); + + event.getPlayer().kickPlayer(kickMessage); + data.counter = 0; // Reset to prevent problems on next login + } + } + + } + + @Override + protected void registerListeners() { + PluginManager pm = Bukkit.getServer().getPluginManager(); + + Listener blockListener = new NukeBlockListener(this); + + // Register listeners for moving check + pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Priority.Lowest, plugin); + pm.registerEvent(Event.Type.BLOCK_DAMAGE, blockListener, Priority.Monitor, plugin); + + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/checks/RunningCheck.java b/src/cc/co/evenprime/bukkit/nocheat/checks/RunningCheck.java index 0acff3bc..e6c264aa 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/checks/RunningCheck.java +++ b/src/cc/co/evenprime/bukkit/nocheat/checks/RunningCheck.java @@ -6,30 +6,27 @@ import cc.co.evenprime.bukkit.nocheat.data.MovingData; public class RunningCheck { + public RunningCheck() {} - public RunningCheck() { } + public double check(final Location from, final Location to, final boolean isSneaking, final boolean isSwimming, final MovingData data, MovingCheck check) { - public double check(final Location from, final Location to, final boolean isSneaking, final boolean isSwimming, final MovingData data, MovingCheck check) { + // How much further did the player move than expected?? + double distanceAboveLimit = 0.0D; - // How much further did the player move than expected?? - double distanceAboveLimit = 0.0D; + // First calculate the distance the player has moved horizontally + final double xDistance = from.getX() - to.getX(); + final double zDistance = from.getZ() - to.getZ(); - // First calculate the distance the player has moved horizontally - final double xDistance = from.getX()-to.getX(); - final double zDistance = from.getZ()-to.getZ(); + final double totalDistance = Math.sqrt((xDistance * xDistance + zDistance * zDistance)); - final double totalDistance = Math.sqrt((xDistance*xDistance + zDistance*zDistance)); + if(isSneaking) { + distanceAboveLimit = totalDistance - check.sneakWidth; + } else if(isSwimming) { + distanceAboveLimit = totalDistance - check.swimWidth; + } else { + distanceAboveLimit = totalDistance - check.stepWidth; + } - if(isSneaking) { - distanceAboveLimit = totalDistance - check.sneakWidth; - } - else if(isSwimming) { - distanceAboveLimit = totalDistance - check.swimWidth; - } - else { - distanceAboveLimit = totalDistance - check.stepWidth; - } - - return distanceAboveLimit - data.horizFreedom; - } + return distanceAboveLimit - data.horizFreedom; + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/checks/SpeedhackCheck.java b/src/cc/co/evenprime/bukkit/nocheat/checks/SpeedhackCheck.java index 5192864a..fc539f71 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/checks/SpeedhackCheck.java +++ b/src/cc/co/evenprime/bukkit/nocheat/checks/SpeedhackCheck.java @@ -22,180 +22,182 @@ import cc.co.evenprime.bukkit.nocheat.data.SpeedhackData; import cc.co.evenprime.bukkit.nocheat.listeners.SpeedhackPlayerListener; /** - * Log if a player sends to many move events in a specific time frame, usually the result of tinkering with the system clock + * Log if a player sends to many move events in a specific time frame, usually + * the result of tinkering with the system clock * * @author Evenprime - * + * */ public class SpeedhackCheck extends Check { - public SpeedhackCheck(NoCheat plugin, NoCheatConfiguration config) { - super(plugin, "speedhack", PermissionData.PERMISSION_SPEEDHACK, config); - } + public SpeedhackCheck(NoCheat plugin, NoCheatConfiguration config) { + super(plugin, "speedhack", PermissionData.PERMISSION_SPEEDHACK, config); + } - private static final int violationsLimit = 3; + private static final int violationsLimit = 3; - // Limits for the speedhack check per second - private int limits[]; + // Limits for the speedhack check per second + private int limits[]; - private String logMessage; + private String logMessage; - // How should speedhack violations be treated? - private Action actions[][]; + // How should speedhack violations be treated? + private Action actions[][]; - public void check(PlayerMoveEvent event) { + public void check(PlayerMoveEvent event) { - Player player = event.getPlayer(); - // Should we check at all? - if(skipCheck(player)) return; + Player player = event.getPlayer(); + // Should we check at all? + if(skipCheck(player)) + return; - // Ignore events of players in vehicles (these can be the cause of event spam between server and client) - // Ignore events if the player has positive y-Velocity (these can be the cause of event spam between server and client) - if(player.isInsideVehicle() || player.getVelocity().getY() > 0.0D) { - return; - } - - // During world transfers many events of same location get sent, ignore them all - if(event.getFrom().equals(event.getTo())) { - return; - } + // Ignore events of players in vehicles (these can be the cause of event + // spam between server and client) + // Ignore events if the player has positive y-Velocity (these can be the + // cause of event spam between server and client) + if(player.isInsideVehicle() || player.getVelocity().getY() > 0.0D) { + return; + } - // Get the player-specific data - SpeedhackData data = plugin.getDataManager().getSpeedhackData(player); + // During world transfers many events of same location get sent, ignore + // them all + if(event.getFrom().equals(event.getTo())) { + return; + } - // Count the event (twice, to interpolate from 0.5 seconds to 1 second - data.eventsSinceLastCheck += 2; + // Get the player-specific data + SpeedhackData data = plugin.getDataManager().getSpeedhackData(player); - // Get the ticks of the server - int ticks = plugin.getServerTicks(); + // Count the event (twice, to interpolate from 0.5 seconds to 1 second + data.eventsSinceLastCheck += 2; - // Roughly half a second (= 10 ticks) passed - if(data.lastCheckTicks + 10 == ticks) { + // Get the ticks of the server + int ticks = plugin.getServerTicks(); - // If we haven't already got a setback point, create one now - if(data.setBackPoint == null) { - data.setBackPoint = event.getFrom(); - } + // Roughly half a second (= 10 ticks) passed + if(data.lastCheckTicks + 10 == ticks) { - if(plugin.getServerLag() > 150) { - // Any data would likely be unreliable with that lag - resetData(data, event.getFrom()); - } - else { + // If we haven't already got a setback point, create one now + if(data.setBackPoint == null) { + data.setBackPoint = event.getFrom(); + } - int level = -1; + if(plugin.getServerLag() > 150) { + // Any data would likely be unreliable with that lag + resetData(data, event.getFrom()); + } else { - if(data.eventsSinceLastCheck > limits[2]) level = 2; - else if(data.eventsSinceLastCheck > limits[1]) level = 1; - else if(data.eventsSinceLastCheck > limits[0]) level = 0; - else { - resetData(data, event.getFrom()); - } + int level = -1; - if(level >= 0) { - data.violationsInARowTotal++; - } + if(data.eventsSinceLastCheck > limits[2]) + level = 2; + else if(data.eventsSinceLastCheck > limits[1]) + level = 1; + else if(data.eventsSinceLastCheck > limits[0]) + level = 0; + else { + resetData(data, event.getFrom()); + } - if(data.violationsInARowTotal >= violationsLimit) { - data.violationsInARow[level]++; - action(actions[level], event, data.violationsInARow[level], data); - } + if(level >= 0) { + data.violationsInARowTotal++; + } - // Reset value for next check - data.eventsSinceLastCheck = 0; - } + if(data.violationsInARowTotal >= violationsLimit) { + data.violationsInARow[level]++; + action(actions[level], event, data.violationsInARow[level], data); + } - data.lastCheckTicks = ticks; - } - else if(data.lastCheckTicks + 10 < ticks) - { - // The player didn't move for the last 10 ticks - resetData(data, event.getFrom()); - data.lastCheckTicks = ticks; - } - } + // Reset value for next check + data.eventsSinceLastCheck = 0; + } - private static void resetData(SpeedhackData data, Location l) { - data.violationsInARow[0] = 0; - data.violationsInARow[1] = 0; - data.violationsInARow[2] = 0; - data.violationsInARowTotal = 0; - data.eventsSinceLastCheck = 0; - data.setBackPoint = l; - } + data.lastCheckTicks = ticks; + } else if(data.lastCheckTicks + 10 < ticks) { + // The player didn't move for the last 10 ticks + resetData(data, event.getFrom()); + data.lastCheckTicks = ticks; + } + } - private void action(Action actions[], PlayerMoveEvent event, int violations, SpeedhackData data) { + private static void resetData(SpeedhackData data, Location l) { + data.violationsInARow[0] = 0; + data.violationsInARow[1] = 0; + data.violationsInARow[2] = 0; + data.violationsInARowTotal = 0; + data.eventsSinceLastCheck = 0; + data.setBackPoint = l; + } - if(actions == null) return; + private void action(Action actions[], PlayerMoveEvent event, int violations, SpeedhackData data) { - for(Action a : actions) { - if(a.firstAfter <= violations) { - if(a instanceof LogAction) { - String log = String.format(logMessage, event.getPlayer().getName(), data.eventsSinceLastCheck*2, limits[0]); - plugin.log(((LogAction)a).level, log); - } - else if(a.firstAfter == violations || a.repeat) { - if(a instanceof CancelAction) { - resetPlayer(event, data); - } - else if(a instanceof CustomAction) { - plugin.handleCustomAction((CustomAction)a, event.getPlayer()); - } - } - } - } - } + if(actions == null) + return; - private static void resetPlayer(PlayerMoveEvent event, SpeedhackData data) { + for(Action a : actions) { + if(a.firstAfter <= violations) { + if(a instanceof LogAction) { + String log = String.format(logMessage, event.getPlayer().getName(), data.eventsSinceLastCheck * 2, limits[0]); + plugin.log(((LogAction) a).level, log); + } else if(a.firstAfter == violations || a.repeat) { + if(a instanceof CancelAction) { + resetPlayer(event, data); + } else if(a instanceof CustomAction) { + plugin.handleCustomAction((CustomAction) a, event.getPlayer()); + } + } + } + } + } - if(data.setBackPoint == null) data.setBackPoint = event.getFrom(); + private static void resetPlayer(PlayerMoveEvent event, SpeedhackData data) { - // If we have stored a location for the player, we put him back there - event.setTo(data.setBackPoint); - } + if(data.setBackPoint == null) + data.setBackPoint = event.getFrom(); - @Override - public void configure(NoCheatConfiguration config) { + // If we have stored a location for the player, we put him back there + event.setTo(data.setBackPoint); + } - try { + @Override + public void configure(NoCheatConfiguration config) { - limits = new int[3]; + try { - limits[0] = config.getIntegerValue("speedhack.limits.low"); - limits[1] = config.getIntegerValue("speedhack.limits.med"); - limits[2] = config.getIntegerValue("speedhack.limits.high"); + limits = new int[3]; - logMessage = config.getStringValue("speedhack.logmessage"). - replace("[player]", "%1$s").replace("[events]", "%2$d").replace("[limit]", "%3$d"); + limits[0] = config.getIntegerValue("speedhack.limits.low"); + limits[1] = config.getIntegerValue("speedhack.limits.med"); + limits[2] = config.getIntegerValue("speedhack.limits.high"); - actions = new Action[3][]; + logMessage = config.getStringValue("speedhack.logmessage").replace("[player]", "%1$s").replace("[events]", "%2$d").replace("[limit]", "%3$d"); - actions[0] = config.getActionValue("speedhack.action.low"); - actions[1] = config.getActionValue("speedhack.action.med"); - actions[2] = config.getActionValue("speedhack.action.high"); + actions = new Action[3][]; - setActive(config.getBooleanValue("active.speedhack")); - } catch (ConfigurationException e) { - setActive(false); - e.printStackTrace(); - } - } + actions[0] = config.getActionValue("speedhack.action.low"); + actions[1] = config.getActionValue("speedhack.action.med"); + actions[2] = config.getActionValue("speedhack.action.high"); + setActive(config.getBooleanValue("active.speedhack")); + } catch(ConfigurationException e) { + setActive(false); + e.printStackTrace(); + } + } + @Override + protected void registerListeners() { + PluginManager pm = Bukkit.getServer().getPluginManager(); - @Override - protected void registerListeners() { - PluginManager pm = Bukkit.getServer().getPluginManager(); + Listener speedhackPlayerListener = new SpeedhackPlayerListener(this); + // Register listeners for speedhack check + pm.registerEvent(Event.Type.PLAYER_MOVE, speedhackPlayerListener, Priority.High, plugin); + pm.registerEvent(Event.Type.PLAYER_TELEPORT, speedhackPlayerListener, Priority.Monitor, plugin); - Listener speedhackPlayerListener = new SpeedhackPlayerListener(this); - // Register listeners for speedhack check - pm.registerEvent(Event.Type.PLAYER_MOVE, speedhackPlayerListener, Priority.High, plugin); - pm.registerEvent(Event.Type.PLAYER_TELEPORT, speedhackPlayerListener, Priority.Monitor, plugin); + } - } - - public void teleported(PlayerTeleportEvent event) { - SpeedhackData data = plugin.getDataManager().getSpeedhackData(event.getPlayer()); - resetData(data, event.getTo()); - } + public void teleported(PlayerTeleportEvent event) { + SpeedhackData data = plugin.getDataManager().getSpeedhackData(event.getPlayer()); + resetData(data, event.getTo()); + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/config/BooleanOption.java b/src/cc/co/evenprime/bukkit/nocheat/config/BooleanOption.java index b5a37170..3476dae5 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/config/BooleanOption.java +++ b/src/cc/co/evenprime/bukkit/nocheat/config/BooleanOption.java @@ -1,31 +1,30 @@ package cc.co.evenprime.bukkit.nocheat.config; - public class BooleanOption extends ChildOption { - /** + /** * */ - private static final long serialVersionUID = 2258827414736580449L; + private static final long serialVersionUID = 2258827414736580449L; - private boolean value; + private boolean value; - public BooleanOption(String name, boolean initialValue) { + public BooleanOption(String name, boolean initialValue) { - super(name); - this.value = initialValue; - } + super(name); + this.value = initialValue; + } - public void setValue(boolean value) { - this.value = value; - } + public void setValue(boolean value) { + this.value = value; + } - @Override - public String getValue() { - return Boolean.toString(value); - } + @Override + public String getValue() { + return Boolean.toString(value); + } - public boolean getBooleanValue() { - return value; - } + public boolean getBooleanValue() { + return value; + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/config/ChildOption.java b/src/cc/co/evenprime/bukkit/nocheat/config/ChildOption.java index 6ff4a0f4..98fc5134 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/config/ChildOption.java +++ b/src/cc/co/evenprime/bukkit/nocheat/config/ChildOption.java @@ -2,28 +2,26 @@ package cc.co.evenprime.bukkit.nocheat.config; import cc.co.evenprime.bukkit.nocheat.wizard.gui.Explainations; - public abstract class ChildOption extends Option { - /** + /** * */ - private static final long serialVersionUID = -4648294833934457776L; + private static final long serialVersionUID = -4648294833934457776L; - public ChildOption(String identifier) { - super(identifier); - } + public ChildOption(String identifier) { + super(identifier); + } + public abstract String getValue(); - public abstract String getValue(); + @Override + public String toYAMLString(String prefix) { + return prefix + getIdentifier() + ": \"" + getValue() + "\"\r\n"; + } - @Override - public String toYAMLString(String prefix) { - return prefix + getIdentifier() + ": \"" + getValue() + "\"\r\n"; - } - - @Override - public String toDescriptionString(String prefix) { - return prefix + getIdentifier() + ": \"" + Explainations.get(getFullIdentifier()).replace("\n", "\r\n" + prefix + "\t\t") + "\"\r\n"; - } + @Override + public String toDescriptionString(String prefix) { + return prefix + getIdentifier() + ": \"" + Explainations.get(getFullIdentifier()).replace("\n", "\r\n" + prefix + "\t\t") + "\"\r\n"; + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/config/CustomActionOption.java b/src/cc/co/evenprime/bukkit/nocheat/config/CustomActionOption.java index 2f36d96f..f9333dca 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/config/CustomActionOption.java +++ b/src/cc/co/evenprime/bukkit/nocheat/config/CustomActionOption.java @@ -4,83 +4,76 @@ import cc.co.evenprime.bukkit.nocheat.actions.CustomAction; public class CustomActionOption extends ChildOption { - private int firstAfter; - private boolean repeat; - private String command; + private int firstAfter; + private boolean repeat; + private String command; + public CustomActionOption(String identifier, String command) { - public CustomActionOption(String identifier, String command) { + super(identifier); - super(identifier); + this.parseCommand(command); + } - this.parseCommand(command); - } + private void parseCommand(String com) { - private void parseCommand(String com) { + if(com.matches("\\[[0-9]*,[a-z]*\\] .*")) { + String s[] = com.split(" ", 2); + String s2[] = s[0].replace("[", "").replace("]", "").split(","); + firstAfter = Integer.parseInt(s2[0]); + repeat = Boolean.parseBoolean(s2[1]); + command = s[1]; + } else if(com.matches("\\[[0-9]*\\] .*")) { + String s[] = com.split(" ", 2); + firstAfter = Integer.parseInt(s[0].replace("[", "").replace("]", "")); + repeat = true; + command = s[1]; + } else { + firstAfter = 1; + repeat = true; + command = com; + } + } - if(com.matches("\\[[0-9]*,[a-z]*\\] .*")) { - String s[] = com.split(" ", 2); - String s2[] = s[0].replace("[", "").replace("]", "").split(","); - firstAfter = Integer.parseInt(s2[0]); - repeat = Boolean.parseBoolean(s2[1]); - command = s[1]; - } - else if(com.matches("\\[[0-9]*\\] .*")) { - String s[] = com.split(" ", 2); - firstAfter = Integer.parseInt(s[0].replace("[", "").replace("]", "")); - repeat = true; - command = s[1]; - } - else - { - firstAfter = 1; - repeat = true; - command = com; - } - } + @Override + public String getValue() { + if(firstAfter <= 1 && repeat) { + return command; + } else if(repeat) { + return "[" + firstAfter + "] " + command; + } else { + return "[" + firstAfter + "," + repeat + "] " + command; + } + } - @Override - public String getValue() { - if(firstAfter <= 1 && repeat) { - return command; - } - else if(repeat) { - return "["+firstAfter+"] "+ command; - } - else { - return "["+firstAfter+","+repeat+"] "+ command; - } - } + public CustomAction getCustomActionValue() { + return new CustomAction(firstAfter, repeat, command); + } + public String getCommandValue() { + return command; + } - public CustomAction getCustomActionValue() { - return new CustomAction(firstAfter, repeat, command); - } + public void setCommandValue(String command) { + this.command = command; + } - public String getCommandValue() { - return command; - } + public void setRepeatValue(boolean value) { + this.repeat = value; - public void setCommandValue(String command) { - this.command = command; - } + } - public void setRepeatValue(boolean value) { - this.repeat = value; + public boolean getRepeatValue() { + return repeat; + } - } + public int getFirstAfterValue() { + return firstAfter; + } - public boolean getRepeatValue() { - return repeat; - } + public void setFirsttAfterValue(int value) { + this.firstAfter = value; - public int getFirstAfterValue() { - return firstAfter; - } - - public void setFirsttAfterValue(int value) { - this.firstAfter = value; - - } + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/config/IntegerOption.java b/src/cc/co/evenprime/bukkit/nocheat/config/IntegerOption.java index 27f88eeb..b5b5009b 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/config/IntegerOption.java +++ b/src/cc/co/evenprime/bukkit/nocheat/config/IntegerOption.java @@ -1,33 +1,32 @@ package cc.co.evenprime.bukkit.nocheat.config; - public class IntegerOption extends TextFieldOption { - /** + /** * */ - private static final long serialVersionUID = 2258827414736580449L; - - public IntegerOption(String name, int initialValue) { - - super(name, String.valueOf(initialValue), 5); - } + private static final long serialVersionUID = 2258827414736580449L; - @Override - public boolean isValid(String value) { - - if(!super.isValid(value)) return false; - - try { - Integer.parseInt(value); - return true; - } - catch(Exception e) { - return false; - } - } + public IntegerOption(String name, int initialValue) { - public int getIntegerValue() { - return Integer.parseInt(this.getValue()); - } + super(name, String.valueOf(initialValue), 5); + } + + @Override + public boolean isValid(String value) { + + if(!super.isValid(value)) + return false; + + try { + Integer.parseInt(value); + return true; + } catch(Exception e) { + return false; + } + } + + public int getIntegerValue() { + return Integer.parseInt(this.getValue()); + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/config/LevelOption.java b/src/cc/co/evenprime/bukkit/nocheat/config/LevelOption.java index 2b30691f..dcabf189 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/config/LevelOption.java +++ b/src/cc/co/evenprime/bukkit/nocheat/config/LevelOption.java @@ -2,81 +2,77 @@ package cc.co.evenprime.bukkit.nocheat.config; import java.util.logging.Level; - public class LevelOption extends ChildOption { - /** + /** * */ - private static final long serialVersionUID = -1609308017422576285L; + private static final long serialVersionUID = -1609308017422576285L; - private LogLevel option; + private LogLevel option; - public enum LogLevel { + public enum LogLevel { + OFF("off", "never", Level.OFF), LOW("low", "all messages", Level.INFO), MED("med", "important messages", Level.WARNING), HIGH("high", "very important messages", Level.SEVERE); - OFF("off", "never", Level.OFF), - LOW("low", "all messages", Level.INFO), - MED("med", "important messages", Level.WARNING), - HIGH("high", "very important messages", Level.SEVERE); + private final String value; + private final String description; + private final Level level; - private final String value; - private final String description; - private final Level level; + private LogLevel(String value, String description, Level level) { + this.value = value; + this.description = description; + this.level = level; + } - private LogLevel(String value, String description, Level level) { - this.value = value; - this.description = description; - this.level = level; - } + public String asString() { + return this.value; + } - public String asString() { return this.value; } + public static LogLevel getLogLevelFromString(String s) { + if(s == null) + return OFF; + if("off".equals(s)) + return OFF; + else if("low".equals(s)) + return LOW; + else if("med".equals(s)) + return MED; + else if("high".equals(s)) + return HIGH; + else + return OFF; + } - public static LogLevel getLogLevelFromString(String s) { - if(s == null) return OFF; - if("off".equals(s)) - return OFF; - else if("low".equals(s)) - return LOW; - else if("med".equals(s)) - return MED; - else if("high".equals(s)) - return HIGH; - else - return OFF; - } + public String toString() { + return this.name() + ": " + description; + } + public Level getLevel() { + return level; + } + } - public String toString() { - return this.name() + ": " + description; - } + public LevelOption(String identifier, LogLevel initialValue) { - public Level getLevel() { - return level; - } - } + super(identifier); + this.option = initialValue; + } - public LevelOption(String identifier, LogLevel initialValue) { + @Override + public String getValue() { + return option.asString(); + } - super(identifier); - this.option = initialValue; - } + public void setValue(LogLevel value) { + this.option = value; + } + public LogLevel getOptionValue() { + return this.option; + } - @Override - public String getValue() { - return option.asString(); - } - - public void setValue(LogLevel value) { - this.option = value; - } - - public LogLevel getOptionValue() { - return this.option; - } - - public Level getLevelValue() { - return this.option.getLevel(); - } + public Level getLevelValue() { + return this.option.getLevel(); + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/config/LongStringOption.java b/src/cc/co/evenprime/bukkit/nocheat/config/LongStringOption.java index 4254ca75..5b3bdbcd 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/config/LongStringOption.java +++ b/src/cc/co/evenprime/bukkit/nocheat/config/LongStringOption.java @@ -2,12 +2,12 @@ package cc.co.evenprime.bukkit.nocheat.config; public class LongStringOption extends TextFieldOption { - /** + /** * */ - private static final long serialVersionUID = 2258827414736580449L; - - public LongStringOption(String name, String initialValue) { - super(name, initialValue, 60); - } + private static final long serialVersionUID = 2258827414736580449L; + + public LongStringOption(String name, String initialValue) { + super(name, initialValue, 60); + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/config/MediumStringOption.java b/src/cc/co/evenprime/bukkit/nocheat/config/MediumStringOption.java index 6c57029f..15d93e3e 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/config/MediumStringOption.java +++ b/src/cc/co/evenprime/bukkit/nocheat/config/MediumStringOption.java @@ -2,12 +2,12 @@ package cc.co.evenprime.bukkit.nocheat.config; public class MediumStringOption extends TextFieldOption { - /** + /** * */ - private static final long serialVersionUID = 2258827414736580449L; - - public MediumStringOption(String name, String initialValue) { - super(name, initialValue, 30); - } + private static final long serialVersionUID = 2258827414736580449L; + + public MediumStringOption(String name, String initialValue) { + super(name, initialValue, 30); + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/config/NoCheatConfiguration.java b/src/cc/co/evenprime/bukkit/nocheat/config/NoCheatConfiguration.java index e349ff0a..254270c1 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/config/NoCheatConfiguration.java +++ b/src/cc/co/evenprime/bukkit/nocheat/config/NoCheatConfiguration.java @@ -25,455 +25,406 @@ import cc.co.evenprime.bukkit.nocheat.yaml.SimpleYaml; * Central location for everything that's described in the configuration file * * @author Evenprime - * + * */ public class NoCheatConfiguration { + public final static String configFile = "plugins/NoCheat/nocheat.yml"; + public final static String descriptionsFile = "plugins/NoCheat/descriptions.txt"; - public final static String configFile = "plugins/NoCheat/nocheat.yml"; - public final static String descriptionsFile = "plugins/NoCheat/descriptions.txt"; + private ParentOption root; - private ParentOption root; + private final Map actionMap = new HashMap(); - private final Map actionMap = new HashMap(); + private Map yamlContent = new HashMap(); - private Map yamlContent = new HashMap(); + // Our personal logger + private final static String loggerName = "cc.co.evenprime.nocheat"; + public final Logger logger = Logger.getLogger(loggerName); - // Our personal logger - private final static String loggerName = "cc.co.evenprime.nocheat"; - public final Logger logger = Logger.getLogger(loggerName); + // Our log output to a file + private FileHandler fh = null; - // Our log output to a file - private FileHandler fh = null; - - public NoCheatConfiguration(File configurationFile, File descriptionsFile) { - - // Setup the configuration tree - config(configurationFile, descriptionsFile); - - } - - /** - * Read the configuration file and assign either standard values or whatever is declared in the file - * @param configurationFile - */ - public void config(File configurationFile, File descriptionsFile) { - - - try { - yamlContent = (Map) SimpleYaml.read(configurationFile); - } catch (Exception e) { - System.out.println("Couldn't use existing nocheat.yml, creating a new file."); - yamlContent = new HashMap(); - } - - - root = new ParentOption("", false); - - - /*** LOGGING section ***/ - { - ParentOption loggingNode = new ParentOption("logging", false); - root.add(loggingNode); - - loggingNode.add(new MediumStringOption("filename", - SimpleYaml.getString("logging.filename", "plugins/NoCheat/nocheat.log", yamlContent))); - - loggingNode.add(new LevelOption("logtofile", - LogLevel.getLogLevelFromString(SimpleYaml.getString("logging.logtofile", LogLevel.LOW.asString(), yamlContent)))); - loggingNode.add(new LevelOption("logtoconsole", - LogLevel.getLogLevelFromString(SimpleYaml.getString("logging.logtoconsole", LogLevel.HIGH.asString(), yamlContent)))); - loggingNode.add(new LevelOption("logtochat", - LogLevel.getLogLevelFromString(SimpleYaml.getString("logging.logtochat", LogLevel.MED.asString(), yamlContent)))); - loggingNode.add(new LevelOption("logtoirc", - LogLevel.getLogLevelFromString(SimpleYaml.getString("logging.logtoirc", LogLevel.MED.asString(), yamlContent)))); - - loggingNode.add(new ShortStringOption("logtoirctag", - SimpleYaml.getString("logging.logtoirctag", "nocheat", yamlContent))); - } - - root.add(new BooleanOption("newpermsystem", SimpleYaml.getBoolean("newpermsystem", false, yamlContent))); - root.add(new BooleanOption("showinfomessages", SimpleYaml.getBoolean("showinfomessages", true, yamlContent))); - - /*** ACTIVE section ***/ - { - ParentOption activeNode = new ParentOption("active", false); - root.add(activeNode); - - activeNode.add(new BooleanOption("speedhack", - SimpleYaml.getBoolean("active.speedhack", true, yamlContent))); - activeNode.add(new BooleanOption("moving", - SimpleYaml.getBoolean("active.moving", true, yamlContent))); - activeNode.add(new BooleanOption("airbuild", - SimpleYaml.getBoolean("active.airbuild", false, yamlContent))); - activeNode.add(new BooleanOption("bogusitems", - SimpleYaml.getBoolean("active.bogusitems", false, yamlContent))); - activeNode.add(new BooleanOption("nuke", - SimpleYaml.getBoolean("active.nuke", false, yamlContent))); - } - - /*** SPEEDHACK section ***/ - { - ParentOption speedhackNode = new ParentOption("speedhack", false); - root.add(speedhackNode); - - speedhackNode.add(new LongStringOption("logmessage", - SimpleYaml.getString("speedhack.logmessage", "[player] sent [events] move events, but only [limit] were allowed. Speedhack?", yamlContent))); - - speedhackNode.add(new BooleanOption("checkops", - SimpleYaml.getBoolean("speedhack.checkops", false, yamlContent))); - - /*** SPEEDHACK LIMITS section ***/ - { - ParentOption speedhackLimitsNode = new ParentOption("limits", false); - speedhackNode.add(speedhackLimitsNode); - - speedhackLimitsNode.add(new IntegerOption("low", - SimpleYaml.getInt("speedhack.limits.low", 22, yamlContent))); - speedhackLimitsNode.add(new IntegerOption("med", - SimpleYaml.getInt("speedhack.limits.med", 33, yamlContent))); - speedhackLimitsNode.add(new IntegerOption("high", - SimpleYaml.getInt("speedhack.limits.high", 44, yamlContent))); - } - - /*** SPEEDHACK ACTIONS section ***/ - { - ParentOption speedhackActionNode = new ParentOption("action", false); - speedhackNode.add(speedhackActionNode); - - speedhackActionNode.add(new MediumStringOption("low", - SimpleYaml.getString("speedhack.action.low", "loglow cancel", yamlContent))); - speedhackActionNode.add(new MediumStringOption("med", - SimpleYaml.getString("speedhack.action.med", "logmed cancel", yamlContent))); - speedhackActionNode.add(new MediumStringOption("high", - SimpleYaml.getString("speedhack.action.high", "loghigh cancel", yamlContent))); - } - } - - /*** MOVING section ***/ - { - ParentOption movingNode = new ParentOption("moving", false); - root.add(movingNode); - - movingNode.add(new LongStringOption("logmessage", - SimpleYaml.getString("moving.logmessage", "Moving violation: [player] from [world] [from] to [to] distance [distance]", yamlContent))); - - movingNode.add(new LongStringOption("summarymessage", - SimpleYaml.getString("moving.summarymessage", "Moving summary of last ~[timeframe] seconds: [player] total Violations: [violations]", yamlContent))); - - movingNode.add(new IntegerOption("summaryafter", - SimpleYaml.getInt("moving.summaryafter", 15, yamlContent))); - - movingNode.add(new BooleanOption("allowflying", - SimpleYaml.getBoolean("moving.allowflying", false, yamlContent))); - movingNode.add(new BooleanOption("allowfakesneak", - SimpleYaml.getBoolean("moving.allowfakesneak", true, yamlContent))); - movingNode.add(new BooleanOption("allowfastswim", - SimpleYaml.getBoolean("moving.allowfastswim", false, yamlContent))); - movingNode.add(new BooleanOption("waterelevators", - SimpleYaml.getBoolean("moving.waterelevators", false, yamlContent))); - - movingNode.add(new BooleanOption("checkops", - SimpleYaml.getBoolean("moving.checkops", false, yamlContent))); - - movingNode.add(new BooleanOption("enforceteleport", - SimpleYaml.getBoolean("moving.enforceteleport", false, yamlContent))); - - - /*** MOVING LIMITS section ***/ - { - ParentOption movingLimitsNode = new ParentOption("limits", false); - movingNode.add(movingLimitsNode); - - movingLimitsNode.add(new IntegerOption("walking", - SimpleYaml.getInt("moving.limits.walking", 22, yamlContent))); - movingLimitsNode.add(new IntegerOption("sneaking", - SimpleYaml.getInt("moving.limits.sneaking", 14, yamlContent))); - movingLimitsNode.add(new IntegerOption("swimming", - SimpleYaml.getInt("moving.limits.swimming", 18, yamlContent))); - } - - /*** MOVING ACTION section ***/ - { - ParentOption movingActionNode = new ParentOption("action", false); - movingNode.add(movingActionNode); - - movingActionNode.add(new MediumStringOption("low", - SimpleYaml.getString("moving.action.low", "loglow cancel", yamlContent))); - movingActionNode.add(new MediumStringOption("med", - SimpleYaml.getString("moving.action.med", "logmed cancel", yamlContent))); - movingActionNode.add(new MediumStringOption("high", - SimpleYaml.getString("moving.action.high", "loghigh cancel", yamlContent))); - } - } - - /*** AIRBUILD section ***/ - { - ParentOption airbuildNode = new ParentOption("airbuild", false); - root.add(airbuildNode); - - airbuildNode.add(new BooleanOption("checkops", - SimpleYaml.getBoolean("airbuild.checkops", false, yamlContent))); - - /*** AIRBUILD LIMITS section ***/ - { - ParentOption airbuildLimitsNode = new ParentOption("limits", false); - airbuildNode.add(airbuildLimitsNode); - - airbuildLimitsNode.add(new IntegerOption("low", - SimpleYaml.getInt("airbuild.limits.low", 1, yamlContent))); - airbuildLimitsNode.add(new IntegerOption("med", - SimpleYaml.getInt("airbuild.limits.med", 3, yamlContent))); - airbuildLimitsNode.add(new IntegerOption("high", - SimpleYaml.getInt("airbuild.limits.high", 10, yamlContent))); - } - - /*** AIRBUILD ACTION section ***/ - { - ParentOption airbuildActionNode = new ParentOption("action", false); - airbuildNode.add(airbuildActionNode); - - airbuildActionNode.add(new MediumStringOption("low", - SimpleYaml.getString("airbuild.action.low", "loglow cancel", yamlContent))); - airbuildActionNode.add(new MediumStringOption("med", - SimpleYaml.getString("airbuild.action.med", "logmed cancel", yamlContent))); - airbuildActionNode.add(new MediumStringOption("high", - SimpleYaml.getString("airbuild.action.high", "loghigh cancel", yamlContent))); - } - - - } - - /*** BOGUSITEMS section ***/ - { - ParentOption bogusitemsNode = new ParentOption("bogusitems", false); - root.add(bogusitemsNode); - - bogusitemsNode.add(new BooleanOption("checkops", - SimpleYaml.getBoolean("bogusitems.checkops", false, yamlContent))); - } - - - /*** NUKE section ***/ - { - ParentOption nukeNode = new ParentOption("nuke", false); - root.add(nukeNode); - - nukeNode.add(new BooleanOption("checkops", - SimpleYaml.getBoolean("nuke.checkops", false, yamlContent))); - nukeNode.add(new LongStringOption("logmessage", - SimpleYaml.getString("nuke.logmessage", "Nuke: [player] tried to nuke the world", yamlContent))); - nukeNode.add(new LongStringOption("kickmessage", - SimpleYaml.getString("nuke.kickmessage", "No nuking allowed", yamlContent))); - nukeNode.add(new BooleanOption("limitreach", - SimpleYaml.getBoolean("nuke.limitreach", true, yamlContent))); - - } - - /*** CUSTOMACTIONS section ***/ - { - ParentOption customActionsNode = new ParentOption("customactions", true); - root.add(customActionsNode); - - Set customs = SimpleYaml.getKeys("customactions", yamlContent); - - for(String s : customs) { - - CustomActionOption o = new CustomActionOption(s, SimpleYaml.getString("customactions."+s, "unknown", yamlContent)); - - customActionsNode.add(o); - actionMap.put(s, o.getCustomActionValue()); - } - } - - writeConfigFile(configurationFile, this); - writeDescriptionFile(descriptionsFile, this); - } - - public void setupFileLogger() { - - logger.setLevel(Level.INFO); - logger.setUseParentHandlers(false); - - if(fh == null) { - try { - fh = new FileHandler(getStringValue("logging.filename"), true); - fh.setLevel(getLogLevelValue("logging.logtofile")); - fh.setFormatter(new LogFileFormatter()); - logger.addHandler(fh); - - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void cleanup() { - - if(fh != null) { - try { - logger.removeHandler(fh); - fh.flush(); - fh.close(); - - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - private Action[] stringToActions(String string) { - - List as = new LinkedList(); - String[] parts = string.split(" "); - - for(String s : parts) { - if(s.equals("loglow")) - as.add(LogAction.loglow); - else if(s.equals("logmed")) - as.add(LogAction.logmed); - else if(s.equals("loghigh")) - as.add(LogAction.loghigh); - else if(s.equals("cancel")) - as.add(CancelAction.cancel); - else if(actionMap.get(s) != null) - as.add(actionMap.get(s)); - else - { - System.out.println("NC: Couldn't parse custom action '" + s + "'"); - } - } - - return as.toArray(new Action[as.size()]); - } - - /** - * Write configuration file to specific filename - * @param f - */ - public static void writeConfigFile(File f, NoCheatConfiguration configuration) { - try { - if(f.getParentFile() != null) - f.getParentFile().mkdirs(); - - f.createNewFile(); - BufferedWriter w = new BufferedWriter(new FileWriter(f)); - - w.write(configuration.getRoot().toYAMLString("")); - - w.flush(); w.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Write a file with the descriptions of all options - * @param f - */ - private static void writeDescriptionFile(File f, NoCheatConfiguration configuration) { - try { - if(f.getParentFile() != null) - f.getParentFile().mkdirs(); - - f.createNewFile(); - BufferedWriter w = new BufferedWriter(new FileWriter(f)); - - w.write(configuration.getRoot().toDescriptionString("")); - - w.flush(); w.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public Action[] getActionValue(String optionName) throws ConfigurationException { - return stringToActions(getStringOption(optionName).getValue()); - } - - - public int getIntegerValue(String optionName) throws ConfigurationException { - return getIntegerOption(optionName).getIntegerValue(); - } - private IntegerOption getIntegerOption(String optionName) throws ConfigurationException { - - Option o = getOption(optionName) ; - if(o instanceof IntegerOption) { - return (IntegerOption)o; - } - - throw new ConfigurationException("Config Node " + optionName + " is not an integer"); - } - - public String getStringValue(String optionName) throws ConfigurationException { - return getStringOption(optionName).getValue(); - } - private TextFieldOption getStringOption(String optionName) throws ConfigurationException { - - Option o = getOption(optionName); - if(o instanceof TextFieldOption) { - return (TextFieldOption)o; - } - - throw new ConfigurationException("Config Node " + optionName + " is not a string"); - } - - public Level getLogLevelValue(String optionName) throws ConfigurationException { - return getLogLevelOption(optionName).getLevelValue(); - } - private LevelOption getLogLevelOption(String optionName) throws ConfigurationException { - - Option o = getOption(optionName); - if(o instanceof LevelOption) { - return (LevelOption)o; - } - - throw new ConfigurationException("Config Node " + optionName + " is not a loglevel"); - } - - - public boolean getBooleanValue(String optionName) throws ConfigurationException { - return getBooleanOption(optionName).getBooleanValue(); - } - - private BooleanOption getBooleanOption(String optionName) throws ConfigurationException { - - Option o = getOption(optionName); - if(o instanceof BooleanOption) { - return (BooleanOption)o; - } - - throw new ConfigurationException("Config Node " + optionName + " is not a boolean"); - } - - - private Option getOption(String optionName) throws ConfigurationException { - LinkedList l = new LinkedList(); - for(String s : optionName.split("\\.")) { - l.addLast(s); - } - return getOption(root, l); - } + public NoCheatConfiguration(File configurationFile, File descriptionsFile) { - private Option getOption(Option parent, LinkedList names) throws ConfigurationException { - - if(names.size() == 0) { - return parent; - } - else if(parent instanceof ParentOption) { - for(Option o2 : ((ParentOption)parent).getChildOptions()) { - if(o2.getIdentifier().equals(names.getFirst())) { - - names.removeFirst(); - return getOption(o2, names); - } - } - } + // Setup the configuration tree + config(configurationFile, descriptionsFile); - throw new ConfigurationException("Config Node doesn't exist"); - } + } - public ParentOption getRoot() { - return root; - } + /** + * Read the configuration file and assign either standard values or whatever + * is declared in the file + * + * @param configurationFile + */ + public void config(File configurationFile, File descriptionsFile) { + + try { + yamlContent = (Map) SimpleYaml.read(configurationFile); + } catch(Exception e) { + System.out.println("Couldn't use existing nocheat.yml, creating a new file."); + yamlContent = new HashMap(); + } + + root = new ParentOption("", false); + + /*** LOGGING section ***/ + { + ParentOption loggingNode = new ParentOption("logging", false); + root.add(loggingNode); + + loggingNode.add(new MediumStringOption("filename", SimpleYaml.getString("logging.filename", "plugins/NoCheat/nocheat.log", yamlContent))); + + loggingNode.add(new LevelOption("logtofile", LogLevel.getLogLevelFromString(SimpleYaml.getString("logging.logtofile", LogLevel.LOW.asString(), yamlContent)))); + loggingNode.add(new LevelOption("logtoconsole", LogLevel.getLogLevelFromString(SimpleYaml.getString("logging.logtoconsole", LogLevel.HIGH.asString(), yamlContent)))); + loggingNode.add(new LevelOption("logtochat", LogLevel.getLogLevelFromString(SimpleYaml.getString("logging.logtochat", LogLevel.MED.asString(), yamlContent)))); + loggingNode.add(new LevelOption("logtoirc", LogLevel.getLogLevelFromString(SimpleYaml.getString("logging.logtoirc", LogLevel.MED.asString(), yamlContent)))); + + loggingNode.add(new ShortStringOption("logtoirctag", SimpleYaml.getString("logging.logtoirctag", "nocheat", yamlContent))); + } + + root.add(new BooleanOption("newpermsystem", SimpleYaml.getBoolean("newpermsystem", false, yamlContent))); + root.add(new BooleanOption("showinfomessages", SimpleYaml.getBoolean("showinfomessages", true, yamlContent))); + + /*** ACTIVE section ***/ + { + ParentOption activeNode = new ParentOption("active", false); + root.add(activeNode); + + activeNode.add(new BooleanOption("speedhack", SimpleYaml.getBoolean("active.speedhack", true, yamlContent))); + activeNode.add(new BooleanOption("moving", SimpleYaml.getBoolean("active.moving", true, yamlContent))); + activeNode.add(new BooleanOption("airbuild", SimpleYaml.getBoolean("active.airbuild", false, yamlContent))); + activeNode.add(new BooleanOption("bogusitems", SimpleYaml.getBoolean("active.bogusitems", false, yamlContent))); + activeNode.add(new BooleanOption("nuke", SimpleYaml.getBoolean("active.nuke", false, yamlContent))); + } + + /*** SPEEDHACK section ***/ + { + ParentOption speedhackNode = new ParentOption("speedhack", false); + root.add(speedhackNode); + + speedhackNode.add(new LongStringOption("logmessage", SimpleYaml.getString("speedhack.logmessage", "[player] sent [events] move events, but only [limit] were allowed. Speedhack?", yamlContent))); + + speedhackNode.add(new BooleanOption("checkops", SimpleYaml.getBoolean("speedhack.checkops", false, yamlContent))); + + /*** SPEEDHACK LIMITS section ***/ + { + ParentOption speedhackLimitsNode = new ParentOption("limits", false); + speedhackNode.add(speedhackLimitsNode); + + speedhackLimitsNode.add(new IntegerOption("low", SimpleYaml.getInt("speedhack.limits.low", 22, yamlContent))); + speedhackLimitsNode.add(new IntegerOption("med", SimpleYaml.getInt("speedhack.limits.med", 33, yamlContent))); + speedhackLimitsNode.add(new IntegerOption("high", SimpleYaml.getInt("speedhack.limits.high", 44, yamlContent))); + } + + /*** SPEEDHACK ACTIONS section ***/ + { + ParentOption speedhackActionNode = new ParentOption("action", false); + speedhackNode.add(speedhackActionNode); + + speedhackActionNode.add(new MediumStringOption("low", SimpleYaml.getString("speedhack.action.low", "loglow cancel", yamlContent))); + speedhackActionNode.add(new MediumStringOption("med", SimpleYaml.getString("speedhack.action.med", "logmed cancel", yamlContent))); + speedhackActionNode.add(new MediumStringOption("high", SimpleYaml.getString("speedhack.action.high", "loghigh cancel", yamlContent))); + } + } + + /*** MOVING section ***/ + { + ParentOption movingNode = new ParentOption("moving", false); + root.add(movingNode); + + movingNode.add(new LongStringOption("logmessage", SimpleYaml.getString("moving.logmessage", "Moving violation: [player] from [world] [from] to [to] distance [distance]", yamlContent))); + + movingNode.add(new LongStringOption("summarymessage", SimpleYaml.getString("moving.summarymessage", "Moving summary of last ~[timeframe] seconds: [player] total Violations: [violations]", yamlContent))); + + movingNode.add(new IntegerOption("summaryafter", SimpleYaml.getInt("moving.summaryafter", 15, yamlContent))); + + movingNode.add(new BooleanOption("allowflying", SimpleYaml.getBoolean("moving.allowflying", false, yamlContent))); + movingNode.add(new BooleanOption("allowfakesneak", SimpleYaml.getBoolean("moving.allowfakesneak", true, yamlContent))); + movingNode.add(new BooleanOption("allowfastswim", SimpleYaml.getBoolean("moving.allowfastswim", false, yamlContent))); + movingNode.add(new BooleanOption("waterelevators", SimpleYaml.getBoolean("moving.waterelevators", false, yamlContent))); + + movingNode.add(new BooleanOption("checkops", SimpleYaml.getBoolean("moving.checkops", false, yamlContent))); + + movingNode.add(new BooleanOption("enforceteleport", SimpleYaml.getBoolean("moving.enforceteleport", false, yamlContent))); + + /*** MOVING LIMITS section ***/ + { + ParentOption movingLimitsNode = new ParentOption("limits", false); + movingNode.add(movingLimitsNode); + + movingLimitsNode.add(new IntegerOption("walking", SimpleYaml.getInt("moving.limits.walking", 22, yamlContent))); + movingLimitsNode.add(new IntegerOption("sneaking", SimpleYaml.getInt("moving.limits.sneaking", 14, yamlContent))); + movingLimitsNode.add(new IntegerOption("swimming", SimpleYaml.getInt("moving.limits.swimming", 18, yamlContent))); + } + + /*** MOVING ACTION section ***/ + { + ParentOption movingActionNode = new ParentOption("action", false); + movingNode.add(movingActionNode); + + movingActionNode.add(new MediumStringOption("low", SimpleYaml.getString("moving.action.low", "loglow cancel", yamlContent))); + movingActionNode.add(new MediumStringOption("med", SimpleYaml.getString("moving.action.med", "logmed cancel", yamlContent))); + movingActionNode.add(new MediumStringOption("high", SimpleYaml.getString("moving.action.high", "loghigh cancel", yamlContent))); + } + } + + /*** AIRBUILD section ***/ + { + ParentOption airbuildNode = new ParentOption("airbuild", false); + root.add(airbuildNode); + + airbuildNode.add(new BooleanOption("checkops", SimpleYaml.getBoolean("airbuild.checkops", false, yamlContent))); + + /*** AIRBUILD LIMITS section ***/ + { + ParentOption airbuildLimitsNode = new ParentOption("limits", false); + airbuildNode.add(airbuildLimitsNode); + + airbuildLimitsNode.add(new IntegerOption("low", SimpleYaml.getInt("airbuild.limits.low", 1, yamlContent))); + airbuildLimitsNode.add(new IntegerOption("med", SimpleYaml.getInt("airbuild.limits.med", 3, yamlContent))); + airbuildLimitsNode.add(new IntegerOption("high", SimpleYaml.getInt("airbuild.limits.high", 10, yamlContent))); + } + + /*** AIRBUILD ACTION section ***/ + { + ParentOption airbuildActionNode = new ParentOption("action", false); + airbuildNode.add(airbuildActionNode); + + airbuildActionNode.add(new MediumStringOption("low", SimpleYaml.getString("airbuild.action.low", "loglow cancel", yamlContent))); + airbuildActionNode.add(new MediumStringOption("med", SimpleYaml.getString("airbuild.action.med", "logmed cancel", yamlContent))); + airbuildActionNode.add(new MediumStringOption("high", SimpleYaml.getString("airbuild.action.high", "loghigh cancel", yamlContent))); + } + + } + + /*** BOGUSITEMS section ***/ + { + ParentOption bogusitemsNode = new ParentOption("bogusitems", false); + root.add(bogusitemsNode); + + bogusitemsNode.add(new BooleanOption("checkops", SimpleYaml.getBoolean("bogusitems.checkops", false, yamlContent))); + } + + /*** NUKE section ***/ + { + ParentOption nukeNode = new ParentOption("nuke", false); + root.add(nukeNode); + + nukeNode.add(new BooleanOption("checkops", SimpleYaml.getBoolean("nuke.checkops", false, yamlContent))); + nukeNode.add(new LongStringOption("logmessage", SimpleYaml.getString("nuke.logmessage", "Nuke: [player] tried to nuke the world", yamlContent))); + nukeNode.add(new LongStringOption("kickmessage", SimpleYaml.getString("nuke.kickmessage", "No nuking allowed", yamlContent))); + nukeNode.add(new BooleanOption("limitreach", SimpleYaml.getBoolean("nuke.limitreach", true, yamlContent))); + + } + + /*** CUSTOMACTIONS section ***/ + { + ParentOption customActionsNode = new ParentOption("customactions", true); + root.add(customActionsNode); + + Set customs = SimpleYaml.getKeys("customactions", yamlContent); + + for(String s : customs) { + + CustomActionOption o = new CustomActionOption(s, SimpleYaml.getString("customactions." + s, "unknown", yamlContent)); + + customActionsNode.add(o); + actionMap.put(s, o.getCustomActionValue()); + } + } + + writeConfigFile(configurationFile, this); + writeDescriptionFile(descriptionsFile, this); + } + + public void setupFileLogger() { + + logger.setLevel(Level.INFO); + logger.setUseParentHandlers(false); + + if(fh == null) { + try { + fh = new FileHandler(getStringValue("logging.filename"), true); + fh.setLevel(getLogLevelValue("logging.logtofile")); + fh.setFormatter(new LogFileFormatter()); + logger.addHandler(fh); + + } catch(Exception e) { + e.printStackTrace(); + } + } + } + + public void cleanup() { + + if(fh != null) { + try { + logger.removeHandler(fh); + fh.flush(); + fh.close(); + + } catch(Exception e) { + e.printStackTrace(); + } + } + } + + private Action[] stringToActions(String string) { + + List as = new LinkedList(); + String[] parts = string.split(" "); + + for(String s : parts) { + if(s.equals("loglow")) + as.add(LogAction.loglow); + else if(s.equals("logmed")) + as.add(LogAction.logmed); + else if(s.equals("loghigh")) + as.add(LogAction.loghigh); + else if(s.equals("cancel")) + as.add(CancelAction.cancel); + else if(actionMap.get(s) != null) + as.add(actionMap.get(s)); + else { + System.out.println("NC: Couldn't parse custom action '" + s + "'"); + } + } + + return as.toArray(new Action[as.size()]); + } + + /** + * Write configuration file to specific filename + * + * @param f + */ + public static void writeConfigFile(File f, NoCheatConfiguration configuration) { + try { + if(f.getParentFile() != null) + f.getParentFile().mkdirs(); + + f.createNewFile(); + BufferedWriter w = new BufferedWriter(new FileWriter(f)); + + w.write(configuration.getRoot().toYAMLString("")); + + w.flush(); + w.close(); + } catch(IOException e) { + e.printStackTrace(); + } + } + + /** + * Write a file with the descriptions of all options + * + * @param f + */ + private static void writeDescriptionFile(File f, NoCheatConfiguration configuration) { + try { + if(f.getParentFile() != null) + f.getParentFile().mkdirs(); + + f.createNewFile(); + BufferedWriter w = new BufferedWriter(new FileWriter(f)); + + w.write(configuration.getRoot().toDescriptionString("")); + + w.flush(); + w.close(); + } catch(IOException e) { + e.printStackTrace(); + } + } + + public Action[] getActionValue(String optionName) throws ConfigurationException { + return stringToActions(getStringOption(optionName).getValue()); + } + + public int getIntegerValue(String optionName) throws ConfigurationException { + return getIntegerOption(optionName).getIntegerValue(); + } + + private IntegerOption getIntegerOption(String optionName) throws ConfigurationException { + + Option o = getOption(optionName); + if(o instanceof IntegerOption) { + return (IntegerOption) o; + } + + throw new ConfigurationException("Config Node " + optionName + " is not an integer"); + } + + public String getStringValue(String optionName) throws ConfigurationException { + return getStringOption(optionName).getValue(); + } + + private TextFieldOption getStringOption(String optionName) throws ConfigurationException { + + Option o = getOption(optionName); + if(o instanceof TextFieldOption) { + return (TextFieldOption) o; + } + + throw new ConfigurationException("Config Node " + optionName + " is not a string"); + } + + public Level getLogLevelValue(String optionName) throws ConfigurationException { + return getLogLevelOption(optionName).getLevelValue(); + } + + private LevelOption getLogLevelOption(String optionName) throws ConfigurationException { + + Option o = getOption(optionName); + if(o instanceof LevelOption) { + return (LevelOption) o; + } + + throw new ConfigurationException("Config Node " + optionName + " is not a loglevel"); + } + + public boolean getBooleanValue(String optionName) throws ConfigurationException { + return getBooleanOption(optionName).getBooleanValue(); + } + + private BooleanOption getBooleanOption(String optionName) throws ConfigurationException { + + Option o = getOption(optionName); + if(o instanceof BooleanOption) { + return (BooleanOption) o; + } + + throw new ConfigurationException("Config Node " + optionName + " is not a boolean"); + } + + private Option getOption(String optionName) throws ConfigurationException { + LinkedList l = new LinkedList(); + for(String s : optionName.split("\\.")) { + l.addLast(s); + } + return getOption(root, l); + } + + private Option getOption(Option parent, LinkedList names) throws ConfigurationException { + + if(names.size() == 0) { + return parent; + } else if(parent instanceof ParentOption) { + for(Option o2 : ((ParentOption) parent).getChildOptions()) { + if(o2.getIdentifier().equals(names.getFirst())) { + + names.removeFirst(); + return getOption(o2, names); + } + } + } + + throw new ConfigurationException("Config Node doesn't exist"); + } + + public ParentOption getRoot() { + return root; + } } diff --git a/src/cc/co/evenprime/bukkit/nocheat/config/Option.java b/src/cc/co/evenprime/bukkit/nocheat/config/Option.java index 67134937..42f02102 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/config/Option.java +++ b/src/cc/co/evenprime/bukkit/nocheat/config/Option.java @@ -1,27 +1,27 @@ package cc.co.evenprime.bukkit.nocheat.config; public abstract class Option { - - private final String identifier; - private Option parent; - - public Option(String identifier) { - this.identifier = identifier; - } - - public final String getIdentifier() { - return identifier; - } - - public final void setParent(Option parent) { - this.parent = parent; - } - - public final String getFullIdentifier() { - return (parent == null || parent.getFullIdentifier() == "") ? identifier : parent.getFullIdentifier() + "." + identifier; - } - - public abstract String toYAMLString(String prefix); - - public abstract String toDescriptionString(String prefix); + + private final String identifier; + private Option parent; + + public Option(String identifier) { + this.identifier = identifier; + } + + public final String getIdentifier() { + return identifier; + } + + public final void setParent(Option parent) { + this.parent = parent; + } + + public final String getFullIdentifier() { + return (parent == null || parent.getFullIdentifier() == "") ? identifier : parent.getFullIdentifier() + "." + identifier; + } + + public abstract String toYAMLString(String prefix); + + public abstract String toDescriptionString(String prefix); } diff --git a/src/cc/co/evenprime/bukkit/nocheat/config/ParentOption.java b/src/cc/co/evenprime/bukkit/nocheat/config/ParentOption.java index c22b4777..9a0bcf61 100644 --- a/src/cc/co/evenprime/bukkit/nocheat/config/ParentOption.java +++ b/src/cc/co/evenprime/bukkit/nocheat/config/ParentOption.java @@ -4,80 +4,75 @@ import java.util.Collection; import java.util.Collections; import java.util.LinkedList; - public class ParentOption extends Option { - /** + /** * */ - private static final long serialVersionUID = 3162246550749560727L; + private static final long serialVersionUID = 3162246550749560727L; - private final LinkedList