From bf3c11878ac19133bf874d74fc9c19f5a20d5c8e Mon Sep 17 00:00:00 2001 From: libraryaddict Date: Sun, 19 Jun 2016 03:16:32 +1200 Subject: [PATCH] Renable some disguises, fix player sleeping? I forgot what I did --- .../libraryaddict/disguise/DisguiseAPI.java | 2 +- .../disguise/DisguiseListener.java | 2 +- .../libraryaddict/disguise/LibsDisguises.java | 2 +- .../commands/BaseDisguiseCommand.java | 43 +- .../commands/CloneDisguiseCommand.java | 150 +- .../disguise/commands/DisguiseCommand.java | 168 +- .../disguise/commands/DisguiseViewSelf.java | 73 +- .../commands/EntityDisguiseCommand.java | 140 +- .../commands/HelpDisguiseCommand.java | 673 ++++--- .../commands/LibsDisguisesCommand.java | 83 +- .../commands/PlayerDisguiseCommand.java | 216 ++- .../commands/RadiusDisguiseCommand.java | 507 +++--- .../disguise/commands/UndisguiseCommand.java | 73 +- .../commands/UndisguiseEntityCommand.java | 58 +- .../commands/UndisguisePlayerCommand.java | 88 +- .../commands/UndisguiseRadiusCommand.java | 149 +- .../disguise/disguisetypes/Disguise.java | 10 +- .../disguise/disguisetypes/FlagType.java | 11 +- .../disguise/disguisetypes/FlagWatcher.java | 171 +- .../disguise/disguisetypes/MiscDisguise.java | 4 +- .../watchers/DroppedItemWatcher.java | 8 +- .../disguisetypes/watchers/LivingWatcher.java | 440 ++--- .../disguisetypes/watchers/PlayerWatcher.java | 4 +- .../disguise/utilities/ClassGetter.java | 2 +- .../disguise/utilities/DisguiseUtilities.java | 38 +- .../disguise/utilities/Metrics.java | 1580 ++++++++--------- .../disguise/utilities/PacketsManager.java | 9 +- .../disguise/utilities/ReflectionManager.java | 101 +- .../disguise/utilities/UpdateChecker.java | 134 +- .../PacketListenerViewDisguises.java | 2 +- 30 files changed, 2647 insertions(+), 2294 deletions(-) diff --git a/src/me/libraryaddict/disguise/DisguiseAPI.java b/src/me/libraryaddict/disguise/DisguiseAPI.java index 2f10863e..f320b363 100644 --- a/src/me/libraryaddict/disguise/DisguiseAPI.java +++ b/src/me/libraryaddict/disguise/DisguiseAPI.java @@ -179,7 +179,7 @@ public class DisguiseAPI } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } } diff --git a/src/me/libraryaddict/disguise/DisguiseListener.java b/src/me/libraryaddict/disguise/DisguiseListener.java index 65ec324e..44220d03 100644 --- a/src/me/libraryaddict/disguise/DisguiseListener.java +++ b/src/me/libraryaddict/disguise/DisguiseListener.java @@ -186,7 +186,7 @@ public class DisguiseListener implements Listener } catch (InvocationTargetException e) { - e.printStackTrace(System.out); + e.printStackTrace(); } } diff --git a/src/me/libraryaddict/disguise/LibsDisguises.java b/src/me/libraryaddict/disguise/LibsDisguises.java index a026209f..cfdb8145 100644 --- a/src/me/libraryaddict/disguise/LibsDisguises.java +++ b/src/me/libraryaddict/disguise/LibsDisguises.java @@ -377,7 +377,7 @@ public class LibsDisguises extends JavaPlugin System.out.print("[LibsDisguises] Development builds are available at (ProtocolLib) " + "http://ci.dmulloy2.net/job/ProtocolLib/ and (LibsDisguises) http://server.o2gaming.com:8080/job/LibsDisguises%201.9+/"); - ex.printStackTrace(System.out); + ex.printStackTrace(); } } } diff --git a/src/me/libraryaddict/disguise/commands/BaseDisguiseCommand.java b/src/me/libraryaddict/disguise/commands/BaseDisguiseCommand.java index 91b5870e..52e2b218 100644 --- a/src/me/libraryaddict/disguise/commands/BaseDisguiseCommand.java +++ b/src/me/libraryaddict/disguise/commands/BaseDisguiseCommand.java @@ -76,7 +76,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor return getPermissions(sender, "libsdisguises." + getClass().getSimpleName().replace("Command", "").toLowerCase() + "."); } - protected HashMap getDisguisePermission(CommandSender sender, DisguiseType type) + protected HashMap getDisguiseOptions(CommandSender sender, DisguiseType type) { switch (type) { @@ -135,7 +135,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } @@ -159,6 +159,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor for (PermissionAttachmentInfo permission : sender.getEffectivePermissions()) { String perm = permission.getPermission().toLowerCase(); + if (perm.startsWith(permissionNode) && (!perms.containsKey(perm) || !permission.getValue())) { perms.put(perm, permission.getValue()); @@ -192,6 +193,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor break; } } + if (dType != null) { HashMap, Boolean> list; @@ -255,9 +257,11 @@ public abstract class BaseDisguiseCommand implements CommandExecutor { options = getOptions(perm); } + if (options != null) { HashMap, Boolean> list; + if (rangeDisguises.containsKey(type)) { list = rangeDisguises.get(type); @@ -267,13 +271,16 @@ public abstract class BaseDisguiseCommand implements CommandExecutor list = new HashMap<>(); rangeDisguises.put(type, list); } + HashMap, Boolean> map1 = getOptions(perm); + list.put(map1.keySet().iterator().next(), map1.values().iterator().next()); } } } } } + for (String perm : perms.keySet()) { if (!perms.get(perm)) @@ -281,6 +288,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor perm = perm.substring(permissionNode.length()); String disguiseType = perm.split("\\.")[0]; DisguiseType dType = null; + for (DisguiseType t : DisguiseType.values()) { if (t.name().replace("_", "").equalsIgnoreCase(disguiseType.replace("_", ""))) @@ -289,6 +297,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor break; } } + if (dType != null) { singleDisguises.remove(dType); @@ -300,6 +309,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor { boolean foundHim = false; Class entityClass = type.getEntityClass(); + switch (disguiseType) { case "mob": @@ -307,6 +317,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor { foundHim = true; } + break; case "animal": case "animals": @@ -314,6 +325,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor { foundHim = true; } + break; case "monster": case "monsters": @@ -321,23 +333,27 @@ public abstract class BaseDisguiseCommand implements CommandExecutor { foundHim = true; } + break; case "misc": if (type.isMisc()) { foundHim = true; } + break; case "ageable": if (Ageable.class.isAssignableFrom(entityClass)) { foundHim = true; } + break; case "*": foundHim = true; break; } + if (foundHim) { rangeDisguises.remove(type); @@ -346,23 +362,29 @@ public abstract class BaseDisguiseCommand implements CommandExecutor } } } + HashMap, Boolean>> map = new HashMap<>(); + for (DisguiseType type : DisguiseType.values()) { HashMap, Boolean> temp = new HashMap<>(); + if (singleDisguises.containsKey(type)) { temp.putAll(singleDisguises.get(type)); } + if (rangeDisguises.containsKey(type)) { temp.putAll(rangeDisguises.get(type)); } + if (!temp.isEmpty()) { map.put(type, temp); } } + return map; } @@ -386,8 +408,10 @@ public abstract class BaseDisguiseCommand implements CommandExecutor } list.add(option); } + HashMap, Boolean> options = new HashMap<>(); options.put(list, isRemove); + return options; } @@ -443,6 +467,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor sendCommandUsage(sender, map); throw new DisguiseParseException(); } + // How many args to skip due to the disugise being constructed // Time to start constructing the disguise. // We will need to check between all 3 kinds of disguises @@ -450,6 +475,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor ArrayList usedOptions = new ArrayList<>(); Disguise disguise = null; HashMap, Boolean> optionPermissions; + if (args[0].startsWith("@")) { if (sender.hasPermission("libsdisguises.disguise.disguiseclone")) @@ -486,6 +512,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor } } } + if (disguiseType == null) { throw new DisguiseParseException( @@ -509,7 +536,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor optionPermissions = map.get(disguiseType); - HashMap disguiseOptions = this.getDisguisePermission(sender, disguiseType); + HashMap disguiseOptions = this.getDisguiseOptions(sender, disguiseType); if (disguiseType.isPlayer()) { @@ -539,6 +566,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor if (disguiseType.isMob()) { // Its a mob, use the mob constructor boolean adult = true; + if (args.length > 1) { if (args[1].equalsIgnoreCase("baby") || args[1].equalsIgnoreCase("adult")) @@ -549,6 +577,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor toSkip++; } } + disguise = new MobDisguise(disguiseType, adult); } else if (disguiseType.isMisc()) @@ -630,6 +659,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor if (!disguiseOptions.isEmpty() && miscId != -1) { String toCheck = "" + miscId; + if (miscData == 0 || miscData == -1) { if (!disguiseOptions.containsKey(toCheck) || !disguiseOptions.get(toCheck)) @@ -641,6 +671,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor { toCheck += ":" + miscData; } + if (!disguiseOptions.containsKey(toCheck) || !disguiseOptions.get(toCheck)) { throw new DisguiseParseException( @@ -1000,7 +1031,7 @@ public abstract class BaseDisguiseCommand implements CommandExecutor } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); methodToUse = null; } } @@ -1010,17 +1041,21 @@ public abstract class BaseDisguiseCommand implements CommandExecutor { throw storedEx; } + throw new DisguiseParseException(ChatColor.RED + "Cannot find the option " + methodName); } if (value == null) { throw new DisguiseParseException(ChatColor.RED + "No value was given for the option " + methodName); } + if (!usedOptions.contains(methodName.toLowerCase())) { usedOptions.add(methodName.toLowerCase()); } + doCheck(optionPermissions, usedOptions); + if (FlagWatcher.class.isAssignableFrom(methodToUse.getDeclaringClass())) { methodToUse.invoke(disguise.getWatcher(), value); diff --git a/src/me/libraryaddict/disguise/commands/CloneDisguiseCommand.java b/src/me/libraryaddict/disguise/commands/CloneDisguiseCommand.java index 8d570966..a9cbf5bb 100644 --- a/src/me/libraryaddict/disguise/commands/CloneDisguiseCommand.java +++ b/src/me/libraryaddict/disguise/commands/CloneDisguiseCommand.java @@ -1,65 +1,85 @@ -package me.libraryaddict.disguise.commands; - -import java.util.ArrayList; -import java.util.HashMap; - -import org.apache.commons.lang.StringUtils; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; - -import me.libraryaddict.disguise.DisguiseConfig; -import me.libraryaddict.disguise.LibsDisguises; -import me.libraryaddict.disguise.disguisetypes.DisguiseType; - -public class CloneDisguiseCommand extends BaseDisguiseCommand { - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if (sender.getName().equals("CONSOLE")) { - sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); - return true; - } - if (sender.hasPermission("libsdisguises.disguise.disguiseclone")) { - boolean doEquipment = true; - boolean doSneak = false; - boolean doSprint = false; - for (String option : args) { - if (StringUtils.startsWithIgnoreCase(option, "ignoreEquip") - || StringUtils.startsWithIgnoreCase(option, "ignoreEnquip")) { - doEquipment = false; - } else if (option.equalsIgnoreCase("doSneakSprint")) { - doSneak = true; - doSprint = true; - } else if (option.equalsIgnoreCase("doSneak")) { - doSneak = true; - } else if (option.equalsIgnoreCase("doSprint")) { - doSprint = true; - } else { - sender.sendMessage(ChatColor.DARK_RED + "Unknown option '" + option - + "' - Valid options are 'IgnoreEquipment' 'DoSneakSprint' 'DoSneak' 'DoSprint'"); - return true; - } - } - LibsDisguises.getInstance().getListener().setDisguiseClone(sender.getName(), new Boolean[]{doEquipment, doSneak, doSprint}); - sender.sendMessage(ChatColor.RED + "Right click a entity in the next " + DisguiseConfig.getDisguiseCloneExpire() - + " seconds to grab the disguise reference!"); - } else { - sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); - } - return true; - } - - /** - * Send the player the information - */ - @Override - protected void sendCommandUsage(CommandSender sender, HashMap, Boolean>> map) { - sender.sendMessage(ChatColor.DARK_GREEN - + "Right click a entity to get a disguise reference you can pass to other disguise commands!"); - sender.sendMessage(ChatColor.DARK_GREEN - + "Security note: Any references you create will be available to all players able to use disguise references."); - sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseclone IgnoreEquipment" + ChatColor.DARK_GREEN + "(" + ChatColor.GREEN - + "Optional" + ChatColor.DARK_GREEN + ")"); - } -} +package me.libraryaddict.disguise.commands; + +import java.util.ArrayList; +import java.util.HashMap; + +import org.apache.commons.lang.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import me.libraryaddict.disguise.DisguiseConfig; +import me.libraryaddict.disguise.LibsDisguises; +import me.libraryaddict.disguise.disguisetypes.DisguiseType; + +public class CloneDisguiseCommand extends BaseDisguiseCommand +{ + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) + { + if (sender.getName().equals("CONSOLE")) + { + sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); + return true; + } + if (sender.hasPermission("libsdisguises.disguise.disguiseclone")) + { + boolean doEquipment = true; + boolean doSneak = false; + boolean doSprint = false; + for (String option : args) + { + if (StringUtils.startsWithIgnoreCase(option, "ignoreEquip") + || StringUtils.startsWithIgnoreCase(option, "ignoreEnquip")) + { + doEquipment = false; + } + else if (option.equalsIgnoreCase("doSneakSprint")) + { + doSneak = true; + doSprint = true; + } + else if (option.equalsIgnoreCase("doSneak")) + { + doSneak = true; + } + else if (option.equalsIgnoreCase("doSprint")) + { + doSprint = true; + } + else + { + sender.sendMessage(ChatColor.DARK_RED + "Unknown option '" + option + + "' - Valid options are 'IgnoreEquipment' 'DoSneakSprint' 'DoSneak' 'DoSprint'"); + return true; + } + } + LibsDisguises.getInstance().getListener().setDisguiseClone(sender.getName(), new Boolean[] + { + doEquipment, doSneak, doSprint + }); + sender.sendMessage(ChatColor.RED + "Right click a entity in the next " + DisguiseConfig.getDisguiseCloneExpire() + + " seconds to grab the disguise reference!"); + } + else + { + sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); + } + return true; + } + + /** + * Send the player the information + */ + @Override + protected void sendCommandUsage(CommandSender sender, HashMap, Boolean>> map) + { + sender.sendMessage(ChatColor.DARK_GREEN + + "Right click a entity to get a disguise reference you can pass to other disguise commands!"); + sender.sendMessage(ChatColor.DARK_GREEN + + "Security note: Any references you create will be available to all players able to use disguise references."); + sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseclone IgnoreEquipment" + ChatColor.DARK_GREEN + "(" + ChatColor.GREEN + + "Optional" + ChatColor.DARK_GREEN + ")"); + } +} diff --git a/src/me/libraryaddict/disguise/commands/DisguiseCommand.java b/src/me/libraryaddict/disguise/commands/DisguiseCommand.java index 1cdba6a9..227fc65f 100644 --- a/src/me/libraryaddict/disguise/commands/DisguiseCommand.java +++ b/src/me/libraryaddict/disguise/commands/DisguiseCommand.java @@ -1,72 +1,96 @@ -package me.libraryaddict.disguise.commands; - -import java.util.ArrayList; -import java.util.HashMap; - -import org.apache.commons.lang.StringUtils; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import me.libraryaddict.disguise.DisguiseAPI; -import me.libraryaddict.disguise.DisguiseConfig; -import me.libraryaddict.disguise.disguisetypes.Disguise; -import me.libraryaddict.disguise.disguisetypes.DisguiseType; -import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher; - -public class DisguiseCommand extends BaseDisguiseCommand { - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if (sender.getName().equals("CONSOLE")) { - sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); - return true; - } - Disguise disguise; - try { - disguise = parseDisguise(sender, args, getPermissions(sender)); - } catch (DisguiseParseException ex) { - if (ex.getMessage() != null) { - sender.sendMessage(ex.getMessage()); - } - return true; - } catch (Exception ex) { - ex.printStackTrace(System.out); - return true; - } - if (DisguiseConfig.isNameOfPlayerShownAboveDisguise()) { - if (disguise.getWatcher() instanceof LivingWatcher) { - disguise.getWatcher().setCustomName(((Player) sender).getDisplayName()); - if (DisguiseConfig.isNameAboveHeadAlwaysVisible()) { - disguise.getWatcher().setCustomNameVisible(true); - } - } - } - DisguiseAPI.disguiseToAll((Player) sender, disguise); - if (disguise.isDisguiseInUse()) { - sender.sendMessage(ChatColor.RED + "Now disguised as a " + disguise.getType().toReadable()); - } else { - sender.sendMessage(ChatColor.RED + "Failed to disguise as a " + disguise.getType().toReadable()); - } - return true; - } - - /** - * Send the player the information - */ - @Override - protected void sendCommandUsage(CommandSender sender, HashMap, Boolean>> map) { - ArrayList allowedDisguises = getAllowedDisguises(map); - sender.sendMessage(ChatColor.DARK_GREEN + "Choose a disguise to become the disguise!"); - sender.sendMessage(ChatColor.DARK_GREEN + "You can use the disguises: " + ChatColor.GREEN - + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)); - if (allowedDisguises.contains("player")) { - sender.sendMessage(ChatColor.DARK_GREEN + "/disguise player "); - } - sender.sendMessage(ChatColor.DARK_GREEN + "/disguise "); - if (allowedDisguises.contains("dropped_item") || allowedDisguises.contains("falling_block")) { - sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseplayer "); - } - } -} +package me.libraryaddict.disguise.commands; + +import java.util.ArrayList; +import java.util.HashMap; + +import org.apache.commons.lang.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import me.libraryaddict.disguise.DisguiseAPI; +import me.libraryaddict.disguise.DisguiseConfig; +import me.libraryaddict.disguise.disguisetypes.Disguise; +import me.libraryaddict.disguise.disguisetypes.DisguiseType; +import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher; + +public class DisguiseCommand extends BaseDisguiseCommand +{ + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) + { + if (sender.getName().equals("CONSOLE")) + { + sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); + return true; + } + Disguise disguise; + try + { + disguise = parseDisguise(sender, args, getPermissions(sender)); + } + catch (DisguiseParseException ex) + { + if (ex.getMessage() != null) + { + sender.sendMessage(ex.getMessage()); + } + + return true; + } + catch (Exception ex) + { + ex.printStackTrace(); + return true; + } + + if (DisguiseConfig.isNameOfPlayerShownAboveDisguise()) + { + if (disguise.getWatcher() instanceof LivingWatcher) + { + disguise.getWatcher().setCustomName(((Player) sender).getDisplayName()); + + if (DisguiseConfig.isNameAboveHeadAlwaysVisible()) + { + disguise.getWatcher().setCustomNameVisible(true); + } + } + } + + DisguiseAPI.disguiseToAll((Player) sender, disguise); + + if (disguise.isDisguiseInUse()) + { + sender.sendMessage(ChatColor.RED + "Now disguised as a " + disguise.getType().toReadable()); + } + else + { + sender.sendMessage(ChatColor.RED + "Failed to disguise as a " + disguise.getType().toReadable()); + } + + return true; + } + + /** + * Send the player the information + */ + @Override + protected void sendCommandUsage(CommandSender sender, HashMap, Boolean>> map) + { + ArrayList allowedDisguises = getAllowedDisguises(map); + sender.sendMessage(ChatColor.DARK_GREEN + "Choose a disguise to become the disguise!"); + sender.sendMessage(ChatColor.DARK_GREEN + "You can use the disguises: " + ChatColor.GREEN + + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)); + if (allowedDisguises.contains("player")) + { + sender.sendMessage(ChatColor.DARK_GREEN + "/disguise player "); + } + sender.sendMessage(ChatColor.DARK_GREEN + "/disguise "); + if (allowedDisguises.contains("dropped_item") || allowedDisguises.contains("falling_block")) + { + sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseplayer "); + } + } +} diff --git a/src/me/libraryaddict/disguise/commands/DisguiseViewSelf.java b/src/me/libraryaddict/disguise/commands/DisguiseViewSelf.java index a1098f22..836b3a95 100644 --- a/src/me/libraryaddict/disguise/commands/DisguiseViewSelf.java +++ b/src/me/libraryaddict/disguise/commands/DisguiseViewSelf.java @@ -1,34 +1,39 @@ -package me.libraryaddict.disguise.commands; - -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import me.libraryaddict.disguise.DisguiseAPI; - -/** - * - * @author Navid - */ -public class DisguiseViewSelf implements CommandExecutor { - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if (sender.getName().equals("CONSOLE")) { - sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); - return true; - } - Player player = (Player) sender; - if (DisguiseAPI.isViewSelfToggled(player)) { - DisguiseAPI.setViewDisguiseToggled(player, false); - sender.sendMessage(ChatColor.GREEN + "Toggled viewing own disguise off!"); - } else { - DisguiseAPI.setViewDisguiseToggled(player, true); - sender.sendMessage(ChatColor.GREEN + "Toggled viewing own disguise on!"); - } - return true; - } - -} +package me.libraryaddict.disguise.commands; + +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import me.libraryaddict.disguise.DisguiseAPI; + +/** + * @author Navid + */ +public class DisguiseViewSelf implements CommandExecutor +{ + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) + { + if (sender.getName().equals("CONSOLE")) + { + sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); + return true; + } + Player player = (Player) sender; + if (DisguiseAPI.isViewSelfToggled(player)) + { + DisguiseAPI.setViewDisguiseToggled(player, false); + sender.sendMessage(ChatColor.GREEN + "Toggled viewing own disguise off!"); + } + else + { + DisguiseAPI.setViewDisguiseToggled(player, true); + sender.sendMessage(ChatColor.GREEN + "Toggled viewing own disguise on!"); + } + return true; + } + +} diff --git a/src/me/libraryaddict/disguise/commands/EntityDisguiseCommand.java b/src/me/libraryaddict/disguise/commands/EntityDisguiseCommand.java index 6ce182dc..8bd17f57 100644 --- a/src/me/libraryaddict/disguise/commands/EntityDisguiseCommand.java +++ b/src/me/libraryaddict/disguise/commands/EntityDisguiseCommand.java @@ -1,64 +1,76 @@ -package me.libraryaddict.disguise.commands; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.HashMap; - -import org.apache.commons.lang.StringUtils; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; - -import me.libraryaddict.disguise.DisguiseConfig; -import me.libraryaddict.disguise.LibsDisguises; -import me.libraryaddict.disguise.disguisetypes.Disguise; -import me.libraryaddict.disguise.disguisetypes.DisguiseType; - -public class EntityDisguiseCommand extends BaseDisguiseCommand { - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if (sender.getName().equals("CONSOLE")) { - sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); - return true; - } - Disguise disguise; - try { - disguise = parseDisguise(sender, args, getPermissions(sender)); - } catch (DisguiseParseException ex) { - if (ex.getMessage() != null) { - sender.sendMessage(ex.getMessage()); - } - return true; - } catch (IllegalAccessException | InvocationTargetException ex) { - ex.printStackTrace(System.out); - return true; - } - LibsDisguises.getInstance().getListener().setDisguiseEntity(sender.getName(), disguise); - sender.sendMessage(ChatColor.RED + "Right click a entity in the next " + DisguiseConfig.getDisguiseEntityExpire() - + " seconds to disguise it as a " + disguise.getType().toReadable() + "!"); - return true; - } - - /** - * Send the player the information - * - * @param sender - * @param map - */ - @Override - protected void sendCommandUsage(CommandSender sender, HashMap, Boolean>> map) { - ArrayList allowedDisguises = getAllowedDisguises(map); - sender.sendMessage(ChatColor.DARK_GREEN + "Choose a disguise then right click a entity to disguise it!"); - sender.sendMessage(ChatColor.DARK_GREEN + "You can use the disguises: " + ChatColor.GREEN - + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)); - if (allowedDisguises.contains("player")) { - sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseentity player "); - } - sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseentity "); - if (allowedDisguises.contains("dropped_item") || allowedDisguises.contains("falling_block")) { - sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseentity "); - } - } - -} +package me.libraryaddict.disguise.commands; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.HashMap; + +import org.apache.commons.lang.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import me.libraryaddict.disguise.DisguiseConfig; +import me.libraryaddict.disguise.LibsDisguises; +import me.libraryaddict.disguise.disguisetypes.Disguise; +import me.libraryaddict.disguise.disguisetypes.DisguiseType; + +public class EntityDisguiseCommand extends BaseDisguiseCommand +{ + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) + { + if (sender.getName().equals("CONSOLE")) + { + sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); + return true; + } + Disguise disguise; + try + { + disguise = parseDisguise(sender, args, getPermissions(sender)); + } + catch (DisguiseParseException ex) + { + if (ex.getMessage() != null) + { + sender.sendMessage(ex.getMessage()); + } + return true; + } + catch (IllegalAccessException | InvocationTargetException ex) + { + ex.printStackTrace(); + return true; + } + LibsDisguises.getInstance().getListener().setDisguiseEntity(sender.getName(), disguise); + sender.sendMessage(ChatColor.RED + "Right click a entity in the next " + DisguiseConfig.getDisguiseEntityExpire() + + " seconds to disguise it as a " + disguise.getType().toReadable() + "!"); + return true; + } + + /** + * Send the player the information + * + * @param sender + * @param map + */ + @Override + protected void sendCommandUsage(CommandSender sender, HashMap, Boolean>> map) + { + ArrayList allowedDisguises = getAllowedDisguises(map); + sender.sendMessage(ChatColor.DARK_GREEN + "Choose a disguise then right click a entity to disguise it!"); + sender.sendMessage(ChatColor.DARK_GREEN + "You can use the disguises: " + ChatColor.GREEN + + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)); + if (allowedDisguises.contains("player")) + { + sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseentity player "); + } + sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseentity "); + if (allowedDisguises.contains("dropped_item") || allowedDisguises.contains("falling_block")) + { + sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseentity "); + } + } + +} diff --git a/src/me/libraryaddict/disguise/commands/HelpDisguiseCommand.java b/src/me/libraryaddict/disguise/commands/HelpDisguiseCommand.java index c6b78d7f..41f12620 100644 --- a/src/me/libraryaddict/disguise/commands/HelpDisguiseCommand.java +++ b/src/me/libraryaddict/disguise/commands/HelpDisguiseCommand.java @@ -1,283 +1,390 @@ -package me.libraryaddict.disguise.commands; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; - -import org.apache.commons.lang.StringUtils; -import org.bukkit.ChatColor; -import org.bukkit.block.BlockFace; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffectType; - -import me.libraryaddict.disguise.disguisetypes.AnimalColor; -import me.libraryaddict.disguise.disguisetypes.DisguiseType; -import me.libraryaddict.disguise.disguisetypes.FlagWatcher; -import me.libraryaddict.disguise.disguisetypes.RabbitType; -import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher; - -public class HelpDisguiseCommand extends BaseDisguiseCommand { - - private class EnumHelp { - - private String enumDescription; - private String enumName; - private String[] enums; - private String readableEnum; - - public EnumHelp(String enumName, String enumReadable, String enumDescription, Enum[] enums) { - String[] strings = new String[enums.length]; - for (int i = 0; i < strings.length; i++) { - strings[i] = toReadable(enums[i].name()); - } - this.enumName = enumName; - this.enumDescription = enumDescription; - this.enums = strings; - this.readableEnum = enumReadable; - } - - public EnumHelp(String enumName, String enumReadable, String enumDescription, String[] enums) { - this.enumName = enumName; - this.enumDescription = enumDescription; - this.enums = enums; - this.readableEnum = enumReadable; - } - - public String getEnumDescription() { - return enumDescription; - } - - public String getEnumName() { - return enumName; - } - - public String[] getEnums() { - return enums; - } - - public String getReadableEnum() { - return readableEnum; - } - } - - private ArrayList enumHelp = new ArrayList<>(); - - public HelpDisguiseCommand() { - try { - enumHelp.add(new EnumHelp("AnimalColor", "Animal colors", ChatColor.RED + "/disguisehelp AnimalColors " - + ChatColor.GREEN + "- View all the colors you can use for a animal color", AnimalColor.values())); - } catch (Exception ex) { - ex.printStackTrace(System.out); - } - try { - enumHelp.add(new EnumHelp("Art", "Arts", ChatColor.RED + "/disguisehelp Art " + ChatColor.GREEN - + "- View all the painting arts you can use on a painting disguise", (Enum[]) Class.forName("org.bukkit.Art") - .getEnumConstants())); - } catch (Exception ex) { - } - try { - enumHelp.add(new EnumHelp("HorseColor", "Horse colors", ChatColor.RED + "/disguisehelp HorseColors " - + ChatColor.GREEN + "- View all the colors you can use for a horses color", (Enum[]) Class.forName( - "org.bukkit.entity.Horse$Color").getEnumConstants())); - } catch (Exception ex) { - } - try { - enumHelp.add(new EnumHelp("HorseStyle", "Horse styles", ChatColor.RED + "/disguisehelp HorseStyles " - + ChatColor.GREEN + "- View all the styles you can use for a horses style", (Enum[]) Class.forName( - "org.bukkit.entity.Horse$Style").getEnumConstants())); - } catch (Exception ex) { - } - try { - enumHelp.add(new EnumHelp("OcelotType", "Ocelot types", ChatColor.RED + "/disguisehelp OcelotTypes " - + ChatColor.GREEN + "- View all the ocelot types you can use for ocelots", (Enum[]) Class.forName( - "org.bukkit.entity.Ocelot$Type").getEnumConstants())); - } catch (Exception ex) { - } - try { - ArrayList enumReturns = new ArrayList<>(); - for (PotionEffectType potionType : PotionEffectType.values()) { - if (potionType != null) { - enumReturns.add(toReadable(potionType.getName()) + ChatColor.RED + "(" + ChatColor.GREEN + potionType.getId() - + ChatColor.RED + ")"); - } - } - enumHelp.add(new EnumHelp("PotionEffect", "PotionEffect", ChatColor.RED + "/disguisehelp PotionEffect " - + ChatColor.GREEN + "- View all the potion effects you can set", enumReturns.toArray(new String[enumReturns - .size()]))); - } catch (Exception ex) { - ex.printStackTrace(System.out); - } - try { - enumHelp.add(new EnumHelp("Profession", "Villager professions", ChatColor.RED + "/disguisehelp Professions " - + ChatColor.GREEN + "- View all the professions you can set on a villager", (Enum[]) Class.forName( - "org.bukkit.entity.Villager$Profession").getEnumConstants())); - } catch (Exception ex) { - } - enumHelp.add(new EnumHelp("Direction", "Directions", ChatColor.RED + "/disguisehelp Directions " + ChatColor.GREEN - + "- View the five directions usable on player setsleeping disguise", Arrays.copyOf(BlockFace.values(), 5))); - enumHelp.add(new EnumHelp("RabbitType", "RabbitType", ChatColor.RED + "/disguisehelp RabbitType " + ChatColor.GREEN - + "View the kinds of rabbits you can turn into", RabbitType.values())); - } - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - for (String node : new String[]{"disguise", "disguiseradius", "disguiseentity", "disguiseplayer"}) { - HashMap, Boolean>> permMap = getPermissions(sender, "libsdisguises." + node - + "."); - if (!permMap.isEmpty()) { - if (args.length == 0) { - sendCommandUsage(sender, null); - return true; - } else { - EnumHelp help = null; - for (EnumHelp s : enumHelp) { - if (args[0].equalsIgnoreCase(s.getEnumName()) || args[0].equalsIgnoreCase(s.getEnumName() + "s")) { - help = s; - break; - } - } - if (help != null) { - sender.sendMessage(ChatColor.RED + help.getReadableEnum() + ": " + ChatColor.GREEN - + StringUtils.join(help.getEnums(), ChatColor.RED + ", " + ChatColor.GREEN)); - return true; - } - DisguiseType type = null; - for (DisguiseType disguiseType : DisguiseType.values()) { - if (args[0].equalsIgnoreCase(disguiseType.name()) - || disguiseType.name().replace("_", "").equalsIgnoreCase(args[0])) { - type = disguiseType; - break; - } - } - if (type == null) { - sender.sendMessage(ChatColor.RED + "Cannot find the disguise " + args[0]); - return true; - } - if (!permMap.containsKey(type)) { - sender.sendMessage(ChatColor.RED + "You do not have permission for that disguise!"); - return true; - } - ArrayList methods = new ArrayList<>(); - HashMap map = new HashMap<>(); - Class watcher = type.getWatcherClass(); - int ignored = 0; - try { - for (Method method : this.getDisguiseWatcherMethods(watcher)) { - if (!method.getName().startsWith("get") && method.getParameterTypes().length == 1 - && method.getAnnotation(Deprecated.class) == null) { - if (args.length < 2 || !args[1].equalsIgnoreCase("show")) { - boolean allowed = false; - for (ArrayList key : permMap.get(type).keySet()) { - if (permMap.get(type).get(key)) { - if (key.contains("*") || key.contains(method.getName().toLowerCase())) { - allowed = true; - break; - } - } else if (!key.contains(method.getName().toLowerCase())) { - allowed = true; - break; - } - } - if (!allowed) { - ignored++; - continue; - } - } - Class c = method.getParameterTypes()[0]; - String valueType = null; - if (c == String.class) { - valueType = "String"; - } else if (boolean.class == c) { - valueType = "True/False"; - } else if (int.class == c) { - valueType = "Number"; - } else if (float.class == c || double.class == c) { - valueType = "Decimal"; - } else if (AnimalColor.class == c) { - valueType = "Color"; - } else if (ItemStack.class == c) { - valueType = "Item (id:damage)"; - } else if (ItemStack[].class == c) { - valueType = "4 items (id:damage,id,...)"; - } else if (c.getSimpleName().equals("Style")) { - valueType = "Horse Style"; - } else if (c.getSimpleName().equals("Color")) { - valueType = "Horse Color"; - } else if (c.getSimpleName().equals("Type")) { - valueType = "Ocelot type"; - } else if (c.getSimpleName().equals("Profession")) { - valueType = "Villager Profession"; - } else if (PotionEffectType.class == c) { - valueType = "Potion effect"; - } else if (c == int[].class) { - valueType = "number,number,number..."; - } else if (c == BlockFace.class) { - valueType = "direction"; - } else if (c == RabbitType.class) { - valueType = "rabbit type"; - } - if (valueType != null) { - ChatColor methodColor = ChatColor.YELLOW; - Class declaring = method.getDeclaringClass(); - if (declaring == LivingWatcher.class) { - methodColor = ChatColor.AQUA; - } else if (!(FlagWatcher.class.isAssignableFrom(declaring)) || declaring == FlagWatcher.class) { - methodColor = ChatColor.GRAY; - } - String str = method.getName() + ChatColor.DARK_RED + "(" + ChatColor.GREEN + valueType - + ChatColor.DARK_RED + ")"; - map.put(str, methodColor); - methods.add(str); - } - } - } - } catch (Exception ex) { - ex.printStackTrace(System.out); - } - Collections.sort(methods, String.CASE_INSENSITIVE_ORDER); - for (int i = 0; i < methods.size(); i++) { - methods.set(i, map.get(methods.get(i)) + methods.get(i)); - } - if (methods.isEmpty()) { - methods.add(ChatColor.RED + "No options with permission to use"); - } - sender.sendMessage(ChatColor.DARK_RED + type.toReadable() + " options: " - + StringUtils.join(methods, ChatColor.DARK_RED + ", ")); - if (ignored > 0) { - sender.sendMessage(ChatColor.RED + "Ignored " + ignored - + " options you do not have permission to view. Add 'show' to view unusable options."); - } - return true; - } - } - } - sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); - return true; - } - - /** - * Send the player the information - */ - @Override - protected void sendCommandUsage(CommandSender sender, HashMap, Boolean>> map) { - sender.sendMessage(ChatColor.RED - + "/disguisehelp " - + ChatColor.GREEN - + "- View the options you can set on a disguise. Add 'show' to reveal the options you don't have permission to use"); - for (EnumHelp s : enumHelp) { - sender.sendMessage(s.getEnumDescription()); - } - } - - public String toReadable(String string) { - String[] split = string.split("_"); - for (int i = 0; i < split.length; i++) { - split[i] = split[i].substring(0, 1) + split[i].substring(1).toLowerCase(); - } - return StringUtils.join(split, "_"); - } -} +package me.libraryaddict.disguise.commands; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; + +import org.apache.commons.lang.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.block.BlockFace; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffectType; + +import me.libraryaddict.disguise.disguisetypes.AnimalColor; +import me.libraryaddict.disguise.disguisetypes.DisguiseType; +import me.libraryaddict.disguise.disguisetypes.FlagWatcher; +import me.libraryaddict.disguise.disguisetypes.RabbitType; +import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher; + +public class HelpDisguiseCommand extends BaseDisguiseCommand +{ + + private class EnumHelp + { + + private String enumDescription; + private String enumName; + private String[] enums; + private String readableEnum; + + public EnumHelp(String enumName, String enumReadable, String enumDescription, Enum[] enums) + { + String[] strings = new String[enums.length]; + for (int i = 0; i < strings.length; i++) + { + strings[i] = toReadable(enums[i].name()); + } + this.enumName = enumName; + this.enumDescription = enumDescription; + this.enums = strings; + this.readableEnum = enumReadable; + } + + public EnumHelp(String enumName, String enumReadable, String enumDescription, String[] enums) + { + this.enumName = enumName; + this.enumDescription = enumDescription; + this.enums = enums; + this.readableEnum = enumReadable; + } + + public String getEnumDescription() + { + return enumDescription; + } + + public String getEnumName() + { + return enumName; + } + + public String[] getEnums() + { + return enums; + } + + public String getReadableEnum() + { + return readableEnum; + } + } + + private ArrayList enumHelp = new ArrayList<>(); + + public HelpDisguiseCommand() + { + try + { + enumHelp.add(new EnumHelp("AnimalColor", "Animal colors", ChatColor.RED + "/disguisehelp AnimalColors " + + ChatColor.GREEN + "- View all the colors you can use for a animal color", AnimalColor.values())); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + try + { + enumHelp.add(new EnumHelp("Art", "Arts", + ChatColor.RED + "/disguisehelp Art " + ChatColor.GREEN + + "- View all the painting arts you can use on a painting disguise", + (Enum[]) Class.forName("org.bukkit.Art").getEnumConstants())); + } + catch (Exception ex) + { + } + try + { + enumHelp.add(new EnumHelp("HorseColor", "Horse colors", + ChatColor.RED + "/disguisehelp HorseColors " + ChatColor.GREEN + + "- View all the colors you can use for a horses color", + (Enum[]) Class.forName("org.bukkit.entity.Horse$Color").getEnumConstants())); + } + catch (Exception ex) + { + } + try + { + enumHelp.add(new EnumHelp("HorseStyle", "Horse styles", + ChatColor.RED + "/disguisehelp HorseStyles " + ChatColor.GREEN + + "- View all the styles you can use for a horses style", + (Enum[]) Class.forName("org.bukkit.entity.Horse$Style").getEnumConstants())); + } + catch (Exception ex) + { + } + try + { + enumHelp.add(new EnumHelp("OcelotType", "Ocelot types", + ChatColor.RED + "/disguisehelp OcelotTypes " + ChatColor.GREEN + + "- View all the ocelot types you can use for ocelots", + (Enum[]) Class.forName("org.bukkit.entity.Ocelot$Type").getEnumConstants())); + } + catch (Exception ex) + { + } + try + { + ArrayList enumReturns = new ArrayList<>(); + for (PotionEffectType potionType : PotionEffectType.values()) + { + if (potionType != null) + { + enumReturns.add(toReadable(potionType.getName()) + ChatColor.RED + "(" + ChatColor.GREEN + potionType.getId() + + ChatColor.RED + ")"); + } + } + enumHelp.add(new EnumHelp("PotionEffect", "PotionEffect", + ChatColor.RED + "/disguisehelp PotionEffect " + ChatColor.GREEN + "- View all the potion effects you can set", + enumReturns.toArray(new String[enumReturns.size()]))); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + try + { + enumHelp.add(new EnumHelp("Profession", "Villager professions", + ChatColor.RED + "/disguisehelp Professions " + ChatColor.GREEN + + "- View all the professions you can set on a villager", + (Enum[]) Class.forName("org.bukkit.entity.Villager$Profession").getEnumConstants())); + } + catch (Exception ex) + { + } + enumHelp.add(new EnumHelp("Direction", "Directions", + ChatColor.RED + "/disguisehelp Directions " + ChatColor.GREEN + + "- View the five directions usable on player setsleeping disguise", + Arrays.copyOf(BlockFace.values(), 5))); + enumHelp.add(new EnumHelp("RabbitType", "RabbitType", + ChatColor.RED + "/disguisehelp RabbitType " + ChatColor.GREEN + "View the kinds of rabbits you can turn into", + RabbitType.values())); + } + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) + { + for (String node : new String[] + { + "disguise", "disguiseradius", "disguiseentity", "disguiseplayer" + }) + { + HashMap, Boolean>> permMap = getPermissions(sender, + "libsdisguises." + node + "."); + if (!permMap.isEmpty()) + { + if (args.length == 0) + { + sendCommandUsage(sender, null); + return true; + } + else + { + EnumHelp help = null; + for (EnumHelp s : enumHelp) + { + if (args[0].equalsIgnoreCase(s.getEnumName()) || args[0].equalsIgnoreCase(s.getEnumName() + "s")) + { + help = s; + break; + } + } + if (help != null) + { + sender.sendMessage(ChatColor.RED + help.getReadableEnum() + ": " + ChatColor.GREEN + + StringUtils.join(help.getEnums(), ChatColor.RED + ", " + ChatColor.GREEN)); + return true; + } + DisguiseType type = null; + for (DisguiseType disguiseType : DisguiseType.values()) + { + if (args[0].equalsIgnoreCase(disguiseType.name()) + || disguiseType.name().replace("_", "").equalsIgnoreCase(args[0])) + { + type = disguiseType; + break; + } + } + if (type == null) + { + sender.sendMessage(ChatColor.RED + "Cannot find the disguise " + args[0]); + return true; + } + if (!permMap.containsKey(type)) + { + sender.sendMessage(ChatColor.RED + "You do not have permission for that disguise!"); + return true; + } + ArrayList methods = new ArrayList<>(); + HashMap map = new HashMap<>(); + Class watcher = type.getWatcherClass(); + int ignored = 0; + try + { + for (Method method : this.getDisguiseWatcherMethods(watcher)) + { + if (!method.getName().startsWith("get") && method.getParameterTypes().length == 1 + && method.getAnnotation(Deprecated.class) == null) + { + if (args.length < 2 || !args[1].equalsIgnoreCase("show")) + { + boolean allowed = false; + for (ArrayList key : permMap.get(type).keySet()) + { + if (permMap.get(type).get(key)) + { + if (key.contains("*") || key.contains(method.getName().toLowerCase())) + { + allowed = true; + break; + } + } + else if (!key.contains(method.getName().toLowerCase())) + { + allowed = true; + break; + } + } + if (!allowed) + { + ignored++; + continue; + } + } + Class c = method.getParameterTypes()[0]; + String valueType = null; + if (c == String.class) + { + valueType = "String"; + } + else if (boolean.class == c) + { + valueType = "True/False"; + } + else if (int.class == c) + { + valueType = "Number"; + } + else if (float.class == c || double.class == c) + { + valueType = "Decimal"; + } + else if (AnimalColor.class == c) + { + valueType = "Color"; + } + else if (ItemStack.class == c) + { + valueType = "Item (id:damage)"; + } + else if (ItemStack[].class == c) + { + valueType = "4 items (id:damage,id,...)"; + } + else if (c.getSimpleName().equals("Style")) + { + valueType = "Horse Style"; + } + else if (c.getSimpleName().equals("Color")) + { + valueType = "Horse Color"; + } + else if (c.getSimpleName().equals("Type")) + { + valueType = "Ocelot type"; + } + else if (c.getSimpleName().equals("Profession")) + { + valueType = "Villager Profession"; + } + else if (PotionEffectType.class == c) + { + valueType = "Potion effect"; + } + else if (c == int[].class) + { + valueType = "number,number,number..."; + } + else if (c == BlockFace.class) + { + valueType = "direction"; + } + else if (c == RabbitType.class) + { + valueType = "rabbit type"; + } + if (valueType != null) + { + ChatColor methodColor = ChatColor.YELLOW; + Class declaring = method.getDeclaringClass(); + if (declaring == LivingWatcher.class) + { + methodColor = ChatColor.AQUA; + } + else if (!(FlagWatcher.class.isAssignableFrom(declaring)) || declaring == FlagWatcher.class) + { + methodColor = ChatColor.GRAY; + } + String str = method.getName() + ChatColor.DARK_RED + "(" + ChatColor.GREEN + valueType + + ChatColor.DARK_RED + ")"; + map.put(str, methodColor); + methods.add(str); + } + } + } + } + catch (Exception ex) + { + ex.printStackTrace(); + } + Collections.sort(methods, String.CASE_INSENSITIVE_ORDER); + for (int i = 0; i < methods.size(); i++) + { + methods.set(i, map.get(methods.get(i)) + methods.get(i)); + } + if (methods.isEmpty()) + { + methods.add(ChatColor.RED + "No options with permission to use"); + } + sender.sendMessage(ChatColor.DARK_RED + type.toReadable() + " options: " + + StringUtils.join(methods, ChatColor.DARK_RED + ", ")); + if (ignored > 0) + { + sender.sendMessage(ChatColor.RED + "Ignored " + ignored + + " options you do not have permission to view. Add 'show' to view unusable options."); + } + return true; + } + } + } + sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); + return true; + } + + /** + * Send the player the information + */ + @Override + protected void sendCommandUsage(CommandSender sender, HashMap, Boolean>> map) + { + sender.sendMessage(ChatColor.RED + "/disguisehelp " + ChatColor.GREEN + + "- View the options you can set on a disguise. Add 'show' to reveal the options you don't have permission to use"); + for (EnumHelp s : enumHelp) + { + sender.sendMessage(s.getEnumDescription()); + } + } + + public String toReadable(String string) + { + String[] split = string.split("_"); + for (int i = 0; i < split.length; i++) + { + split[i] = split[i].substring(0, 1) + split[i].substring(1).toLowerCase(); + } + return StringUtils.join(split, "_"); + } +} diff --git a/src/me/libraryaddict/disguise/commands/LibsDisguisesCommand.java b/src/me/libraryaddict/disguise/commands/LibsDisguisesCommand.java index 840bd78b..82a91e13 100644 --- a/src/me/libraryaddict/disguise/commands/LibsDisguisesCommand.java +++ b/src/me/libraryaddict/disguise/commands/LibsDisguisesCommand.java @@ -1,37 +1,46 @@ -package me.libraryaddict.disguise.commands; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; - -import me.libraryaddict.disguise.LibsDisguises; - -public class LibsDisguisesCommand implements CommandExecutor { - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if (args.length == 0) { - sender.sendMessage(ChatColor.DARK_GREEN - + "This server is running " - + "Lib's Disguises v." - + Bukkit.getPluginManager().getPlugin("LibsDisguises").getDescription().getVersion() - + " by libraryaddict, maintained by NavidK0.\n" - + "Use /libsdisguises reload to reload the config. All disguises will be blown by doing this."); - } else if (args.length > 0) { - if (sender.hasPermission("libsdisguises.reload")) { - if (args[0].equalsIgnoreCase("reload")) { - LibsDisguises.getInstance().reload(); - sender.sendMessage(ChatColor.GREEN + "[LibsDisguises] Reloaded config."); - return true; - } else { - sender.sendMessage(ChatColor.RED + "[LibsDisguises] That command doesn't exist!"); - } - } else { - sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); - } - } - return true; - } -} +package me.libraryaddict.disguise.commands; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; + +import me.libraryaddict.disguise.LibsDisguises; + +public class LibsDisguisesCommand implements CommandExecutor +{ + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) + { + if (args.length == 0) + { + sender.sendMessage(ChatColor.DARK_GREEN + "This server is running " + "Lib's Disguises v." + + Bukkit.getPluginManager().getPlugin("LibsDisguises").getDescription().getVersion() + + " by libraryaddict, maintained by NavidK0.\n" + + "Use /libsdisguises reload to reload the config. All disguises will be blown by doing this."); + } + else if (args.length > 0) + { + if (sender.hasPermission("libsdisguises.reload")) + { + if (args[0].equalsIgnoreCase("reload")) + { + LibsDisguises.getInstance().reload(); + sender.sendMessage(ChatColor.GREEN + "[LibsDisguises] Reloaded config."); + return true; + } + else + { + sender.sendMessage(ChatColor.RED + "[LibsDisguises] That command doesn't exist!"); + } + } + else + { + sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); + } + } + return true; + } +} diff --git a/src/me/libraryaddict/disguise/commands/PlayerDisguiseCommand.java b/src/me/libraryaddict/disguise/commands/PlayerDisguiseCommand.java index d986af6b..df559943 100644 --- a/src/me/libraryaddict/disguise/commands/PlayerDisguiseCommand.java +++ b/src/me/libraryaddict/disguise/commands/PlayerDisguiseCommand.java @@ -1,97 +1,119 @@ -package me.libraryaddict.disguise.commands; - -import java.util.ArrayList; -import java.util.HashMap; - -import org.apache.commons.lang.StringUtils; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import me.libraryaddict.disguise.DisguiseAPI; -import me.libraryaddict.disguise.DisguiseConfig; -import me.libraryaddict.disguise.disguisetypes.Disguise; -import me.libraryaddict.disguise.disguisetypes.DisguiseType; -import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher; - -public class PlayerDisguiseCommand extends BaseDisguiseCommand { - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - HashMap, Boolean>> map = getPermissions(sender); - if (map.isEmpty()) { - sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); - return true; - } - if (args.length == 0) { - sendCommandUsage(sender, map); - return true; - } - if (args.length == 1) { - sender.sendMessage(ChatColor.RED + "You need to supply a disguise as well as the player"); - return true; - } - Player player = Bukkit.getPlayer(args[0]); - if (player == null) { - sender.sendMessage(ChatColor.RED + "Cannot find the player '" + args[0] + "'"); - return true; - } - String[] newArgs = new String[args.length - 1]; - System.arraycopy(args, 1, newArgs, 0, newArgs.length); - Disguise disguise; - try { - disguise = parseDisguise(sender, newArgs, map); - } catch (DisguiseParseException ex) { - if (ex.getMessage() != null) { - sender.sendMessage(ex.getMessage()); - } - return true; - } catch (Exception ex) { - ex.printStackTrace(System.out); - return true; - } - if (disguise.isMiscDisguise() && !DisguiseConfig.isMiscDisguisesForLivingEnabled()) { - sender.sendMessage(ChatColor.RED - + "Can't disguise a living entity as a misc disguise. This has been disabled in the config!"); - return true; - } - if (DisguiseConfig.isNameOfPlayerShownAboveDisguise()) { - if (disguise.getWatcher() instanceof LivingWatcher) { - disguise.getWatcher().setCustomName(player.getDisplayName()); - if (DisguiseConfig.isNameAboveHeadAlwaysVisible()) { - disguise.getWatcher().setCustomNameVisible(true); - } - } - } - DisguiseAPI.disguiseToAll(player, disguise); - if (disguise.isDisguiseInUse()) { - sender.sendMessage(ChatColor.RED + "Successfully disguised " + player.getName() + " as a " - + disguise.getType().toReadable() + "!"); - } else { - sender.sendMessage(ChatColor.RED + "Failed to disguise " + player.getName() + " as a " - + disguise.getType().toReadable() + "!"); - } - return true; - } - - /** - * Send the player the information - */ - @Override - protected void sendCommandUsage(CommandSender sender, HashMap, Boolean>> map) { - ArrayList allowedDisguises = getAllowedDisguises(map); - sender.sendMessage(ChatColor.DARK_GREEN + "Disguise another player!"); - sender.sendMessage(ChatColor.DARK_GREEN + "You can use the disguises: " + ChatColor.GREEN - + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)); - if (allowedDisguises.contains("player")) { - sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseplayer player "); - } - sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseplayer "); - if (allowedDisguises.contains("dropped_item") || allowedDisguises.contains("falling_block")) { - sender.sendMessage(ChatColor.DARK_GREEN - + "/disguiseplayer "); - } - } -} +package me.libraryaddict.disguise.commands; + +import java.util.ArrayList; +import java.util.HashMap; + +import org.apache.commons.lang.StringUtils; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import me.libraryaddict.disguise.DisguiseAPI; +import me.libraryaddict.disguise.DisguiseConfig; +import me.libraryaddict.disguise.disguisetypes.Disguise; +import me.libraryaddict.disguise.disguisetypes.DisguiseType; +import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher; + +public class PlayerDisguiseCommand extends BaseDisguiseCommand +{ + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) + { + HashMap, Boolean>> map = getPermissions(sender); + if (map.isEmpty()) + { + sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); + return true; + } + if (args.length == 0) + { + sendCommandUsage(sender, map); + return true; + } + if (args.length == 1) + { + sender.sendMessage(ChatColor.RED + "You need to supply a disguise as well as the player"); + return true; + } + Player player = Bukkit.getPlayer(args[0]); + if (player == null) + { + sender.sendMessage(ChatColor.RED + "Cannot find the player '" + args[0] + "'"); + return true; + } + String[] newArgs = new String[args.length - 1]; + System.arraycopy(args, 1, newArgs, 0, newArgs.length); + Disguise disguise; + try + { + disguise = parseDisguise(sender, newArgs, map); + } + catch (DisguiseParseException ex) + { + if (ex.getMessage() != null) + { + sender.sendMessage(ex.getMessage()); + } + return true; + } + catch (Exception ex) + { + ex.printStackTrace(); + return true; + } + if (disguise.isMiscDisguise() && !DisguiseConfig.isMiscDisguisesForLivingEnabled()) + { + sender.sendMessage( + ChatColor.RED + "Can't disguise a living entity as a misc disguise. This has been disabled in the config!"); + return true; + } + if (DisguiseConfig.isNameOfPlayerShownAboveDisguise()) + { + if (disguise.getWatcher() instanceof LivingWatcher) + { + disguise.getWatcher().setCustomName(player.getDisplayName()); + if (DisguiseConfig.isNameAboveHeadAlwaysVisible()) + { + disguise.getWatcher().setCustomNameVisible(true); + } + } + } + DisguiseAPI.disguiseToAll(player, disguise); + if (disguise.isDisguiseInUse()) + { + sender.sendMessage(ChatColor.RED + "Successfully disguised " + player.getName() + " as a " + + disguise.getType().toReadable() + "!"); + } + else + { + sender.sendMessage( + ChatColor.RED + "Failed to disguise " + player.getName() + " as a " + disguise.getType().toReadable() + "!"); + } + return true; + } + + /** + * Send the player the information + */ + @Override + protected void sendCommandUsage(CommandSender sender, HashMap, Boolean>> map) + { + ArrayList allowedDisguises = getAllowedDisguises(map); + sender.sendMessage(ChatColor.DARK_GREEN + "Disguise another player!"); + sender.sendMessage(ChatColor.DARK_GREEN + "You can use the disguises: " + ChatColor.GREEN + + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)); + if (allowedDisguises.contains("player")) + { + sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseplayer player "); + } + sender.sendMessage(ChatColor.DARK_GREEN + "/disguiseplayer "); + if (allowedDisguises.contains("dropped_item") || allowedDisguises.contains("falling_block")) + { + sender.sendMessage( + ChatColor.DARK_GREEN + "/disguiseplayer "); + } + } +} diff --git a/src/me/libraryaddict/disguise/commands/RadiusDisguiseCommand.java b/src/me/libraryaddict/disguise/commands/RadiusDisguiseCommand.java index d80a7337..f0e898b9 100644 --- a/src/me/libraryaddict/disguise/commands/RadiusDisguiseCommand.java +++ b/src/me/libraryaddict/disguise/commands/RadiusDisguiseCommand.java @@ -1,254 +1,253 @@ -package me.libraryaddict.disguise.commands; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; - -import org.apache.commons.lang.StringUtils; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; - -import me.libraryaddict.disguise.DisguiseAPI; -import me.libraryaddict.disguise.DisguiseConfig; -import me.libraryaddict.disguise.disguisetypes.Disguise; -import me.libraryaddict.disguise.disguisetypes.DisguiseType; -import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher; -import me.libraryaddict.disguise.utilities.ClassGetter; - -public class RadiusDisguiseCommand extends BaseDisguiseCommand -{ - - private int maxRadius = 30; - private ArrayList validClasses = new ArrayList<>(); - - public RadiusDisguiseCommand(int maxRadius) - { - this.maxRadius = maxRadius; - - for (Class c : ClassGetter.getClassesForPackage("org.bukkit.entity")) - { - if (c != Entity.class && Entity.class.isAssignableFrom(c) && c.getAnnotation(Deprecated.class) == null) - { - validClasses.add(c); - } - } - } - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) - { - if (sender.getName().equals("CONSOLE")) - { - sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); - return true; - } - - HashMap, Boolean>> map = getPermissions(sender); - - if (map.isEmpty()) - { - sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); - return true; - } - - if (args.length == 0) - { - sendCommandUsage(sender, map); - return true; - } - - if (args[0].equalsIgnoreCase("entitytype") || args[0].equalsIgnoreCase("entitytypes")) - { - ArrayList classes = new ArrayList<>(); - - for (Class c : validClasses) - { - classes.add(c.getSimpleName()); - } - - Collections.sort(classes); - - sender.sendMessage(ChatColor.DARK_GREEN + "EntityTypes usable are: " + ChatColor.GREEN - + StringUtils.join(classes, ChatColor.DARK_GREEN + ", " + ChatColor.GREEN) + ChatColor.DARK_GREEN + "."); - return true; - } - - Class entityClass = Entity.class; - EntityType type = null; - int starting = 0; - - if (!isNumeric(args[0])) - { - for (Class c : validClasses) - { - if (c.getSimpleName().equalsIgnoreCase(args[0])) - { - entityClass = c; - starting = 1; - break; - } - } - - if (starting == 0) - { - try - { - type = EntityType.valueOf(args[0].toUpperCase()); - } - catch (Exception ex) - { - } - - if (type == null) - { - sender.sendMessage(ChatColor.RED + "Unrecognised EntityType " + args[0]); - return true; - } - } - } - - if (args.length == starting + 1) - { - sender.sendMessage(ChatColor.RED + "You need to supply a disguise as well as the radius" - + (starting != 0 ? " and EntityType" : "")); - return true; - } - - if (!isNumeric(args[starting])) - { - sender.sendMessage(ChatColor.RED + args[starting] + " is not a number"); - return true; - } - - int radius = Integer.parseInt(args[starting]); - - if (radius > maxRadius) - { - sender.sendMessage(ChatColor.RED + "Limited radius to " + maxRadius + "! Don't want to make too much lag right?"); - radius = maxRadius; - } - - String[] newArgs = new String[args.length - (starting + 1)]; - System.arraycopy(args, starting + 1, newArgs, 0, newArgs.length); - Disguise disguise; - - try - { - disguise = parseDisguise(sender, newArgs, map); - } - catch (DisguiseParseException ex) - { - if (ex.getMessage() != null) - { - sender.sendMessage(ex.getMessage()); - } - - return true; - } - catch (Exception ex) - { - ex.printStackTrace(System.out); - return true; - } - - // Time to use it! - int disguisedEntitys = 0; - int miscDisguises = 0; - - for (Entity entity : ((Player) sender).getNearbyEntities(radius, radius, radius)) - { - if (entity == sender) - { - continue; - } - - if (type != null ? entity.getType() == type : entityClass.isAssignableFrom(entity.getClass())) - { - if (disguise.isMiscDisguise() && !DisguiseConfig.isMiscDisguisesForLivingEnabled() - && entity instanceof LivingEntity) - { - miscDisguises++; - continue; - } - - disguise = disguise.clone(); - - if (entity instanceof Player && DisguiseConfig.isNameOfPlayerShownAboveDisguise()) - { - if (disguise.getWatcher() instanceof LivingWatcher) - { - disguise.getWatcher().setCustomName(((Player) entity).getDisplayName()); - if (DisguiseConfig.isNameAboveHeadAlwaysVisible()) - { - disguise.getWatcher().setCustomNameVisible(true); - } - } - } - - DisguiseAPI.disguiseToAll(entity, disguise); - - if (disguise.isDisguiseInUse()) - { - disguisedEntitys++; - } - } - } - - if (disguisedEntitys > 0) - { - sender.sendMessage(ChatColor.RED + "Successfully disguised " + disguisedEntitys + " entities!"); - } - else - { - sender.sendMessage(ChatColor.RED + "Couldn't find any entities to disguise!"); - } - - if (miscDisguises > 0) - { - sender.sendMessage(ChatColor.RED + "Failed to disguise " + miscDisguises - + " entities because the option to disguise a living entity as a non-living has been disabled in the config"); - } - - return true; - } - - /** - * Send the player the information - */ - @Override - protected void sendCommandUsage(CommandSender sender, HashMap, Boolean>> map) - { - ArrayList allowedDisguises = getAllowedDisguises(map); - - sender.sendMessage(ChatColor.DARK_GREEN + "Disguise all entities in a radius! Caps at 30 blocks!"); - sender.sendMessage(ChatColor.DARK_GREEN + "You can use the disguises: " + ChatColor.GREEN - + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)); - - String optional = ChatColor.DARK_GREEN + "(" + ChatColor.GREEN + "Optional" + ChatColor.DARK_GREEN + ")"; - - if (allowedDisguises.contains("player")) - { - sender.sendMessage((ChatColor.DARK_GREEN + "/disguiseradius player ") - .replace("<", "<" + ChatColor.GREEN).replace(">", ChatColor.DARK_GREEN + ">")); - } - - sender.sendMessage((ChatColor.DARK_GREEN + "/disguiseradius ").replace("<", "<" + ChatColor.GREEN).replace(">", ChatColor.DARK_GREEN + ">")); - - if (allowedDisguises.contains("dropped_item") || allowedDisguises.contains("falling_block")) - { - sender.sendMessage((ChatColor.DARK_GREEN + "/disguiseradius ") - .replace("<", "<" + ChatColor.GREEN).replace(">", ChatColor.DARK_GREEN + ">")); - } - - sender.sendMessage( - ChatColor.DARK_GREEN + "See the EntityType's usable by " + ChatColor.GREEN + "/disguiseradius EntityTypes"); - } - -} +package me.libraryaddict.disguise.commands; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; + +import org.apache.commons.lang.StringUtils; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +import me.libraryaddict.disguise.DisguiseAPI; +import me.libraryaddict.disguise.DisguiseConfig; +import me.libraryaddict.disguise.disguisetypes.Disguise; +import me.libraryaddict.disguise.disguisetypes.DisguiseType; +import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher; +import me.libraryaddict.disguise.utilities.ClassGetter; + +public class RadiusDisguiseCommand extends BaseDisguiseCommand +{ + private int maxRadius = 30; + private ArrayList validClasses = new ArrayList<>(); + + public RadiusDisguiseCommand(int maxRadius) + { + this.maxRadius = maxRadius; + + for (Class c : ClassGetter.getClassesForPackage("org.bukkit.entity")) + { + if (c != Entity.class && Entity.class.isAssignableFrom(c) && c.getAnnotation(Deprecated.class) == null) + { + validClasses.add(c); + } + } + } + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) + { + if (sender.getName().equals("CONSOLE")) + { + sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); + return true; + } + + HashMap, Boolean>> map = getPermissions(sender); + + if (map.isEmpty()) + { + sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); + return true; + } + + if (args.length == 0) + { + sendCommandUsage(sender, map); + return true; + } + + if (args[0].equalsIgnoreCase("entitytype") || args[0].equalsIgnoreCase("entitytypes")) + { + ArrayList classes = new ArrayList<>(); + + for (Class c : validClasses) + { + classes.add(c.getSimpleName()); + } + + Collections.sort(classes); + + sender.sendMessage(ChatColor.DARK_GREEN + "EntityTypes usable are: " + ChatColor.GREEN + + StringUtils.join(classes, ChatColor.DARK_GREEN + ", " + ChatColor.GREEN) + ChatColor.DARK_GREEN + "."); + return true; + } + + Class entityClass = Entity.class; + EntityType type = null; + int starting = 0; + + if (!isNumeric(args[0])) + { + for (Class c : validClasses) + { + if (c.getSimpleName().equalsIgnoreCase(args[0])) + { + entityClass = c; + starting = 1; + break; + } + } + + if (starting == 0) + { + try + { + type = EntityType.valueOf(args[0].toUpperCase()); + } + catch (Exception ex) + { + } + + if (type == null) + { + sender.sendMessage(ChatColor.RED + "Unrecognised EntityType " + args[0]); + return true; + } + } + } + + if (args.length == starting + 1) + { + sender.sendMessage(ChatColor.RED + "You need to supply a disguise as well as the radius" + + (starting != 0 ? " and EntityType" : "")); + return true; + } + + if (!isNumeric(args[starting])) + { + sender.sendMessage(ChatColor.RED + args[starting] + " is not a number"); + return true; + } + + int radius = Integer.parseInt(args[starting]); + + if (radius > maxRadius) + { + sender.sendMessage(ChatColor.RED + "Limited radius to " + maxRadius + "! Don't want to make too much lag right?"); + radius = maxRadius; + } + + String[] newArgs = new String[args.length - (starting + 1)]; + System.arraycopy(args, starting + 1, newArgs, 0, newArgs.length); + Disguise disguise; + + try + { + disguise = parseDisguise(sender, newArgs, map); + } + catch (DisguiseParseException ex) + { + if (ex.getMessage() != null) + { + sender.sendMessage(ex.getMessage()); + } + + return true; + } + catch (Exception ex) + { + ex.printStackTrace(); + return true; + } + + // Time to use it! + int disguisedEntitys = 0; + int miscDisguises = 0; + + for (Entity entity : ((Player) sender).getNearbyEntities(radius, radius, radius)) + { + if (entity == sender) + { + continue; + } + + if (type != null ? entity.getType() == type : entityClass.isAssignableFrom(entity.getClass())) + { + if (disguise.isMiscDisguise() && !DisguiseConfig.isMiscDisguisesForLivingEnabled() + && entity instanceof LivingEntity) + { + miscDisguises++; + continue; + } + + disguise = disguise.clone(); + + if (entity instanceof Player && DisguiseConfig.isNameOfPlayerShownAboveDisguise()) + { + if (disguise.getWatcher() instanceof LivingWatcher) + { + disguise.getWatcher().setCustomName(((Player) entity).getDisplayName()); + if (DisguiseConfig.isNameAboveHeadAlwaysVisible()) + { + disguise.getWatcher().setCustomNameVisible(true); + } + } + } + + DisguiseAPI.disguiseToAll(entity, disguise); + + if (disguise.isDisguiseInUse()) + { + disguisedEntitys++; + } + } + } + + if (disguisedEntitys > 0) + { + sender.sendMessage(ChatColor.RED + "Successfully disguised " + disguisedEntitys + " entities!"); + } + else + { + sender.sendMessage(ChatColor.RED + "Couldn't find any entities to disguise!"); + } + + if (miscDisguises > 0) + { + sender.sendMessage(ChatColor.RED + "Failed to disguise " + miscDisguises + + " entities because the option to disguise a living entity as a non-living has been disabled in the config"); + } + + return true; + } + + /** + * Send the player the information + */ + @Override + protected void sendCommandUsage(CommandSender sender, HashMap, Boolean>> map) + { + ArrayList allowedDisguises = getAllowedDisguises(map); + + sender.sendMessage(ChatColor.DARK_GREEN + "Disguise all entities in a radius! Caps at 30 blocks!"); + sender.sendMessage(ChatColor.DARK_GREEN + "You can use the disguises: " + ChatColor.GREEN + + StringUtils.join(allowedDisguises, ChatColor.RED + ", " + ChatColor.GREEN)); + + String optional = ChatColor.DARK_GREEN + "(" + ChatColor.GREEN + "Optional" + ChatColor.DARK_GREEN + ")"; + + if (allowedDisguises.contains("player")) + { + sender.sendMessage((ChatColor.DARK_GREEN + "/disguiseradius player ") + .replace("<", "<" + ChatColor.GREEN).replace(">", ChatColor.DARK_GREEN + ">")); + } + + sender.sendMessage((ChatColor.DARK_GREEN + "/disguiseradius ").replace("<", "<" + ChatColor.GREEN).replace(">", ChatColor.DARK_GREEN + ">")); + + if (allowedDisguises.contains("dropped_item") || allowedDisguises.contains("falling_block")) + { + sender.sendMessage((ChatColor.DARK_GREEN + "/disguiseradius ") + .replace("<", "<" + ChatColor.GREEN).replace(">", ChatColor.DARK_GREEN + ">")); + } + + sender.sendMessage( + ChatColor.DARK_GREEN + "See the EntityType's usable by " + ChatColor.GREEN + "/disguiseradius EntityTypes"); + } + +} diff --git a/src/me/libraryaddict/disguise/commands/UndisguiseCommand.java b/src/me/libraryaddict/disguise/commands/UndisguiseCommand.java index f2be148b..27abc63c 100644 --- a/src/me/libraryaddict/disguise/commands/UndisguiseCommand.java +++ b/src/me/libraryaddict/disguise/commands/UndisguiseCommand.java @@ -1,32 +1,41 @@ -package me.libraryaddict.disguise.commands; - -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -import me.libraryaddict.disguise.DisguiseAPI; - -public class UndisguiseCommand implements CommandExecutor { - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if (sender.getName().equals("CONSOLE")) { - sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); - return true; - } - if (sender.hasPermission("libsdisguises.undisguise")) { - if (DisguiseAPI.isDisguised((Entity) sender)) { - DisguiseAPI.undisguiseToAll((Player) sender); - sender.sendMessage(ChatColor.RED + "You are no longer disguised"); - } else { - sender.sendMessage(ChatColor.RED + "You are not disguised!"); - } - } else { - sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); - } - return true; - } -} +package me.libraryaddict.disguise.commands; + +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +import me.libraryaddict.disguise.DisguiseAPI; + +public class UndisguiseCommand implements CommandExecutor +{ + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) + { + if (sender.getName().equals("CONSOLE")) + { + sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); + return true; + } + if (sender.hasPermission("libsdisguises.undisguise")) + { + if (DisguiseAPI.isDisguised((Entity) sender)) + { + DisguiseAPI.undisguiseToAll((Player) sender); + sender.sendMessage(ChatColor.RED + "You are no longer disguised"); + } + else + { + sender.sendMessage(ChatColor.RED + "You are not disguised!"); + } + } + else + { + sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); + } + return true; + } +} diff --git a/src/me/libraryaddict/disguise/commands/UndisguiseEntityCommand.java b/src/me/libraryaddict/disguise/commands/UndisguiseEntityCommand.java index 1f42f994..6b586f2c 100644 --- a/src/me/libraryaddict/disguise/commands/UndisguiseEntityCommand.java +++ b/src/me/libraryaddict/disguise/commands/UndisguiseEntityCommand.java @@ -1,26 +1,32 @@ -package me.libraryaddict.disguise.commands; - -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; - -import me.libraryaddict.disguise.LibsDisguises; - -public class UndisguiseEntityCommand implements CommandExecutor { - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if (sender.getName().equals("CONSOLE")) { - sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); - return true; - } - if (sender.hasPermission("libsdisguises.undisguiseentity")) { - LibsDisguises.getInstance().getListener().setDisguiseEntity(sender.getName(), null); - sender.sendMessage(ChatColor.RED + "Right click a disguised entity to undisguise them!"); - } else { - sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); - } - return true; - } -} +package me.libraryaddict.disguise.commands; + +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; + +import me.libraryaddict.disguise.LibsDisguises; + +public class UndisguiseEntityCommand implements CommandExecutor +{ + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) + { + if (sender.getName().equals("CONSOLE")) + { + sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); + return true; + } + if (sender.hasPermission("libsdisguises.undisguiseentity")) + { + LibsDisguises.getInstance().getListener().setDisguiseEntity(sender.getName(), null); + sender.sendMessage(ChatColor.RED + "Right click a disguised entity to undisguise them!"); + } + else + { + sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); + } + return true; + } +} diff --git a/src/me/libraryaddict/disguise/commands/UndisguisePlayerCommand.java b/src/me/libraryaddict/disguise/commands/UndisguisePlayerCommand.java index 22844f41..3b973c79 100644 --- a/src/me/libraryaddict/disguise/commands/UndisguisePlayerCommand.java +++ b/src/me/libraryaddict/disguise/commands/UndisguisePlayerCommand.java @@ -1,37 +1,51 @@ -package me.libraryaddict.disguise.commands; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import me.libraryaddict.disguise.DisguiseAPI; - -public class UndisguisePlayerCommand implements CommandExecutor { - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if (sender.hasPermission("libsdisguises.undisguiseplayer")) { - if (args.length > 0) { - Player p = Bukkit.getPlayer(args[0]); - if (p != null) { - if (DisguiseAPI.isDisguised(p)) { - DisguiseAPI.undisguiseToAll(p); - sender.sendMessage(ChatColor.RED + "The player is no longer disguised"); - } else { - sender.sendMessage(ChatColor.RED + "The player is not disguised!"); - } - } else { - sender.sendMessage(ChatColor.RED + "Player not found"); - } - } else { - sender.sendMessage(ChatColor.RED + "/undisguiseplayer "); - } - } else { - sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); - } - return true; - } -} +package me.libraryaddict.disguise.commands; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import me.libraryaddict.disguise.DisguiseAPI; + +public class UndisguisePlayerCommand implements CommandExecutor +{ + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) + { + if (sender.hasPermission("libsdisguises.undisguiseplayer")) + { + if (args.length > 0) + { + Player p = Bukkit.getPlayer(args[0]); + if (p != null) + { + if (DisguiseAPI.isDisguised(p)) + { + DisguiseAPI.undisguiseToAll(p); + sender.sendMessage(ChatColor.RED + "The player is no longer disguised"); + } + else + { + sender.sendMessage(ChatColor.RED + "The player is not disguised!"); + } + } + else + { + sender.sendMessage(ChatColor.RED + "Player not found"); + } + } + else + { + sender.sendMessage(ChatColor.RED + "/undisguiseplayer "); + } + } + else + { + sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); + } + return true; + } +} diff --git a/src/me/libraryaddict/disguise/commands/UndisguiseRadiusCommand.java b/src/me/libraryaddict/disguise/commands/UndisguiseRadiusCommand.java index 37580860..e3a33730 100644 --- a/src/me/libraryaddict/disguise/commands/UndisguiseRadiusCommand.java +++ b/src/me/libraryaddict/disguise/commands/UndisguiseRadiusCommand.java @@ -1,66 +1,83 @@ -package me.libraryaddict.disguise.commands; - -import org.bukkit.ChatColor; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -import me.libraryaddict.disguise.DisguiseAPI; - -public class UndisguiseRadiusCommand implements CommandExecutor { - - private int maxRadius = 30; - - public UndisguiseRadiusCommand(int maxRadius) { - this.maxRadius = maxRadius; - } - - private boolean isNumeric(String string) { - try { - Integer.parseInt(string); - return true; - } catch (Exception ex) { - return false; - } - } - - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if (sender.getName().equals("CONSOLE")) { - sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); - return true; - } - if (sender.hasPermission("libsdisguises.undisguiseradius")) { - int radius = maxRadius; - if (args.length > 0) { - if (!isNumeric(args[0])) { - sender.sendMessage(ChatColor.RED + "Error! " + ChatColor.GREEN + args[0] + ChatColor.RED - + " is not a number!"); - return true; - } - radius = Integer.parseInt(args[0]); - if (radius > maxRadius) { - sender.sendMessage(ChatColor.RED + "Limited radius to " + maxRadius - + "! Don't want to make too much lag right?"); - radius = maxRadius; - } - } - int disguisedEntitys = 0; - for (Entity entity : ((Player) sender).getNearbyEntities(radius, radius, radius)) { - if (entity == sender) { - continue; - } - if (DisguiseAPI.isDisguised(entity)) { - DisguiseAPI.undisguiseToAll(entity); - disguisedEntitys++; - } - } - sender.sendMessage(ChatColor.RED + "Successfully undisguised " + disguisedEntitys + " entities!"); - } else { - sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); - } - return true; - } -} +package me.libraryaddict.disguise.commands; + +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; + +import me.libraryaddict.disguise.DisguiseAPI; + +public class UndisguiseRadiusCommand implements CommandExecutor +{ + + private int maxRadius = 30; + + public UndisguiseRadiusCommand(int maxRadius) + { + this.maxRadius = maxRadius; + } + + private boolean isNumeric(String string) + { + try + { + Integer.parseInt(string); + return true; + } + catch (Exception ex) + { + return false; + } + } + + @Override + public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) + { + if (sender.getName().equals("CONSOLE")) + { + sender.sendMessage(ChatColor.RED + "You may not use this command from the console!"); + return true; + } + if (sender.hasPermission("libsdisguises.undisguiseradius")) + { + int radius = maxRadius; + if (args.length > 0) + { + if (!isNumeric(args[0])) + { + sender.sendMessage( + ChatColor.RED + "Error! " + ChatColor.GREEN + args[0] + ChatColor.RED + " is not a number!"); + return true; + } + radius = Integer.parseInt(args[0]); + if (radius > maxRadius) + { + sender.sendMessage( + ChatColor.RED + "Limited radius to " + maxRadius + "! Don't want to make too much lag right?"); + radius = maxRadius; + } + } + int disguisedEntitys = 0; + for (Entity entity : ((Player) sender).getNearbyEntities(radius, radius, radius)) + { + if (entity == sender) + { + continue; + } + if (DisguiseAPI.isDisguised(entity)) + { + DisguiseAPI.undisguiseToAll(entity); + disguisedEntitys++; + } + } + sender.sendMessage(ChatColor.RED + "Successfully undisguised " + disguisedEntitys + " entities!"); + } + else + { + sender.sendMessage(ChatColor.RED + "You are forbidden to use this command."); + } + return true; + } +} diff --git a/src/me/libraryaddict/disguise/disguisetypes/Disguise.java b/src/me/libraryaddict/disguise/disguisetypes/Disguise.java index 4d93006b..4cb273ea 100644 --- a/src/me/libraryaddict/disguise/disguisetypes/Disguise.java +++ b/src/me/libraryaddict/disguise/disguisetypes/Disguise.java @@ -102,7 +102,7 @@ public abstract class Disguise } catch (Exception e) { - e.printStackTrace(System.out); + e.printStackTrace(); } // Set the disguise if its a baby or not @@ -355,7 +355,7 @@ public abstract class Disguise } catch (InvocationTargetException e) { - e.printStackTrace(System.out); + e.printStackTrace(); } } } @@ -398,7 +398,7 @@ public abstract class Disguise } catch (Exception e) { - e.printStackTrace(System.out); + e.printStackTrace(); } } // If we need to send a packet to update the exp position as it likes to gravitate client sided to @@ -430,14 +430,14 @@ public abstract class Disguise } catch (InvocationTargetException e) { - e.printStackTrace(System.out); + e.printStackTrace(); } } } } catch (InvocationTargetException e) { - e.printStackTrace(System.out); + e.printStackTrace(); } } } diff --git a/src/me/libraryaddict/disguise/disguisetypes/FlagType.java b/src/me/libraryaddict/disguise/disguisetypes/FlagType.java index e3923732..bb2db874 100644 --- a/src/me/libraryaddict/disguise/disguisetypes/FlagType.java +++ b/src/me/libraryaddict/disguise/disguisetypes/FlagType.java @@ -116,10 +116,11 @@ public class FlagType public static FlagType CREEPER_STATE = new FlagType(CreeperWatcher.class, 0, -1); - public static FlagType DROPPED_ITEM = new FlagType(DroppedItemWatcher.class, 0, - new ItemStack(Material.AIR)); + public static FlagType> DROPPED_ITEM = new FlagType>(DroppedItemWatcher.class, 0, + Optional. of(new ItemStack(Material.STONE))); - public static FlagType ENDER_CRYSTAL_BEAM = new FlagType(EnderCrystalWatcher.class, 0, Optional.absent()); + public static FlagType> ENDER_CRYSTAL_BEAM = new FlagType>(EnderCrystalWatcher.class, 0, + Optional. absent()); public static FlagType ENDER_CRYSTAL_PLATE = new FlagType(EnderCrystalWatcher.class, 1, false); @@ -180,7 +181,7 @@ public class FlagType public static FlagType LIVING_HAND = new FlagType(LivingWatcher.class, 0, (byte) 0); - public static FlagType LIVING_HEALTH = new FlagType(LivingWatcher.class, 1, 0F); + public static FlagType LIVING_HEALTH = new FlagType(LivingWatcher.class, 1, 1F); public static FlagType LIVING_POTION_AMBIENT = new FlagType(LivingWatcher.class, 3, false); @@ -208,7 +209,7 @@ public class FlagType public static FlagType PLAYER_SCORE = new FlagType(PlayerWatcher.class, 1, 0); - public static FlagType PLAYER_SKIN = new FlagType(PlayerWatcher.class, 2, (byte) 0); + public static FlagType PLAYER_SKIN = new FlagType(PlayerWatcher.class, 2, (byte) 127); public static FlagType POLAR_BEAR_STANDING = new FlagType(PolarBearWatcher.class, 0, false); diff --git a/src/me/libraryaddict/disguise/disguisetypes/FlagWatcher.java b/src/me/libraryaddict/disguise/disguisetypes/FlagWatcher.java index d9008b8a..30b4c860 100644 --- a/src/me/libraryaddict/disguise/disguisetypes/FlagWatcher.java +++ b/src/me/libraryaddict/disguise/disguisetypes/FlagWatcher.java @@ -28,22 +28,22 @@ import me.libraryaddict.disguise.utilities.ReflectionManager; public class FlagWatcher { - private boolean addEntityAnimations = DisguiseConfig.isEntityAnimationsAdded(); + private boolean _addEntityAnimations = DisguiseConfig.isEntityAnimationsAdded(); /** * These are the entity values I need to add else it could crash them.. */ - private HashMap backupEntityValues = new HashMap<>(); - private TargetedDisguise disguise; - private HashMap entityValues = new HashMap<>(); - private EntityEquipment equipment; - private boolean hasDied; - private HashSet modifiedEntityAnimations = new HashSet<>(); - private List watchableObjects; + private HashMap _backupEntityValues = new HashMap<>(); + private TargetedDisguise _disguise; + private HashMap _entityValues = new HashMap<>(); + private EntityEquipment _equipment; + private boolean _hasDied; + private HashSet _modifiedEntityAnimations = new HashSet<>(); + private List _watchableObjects; public FlagWatcher(Disguise disguise) { - this.disguise = (TargetedDisguise) disguise; - equipment = ReflectionManager.createEntityEquipment(disguise.getEntity()); + _disguise = (TargetedDisguise) disguise; + _equipment = ReflectionManager.createEntityEquipment(disguise.getEntity()); } private byte addEntityAnimations(byte originalValue, byte entityValue) @@ -52,7 +52,7 @@ public class FlagWatcher for (int i = 0; i < 6; i++) { - if ((entityValue & 1 << i) != 0 && !modifiedEntityAnimations.contains(i)) + if ((entityValue & 1 << i) != 0 && !_modifiedEntityAnimations.contains(i)) { valueByte = (byte) (valueByte | 1 << i); } @@ -73,14 +73,14 @@ public class FlagWatcher } catch (Exception e) { - e.printStackTrace(System.out); + e.printStackTrace(); cloned = new FlagWatcher(getDisguise()); } - cloned.entityValues = (HashMap) entityValues.clone(); - cloned.equipment = ReflectionManager.createEntityEquipment(cloned.getDisguise().getEntity()); - cloned.modifiedEntityAnimations = (HashSet) modifiedEntityAnimations.clone(); - cloned.addEntityAnimations = addEntityAnimations; + cloned._entityValues = (HashMap) _entityValues.clone(); + cloned._equipment = ReflectionManager.createEntityEquipment(cloned.getDisguise().getEntity()); + cloned._modifiedEntityAnimations = (HashSet) _modifiedEntityAnimations.clone(); + cloned._addEntityAnimations = _addEntityAnimations; return cloned; } @@ -105,35 +105,38 @@ public class FlagWatcher Object value = null; - if (entityValues.containsKey(id)) + if (_entityValues.containsKey(id)) { - if (entityValues.get(id) == null) + if (_entityValues.get(id) == null) { continue; } - value = entityValues.get(id); + value = _entityValues.get(id); } - else if (backupEntityValues.containsKey(id)) + else if (_backupEntityValues.containsKey(id)) { - if (backupEntityValues.get(id) == null) + if (_backupEntityValues.get(id) == null) { continue; } - value = backupEntityValues.get(id); + value = _backupEntityValues.get(id); } if (value != null) { if (isEntityAnimationsAdded() && id == 0) { - value = this.addEntityAnimations((byte) value, (byte) watch.getValue()); + value = addEntityAnimations((byte) value, (byte) watch.getValue()); } boolean isDirty = watch.getDirtyState(); - watch = new WrappedWatchableObject(ReflectionManager.createDataWatcherItem(id, value)); + watch = ReflectionManager.createWatchable(id, value); + + if (watch == null) + continue; if (!isDirty) { @@ -144,7 +147,10 @@ public class FlagWatcher { boolean isDirty = watch.getDirtyState(); - watch = new WrappedWatchableObject(ReflectionManager.createDataWatcherItem(id, watch.getValue())); + watch = ReflectionManager.createWatchable(id, watch.getValue()); + + if (watch == null) + continue; if (!isDirty) { @@ -158,21 +164,24 @@ public class FlagWatcher if (sendAllCustom) { // Its sending the entire meta data. Better add the custom meta - for (Integer id : entityValues.keySet()) + for (Integer id : _entityValues.keySet()) { if (sentValues.contains(id)) { continue; } - Object value = entityValues.get(id); + Object value = _entityValues.get(id); if (value == null) { continue; } - WrappedWatchableObject watch = new WrappedWatchableObject(ReflectionManager.createDataWatcherItem(id, value)); + WrappedWatchableObject watch = ReflectionManager.createWatchable(id, value); + + if (watch == null) + continue; newList.add(watch); } @@ -192,9 +201,9 @@ public class FlagWatcher { float newHealth = (Float) value; - if (newHealth > 0 && hasDied) + if (newHealth > 0 && _hasDied) { - hasDied = false; + _hasDied = false; Bukkit.getScheduler().scheduleSyncDelayedTask(DisguiseUtilities.getPlugin(), new Runnable() { @@ -203,18 +212,18 @@ public class FlagWatcher { try { - DisguiseUtilities.sendSelfDisguise((Player) getDisguise().getEntity(), disguise); + DisguiseUtilities.sendSelfDisguise((Player) getDisguise().getEntity(), _disguise); } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } }, 2); } - else if (newHealth <= 0 && !hasDied) + else if (newHealth <= 0 && !_hasDied) { - hasDied = true; + _hasDied = true; } } } @@ -239,7 +248,7 @@ public class FlagWatcher protected TargetedDisguise getDisguise() { - return disguise; + return _disguise; } private boolean getEntityFlag(int byteValue) @@ -249,44 +258,44 @@ public class FlagWatcher public EntityEquipment getEquipment() { - return equipment; + return _equipment; } public ItemStack getItemInMainHand() { - if (equipment == null) + if (_equipment == null) return null; - return equipment.getItemInMainHand(); + return _equipment.getItemInMainHand(); } public ItemStack getItemInOffHand() { - if (equipment == null) + if (_equipment == null) return null; - return equipment.getItemInOffHand(); + return _equipment.getItemInOffHand(); } public ItemStack getItemStack(EquipmentSlot slot) { - if (equipment == null) + if (_equipment == null) return null; switch (slot) { case CHEST: - return equipment.getChestplate(); + return _equipment.getChestplate(); case FEET: - return equipment.getBoots(); + return _equipment.getBoots(); case HAND: - return equipment.getItemInMainHand(); + return _equipment.getItemInMainHand(); case HEAD: - return equipment.getHelmet(); + return _equipment.getHelmet(); case LEGS: - return equipment.getLeggings(); + return _equipment.getLeggings(); case OFF_HAND: - return equipment.getItemInOffHand(); + return _equipment.getItemInOffHand(); } return null; @@ -294,9 +303,9 @@ public class FlagWatcher protected Y getValue(FlagType flagType) { - if (entityValues.containsKey(flagType.getIndex())) + if (_entityValues.containsKey(flagType.getIndex())) { - return (Y) entityValues.get(flagType.getIndex()); + return (Y) _entityValues.get(flagType.getIndex()); } return flagType.getDefault(); @@ -304,12 +313,12 @@ public class FlagWatcher public List getWatchableObjects() { - if (watchableObjects == null) + if (_watchableObjects == null) { rebuildWatchableObjects(); } - return watchableObjects; + return _watchableObjects; } public boolean hasCustomName() @@ -319,7 +328,7 @@ public class FlagWatcher protected boolean hasValue(FlagType no) { - return entityValues.containsKey(no.getIndex()); + return _entityValues.containsKey(no.getIndex()); } public boolean isBurning() @@ -334,7 +343,7 @@ public class FlagWatcher public boolean isEntityAnimationsAdded() { - return addEntityAnimations; + return _addEntityAnimations; } public boolean isFlyingWithElytra() @@ -374,25 +383,29 @@ public class FlagWatcher public void rebuildWatchableObjects() { - watchableObjects = new ArrayList<>(); + _watchableObjects = new ArrayList<>(); - for (int i = 0; i <= 31; i++)// TODO + for (int i = 0; i <= 31; i++) { WrappedWatchableObject watchable = null; - if (this.entityValues.containsKey(i) && this.entityValues.get(i) != null) + if (_entityValues.containsKey(i) && _entityValues.get(i) != null) { - watchable = new WrappedWatchableObject(ReflectionManager.createDataWatcherItem(i, entityValues.get(i))); + watchable = ReflectionManager.createWatchable(i, _entityValues.get(i)); } - else if (this.backupEntityValues.containsKey(i) && this.backupEntityValues.get(i) != null) + else if (_backupEntityValues.containsKey(i) && _backupEntityValues.get(i) != null) { - watchable = new WrappedWatchableObject(ReflectionManager.createDataWatcherItem(i, entityValues.get(i))); + watchable = ReflectionManager.createWatchable(i, _backupEntityValues.get(i)); + } + else + { + continue; } - if (watchable != null) - { - watchableObjects.add(watchable); - } + if (watchable == null) + continue; + + _watchableObjects.add(watchable); } } @@ -407,24 +420,26 @@ public class FlagWatcher for (FlagType data : dataValues) { - if (!entityValues.containsKey(data) || entityValues.get(data) == null) + if (!_entityValues.containsKey(data) || _entityValues.get(data) == null) { continue; } - Object value = entityValues.get(data); + Object value = _entityValues.get(data); if (isEntityAnimationsAdded() && DisguiseConfig.isMetadataPacketsEnabled() && data == FlagType.ENTITY_META) { - if (!PacketsManager.isStaticMetadataDisguiseType(disguise)) + if (!PacketsManager.isStaticMetadataDisguiseType(_disguise)) { value = addEntityAnimations((byte) value, - WrappedDataWatcher.getEntityWatcher(disguise.getEntity()).getByte(0)); + WrappedDataWatcher.getEntityWatcher(_disguise.getEntity()).getByte(0)); } } - WrappedWatchableObject watch = new WrappedWatchableObject( - ReflectionManager.createDataWatcherItem(data.getIndex(), value)); + WrappedWatchableObject watch = ReflectionManager.createWatchable(data.getIndex(), value); + + if (watch == null) + continue; list.add(watch); } @@ -446,7 +461,7 @@ public class FlagWatcher } catch (InvocationTargetException e) { - e.printStackTrace(System.out); + e.printStackTrace(); } } } @@ -454,7 +469,7 @@ public class FlagWatcher public void setAddEntityAnimations(boolean isEntityAnimationsAdded) { - this.addEntityAnimations = isEntityAnimationsAdded; + _addEntityAnimations = isEntityAnimationsAdded; } public void setArmor(ItemStack[] itemstack) @@ -467,7 +482,7 @@ public class FlagWatcher protected void setBackupValue(FlagType no, Object value) { - backupEntityValues.put(no.getIndex(), value); + _backupEntityValues.put(no.getIndex(), value); } public void setBurning(boolean setBurning) @@ -496,7 +511,7 @@ public class FlagWatcher private void setEntityFlag(int byteValue, boolean flag) { - modifiedEntityAnimations.add(byteValue); + _modifiedEntityAnimations.add(byteValue); byte b0 = (byte) getValue(FlagType.ENTITY_META); @@ -579,7 +594,7 @@ public class FlagWatcher public void setItemStack(EquipmentSlot slot, ItemStack itemStack) { - if (equipment == null) + if (_equipment == null) return; // Itemstack which is null means that its not replacing the disguises itemstack. @@ -600,7 +615,7 @@ public class FlagWatcher itemToSend = ReflectionManager.getNmsItem(itemStack); } - setItemStack(equipment, slot, itemStack); + setItemStack(_equipment, slot, itemStack); if (DisguiseAPI.isDisguiseInUse(getDisguise()) && getDisguise().getWatcher() == this) { @@ -620,7 +635,7 @@ public class FlagWatcher } catch (InvocationTargetException e) { - e.printStackTrace(System.out); + e.printStackTrace(); } } } @@ -652,11 +667,11 @@ public class FlagWatcher protected void setValue(FlagType id, Y value) { - entityValues.put(id.getIndex(), value); + _entityValues.put(id.getIndex(), value); if (!DisguiseConfig.isMetadataPacketsEnabled()) { - this.rebuildWatchableObjects(); + rebuildWatchableObjects(); } } diff --git a/src/me/libraryaddict/disguise/disguisetypes/MiscDisguise.java b/src/me/libraryaddict/disguise/disguisetypes/MiscDisguise.java index a8f622fe..130afdf4 100644 --- a/src/me/libraryaddict/disguise/disguisetypes/MiscDisguise.java +++ b/src/me/libraryaddict/disguise/disguisetypes/MiscDisguise.java @@ -14,7 +14,6 @@ import me.libraryaddict.disguise.disguisetypes.watchers.SplashPotionWatcher; public class MiscDisguise extends TargetedDisguise { - private int id = -1, data = 0; public MiscDisguise(DisguiseType disguiseType) @@ -51,9 +50,10 @@ public class MiscDisguise extends TargetedDisguise ((SplashPotionWatcher) getWatcher()).setPotionId(Math.max(0, id)); break; case DROPPED_ITEM: + if (id > 0) { - ((DroppedItemWatcher) getWatcher()).setItemStack(new ItemStack(id, Math.max(0, data))); + ((DroppedItemWatcher) getWatcher()).setItemStack(new ItemStack(id, Math.max(1, data))); } break; case FISHING_HOOK: // Entity ID of whoever is holding fishing rod diff --git a/src/me/libraryaddict/disguise/disguisetypes/watchers/DroppedItemWatcher.java b/src/me/libraryaddict/disguise/disguisetypes/watchers/DroppedItemWatcher.java index ee0f8333..94436d0f 100644 --- a/src/me/libraryaddict/disguise/disguisetypes/watchers/DroppedItemWatcher.java +++ b/src/me/libraryaddict/disguise/disguisetypes/watchers/DroppedItemWatcher.java @@ -2,14 +2,14 @@ package me.libraryaddict.disguise.disguisetypes.watchers; import org.bukkit.inventory.ItemStack; +import com.google.common.base.Optional; + import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.FlagType; import me.libraryaddict.disguise.disguisetypes.FlagWatcher; -//TODO: Add support for custom items instead of just stone public class DroppedItemWatcher extends FlagWatcher { - public DroppedItemWatcher(Disguise disguise) { super(disguise); @@ -17,12 +17,12 @@ public class DroppedItemWatcher extends FlagWatcher public ItemStack getItemStack() { - return getValue(FlagType.DROPPED_ITEM); + return getValue(FlagType.DROPPED_ITEM).get(); } public void setItemStack(ItemStack item) { - setValue(FlagType.DROPPED_ITEM, item); + setValue(FlagType.DROPPED_ITEM, Optional. of(item)); sendData(FlagType.DROPPED_ITEM); } } diff --git a/src/me/libraryaddict/disguise/disguisetypes/watchers/LivingWatcher.java b/src/me/libraryaddict/disguise/disguisetypes/watchers/LivingWatcher.java index f18bf354..972b7774 100644 --- a/src/me/libraryaddict/disguise/disguisetypes/watchers/LivingWatcher.java +++ b/src/me/libraryaddict/disguise/disguisetypes/watchers/LivingWatcher.java @@ -1,220 +1,220 @@ -package me.libraryaddict.disguise.disguisetypes.watchers; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffectType; - -import com.comphenix.protocol.PacketType.Play.Server; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.events.PacketContainer; -import com.comphenix.protocol.wrappers.WrappedAttribute; -import com.comphenix.protocol.wrappers.WrappedAttribute.Builder; - -import me.libraryaddict.disguise.DisguiseAPI; -import me.libraryaddict.disguise.disguisetypes.Disguise; -import me.libraryaddict.disguise.disguisetypes.FlagType; -import me.libraryaddict.disguise.disguisetypes.FlagWatcher; -import me.libraryaddict.disguise.utilities.DisguiseUtilities; -import me.libraryaddict.disguise.utilities.ReflectionManager; - -public class LivingWatcher extends FlagWatcher -{ - static Map list = new HashMap<>(); - static Method getId; - - static - { - try - { - getId = ReflectionManager.getNmsMethod("MobEffectList", "getId", ReflectionManager.getNmsClass("MobEffectList")); - Object REGISTRY = ReflectionManager.getNmsField("MobEffectList", "REGISTRY").get(null); - - for (Object next : ((Iterable) REGISTRY)) - { - int id = (int) getId.invoke(null, next); - list.put(id, next); - } - } - catch (Exception ex) - { - ex.printStackTrace(System.out); - } - } - - private double maxHealth; - private boolean maxHealthSet; - private HashSet potionEffects = new HashSet<>(); - - public LivingWatcher(Disguise disguise) - { - super(disguise); - } - - public void addPotionEffect(PotionEffectType potionEffect) - { - if (!hasPotionEffect(potionEffect)) - { - removePotionEffect(potionEffect); - potionEffects.add(potionEffect.getId()); - - sendPotionEffects(); - } - } - - @Override - public LivingWatcher clone(Disguise disguise) - { - LivingWatcher clone = (LivingWatcher) super.clone(disguise); - clone.potionEffects = (HashSet) potionEffects.clone(); - clone.maxHealth = maxHealth; - clone.maxHealthSet = maxHealthSet; - - return clone; - } - - public float getHealth() - { - return (float) getValue(FlagType.LIVING_HEALTH); - } - - public double getMaxHealth() - { - return maxHealth; - } - - public boolean isPotionParticlesAmbient() - { - return (boolean) getValue(FlagType.LIVING_POTION_AMBIENT); - } - - private int getPotions() - { - int m = 3694022; - - if (potionEffects.isEmpty()) - { - return m; - } - - float f1 = 0.0F; - float f2 = 0.0F; - float f3 = 0.0F; - float f4 = 0.0F; - try - { - for (int localMobEffect : potionEffects) - { - int n = (Integer) getId.invoke(list.get(localMobEffect)); - f1 += (n >> 16 & 0xFF) / 255.0F; - f2 += (n >> 8 & 0xFF) / 255.0F; - f3 += (n & 0xFF) / 255.0F; - f4 += 1.0F; - } - } - catch (Exception ex) - { - ex.printStackTrace(System.out); - } - - f1 = f1 / f4 * 255.0F; - f2 = f2 / f4 * 255.0F; - f3 = f3 / f4 * 255.0F; - - return (int) f1 << 16 | (int) f2 << 8 | (int) f3; - } - - public boolean hasPotionEffect(PotionEffectType type) - { - return potionEffects.contains(type.getId()); - } - - public boolean isMaxHealthSet() - { - return maxHealthSet; - } - - public void removePotionEffect(PotionEffectType type) - { - if (potionEffects.contains(type.getId())) - { - potionEffects.remove(type.getId()); - sendPotionEffects(); - } - } - - public void setPotionParticlesAmbient(boolean particles) - { - setValue(FlagType.LIVING_POTION_AMBIENT, particles); - sendData(FlagType.LIVING_POTION_AMBIENT); - } - - private void sendPotionEffects() - { - setValue(FlagType.LIVING_POTIONS, getPotions()); - sendData(FlagType.LIVING_POTIONS); - } - - public void setHealth(float health) - { - setValue(FlagType.LIVING_HEALTH, health); - sendData(FlagType.LIVING_HEALTH); - } - - public int getArrowsSticking() - { - return (int) getValue(FlagType.LIVING_ARROWS); - } - - public void setArrowsSticking(int arrowsNo) - { - setValue(FlagType.LIVING_ARROWS, arrowsNo); - sendData(FlagType.LIVING_ARROWS); - } - - public void setMaxHealth(double newHealth) - { - this.maxHealth = newHealth; - this.maxHealthSet = true; - - if (DisguiseAPI.isDisguiseInUse(getDisguise()) && getDisguise().getWatcher() == this) - { - PacketContainer packet = new PacketContainer(Server.UPDATE_ATTRIBUTES); - - List attributes = new ArrayList<>(); - - Builder builder; - builder = WrappedAttribute.newBuilder(); - builder.attributeKey("generic.maxHealth"); - builder.baseValue(getMaxHealth()); - builder.packet(packet); - - attributes.add(builder.build()); - - Entity entity = getDisguise().getEntity(); - - packet.getIntegers().write(0, entity.getEntityId()); - packet.getAttributeCollectionModifier().write(0, attributes); - - for (Player player : DisguiseUtilities.getPerverts(getDisguise())) - { - try - { - ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); - } - catch (InvocationTargetException e) - { - e.printStackTrace(System.out); - } - } - } - } - -} +package me.libraryaddict.disguise.disguisetypes.watchers; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; + +import com.comphenix.protocol.PacketType.Play.Server; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.WrappedAttribute; +import com.comphenix.protocol.wrappers.WrappedAttribute.Builder; + +import me.libraryaddict.disguise.DisguiseAPI; +import me.libraryaddict.disguise.disguisetypes.Disguise; +import me.libraryaddict.disguise.disguisetypes.FlagType; +import me.libraryaddict.disguise.disguisetypes.FlagWatcher; +import me.libraryaddict.disguise.utilities.DisguiseUtilities; +import me.libraryaddict.disguise.utilities.ReflectionManager; + +public class LivingWatcher extends FlagWatcher +{ + static Map list = new HashMap<>(); + static Method getId; + + static + { + try + { + getId = ReflectionManager.getNmsMethod("MobEffectList", "getId", ReflectionManager.getNmsClass("MobEffectList")); + Object REGISTRY = ReflectionManager.getNmsField("MobEffectList", "REGISTRY").get(null); + + for (Object next : ((Iterable) REGISTRY)) + { + int id = (int) getId.invoke(null, next); + list.put(id, next); + } + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + + private double maxHealth; + private boolean maxHealthSet; + private HashSet potionEffects = new HashSet<>(); + + public LivingWatcher(Disguise disguise) + { + super(disguise); + } + + public void addPotionEffect(PotionEffectType potionEffect) + { + if (!hasPotionEffect(potionEffect)) + { + removePotionEffect(potionEffect); + potionEffects.add(potionEffect.getId()); + + sendPotionEffects(); + } + } + + @Override + public LivingWatcher clone(Disguise disguise) + { + LivingWatcher clone = (LivingWatcher) super.clone(disguise); + clone.potionEffects = (HashSet) potionEffects.clone(); + clone.maxHealth = maxHealth; + clone.maxHealthSet = maxHealthSet; + + return clone; + } + + public float getHealth() + { + return (float) getValue(FlagType.LIVING_HEALTH); + } + + public double getMaxHealth() + { + return maxHealth; + } + + public boolean isPotionParticlesAmbient() + { + return (boolean) getValue(FlagType.LIVING_POTION_AMBIENT); + } + + private int getPotions() + { + int m = 3694022; + + if (potionEffects.isEmpty()) + { + return m; + } + + float f1 = 0.0F; + float f2 = 0.0F; + float f3 = 0.0F; + float f4 = 0.0F; + try + { + for (int localMobEffect : potionEffects) + { + int n = (Integer) getId.invoke(list.get(localMobEffect)); + f1 += (n >> 16 & 0xFF) / 255.0F; + f2 += (n >> 8 & 0xFF) / 255.0F; + f3 += (n & 0xFF) / 255.0F; + f4 += 1.0F; + } + } + catch (Exception ex) + { + ex.printStackTrace(); + } + + f1 = f1 / f4 * 255.0F; + f2 = f2 / f4 * 255.0F; + f3 = f3 / f4 * 255.0F; + + return (int) f1 << 16 | (int) f2 << 8 | (int) f3; + } + + public boolean hasPotionEffect(PotionEffectType type) + { + return potionEffects.contains(type.getId()); + } + + public boolean isMaxHealthSet() + { + return maxHealthSet; + } + + public void removePotionEffect(PotionEffectType type) + { + if (potionEffects.contains(type.getId())) + { + potionEffects.remove(type.getId()); + sendPotionEffects(); + } + } + + public void setPotionParticlesAmbient(boolean particles) + { + setValue(FlagType.LIVING_POTION_AMBIENT, particles); + sendData(FlagType.LIVING_POTION_AMBIENT); + } + + private void sendPotionEffects() + { + setValue(FlagType.LIVING_POTIONS, getPotions()); + sendData(FlagType.LIVING_POTIONS); + } + + public void setHealth(float health) + { + setValue(FlagType.LIVING_HEALTH, health); + sendData(FlagType.LIVING_HEALTH); + } + + public int getArrowsSticking() + { + return (int) getValue(FlagType.LIVING_ARROWS); + } + + public void setArrowsSticking(int arrowsNo) + { + setValue(FlagType.LIVING_ARROWS, arrowsNo); + sendData(FlagType.LIVING_ARROWS); + } + + public void setMaxHealth(double newHealth) + { + this.maxHealth = newHealth; + this.maxHealthSet = true; + + if (DisguiseAPI.isDisguiseInUse(getDisguise()) && getDisguise().getWatcher() == this) + { + PacketContainer packet = new PacketContainer(Server.UPDATE_ATTRIBUTES); + + List attributes = new ArrayList<>(); + + Builder builder; + builder = WrappedAttribute.newBuilder(); + builder.attributeKey("generic.maxHealth"); + builder.baseValue(getMaxHealth()); + builder.packet(packet); + + attributes.add(builder.build()); + + Entity entity = getDisguise().getEntity(); + + packet.getIntegers().write(0, entity.getEntityId()); + packet.getAttributeCollectionModifier().write(0, attributes); + + for (Player player : DisguiseUtilities.getPerverts(getDisguise())) + { + try + { + ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet, false); + } + catch (InvocationTargetException e) + { + e.printStackTrace(); + } + } + } + } + +} diff --git a/src/me/libraryaddict/disguise/disguisetypes/watchers/PlayerWatcher.java b/src/me/libraryaddict/disguise/disguisetypes/watchers/PlayerWatcher.java index ac80e3fa..fff75f7d 100644 --- a/src/me/libraryaddict/disguise/disguisetypes/watchers/PlayerWatcher.java +++ b/src/me/libraryaddict/disguise/disguisetypes/watchers/PlayerWatcher.java @@ -25,6 +25,8 @@ public class PlayerWatcher extends LivingWatcher public PlayerWatcher(Disguise disguise) { super(disguise); + + setValue(FlagType.PLAYER_SKIN, FlagType.PLAYER_SKIN.getDefault()); } @Override @@ -248,7 +250,7 @@ public class PlayerWatcher extends LivingWatcher } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } } diff --git a/src/me/libraryaddict/disguise/utilities/ClassGetter.java b/src/me/libraryaddict/disguise/utilities/ClassGetter.java index ef9885bf..bf03c904 100644 --- a/src/me/libraryaddict/disguise/utilities/ClassGetter.java +++ b/src/me/libraryaddict/disguise/utilities/ClassGetter.java @@ -89,7 +89,7 @@ public class ClassGetter } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } } diff --git a/src/me/libraryaddict/disguise/utilities/DisguiseUtilities.java b/src/me/libraryaddict/disguise/utilities/DisguiseUtilities.java index 52e29a16..5630ee29 100644 --- a/src/me/libraryaddict/disguise/utilities/DisguiseUtilities.java +++ b/src/me/libraryaddict/disguise/utilities/DisguiseUtilities.java @@ -142,7 +142,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } @@ -375,7 +375,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } @@ -631,7 +631,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return players; @@ -807,7 +807,7 @@ public class DisguiseUtilities runnables.get(playerName).add(runnable); } - return ReflectionManager.getGameProfile(null, origName); + return null; } /** @@ -895,7 +895,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } }, 2); @@ -941,7 +941,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } }, 2); @@ -954,7 +954,7 @@ public class DisguiseUtilities Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } @@ -1008,7 +1008,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } }, 2); @@ -1018,7 +1018,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } } @@ -1055,7 +1055,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } }, 2); @@ -1098,7 +1098,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } }, 2); @@ -1110,7 +1110,7 @@ public class DisguiseUtilities Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } @@ -1162,7 +1162,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } // Code to stop player pushing in 1.9 @@ -1204,7 +1204,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } // Resend entity metadata else he will be invisible to himself until its resent @@ -1218,7 +1218,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } player.updateInventory(); @@ -1313,7 +1313,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } // Send the velocity packets @@ -1396,7 +1396,7 @@ public class DisguiseUtilities } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } @@ -1449,7 +1449,7 @@ public class DisguiseUtilities } catch (InvocationTargetException e) { - e.printStackTrace(System.out); + e.printStackTrace(); } } }); @@ -1457,7 +1457,7 @@ public class DisguiseUtilities } catch (InvocationTargetException e) { - e.printStackTrace(System.out); + e.printStackTrace(); } } diff --git a/src/me/libraryaddict/disguise/utilities/Metrics.java b/src/me/libraryaddict/disguise/utilities/Metrics.java index f32a325d..76c9fe11 100644 --- a/src/me/libraryaddict/disguise/utilities/Metrics.java +++ b/src/me/libraryaddict/disguise/utilities/Metrics.java @@ -1,790 +1,790 @@ -/* - * Copyright 2011-2013 Tyler Blair. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and contributors and should not be interpreted as representing official policies, - * either expressed or implied, of anybody else. - */ -package me.libraryaddict.disguise.utilities; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.Proxy; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.UUID; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.scheduler.BukkitTask; - -public class Metrics -{ - - /** - * The current revision number - */ - private final static int REVISION = 7; - /** - * The base url of the metrics domain - */ - private static final String BASE_URL = "http://report.mcstats.org"; - /** - * The url used to report a server's status - */ - private static final String REPORT_URL = "/plugin/%s"; - /** - * Interval of time to ping (in minutes) - */ - private static final int PING_INTERVAL = 15; - /** - * The plugin this metrics submits for - */ - private final Plugin plugin; - /** - * All of the custom graphs to submit to metrics - */ - private final Set graphs = Collections.synchronizedSet(new HashSet()); - /** - * The plugin configuration file - */ - private final YamlConfiguration configuration; - /** - * The plugin configuration file - */ - private final File configurationFile; - /** - * Unique server id - */ - private final String guid; - /** - * Debug mode - */ - private final boolean debug; - /** - * Lock for synchronization - */ - private final Object optOutLock = new Object(); - /** - * The scheduled task - */ - private volatile BukkitTask task = null; - - public Metrics(final Plugin plugin) throws IOException - { - if (plugin == null) - { - throw new IllegalArgumentException("Plugin cannot be null"); - } - this.plugin = plugin; - // load the config - configurationFile = getConfigFile(); - configuration = YamlConfiguration.loadConfiguration(configurationFile); - // add some defaults - configuration.addDefault("opt-out", false); - configuration.addDefault("guid", UUID.randomUUID().toString()); - configuration.addDefault("debug", false); - // Do we need to create the file? - if (configuration.get("guid", null) == null) - { - configuration.options().header("http://mcstats.org").copyDefaults(true); - configuration.save(configurationFile); - } - // Load the guid then - guid = configuration.getString("guid"); - debug = configuration.getBoolean("debug", false); - } - - /** - * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics website. - * Plotters can be added to the graph object returned. - * - * @param name - * The name of the graph - * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given - */ - public Graph createGraph(final String name) - { - if (name == null) - { - throw new IllegalArgumentException("Graph name cannot be null"); - } - // Construct the graph object - final Graph graph = new Graph(name); - // Now we can add our graph - graphs.add(graph); - // and return back - return graph; - } - - /** - * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend - * - * @param graph - * The name of the graph - */ - public void addGraph(final Graph graph) - { - if (graph == null) - { - throw new IllegalArgumentException("Graph cannot be null"); - } - graphs.add(graph); - } - - /** - * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the initial data to - * the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 ticks. - * - * @return True if statistics measuring is running, otherwise false. - */ - public boolean start() - { - synchronized (optOutLock) - { - // Did we opt out? - if (isOptOut()) - { - return false; - } - // Is metrics already running? - if (task != null) - { - return true; - } - // Begin hitting the server with glorious data - task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() - { - private boolean firstPost = true; - - @Override - public void run() - { - try - { - // This has to be synchronized or it can collide with the disable method. - synchronized (optOutLock) - { - // Disable Task, if it is running and the server owner decided to opt-out - if (isOptOut() && task != null) - { - task.cancel(); - task = null; - // Tell all plotters to stop gathering information. - for (Graph graph : graphs) - { - graph.onOptOut(); - } - } - } - // We use the inverse of firstPost because if it is the first time we are posting, - // it is not a interval ping, so it evaluates to FALSE - // Each time thereafter it will evaluate to TRUE, i.e PING! - postPlugin(!firstPost); - // After the first post we set firstPost to false - // Each post thereafter will be a ping - firstPost = false; - } - catch (IOException e) - { - if (debug) - { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); - } - } - } - }, 0, PING_INTERVAL * 1200); - return true; - } - } - - /** - * Has the server owner denied plugin metrics? - * - * @return true if metrics should be opted out of it - */ - public boolean isOptOut() - { - synchronized (optOutLock) - { - try - { - // Reload the metrics file - configuration.load(getConfigFile()); - } - catch (IOException | InvalidConfigurationException ex) - { - if (debug) - { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } - return configuration.getBoolean("opt-out", false); - } - } - - /** - * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. - * - * @throws java.io.IOException - */ - public void enable() throws IOException - { - // This has to be synchronized or it can collide with the check in the task. - synchronized (optOutLock) - { - // Check if the server owner has already set opt-out, if not, set it. - if (isOptOut()) - { - configuration.set("opt-out", false); - configuration.save(configurationFile); - } - // Enable Task, if it is not running - if (task == null) - { - start(); - } - } - } - - /** - * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. - * - * @throws java.io.IOException - */ - public void disable() throws IOException - { - // This has to be synchronized or it can collide with the check in the task. - synchronized (optOutLock) - { - // Check if the server owner has already set opt-out, if not, set it. - if (!isOptOut()) - { - configuration.set("opt-out", true); - configuration.save(configurationFile); - } - // Disable Task, if it is running - if (task != null) - { - task.cancel(); - task = null; - } - } - } - - /** - * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status - * - * @return the File object for the config file - */ - public File getConfigFile() - { - // I believe the easiest way to get the base folder (e.g Spigot set via -P) for plugins to use - // is to abuse the plugin object we already have - // plugin.getDataFolder() => base/plugins/PluginA/ - // pluginsFolder => base/plugins/ - // The base is not necessarily relative to the startup directory. - File pluginsFolder = plugin.getDataFolder().getParentFile(); - // return => base/plugins/PluginMetrics/config.yml - return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); - } - - /** - * Generic method that posts a plugin to the metrics website - */ - private void postPlugin(final boolean isPing) throws IOException - { - // Server software specific section - PluginDescriptionFile description = plugin.getDescription(); - String pluginName = description.getName(); - boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled - String pluginVersion = description.getVersion(); - String serverVersion = Bukkit.getVersion(); - int playersOnline = Bukkit.getServer().getOnlinePlayers().size(); - // END server software specific section -- all code below does not use any code outside of this class / Java - // Construct the post data - StringBuilder json = new StringBuilder(1024); - json.append('{'); - // The plugin's description file containg all of the plugin data such as name, version, author, etc - appendJSONPair(json, "guid", guid); - appendJSONPair(json, "plugin_version", pluginVersion); - appendJSONPair(json, "server_version", serverVersion); - appendJSONPair(json, "players_online", Integer.toString(playersOnline)); - // New data as of R6 - String osname = System.getProperty("os.name"); - String osarch = System.getProperty("os.arch"); - String osversion = System.getProperty("os.version"); - String java_version = System.getProperty("java.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - // normalize os arch .. amd64 -> x86_64 - if (osarch.equals("amd64")) - { - osarch = "x86_64"; - } - appendJSONPair(json, "osname", osname); - appendJSONPair(json, "osarch", osarch); - appendJSONPair(json, "osversion", osversion); - appendJSONPair(json, "cores", Integer.toString(coreCount)); - appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); - appendJSONPair(json, "java_version", java_version); - // If we're pinging, append it - if (isPing) - { - appendJSONPair(json, "ping", "1"); - } - if (graphs.size() > 0) - { - synchronized (graphs) - { - json.append(','); - json.append('"'); - json.append("graphs"); - json.append('"'); - json.append(':'); - json.append('{'); - boolean firstGraph = true; - for (Graph graph : graphs) - { - StringBuilder graphJson = new StringBuilder(); - graphJson.append('{'); - for (Plotter plotter : graph.getPlotters()) - { - appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); - } - graphJson.append('}'); - if (!firstGraph) - { - json.append(','); - } - json.append(escapeJSON(graph.getName())); - json.append(':'); - json.append(graphJson); - firstGraph = false; - } - json.append('}'); - } - } - // close json - json.append('}'); - // Create the url - URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); - // Connect to the website - URLConnection connection; - // Mineshafter creates a socks proxy, so we can safely bypass it - // It does not reroute POST requests so we need to go around it - if (isMineshafterPresent()) - { - connection = url.openConnection(Proxy.NO_PROXY); - } - else - { - connection = url.openConnection(); - } - byte[] uncompressed = json.toString().getBytes(); - byte[] compressed = gzip(json.toString()); - // Headers - connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); - connection.addRequestProperty("Content-Type", "application/json"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.setDoOutput(true); - if (debug) - { - System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length - + " compressed=" + compressed.length); - } - // Write the data - OutputStream os = connection.getOutputStream(); - os.write(compressed); - os.flush(); - String response; - try ( // Now read the response - BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) - { - response = reader.readLine(); - // close resources - os.close(); - } - if (response == null || response.startsWith("ERR") || response.startsWith("7")) - { - if (response == null) - { - response = "null"; - } - else if (response.startsWith("7")) - { - response = response.substring(response.startsWith("7,") ? 2 : 1); - } - throw new IOException(response); - } - else - { - // Is this the first update this hour? - if (response.equals("1") || response.contains("This is your first update this hour")) - { - synchronized (graphs) - { - for (Graph graph : graphs) - { - for (Plotter plotter : graph.getPlotters()) - { - plotter.reset(); - } - } - } - } - } - } - - /** - * GZip compress a string of bytes - * - * @param input - * @return byte[] - */ - public static byte[] gzip(String input) - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream gzos = null; - try - { - gzos = new GZIPOutputStream(baos); - gzos.write(input.getBytes("UTF-8")); - } - catch (IOException e) - { - e.printStackTrace(System.out); - } - finally - { - if (gzos != null) - { - try - { - gzos.close(); - } - catch (IOException ignore) - { - } - } - } - return baos.toByteArray(); - } - - /** - * Check if mineshafter is present. If it is, we need to bypass it to send POST requests - * - * @return true if mineshafter is installed on the server - */ - private boolean isMineshafterPresent() - { - try - { - Class.forName("mineshafter.MineServer"); - return true; - } - catch (Exception e) - { - return false; - } - } - - /** - * Appends a json encoded key/value pair to the given string builder. - * - * @param json - * @param key - * @param value - * @throws UnsupportedEncodingException - */ - private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException - { - boolean isValueNumeric = false; - try - { - if (value.equals("0") || !value.endsWith("0")) - { - Double.parseDouble(value); - isValueNumeric = true; - } - } - catch (NumberFormatException e) - { - isValueNumeric = false; - } - if (json.charAt(json.length() - 1) != '{') - { - json.append(','); - } - json.append(escapeJSON(key)); - json.append(':'); - if (isValueNumeric) - { - json.append(value); - } - else - { - json.append(escapeJSON(value)); - } - } - - /** - * Escape a string to create a valid JSON string - * - * @param text - * @return String - */ - private static String escapeJSON(String text) - { - StringBuilder builder = new StringBuilder(); - builder.append('"'); - for (int index = 0; index < text.length(); index++) - { - char chr = text.charAt(index); - switch (chr) - { - case '"': - case '\\': - builder.append('\\'); - builder.append(chr); - break; - case '\b': - builder.append("\\b"); - break; - case '\t': - builder.append("\\t"); - break; - case '\n': - builder.append("\\n"); - break; - case '\r': - builder.append("\\r"); - break; - default: - if (chr < ' ') - { - String t = "000" + Integer.toHexString(chr); - builder.append("\\u").append(t.substring(t.length() - 4)); - } - else - { - builder.append(chr); - } - break; - } - } - builder.append('"'); - return builder.toString(); - } - - /** - * Encode text as UTF-8 - * - * @param text - * the text to encode - * @return the encoded text, as UTF-8 - */ - private static String urlEncode(final String text) throws UnsupportedEncodingException - { - return URLEncoder.encode(text, "UTF-8"); - } - - /** - * Represents a custom graph on the website - */ - public static class Graph - { - - /** - * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is rejected - */ - private final String name; - /** - * The set of plotters that are contained within this graph - */ - private final Set plotters = new LinkedHashSet<>(); - - private Graph(final String name) - { - this.name = name; - } - - /** - * Gets the graph's name - * - * @return the Graph's name - */ - public String getName() - { - return name; - } - - /** - * Add a plotter to the graph, which will be used to plot entries - * - * @param plotter - * the plotter to add to the graph - */ - public void addPlotter(final Plotter plotter) - { - plotters.add(plotter); - } - - /** - * Remove a plotter from the graph - * - * @param plotter - * the plotter to remove from the graph - */ - public void removePlotter(final Plotter plotter) - { - plotters.remove(plotter); - } - - /** - * Gets an unmodifiable set of the plotter objects in the graph - * - * @return an unmodifiable {@link java.util.Set} of the plotter objects - */ - public Set getPlotters() - { - return Collections.unmodifiableSet(plotters); - } - - @Override - public int hashCode() - { - return name.hashCode(); - } - - @Override - public boolean equals(final Object object) - { - if (!(object instanceof Graph)) - { - return false; - } - final Graph graph = (Graph) object; - return graph.name.equals(name); - } - - /** - * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. - */ - protected void onOptOut() - { - } - } - - /** - * Interface used to collect custom data for a plugin - */ - public static abstract class Plotter - { - - /** - * The plot's name - */ - private final String name; - - /** - * Construct a plotter with the default plot name - */ - public Plotter() - { - this("Default"); - } - - /** - * Construct a plotter with a specific plot name - * - * @param name - * the name of the plotter to use, which will show up on the website - */ - public Plotter(final String name) - { - this.name = name; - } - - /** - * Get the current value for the plotted point. Since this function defers to an external function it may or may not - * return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called from any thread - * so care should be taken when accessing resources that need to be synchronized. - * - * @return the current value for the point to be plotted. - */ - public abstract int getValue(); - - /** - * Get the column name for the plotted point - * - * @return the plotted point's column name - */ - public String getColumnName() - { - return name; - } - - /** - * Called after the website graphs have been updated - */ - public void reset() - { - } - - @Override - public int hashCode() - { - return getColumnName().hashCode(); - } - - @Override - public boolean equals(final Object object) - { - if (!(object instanceof Plotter)) - { - return false; - } - final Plotter plotter = (Plotter) object; - return plotter.name.equals(name) && plotter.getValue() == getValue(); - } - } -} +/* + * Copyright 2011-2013 Tyler Blair. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and contributors and should not be interpreted as representing official policies, + * either expressed or implied, of anybody else. + */ +package me.libraryaddict.disguise.utilities; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.Proxy; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.UUID; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.scheduler.BukkitTask; + +public class Metrics +{ + + /** + * The current revision number + */ + private final static int REVISION = 7; + /** + * The base url of the metrics domain + */ + private static final String BASE_URL = "http://report.mcstats.org"; + /** + * The url used to report a server's status + */ + private static final String REPORT_URL = "/plugin/%s"; + /** + * Interval of time to ping (in minutes) + */ + private static final int PING_INTERVAL = 15; + /** + * The plugin this metrics submits for + */ + private final Plugin plugin; + /** + * All of the custom graphs to submit to metrics + */ + private final Set graphs = Collections.synchronizedSet(new HashSet()); + /** + * The plugin configuration file + */ + private final YamlConfiguration configuration; + /** + * The plugin configuration file + */ + private final File configurationFile; + /** + * Unique server id + */ + private final String guid; + /** + * Debug mode + */ + private final boolean debug; + /** + * Lock for synchronization + */ + private final Object optOutLock = new Object(); + /** + * The scheduled task + */ + private volatile BukkitTask task = null; + + public Metrics(final Plugin plugin) throws IOException + { + if (plugin == null) + { + throw new IllegalArgumentException("Plugin cannot be null"); + } + this.plugin = plugin; + // load the config + configurationFile = getConfigFile(); + configuration = YamlConfiguration.loadConfiguration(configurationFile); + // add some defaults + configuration.addDefault("opt-out", false); + configuration.addDefault("guid", UUID.randomUUID().toString()); + configuration.addDefault("debug", false); + // Do we need to create the file? + if (configuration.get("guid", null) == null) + { + configuration.options().header("http://mcstats.org").copyDefaults(true); + configuration.save(configurationFile); + } + // Load the guid then + guid = configuration.getString("guid"); + debug = configuration.getBoolean("debug", false); + } + + /** + * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics website. + * Plotters can be added to the graph object returned. + * + * @param name + * The name of the graph + * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given + */ + public Graph createGraph(final String name) + { + if (name == null) + { + throw new IllegalArgumentException("Graph name cannot be null"); + } + // Construct the graph object + final Graph graph = new Graph(name); + // Now we can add our graph + graphs.add(graph); + // and return back + return graph; + } + + /** + * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend + * + * @param graph + * The name of the graph + */ + public void addGraph(final Graph graph) + { + if (graph == null) + { + throw new IllegalArgumentException("Graph cannot be null"); + } + graphs.add(graph); + } + + /** + * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the initial data to + * the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 ticks. + * + * @return True if statistics measuring is running, otherwise false. + */ + public boolean start() + { + synchronized (optOutLock) + { + // Did we opt out? + if (isOptOut()) + { + return false; + } + // Is metrics already running? + if (task != null) + { + return true; + } + // Begin hitting the server with glorious data + task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() + { + private boolean firstPost = true; + + @Override + public void run() + { + try + { + // This has to be synchronized or it can collide with the disable method. + synchronized (optOutLock) + { + // Disable Task, if it is running and the server owner decided to opt-out + if (isOptOut() && task != null) + { + task.cancel(); + task = null; + // Tell all plotters to stop gathering information. + for (Graph graph : graphs) + { + graph.onOptOut(); + } + } + } + // We use the inverse of firstPost because if it is the first time we are posting, + // it is not a interval ping, so it evaluates to FALSE + // Each time thereafter it will evaluate to TRUE, i.e PING! + postPlugin(!firstPost); + // After the first post we set firstPost to false + // Each post thereafter will be a ping + firstPost = false; + } + catch (IOException e) + { + if (debug) + { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); + } + } + } + }, 0, PING_INTERVAL * 1200); + return true; + } + } + + /** + * Has the server owner denied plugin metrics? + * + * @return true if metrics should be opted out of it + */ + public boolean isOptOut() + { + synchronized (optOutLock) + { + try + { + // Reload the metrics file + configuration.load(getConfigFile()); + } + catch (IOException | InvalidConfigurationException ex) + { + if (debug) + { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); + } + return true; + } + return configuration.getBoolean("opt-out", false); + } + } + + /** + * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. + * + * @throws java.io.IOException + */ + public void enable() throws IOException + { + // This has to be synchronized or it can collide with the check in the task. + synchronized (optOutLock) + { + // Check if the server owner has already set opt-out, if not, set it. + if (isOptOut()) + { + configuration.set("opt-out", false); + configuration.save(configurationFile); + } + // Enable Task, if it is not running + if (task == null) + { + start(); + } + } + } + + /** + * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. + * + * @throws java.io.IOException + */ + public void disable() throws IOException + { + // This has to be synchronized or it can collide with the check in the task. + synchronized (optOutLock) + { + // Check if the server owner has already set opt-out, if not, set it. + if (!isOptOut()) + { + configuration.set("opt-out", true); + configuration.save(configurationFile); + } + // Disable Task, if it is running + if (task != null) + { + task.cancel(); + task = null; + } + } + } + + /** + * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status + * + * @return the File object for the config file + */ + public File getConfigFile() + { + // I believe the easiest way to get the base folder (e.g Spigot set via -P) for plugins to use + // is to abuse the plugin object we already have + // plugin.getDataFolder() => base/plugins/PluginA/ + // pluginsFolder => base/plugins/ + // The base is not necessarily relative to the startup directory. + File pluginsFolder = plugin.getDataFolder().getParentFile(); + // return => base/plugins/PluginMetrics/config.yml + return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); + } + + /** + * Generic method that posts a plugin to the metrics website + */ + private void postPlugin(final boolean isPing) throws IOException + { + // Server software specific section + PluginDescriptionFile description = plugin.getDescription(); + String pluginName = description.getName(); + boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled + String pluginVersion = description.getVersion(); + String serverVersion = Bukkit.getVersion(); + int playersOnline = Bukkit.getServer().getOnlinePlayers().size(); + // END server software specific section -- all code below does not use any code outside of this class / Java + // Construct the post data + StringBuilder json = new StringBuilder(1024); + json.append('{'); + // The plugin's description file containg all of the plugin data such as name, version, author, etc + appendJSONPair(json, "guid", guid); + appendJSONPair(json, "plugin_version", pluginVersion); + appendJSONPair(json, "server_version", serverVersion); + appendJSONPair(json, "players_online", Integer.toString(playersOnline)); + // New data as of R6 + String osname = System.getProperty("os.name"); + String osarch = System.getProperty("os.arch"); + String osversion = System.getProperty("os.version"); + String java_version = System.getProperty("java.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + // normalize os arch .. amd64 -> x86_64 + if (osarch.equals("amd64")) + { + osarch = "x86_64"; + } + appendJSONPair(json, "osname", osname); + appendJSONPair(json, "osarch", osarch); + appendJSONPair(json, "osversion", osversion); + appendJSONPair(json, "cores", Integer.toString(coreCount)); + appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); + appendJSONPair(json, "java_version", java_version); + // If we're pinging, append it + if (isPing) + { + appendJSONPair(json, "ping", "1"); + } + if (graphs.size() > 0) + { + synchronized (graphs) + { + json.append(','); + json.append('"'); + json.append("graphs"); + json.append('"'); + json.append(':'); + json.append('{'); + boolean firstGraph = true; + for (Graph graph : graphs) + { + StringBuilder graphJson = new StringBuilder(); + graphJson.append('{'); + for (Plotter plotter : graph.getPlotters()) + { + appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); + } + graphJson.append('}'); + if (!firstGraph) + { + json.append(','); + } + json.append(escapeJSON(graph.getName())); + json.append(':'); + json.append(graphJson); + firstGraph = false; + } + json.append('}'); + } + } + // close json + json.append('}'); + // Create the url + URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); + // Connect to the website + URLConnection connection; + // Mineshafter creates a socks proxy, so we can safely bypass it + // It does not reroute POST requests so we need to go around it + if (isMineshafterPresent()) + { + connection = url.openConnection(Proxy.NO_PROXY); + } + else + { + connection = url.openConnection(); + } + byte[] uncompressed = json.toString().getBytes(); + byte[] compressed = gzip(json.toString()); + // Headers + connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); + connection.addRequestProperty("Content-Type", "application/json"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.setDoOutput(true); + if (debug) + { + System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + + " compressed=" + compressed.length); + } + // Write the data + OutputStream os = connection.getOutputStream(); + os.write(compressed); + os.flush(); + String response; + try ( // Now read the response + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) + { + response = reader.readLine(); + // close resources + os.close(); + } + if (response == null || response.startsWith("ERR") || response.startsWith("7")) + { + if (response == null) + { + response = "null"; + } + else if (response.startsWith("7")) + { + response = response.substring(response.startsWith("7,") ? 2 : 1); + } + throw new IOException(response); + } + else + { + // Is this the first update this hour? + if (response.equals("1") || response.contains("This is your first update this hour")) + { + synchronized (graphs) + { + for (Graph graph : graphs) + { + for (Plotter plotter : graph.getPlotters()) + { + plotter.reset(); + } + } + } + } + } + } + + /** + * GZip compress a string of bytes + * + * @param input + * @return byte[] + */ + public static byte[] gzip(String input) + { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + GZIPOutputStream gzos = null; + try + { + gzos = new GZIPOutputStream(baos); + gzos.write(input.getBytes("UTF-8")); + } + catch (IOException e) + { + e.printStackTrace(); + } + finally + { + if (gzos != null) + { + try + { + gzos.close(); + } + catch (IOException ignore) + { + } + } + } + return baos.toByteArray(); + } + + /** + * Check if mineshafter is present. If it is, we need to bypass it to send POST requests + * + * @return true if mineshafter is installed on the server + */ + private boolean isMineshafterPresent() + { + try + { + Class.forName("mineshafter.MineServer"); + return true; + } + catch (Exception e) + { + return false; + } + } + + /** + * Appends a json encoded key/value pair to the given string builder. + * + * @param json + * @param key + * @param value + * @throws UnsupportedEncodingException + */ + private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException + { + boolean isValueNumeric = false; + try + { + if (value.equals("0") || !value.endsWith("0")) + { + Double.parseDouble(value); + isValueNumeric = true; + } + } + catch (NumberFormatException e) + { + isValueNumeric = false; + } + if (json.charAt(json.length() - 1) != '{') + { + json.append(','); + } + json.append(escapeJSON(key)); + json.append(':'); + if (isValueNumeric) + { + json.append(value); + } + else + { + json.append(escapeJSON(value)); + } + } + + /** + * Escape a string to create a valid JSON string + * + * @param text + * @return String + */ + private static String escapeJSON(String text) + { + StringBuilder builder = new StringBuilder(); + builder.append('"'); + for (int index = 0; index < text.length(); index++) + { + char chr = text.charAt(index); + switch (chr) + { + case '"': + case '\\': + builder.append('\\'); + builder.append(chr); + break; + case '\b': + builder.append("\\b"); + break; + case '\t': + builder.append("\\t"); + break; + case '\n': + builder.append("\\n"); + break; + case '\r': + builder.append("\\r"); + break; + default: + if (chr < ' ') + { + String t = "000" + Integer.toHexString(chr); + builder.append("\\u").append(t.substring(t.length() - 4)); + } + else + { + builder.append(chr); + } + break; + } + } + builder.append('"'); + return builder.toString(); + } + + /** + * Encode text as UTF-8 + * + * @param text + * the text to encode + * @return the encoded text, as UTF-8 + */ + private static String urlEncode(final String text) throws UnsupportedEncodingException + { + return URLEncoder.encode(text, "UTF-8"); + } + + /** + * Represents a custom graph on the website + */ + public static class Graph + { + + /** + * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is rejected + */ + private final String name; + /** + * The set of plotters that are contained within this graph + */ + private final Set plotters = new LinkedHashSet<>(); + + private Graph(final String name) + { + this.name = name; + } + + /** + * Gets the graph's name + * + * @return the Graph's name + */ + public String getName() + { + return name; + } + + /** + * Add a plotter to the graph, which will be used to plot entries + * + * @param plotter + * the plotter to add to the graph + */ + public void addPlotter(final Plotter plotter) + { + plotters.add(plotter); + } + + /** + * Remove a plotter from the graph + * + * @param plotter + * the plotter to remove from the graph + */ + public void removePlotter(final Plotter plotter) + { + plotters.remove(plotter); + } + + /** + * Gets an unmodifiable set of the plotter objects in the graph + * + * @return an unmodifiable {@link java.util.Set} of the plotter objects + */ + public Set getPlotters() + { + return Collections.unmodifiableSet(plotters); + } + + @Override + public int hashCode() + { + return name.hashCode(); + } + + @Override + public boolean equals(final Object object) + { + if (!(object instanceof Graph)) + { + return false; + } + final Graph graph = (Graph) object; + return graph.name.equals(name); + } + + /** + * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. + */ + protected void onOptOut() + { + } + } + + /** + * Interface used to collect custom data for a plugin + */ + public static abstract class Plotter + { + + /** + * The plot's name + */ + private final String name; + + /** + * Construct a plotter with the default plot name + */ + public Plotter() + { + this("Default"); + } + + /** + * Construct a plotter with a specific plot name + * + * @param name + * the name of the plotter to use, which will show up on the website + */ + public Plotter(final String name) + { + this.name = name; + } + + /** + * Get the current value for the plotted point. Since this function defers to an external function it may or may not + * return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called from any thread + * so care should be taken when accessing resources that need to be synchronized. + * + * @return the current value for the point to be plotted. + */ + public abstract int getValue(); + + /** + * Get the column name for the plotted point + * + * @return the plotted point's column name + */ + public String getColumnName() + { + return name; + } + + /** + * Called after the website graphs have been updated + */ + public void reset() + { + } + + @Override + public int hashCode() + { + return getColumnName().hashCode(); + } + + @Override + public boolean equals(final Object object) + { + if (!(object instanceof Plotter)) + { + return false; + } + final Plotter plotter = (Plotter) object; + return plotter.name.equals(name) && plotter.getValue() == getValue(); + } + } +} diff --git a/src/me/libraryaddict/disguise/utilities/PacketsManager.java b/src/me/libraryaddict/disguise/utilities/PacketsManager.java index 0f01b0fd..a11fb690 100644 --- a/src/me/libraryaddict/disguise/utilities/PacketsManager.java +++ b/src/me/libraryaddict/disguise/utilities/PacketsManager.java @@ -1053,8 +1053,8 @@ public class PacketsManager if (DisguiseConfig.isMetadataPacketsEnabled() && !isStaticMetadataDisguiseType(disguise)) { - WrappedWatchableObject watch = new WrappedWatchableObject(ReflectionManager - .createDataWatcherItem(0, WrappedDataWatcher.getEntityWatcher(entity).getByte(0))); + WrappedWatchableObject watch = ReflectionManager.createWatchable(0, + WrappedDataWatcher.getEntityWatcher(entity).getByte(0)); list.add(watch); @@ -1172,9 +1172,10 @@ public class PacketsManager */ public static boolean isStaticMetadataDisguiseType(Disguise disguise) { - return (disguise.getType() == DisguiseType.WOLF || disguise.getType() == DisguiseType.OCELOT + return false; + /* return (disguise.getType() == DisguiseType.WOLF || disguise.getType() == DisguiseType.OCELOT || disguise.getType() == DisguiseType.ENDERMAN || disguise.getType() == DisguiseType.SHULKER || disguise.getType() == DisguiseType.SPLASH_POTION || disguise.getType() == DisguiseType.FIREWORK - || disguise.getType() == DisguiseType.DROPPED_ITEM || disguise.getType() == DisguiseType.ENDER_CRYSTAL); + || disguise.getType() == DisguiseType.DROPPED_ITEM || disguise.getType() == DisguiseType.ENDER_CRYSTAL);*/ } } diff --git a/src/me/libraryaddict/disguise/utilities/ReflectionManager.java b/src/me/libraryaddict/disguise/utilities/ReflectionManager.java index 39224760..40a89617 100644 --- a/src/me/libraryaddict/disguise/utilities/ReflectionManager.java +++ b/src/me/libraryaddict/disguise/utilities/ReflectionManager.java @@ -25,11 +25,14 @@ import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; +import com.comphenix.protocol.wrappers.BlockPosition; import com.comphenix.protocol.wrappers.MinecraftKey; import com.comphenix.protocol.wrappers.WrappedDataWatcher.Registry; import com.comphenix.protocol.wrappers.WrappedDataWatcher.Serializer; import com.comphenix.protocol.wrappers.WrappedDataWatcher.WrappedDataWatcherObject; import com.comphenix.protocol.wrappers.WrappedGameProfile; +import com.comphenix.protocol.wrappers.WrappedWatchableObject; +import com.google.common.base.Optional; import com.mojang.authlib.GameProfile; import me.libraryaddict.disguise.disguisetypes.DisguiseType; @@ -71,7 +74,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } @@ -137,7 +140,7 @@ public class ReflectionManager } catch (Exception e) { - e.printStackTrace(System.out); + e.printStackTrace(); } return null; @@ -175,7 +178,7 @@ public class ReflectionManager } catch (Exception e) { - e.printStackTrace(System.out); + e.printStackTrace(); } return null; @@ -226,7 +229,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; @@ -240,7 +243,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; @@ -254,7 +257,7 @@ public class ReflectionManager } catch (Exception e) { - e.printStackTrace(System.out); + e.printStackTrace(); } return null; @@ -273,7 +276,7 @@ public class ReflectionManager } catch (Exception e) { - e.printStackTrace(System.out); + e.printStackTrace(); } return null; @@ -289,7 +292,7 @@ public class ReflectionManager } catch (NoSuchMethodException e) { - e.printStackTrace(System.out); + e.printStackTrace(); } return null; @@ -308,7 +311,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; @@ -351,7 +354,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; @@ -365,7 +368,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; @@ -379,7 +382,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; @@ -393,7 +396,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; @@ -414,7 +417,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; @@ -433,7 +436,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; } @@ -455,7 +458,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; @@ -469,7 +472,7 @@ public class ReflectionManager } catch (Exception e) { - e.printStackTrace(System.out); + e.printStackTrace(); } return null; @@ -485,7 +488,7 @@ public class ReflectionManager } catch (NoSuchMethodException e) { - e.printStackTrace(System.out); + e.printStackTrace(); } return null; @@ -504,7 +507,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; @@ -521,7 +524,7 @@ public class ReflectionManager } catch (NoSuchFieldException e) { - e.printStackTrace(System.out); + e.printStackTrace(); } return null; @@ -540,7 +543,7 @@ public class ReflectionManager } catch (Exception e) { - e.printStackTrace(System.out); + e.printStackTrace(); } return null; @@ -562,7 +565,7 @@ public class ReflectionManager } catch (NoSuchMethodException e) { - e.printStackTrace(System.out); + e.printStackTrace(); } return null; @@ -579,7 +582,7 @@ public class ReflectionManager } catch (NoSuchMethodException e) { - e.printStackTrace(System.out); + e.printStackTrace(); } return null; @@ -598,7 +601,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return 0; @@ -619,7 +622,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; @@ -645,7 +648,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; @@ -698,7 +701,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } return null; @@ -723,7 +726,7 @@ public class ReflectionManager } catch (Exception ex) { - ex.printStackTrace(System.out); + ex.printStackTrace(); } } @@ -915,12 +918,21 @@ public class ReflectionManager * @param value * @return */ - public static Object createDataWatcherItem(int id, Object value) + private static Object createDataWatcherItem(int id, Object value) { if (value == null) return null; - Serializer serializer = Registry.get(value.getClass()); + Serializer serializer; + + if (value instanceof Optional) + { + serializer = Registry.get(((Optional) value).get().getClass(), true); + } + else + { + serializer = Registry.get(value.getClass()); + } WrappedDataWatcherObject watcherObject = new WrappedDataWatcherObject(id, serializer); @@ -938,6 +950,35 @@ public class ReflectionManager return null; } + public static WrappedWatchableObject createWatchable(int index, Object obj) + { + if (obj instanceof Optional) + { + Object value = ((Optional) obj).get(); + + if (value instanceof BlockPosition) + { + value = BlockPosition.getConverter().getSpecific(value); + + if (value == null) + return null; + + obj = Optional.of(value); + } + else if (value instanceof ItemStack) + { + value = ReflectionManager.getNmsItem((ItemStack) value); + + if (value == null) + return null; + + obj = Optional.of(value); + } + } + + return new WrappedWatchableObject(createDataWatcherItem(index, obj)); + } + public static EntityEquipment createEntityEquipment(Entity entity) { if (!(entity instanceof LivingEntity)) diff --git a/src/me/libraryaddict/disguise/utilities/UpdateChecker.java b/src/me/libraryaddict/disguise/utilities/UpdateChecker.java index 2cf27971..56d6a31e 100644 --- a/src/me/libraryaddict/disguise/utilities/UpdateChecker.java +++ b/src/me/libraryaddict/disguise/utilities/UpdateChecker.java @@ -1,60 +1,74 @@ -package me.libraryaddict.disguise.utilities; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.regex.Pattern; - -public class UpdateChecker { - - private String latestVersion; - - private boolean checkHigher(String currentVersion, String newVersion) { - String current = toReadable(currentVersion); - String newVers = toReadable(newVersion); - return current.compareTo(newVers) < 0; - } - - public void checkUpdate(String currentVersion) { - String version = getSpigotVersion(); - if (version != null) { - if (checkHigher(currentVersion, version)) { - latestVersion = version; - } - } - } - - public String getLatestVersion() { - return latestVersion; - } - - /** - * Asks spigot for the version - */ - private String getSpigotVersion() { - try { - HttpURLConnection con = (HttpURLConnection) new URL("http://www.spigotmc.org/api/general.php").openConnection(); - con.setDoOutput(true); - con.setRequestMethod("POST"); - con.getOutputStream().write( - ("key=98BE0FE67F88AB82B4C197FAF1DC3B69206EFDCC4D3B80FC83A00037510B99B4&resource=81").getBytes("UTF-8")); - String version = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine(); - if (version.length() <= 7) { - return version; - } - } catch (Exception ex) { - System.out.print("[LibsDisguises] Failed to check for a update on spigot. Now checking bukkit.."); - } - return null; - } - - private String toReadable(String version) { - String[] split = Pattern.compile(".", Pattern.LITERAL).split(version.replace("v", "")); - version = ""; - for (String s : split) { - version += String.format("%4s", s); - } - return version; - } -} +package me.libraryaddict.disguise.utilities; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.regex.Pattern; + +public class UpdateChecker +{ + + private String latestVersion; + + private boolean checkHigher(String currentVersion, String newVersion) + { + String current = toReadable(currentVersion); + String newVers = toReadable(newVersion); + return current.compareTo(newVers) < 0; + } + + public void checkUpdate(String currentVersion) + { + String version = getSpigotVersion(); + + if (version == null) + return; + + if (!checkHigher(currentVersion, version)) + return; + + latestVersion = version; + } + + public String getLatestVersion() + { + return latestVersion; + } + + /** + * Asks spigot for the version + */ + private String getSpigotVersion() + { + try + { + HttpURLConnection con = (HttpURLConnection) new URL("http://www.spigotmc.org/api/general.php").openConnection(); + con.setDoOutput(true); + con.setRequestMethod("POST"); + con.getOutputStream().write( + ("key=98BE0FE67F88AB82B4C197FAF1DC3B69206EFDCC4D3B80FC83A00037510B99B4&resource=81").getBytes("UTF-8")); + String version = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine(); + if (version.length() <= 7) + { + return version; + } + } + catch (Exception ex) + { + System.out.print("[LibsDisguises] Failed to check for a update on spigot."); + } + return null; + } + + private String toReadable(String version) + { + String[] split = Pattern.compile(".", Pattern.LITERAL).split(version.replace("v", "")); + version = ""; + for (String s : split) + { + version += String.format("%4s", s); + } + return version; + } +} diff --git a/src/me/libraryaddict/disguise/utilities/packetlisteners/PacketListenerViewDisguises.java b/src/me/libraryaddict/disguise/utilities/packetlisteners/PacketListenerViewDisguises.java index 2b6742fa..3ea108e9 100644 --- a/src/me/libraryaddict/disguise/utilities/packetlisteners/PacketListenerViewDisguises.java +++ b/src/me/libraryaddict/disguise/utilities/packetlisteners/PacketListenerViewDisguises.java @@ -150,7 +150,7 @@ public class PacketListenerViewDisguises extends PacketAdapter if (observer.isSprinting()) b = (byte) (b | 1 << 3); - WrappedWatchableObject watch = new WrappedWatchableObject(ReflectionManager.createDataWatcherItem(0, b)); + WrappedWatchableObject watch = ReflectionManager.createWatchable(0, b); watchableList.add(watch); packet.getWatchableCollectionModifier().write(0, watchableList);