- Changed entire project to gradle

- Updated for 1.8.3
- No more errors, woo
This commit is contained in:
NavidK0
2015-03-09 20:28:41 -04:00
parent 14757a035b
commit 573f4cdc88
81 changed files with 299 additions and 645 deletions

View File

@@ -1,736 +0,0 @@
package me.libraryaddict.disguise.utilities;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;
import me.libraryaddict.disguise.disguisetypes.AnimalColor;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
import me.libraryaddict.disguise.disguisetypes.MiscDisguise;
import me.libraryaddict.disguise.disguisetypes.MobDisguise;
import me.libraryaddict.disguise.disguisetypes.PlayerDisguise;
import me.libraryaddict.disguise.disguisetypes.RabbitType;
import me.libraryaddict.disguise.utilities.ReflectionManager.LibVersion;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Monster;
import org.bukkit.inventory.ItemStack;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.potion.PotionEffectType;
public abstract class BaseDisguiseCommand implements CommandExecutor {
public class DisguiseParseException extends Exception {
private static final long serialVersionUID = 1276971370793124510L;
public DisguiseParseException() {
super();
}
public DisguiseParseException(String string) {
super(string);
}
}
protected ArrayList<String> getAllowedDisguises(HashMap<DisguiseType, HashMap<ArrayList<String>, Boolean>> hashMap) {
ArrayList<String> allowedDisguises = new ArrayList<String>();
for (DisguiseType type : hashMap.keySet()) {
allowedDisguises.add(type.toReadable().replace(" ", "_"));
}
Collections.sort(allowedDisguises, String.CASE_INSENSITIVE_ORDER);
return allowedDisguises;
}
protected HashMap<DisguiseType, HashMap<ArrayList<String>, Boolean>> getPermissions(CommandSender sender) {
return getPermissions(sender, "libsdisguises." + getClass().getSimpleName().replace("Command", "").toLowerCase() + ".");
}
protected HashMap<String, Boolean> getDisguisePermission(CommandSender sender, DisguiseType type) {
switch (type) {
case PLAYER:
case FALLING_BLOCK:
case PAINTING:
case SPLASH_POTION:
case FISHING_HOOK:
case DROPPED_ITEM:
HashMap<String, Boolean> returns = new HashMap<String, Boolean>();
String beginning = "libsdisguises.options." + getClass().getSimpleName().toLowerCase().replace("command", "") + ".";
for (PermissionAttachmentInfo permission : sender.getEffectivePermissions()) {
String lowerPerm = permission.getPermission().toLowerCase();
if (lowerPerm.startsWith(beginning)) {
String[] split = lowerPerm.substring(beginning.length()).split("\\.");
if (split.length > 1) {
if (split[0].replace("_", "").equals(type.name().toLowerCase().replace("_", ""))) {
for (int i = 1; i < split.length; i++) {
returns.put(split[i], permission.getValue());
}
}
}
}
}
return returns;
default:
return new HashMap<String, Boolean>();
}
}
protected Method[] getDisguiseWatcherMethods(Class<? extends FlagWatcher> watcherClass) {
Method[] methods = watcherClass.getMethods();
methods = Arrays.copyOf(methods, methods.length + 4);
int i = 4;
for (String methodName : new String[] { "setViewSelfDisguise", "setHideHeldItemFromSelf", "setHideArmorFromSelf",
"setHearSelfDisguise" }) {
try {
methods[methods.length - i--] = Disguise.class.getMethod(methodName, boolean.class);
} catch (Exception ex) {
ex.printStackTrace();
}
}
return methods;
}
/**
* Get perms for the node. Returns a hashmap of allowed disguisetypes and their options
*/
protected HashMap<DisguiseType, HashMap<ArrayList<String>, Boolean>> getPermissions(CommandSender sender,
String permissionNode) {
HashMap<DisguiseType, HashMap<ArrayList<String>, Boolean>> singleDisguises = new HashMap<DisguiseType, HashMap<ArrayList<String>, Boolean>>();
HashMap<DisguiseType, HashMap<ArrayList<String>, Boolean>> rangeDisguises = new HashMap<DisguiseType, HashMap<ArrayList<String>, Boolean>>();
HashMap<String, Boolean> perms = new HashMap<String, Boolean>();
for (PermissionAttachmentInfo permission : sender.getEffectivePermissions()) {
String perm = permission.getPermission().toLowerCase();
if (perm.startsWith(permissionNode) && (!perms.containsKey(perm) || !permission.getValue())) {
perms.put(perm, permission.getValue());
}
}
if (!perms.containsKey(permissionNode + "*") && sender.hasPermission(permissionNode + "*")) {
perms.put(permissionNode + "*", true);
}
if (!perms.containsKey(permissionNode + "*.*") && sender.hasPermission(permissionNode + "*.*")) {
perms.put(permissionNode + "*.*", true);
}
for (String perm : perms.keySet()) {
if (perms.get(perm)) {
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("_", ""))) {
dType = t;
break;
}
}
if (dType != null) {
HashMap<ArrayList<String>, Boolean> list;
if (singleDisguises.containsKey(dType)) {
list = singleDisguises.get(dType);
} else {
list = new HashMap<ArrayList<String>, Boolean>();
singleDisguises.put(dType, list);
}
HashMap<ArrayList<String>, Boolean> map1 = getOptions(perm);
list.put(map1.keySet().iterator().next(), map1.values().iterator().next());
} else {
for (DisguiseType type : DisguiseType.values()) {
HashMap<ArrayList<String>, Boolean> options = null;
Class entityClass = type.getEntityClass();
if (disguiseType.equals("mob")) {
if (type.isMob()) {
options = getOptions(perm);
}
} else if (disguiseType.equals("animal") || disguiseType.equals("animals")) {
if (Animals.class.isAssignableFrom(entityClass)) {
options = getOptions(perm);
}
} else if (disguiseType.equals("monster") || disguiseType.equals("monsters")) {
if (Monster.class.isAssignableFrom(entityClass)) {
options = getOptions(perm);
}
} else if (disguiseType.equals("misc")) {
if (type.isMisc()) {
options = getOptions(perm);
}
} else if (disguiseType.equals("ageable")) {
if (Ageable.class.isAssignableFrom(entityClass)) {
options = getOptions(perm);
}
} else if (disguiseType.equals("*")) {
options = getOptions(perm);
}
if (options != null) {
HashMap<ArrayList<String>, Boolean> list;
if (rangeDisguises.containsKey(type)) {
list = rangeDisguises.get(type);
} else {
list = new HashMap<ArrayList<String>, Boolean>();
rangeDisguises.put(type, list);
}
HashMap<ArrayList<String>, Boolean> map1 = getOptions(perm);
list.put(map1.keySet().iterator().next(), map1.values().iterator().next());
}
}
}
}
}
for (String perm : perms.keySet()) {
if (!perms.get(perm)) {
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("_", ""))) {
dType = t;
break;
}
}
if (dType != null) {
singleDisguises.remove(dType);
rangeDisguises.remove(dType);
} else {
for (DisguiseType type : DisguiseType.values()) {
boolean foundHim = false;
Class entityClass = type.getEntityClass();
if (disguiseType.equals("mob")) {
if (type.isMob()) {
foundHim = true;
}
} else if (disguiseType.equals("animal") || disguiseType.equals("animals")) {
if (Animals.class.isAssignableFrom(entityClass)) {
foundHim = true;
}
} else if (disguiseType.equals("monster") || disguiseType.equals("monsters")) {
if (Monster.class.isAssignableFrom(entityClass)) {
foundHim = true;
}
} else if (disguiseType.equals("misc")) {
if (type.isMisc()) {
foundHim = true;
}
} else if (disguiseType.equals("ageable")) {
if (Ageable.class.isAssignableFrom(entityClass)) {
foundHim = true;
}
} else if (disguiseType.equals("*")) {
foundHim = true;
}
if (foundHim) {
rangeDisguises.remove(type);
}
}
}
}
}
HashMap<DisguiseType, HashMap<ArrayList<String>, Boolean>> map = new HashMap<DisguiseType, HashMap<ArrayList<String>, Boolean>>();
for (DisguiseType type : DisguiseType.values()) {
HashMap<ArrayList<String>, Boolean> temp = new HashMap<ArrayList<String>, Boolean>();
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;
}
private HashMap<ArrayList<String>, Boolean> getOptions(String perm) {
ArrayList<String> list = new ArrayList<String>();
boolean isRemove = true;
String[] split = perm.split("\\.");
for (int i = 1; i < split.length; i++) {
String option = split[i];
boolean value = option.startsWith("-");
if (value) {
option = option.substring(1);
isRemove = false;
}
if (option.equals("baby"))
option = "setbaby";
list.add(option);
}
HashMap<ArrayList<String>, Boolean> options = new HashMap<ArrayList<String>, Boolean>();
options.put(list, isRemove);
return options;
}
protected boolean isDouble(String string) {
try {
Float.parseFloat(string);
return true;
} catch (Exception ex) {
return false;
}
}
protected boolean isNumeric(String string) {
try {
Integer.parseInt(string);
return true;
} catch (Exception ex) {
return false;
}
}
/**
* Returns the disguise if it all parsed correctly. Returns a exception with a complete message if it didn't. The
* commandsender is purely used for checking permissions. Would defeat the purpose otherwise. To reach this point, the
* disguise has been feed a proper disguisetype.
*/
protected Disguise parseDisguise(CommandSender sender, String[] args,
HashMap<DisguiseType, HashMap<ArrayList<String>, Boolean>> map) throws DisguiseParseException,
IllegalAccessException, InvocationTargetException {
if (map.isEmpty()) {
throw new DisguiseParseException(ChatColor.RED + "You are forbidden to use this command.");
}
if (args.length == 0) {
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
int toSkip = 1;
ArrayList<String> usedOptions = new ArrayList<String>();
Disguise disguise = null;
HashMap<ArrayList<String>, Boolean> optionPermissions;
if (args[0].startsWith("@")) {
if (sender.hasPermission("libsdisguises.disguise.disguiseclone")) {
disguise = DisguiseUtilities.getClonedDisguise(args[0].toLowerCase());
if (disguise == null) {
throw new DisguiseParseException(ChatColor.RED + "Cannot find a disguise under the reference " + args[0]);
}
} else {
throw new DisguiseParseException(ChatColor.RED + "You do not have perimssion to use disguise references!");
}
optionPermissions = (map.containsKey(disguise.getType()) ? map.get(disguise.getType())
: new HashMap<ArrayList<String>, Boolean>());
} else {
DisguiseType disguiseType = null;
if (args[0].equalsIgnoreCase("p")) {
disguiseType = DisguiseType.PLAYER;
} else {
for (DisguiseType type : DisguiseType.values()) {
if (args[0].equalsIgnoreCase(type.name()) || args[0].equalsIgnoreCase(type.name().replace("_", ""))) {
disguiseType = type;
break;
}
}
}
if (disguiseType == null) {
throw new DisguiseParseException(ChatColor.RED + "Error! The disguise " + ChatColor.GREEN + args[0]
+ ChatColor.RED + " doesn't exist!");
}
if (!(LibVersion.is1_8() && disguiseType.is1_8()) && disguiseType.getEntityType() == null) {
throw new DisguiseParseException(ChatColor.RED + "Error! This version of minecraft does not have that disguise!");
}
if (!map.containsKey(disguiseType)) {
throw new DisguiseParseException(ChatColor.RED + "You are forbidden to use this disguise.");
}
optionPermissions = map.get(disguiseType);
HashMap<String, Boolean> disguiseOptions = this.getDisguisePermission(sender, disguiseType);
if (disguiseType.isPlayer()) {// If he is doing a player disguise
if (args.length == 1) {
// He needs to give the player name
throw new DisguiseParseException(ChatColor.RED + "Error! You need to give a player name!");
} else {
if (!disguiseOptions.isEmpty()
&& (!disguiseOptions.containsKey(args[1].toLowerCase()) || !disguiseOptions
.get(args[1].toLowerCase()))) {
throw new DisguiseParseException(ChatColor.RED + "Error! You don't have permission to use that name!");
}
// Construct the player disguise
disguise = new PlayerDisguise(ChatColor.translateAlternateColorCodes('&', args[1]));
toSkip++;
}
} else {
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")) {
usedOptions.add("setbaby");
doCheck(optionPermissions, usedOptions);
adult = args[1].equalsIgnoreCase("adult");
toSkip++;
}
}
disguise = new MobDisguise(disguiseType, adult);
} else if (disguiseType.isMisc()) {
// Its a misc, we are going to use the MiscDisguise constructor.
int miscId = -1;
int miscData = -1;
String secondArg = null;
if (args.length > 1) {
// They have defined more arguements!
// If the first arg is a number
if (args[1].contains(":")) {
String[] split = args[1].split(":");
if (isNumeric(split[1])) {
secondArg = split[1];
}
args[1] = split[0];
}
if (isNumeric(args[1])) {
miscId = Integer.parseInt(args[1]);
} else {
if (disguiseType == DisguiseType.FALLING_BLOCK || disguiseType == DisguiseType.DROPPED_ITEM) {
for (Material mat : Material.values()) {
if (mat.name().replace("_", "").equalsIgnoreCase(args[1].replace("_", ""))) {
miscId = mat.getId();
break;
}
}
}
}
if (miscId != -1) {
switch (disguiseType) {
case PAINTING:
case FALLING_BLOCK:
case SPLASH_POTION:
case DROPPED_ITEM:
case FISHING_HOOK:
case ARROW:
case SMALL_FIREBALL:
case FIREBALL:
case WITHER_SKULL:
break;
default:
throw new DisguiseParseException(ChatColor.RED + "Error! " + disguiseType.toReadable()
+ " doesn't know what to do with " + args[1] + "!");
}
toSkip++;
// If they also defined a data value
if (args.length > 2 && secondArg == null && isNumeric(args[2])) {
secondArg = args[2];
toSkip++;
}
if (secondArg != null) {
if (disguiseType != DisguiseType.FALLING_BLOCK && disguiseType != DisguiseType.DROPPED_ITEM) {
throw new DisguiseParseException(ChatColor.RED + "Error! Only the disguises "
+ DisguiseType.FALLING_BLOCK.toReadable() + " and "
+ DisguiseType.DROPPED_ITEM.toReadable() + " uses a second number!");
}
miscData = Integer.parseInt(secondArg);
}
}
}
if (!disguiseOptions.isEmpty() && miscId != -1) {
String toCheck = "" + miscId;
if (miscData == 0 || miscData == -1) {
if (!disguiseOptions.containsKey(toCheck) || !disguiseOptions.get(toCheck)) {
toCheck += ":0";
}
} else {
toCheck += ":" + miscData;
}
if (!disguiseOptions.containsKey(toCheck) || !disguiseOptions.get(toCheck)) {
throw new DisguiseParseException(ChatColor.RED
+ "Error! You do not have permission to use the parameter " + toCheck + " on the "
+ disguiseType.toReadable() + " disguise!");
}
}
if (miscId != -1) {
if (disguiseType == DisguiseType.FALLING_BLOCK) {
usedOptions.add("setblock");
doCheck(optionPermissions, usedOptions);
} else if (disguiseType == DisguiseType.PAINTING) {
usedOptions.add("setpainting");
doCheck(optionPermissions, usedOptions);
} else if (disguiseType == DisguiseType.SPLASH_POTION) {
usedOptions.add("setpotionid");
doCheck(optionPermissions, usedOptions);
}
}
// Construct the disguise
disguise = new MiscDisguise(disguiseType, miscId, miscData);
}
}
}
// Copy strings to their new range
String[] newArgs = new String[args.length - toSkip];
System.arraycopy(args, toSkip, newArgs, 0, args.length - toSkip);
args = newArgs;
Method[] methods = this.getDisguiseWatcherMethods(disguise.getWatcher().getClass());
for (int i = 0; i < args.length; i += 2) {
String methodName = args[i];
String valueString = (args.length - 1 == i ? null : args[i + 1]);
Method methodToUse = null;
Object value = null;
DisguiseParseException storedEx = null;
int c = 0;
while (c < methods.length) {
try {
Entry<Method, Integer> entry = getMethod(methods, methodName, c);
if (entry == null) {
break;
}
methodToUse = entry.getKey();
c = entry.getValue();
methodName = methodToUse.getName();
Class<?>[] types = methodToUse.getParameterTypes();
Class param = types[0];
if (valueString != null) {
if (int.class == param) {
// Parse to integer
if (isNumeric(valueString)) {
value = (int) Integer.parseInt(valueString);
} else {
throw parseToException("number", valueString, methodName);
}
} else if (float.class == param || double.class == param) {
// Parse to number
if (isDouble(valueString)) {
float obj = Float.parseFloat(valueString);
if (param == float.class) {
value = (float) obj;
} else if (param == double.class) {
value = (double) obj;
}
} else {
throw parseToException("number.0", valueString, methodName);
}
} else if (param == String.class) {
// Parse to string
value = ChatColor.translateAlternateColorCodes('&', valueString);
} else if (param == AnimalColor.class) {
// Parse to animal color
try {
value = AnimalColor.valueOf(valueString.toUpperCase());
} catch (Exception ex) {
throw parseToException("animal color", valueString, methodName);
}
} else if (param == ItemStack.class) {
// Parse to itemstack
try {
value = parseToItemstack(valueString);
} catch (Exception ex) {
throw new DisguiseParseException(String.format(ex.getMessage(), methodName));
}
} else if (param == ItemStack[].class) {
// Parse to itemstack array
ItemStack[] items = new ItemStack[4];
String[] split = valueString.split(",");
if (split.length == 4) {
for (int a = 0; a < 4; a++) {
try {
items[a] = parseToItemstack(split[a]);
} catch (Exception ex) {
throw parseToException("item ID,ID,ID,ID" + ChatColor.RED + " or " + ChatColor.GREEN
+ "ID:Data,ID:Data,ID:Data,ID:Data combo", valueString, methodName);
}
}
} else {
throw parseToException("item ID,ID,ID,ID" + ChatColor.RED + " or " + ChatColor.GREEN
+ "ID:Data,ID:Data,ID:Data,ID:Data combo", valueString, methodName);
}
value = items;
} else if (param.getSimpleName().equals("Color")) {
// Parse to horse color
value = callValueOf(param, valueString, methodName, "a horse color");
} else if (param.getSimpleName().equals("Style")) {
// Parse to horse style
value = callValueOf(param, valueString, methodName, "a horse style");
} else if (param.getSimpleName().equals("Profession")) {
// Parse to villager profession
value = callValueOf(param, valueString, methodName, "a villager profession");
} else if (param.getSimpleName().equals("Art")) {
// Parse to art type
value = callValueOf(param, valueString, methodName, "a painting art");
} else if (param.getSimpleName().equals("Type")) {
// Parse to ocelot type
value = callValueOf(param, valueString, methodName, "a ocelot type");
} else if (param == PotionEffectType.class) {
// Parse to potion effect
try {
PotionEffectType potionType = PotionEffectType.getByName(valueString.toUpperCase());
if (potionType == null && isNumeric(valueString)) {
potionType = PotionEffectType.getById(Integer.parseInt(valueString));
}
if (potionType == null)
throw new DisguiseParseException();
value = potionType;
} catch (Exception ex) {
throw parseToException("a potioneffect type", valueString, methodName);
}
} else if (param == int[].class) {
String[] split = valueString.split(",");
int[] values = new int[split.length];
for (int b = 0; b < values.length; b++) {
try {
values[b] = Integer.parseInt(split[b]);
} catch (NumberFormatException ex) {
throw parseToException("Number,Number,Number...", valueString, methodName);
}
}
value = values;
} else if (param == BlockFace.class) {
try {
BlockFace face = BlockFace.valueOf(valueString.toUpperCase());
if (face.ordinal() > 4)
throw new DisguiseParseException();
value = face;
} catch (Exception ex) {
throw parseToException("a direction (north, east, south, west, up)", valueString, methodName);
}
} else if (param == RabbitType.class) {
try {
for (RabbitType type : RabbitType.values()) {
if (type.name().replace("_", "")
.equalsIgnoreCase(valueString.replace("_", "").replace(" ", ""))) {
value = type;
break;
}
}
if (value == null) {
throw new Exception();
}
} catch (Exception ex) {
throw parseToException("rabbit type (white, brown, patches...)", valueString, methodName);
}
}
}
if (value == null && boolean.class == param) {
if (valueString == null) {
value = true;
i--;
} else if (valueString.equalsIgnoreCase("true")) {
value = true;
} else if (valueString.equalsIgnoreCase("false")) {
value = false;
} else {
if (getMethod(methods, valueString, 0) == null) {
throw parseToException("true/false", valueString, methodName);
} else {
value = true;
i--;
}
}
}
if (value != null) {
break;
}
} catch (DisguiseParseException ex) {
storedEx = ex;
methodToUse = null;
} catch (Exception ex) {
ex.printStackTrace();
methodToUse = null;
}
}
if (methodToUse == null) {
if (storedEx != null) {
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);
else
methodToUse.invoke(disguise, value);
}
// Alright. We've constructed our disguise.
return disguise;
}
private Entry<Method, Integer> getMethod(Method[] methods, String methodName, int toStart) {
for (int i = toStart; i < methods.length; i++) {
Method method = methods[i];
if (!method.getName().startsWith("get") && method.getName().equalsIgnoreCase(methodName)
&& method.getAnnotation(Deprecated.class) == null && method.getParameterTypes().length == 1) {
return new HashMap.SimpleEntry(method, ++i);
}
}
return null;
}
private Object callValueOf(Class<?> param, String valueString, String methodName, String description)
throws DisguiseParseException {
Object value;
try {
value = param.getMethod("valueOf", String.class).invoke(null, valueString.toUpperCase());
} catch (Exception ex) {
throw parseToException(description, valueString, methodName);
}
return value;
}
private boolean passesCheck(HashMap<ArrayList<String>, Boolean> map1, ArrayList<String> usedOptions) {
boolean hasPermission = false;
for (ArrayList<String> list : map1.keySet()) {
boolean myPerms = true;
for (String option : usedOptions) {
if (!(map1.get(list) && list.contains("*")) && (list.contains(option) != map1.get(list))) {
myPerms = false;
break;
}
}
if (myPerms) {
hasPermission = true;
}
}
return hasPermission;
}
private void doCheck(HashMap<ArrayList<String>, Boolean> optionPermissions, ArrayList<String> usedOptions)
throws DisguiseParseException {
if (!passesCheck(optionPermissions, usedOptions)) {
throw new DisguiseParseException(ChatColor.RED + "You do not have the permission to use the option "
+ usedOptions.get(usedOptions.size() - 1));
}
}
private DisguiseParseException parseToException(String expectedValue, String receivedInstead, String methodName) {
return new DisguiseParseException(ChatColor.RED + "Expected " + ChatColor.GREEN + expectedValue + ChatColor.RED
+ ", received " + ChatColor.GREEN + receivedInstead + ChatColor.RED + " instead for " + ChatColor.GREEN
+ methodName);
}
private ItemStack parseToItemstack(String string) throws Exception {
String[] split = string.split(":", -1);
if (isNumeric(split[0])) {
int itemId = Integer.parseInt(split[0]);
short itemDura = 0;
if (split.length > 1) {
if (isNumeric(split[1])) {
itemDura = Short.parseShort(split[1]);
} else {
throw parseToException("item ID:Durability combo", string, "%s");
}
}
return new ItemStack(itemId, 1, itemDura);
} else {
if (split.length == 1) {
throw parseToException("item ID", string, "%s");
} else {
throw parseToException("item ID:Durability combo", string, "%s");
}
}
}
protected abstract void sendCommandUsage(CommandSender sender, HashMap<DisguiseType, HashMap<ArrayList<String>, Boolean>> map);
}

View File

@@ -1,70 +0,0 @@
package me.libraryaddict.disguise.utilities;
import org.bukkit.entity.Entity;
import java.net.URL;
import java.net.URLDecoder;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* User: Austin Date: 4/22/13 Time: 11:47 PM (c) lazertester
*/
// Code for this taken and slightly modified from
// https://github.com/ddopson/java-class-enumerator
public class ClassGetter {
public static ArrayList<Class<?>> getClassesForPackage(String pkgname) {
ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
// String relPath = pkgname.replace('.', '/');
// Get a File object for the package
CodeSource src = Entity.class.getProtectionDomain().getCodeSource();
if (src != null) {
URL resource = src.getLocation();
resource.getPath();
processJarfile(resource, pkgname, classes);
}
return classes;
}
private static Class<?> loadClass(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Unexpected ClassNotFoundException loading class '" + className + "'");
} catch (NoClassDefFoundError e) {
return null;
}
}
private static void processJarfile(URL resource, String pkgname, ArrayList<Class<?>> classes) {
try {
String relPath = pkgname.replace('.', '/');
String resPath = URLDecoder.decode(resource.getPath(), "UTF-8");
String jarPath = resPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
JarFile jarFile = new JarFile(jarPath);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
String className = null;
if (entryName.endsWith(".class") && entryName.startsWith(relPath)
&& entryName.length() > (relPath.length() + "/".length())) {
className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
}
if (className != null) {
Class<?> c = loadClass(className);
if (c != null)
classes.add(c);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

View File

@@ -1,231 +0,0 @@
package me.libraryaddict.disguise.utilities;
import java.util.HashMap;
import java.util.HashSet;
import me.libraryaddict.disguise.utilities.ReflectionManager.LibVersion;
import org.bukkit.Sound;
/**
* Only living disguises go in here!
*/
public enum DisguiseSound {
ARROW(null, null, null, null, "random.bowhit"),
BAT("mob.bat.hurt", null, "mob.bat.death", "mob.bat.idle", "damage.fallsmall", "mob.bat.loop", "damage.fallbig",
"mob.bat.takeoff"),
BLAZE("mob.blaze.hit", null, "mob.blaze.death", "mob.blaze.breathe", "damage.fallsmall", "damage.fallbig"),
CAVE_SPIDER("mob.spider.say", "mob.spider.step", "mob.spider.death", "mob.spider.say"),
CHICKEN("mob.chicken.hurt", "mob.chicken.step", "mob.chicken.hurt", "mob.chicken.say", "damage.fallsmall",
"mob.chicken.plop", "damage.fallbig"),
COW("mob.cow.hurt", "mob.cow.step", "mob.cow.hurt", "mob.cow.say"),
CREEPER("mob.creeper.say", "step.grass", "mob.creeper.death", null),
DONKEY("mob.horse.donkey.hit", "step.grass", "mob.horse.donkey.death", "mob.horse.donkey.idle", "mob.horse.gallop",
"mob.horse.leather", "mob.horse.donkey.angry", "mob.horse.wood", "mob.horse.armor", "mob.horse.soft",
"mob.horse.land", "mob.horse.jump", "mob.horse.angry"),
ELDER_GUARDIAN("mob.guardian.elder.hit", null, "mob.guardian.elder.death", "mob.guardian.elder.death"),
ENDER_DRAGON("mob.enderdragon.hit", null, "mob.enderdragon.end", "mob.enderdragon.growl", "damage.fallsmall",
"mob.enderdragon.wings", "damage.fallbig"),
ENDERMAN("mob.endermen.hit", "step.grass", "mob.endermen.death", "mob.endermen.idle", "mob.endermen.scream",
"mob.endermen.portal", "mob.endermen.stare"),
ENDERMITE("mob.silverfish.hit", "mob.silverfish.step", "mob.silverfish.kill", "mob.silverfish.say"),
GHAST("mob.ghast.scream", null, "mob.ghast.death", "mob.ghast.moan", "damage.fallsmall", "mob.ghast.fireball",
"damage.fallbig", "mob.ghast.affectionate_scream", "mob.ghast.charge"),
GIANT("damage.hit", "step.grass", null, null),
GUARDIAN("mob.guardian.hit", null, "mob.guardian.death", "mob.guardian.death"),
HORSE("mob.horse.hit", "step.grass", "mob.horse.death", "mob.horse.idle", "mob.horse.gallop", "mob.horse.leather",
"mob.horse.wood", "mob.horse.armor", "mob.horse.soft", "mob.horse.land", "mob.horse.jump", "mob.horse.angry",
"mob.horse.leather"),
IRON_GOLEM("mob.irongolem.hit", "mob.irongolem.walk", "mob.irongolem.death", "mob.irongolem.throw"),
MAGMA_CUBE("mob.slime.attack", "mob.slime.big", null, null, "mob.slime.small"),
MULE("mob.horse.donkey.hit", "step.grass", "mob.horse.donkey.death", "mob.horse.donkey.idle"),
MUSHROOM_COW("mob.cow.hurt", "mob.cow.step", "mob.cow.hurt", "mob.cow.say"),
OCELOT("mob.cat.hitt", "step.grass", "mob.cat.hitt", "mob.cat.meow", "mob.cat.purreow", "mob.cat.purr"),
PIG("mob.pig.say", "mob.pig.step", "mob.pig.death", "mob.pig.say"),
PIG_ZOMBIE("mob.zombiepig.zpighurt", null, "mob.zombiepig.zpigdeath", "mob.zombiepig.zpig", "mob.zombiepig.zpigangry"),
PLAYER(LibVersion.is1_7() ? "game.player.hurt" : "damage.hit", "step.grass", LibVersion.is1_7() ? "game.player.hurt"
: "damage.hit", null),
RABBIT("mob.rabbit.hurt", "mob.rabbit.hop", "mob.rabbit.death", "mob.rabbit.idle"),
SHEEP("mob.sheep.say", "mob.sheep.step", null, "mob.sheep.say", "mob.sheep.shear"),
SILVERFISH("mob.silverfish.hit", "mob.silverfish.step", "mob.silverfish.kill", "mob.silverfish.say"),
SKELETON("mob.skeleton.hurt", "mob.skeleton.step", "mob.skeleton.death", "mob.skeleton.say"),
SKELETON_HORSE("mob.horse.skeleton.hit", "step.grass", "mob.horse.skeleton.death", "mob.horse.skeleton.idle",
"mob.horse.gallop", "mob.horse.leather", "mob.horse.wood", "mob.horse.armor", "mob.horse.soft", "mob.horse.land",
"mob.horse.jump", "mob.horse.angry"),
SLIME("mob.slime.attack", "mob.slime.big", null, null, "mob.slime.small"),
SNOWMAN(),
SPIDER("mob.spider.say", "mob.spider.step", "mob.spider.death", "mob.spider.say"),
SQUID(),
UNDEAD_HORSE("mob.horse.zombie.hit", "step.grass", "mob.horse.zombie.death", "mob.horse.zombie.idle", "mob.horse.gallop",
"mob.horse.leather", "mob.horse.wood", "mob.horse.armor", "mob.horse.soft", "mob.horse.land", "mob.horse.jump",
"mob.horse.angry"),
VILLAGER("mob.villager.hit", null, "mob.villager.death", "mob.villager.idle", "mob.villager.haggle", "mob.villager.no",
"mob.villager.yes"),
WITCH("mob.witch.hurt", null, "mob.witch.death", "mob.witch.idle"),
WITHER("mob.wither.hurt", null, "mob.wither.death", "mob.wither.idle", "damage.fallsmall", "mob.wither.spawn",
"damage.fallbig", "mob.wither.shoot"),
WITHER_SKELETON("mob.skeleton.hurt", "mob.skeleton.step", "mob.skeleton.death", "mob.skeleton.say"),
WOLF("mob.wolf.hurt", "mob.wolf.step", "mob.wolf.death", "mob.wolf.bark", "mob.wolf.panting", "mob.wolf.whine",
"mob.wolf.howl", "mob.wolf.growl", "mob.wolf.shake"),
ZOMBIE("mob.zombie.hurt", "mob.zombie.step", "mob.zombie.death", "mob.zombie.say", "mob.zombie.infect",
"mob.zombie.woodbreak", "mob.zombie.metal", "mob.zombie.wood"),
ZOMBIE_VILLAGER("mob.zombie.hurt", "mob.zombie.step", "mob.zombie.death", "mob.zombie.say", "mob.zombie.infect",
"mob.zombie.woodbreak", "mob.zombie.metal", "mob.zombie.wood");
public enum SoundType {
CANCEL, DEATH, HURT, IDLE, STEP;
}
public static DisguiseSound getType(String name) {
try {
return valueOf(name);
} catch (Exception ex) {
return null;
}
}
private HashSet<String> cancelSounds = new HashSet<String>();
private float damageSoundVolume = 1F;
private HashMap<SoundType, String> disguiseSounds = new HashMap<SoundType, String>();
private DisguiseSound(Object... sounds) {
for (int i = 0; i < sounds.length; i++) {
Object obj = sounds[i];
String s;
if (obj == null)
continue;
else if (obj instanceof String) {
s = (String) obj;
} else if (obj instanceof Sound) {
s = ReflectionManager.getCraftSound((Sound) obj);
System.out.print("Warning! The sound " + obj + " needs to be converted to a string");
} else {
throw new RuntimeException("Was given a unknown object " + obj);
}
switch (i) {
case 0:
disguiseSounds.put(SoundType.HURT, s);
break;
case 1:
disguiseSounds.put(SoundType.STEP, s);
break;
case 2:
disguiseSounds.put(SoundType.DEATH, s);
break;
case 3:
disguiseSounds.put(SoundType.IDLE, s);
break;
default:
cancelSounds.add(s);
break;
}
}
}
public float getDamageAndIdleSoundVolume() {
return damageSoundVolume;
}
public String getSound(SoundType type) {
if (type == null || !disguiseSounds.containsKey(type))
return null;
return disguiseSounds.get(type);
}
public HashSet<String> getSoundsToCancel() {
return cancelSounds;
}
/**
* Used to check if this sound name is owned by this disguise sound.
*/
public SoundType getType(String sound, boolean ignoreDamage) {
if (isCancelSound(sound))
return SoundType.CANCEL;
if (disguiseSounds.containsKey(SoundType.STEP) && disguiseSounds.get(SoundType.STEP).startsWith("step.")
&& sound.startsWith("step."))
return SoundType.STEP;
for (SoundType type : SoundType.values()) {
if (!disguiseSounds.containsKey(type) || type == SoundType.DEATH || (ignoreDamage && type == SoundType.HURT))
continue;
String s = disguiseSounds.get(type);
if (s != null) {
if (s.equals(sound))
return type;
}
}
return null;
}
public boolean isCancelSound(String sound) {
return getSoundsToCancel().contains(sound);
}
public void removeSound(SoundType type, Sound sound) {
removeSound(type, ReflectionManager.getCraftSound(sound));
}
public void removeSound(SoundType type, String sound) {
if (type == SoundType.CANCEL)
cancelSounds.remove(sound);
else {
disguiseSounds.remove(type);
}
}
public void setDamageAndIdleSoundVolume(float strength) {
this.damageSoundVolume = strength;
}
public void setSound(SoundType type, Sound sound) {
setSound(type, ReflectionManager.getCraftSound(sound));
}
public void setSound(SoundType type, String sound) {
if (type == SoundType.CANCEL)
cancelSounds.add(sound);
else {
disguiseSounds.put(type, sound);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,145 +0,0 @@
package me.libraryaddict.disguise.utilities;
import java.util.HashMap;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
public class DisguiseValues {
private static HashMap<DisguiseType, DisguiseValues> values = new HashMap<DisguiseType, DisguiseValues>();
public static DisguiseValues getDisguiseValues(DisguiseType type) {
switch (type) {
case DONKEY:
case MULE:
case UNDEAD_HORSE:
case SKELETON_HORSE:
type = DisguiseType.HORSE;
break;
case MINECART_CHEST:
case MINECART_COMMAND:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_TNT:
case MINECART_MOB_SPAWNER:
type = DisguiseType.MINECART;
break;
case WITHER_SKELETON:
type = DisguiseType.SKELETON;
break;
case ZOMBIE_VILLAGER:
type = DisguiseType.ZOMBIE;
break;
default:
break;
}
return values.get(type);
}
public static HashMap<Integer, Object> getMetaValues(DisguiseType type) {
return getDisguiseValues(type).getMetaValues();
}
public static Class getNmsEntityClass(DisguiseType type) {
return getDisguiseValues(type).getNmsEntityClass();
}
private FakeBoundingBox adultBox;
private FakeBoundingBox babyBox;
private float[] entitySize;
private int enumEntitySize;
private double maxHealth;
private HashMap<Integer, Object> metaValues = new HashMap<Integer, Object>();
private Class nmsEntityClass;
public DisguiseValues(DisguiseType type, Class classType, int entitySize, double maxHealth) {
values.put(type, this);
enumEntitySize = entitySize;
nmsEntityClass = classType;
this.maxHealth = maxHealth;
}
public FakeBoundingBox getAdultBox() {
return adultBox;
}
public FakeBoundingBox getBabyBox() {
return babyBox;
}
public float[] getEntitySize() {
return entitySize;
}
public int getEntitySize(double paramDouble) {
double d = paramDouble - (((int) Math.floor(paramDouble)) + 0.5D);
switch (enumEntitySize) {
case 1:
if (d < 0.0D ? d < -0.3125D : d < 0.3125D) {
return (int) Math.ceil(paramDouble * 32.0D);
}
return (int) Math.floor(paramDouble * 32.0D);
case 2:
if (d < 0.0D ? d < -0.3125D : d < 0.3125D) {
return (int) Math.floor(paramDouble * 32.0D);
}
return (int) Math.ceil(paramDouble * 32.0D);
case 3:
if (d > 0.0D) {
return (int) Math.floor(paramDouble * 32.0D);
}
return (int) Math.ceil(paramDouble * 32.0D);
case 4:
if (d < 0.0D ? d < -0.1875D : d < 0.1875D) {
return (int) Math.ceil(paramDouble * 32.0D);
}
return (int) Math.floor(paramDouble * 32.0D);
case 5:
if (d < 0.0D ? d < -0.1875D : d < 0.1875D) {
return (int) Math.floor(paramDouble * 32.0D);
}
return (int) Math.ceil(paramDouble * 32.0D);
default:
break;
}
if (d > 0.0D) {
return (int) Math.ceil(paramDouble * 32.0D);
}
return (int) Math.floor(paramDouble * 32.0D);
}
public double getMaxHealth() {
return maxHealth;
}
public HashMap<Integer, Object> getMetaValues() {
return metaValues;
}
public Class getNmsEntityClass() {
return nmsEntityClass;
}
public void setAdultBox(FakeBoundingBox newBox) {
adultBox = newBox;
}
public void setBabyBox(FakeBoundingBox newBox) {
babyBox = newBox;
}
public void setEntitySize(float[] size) {
this.entitySize = size;
}
public void setMetaValue(int no, Object value) {
metaValues.put(no, value);
}
}

View File

@@ -1,26 +0,0 @@
package me.libraryaddict.disguise.utilities;
public class FakeBoundingBox {
private double xMod;
private double yMod;
private double zMod;
public FakeBoundingBox(double xMod, double yMod, double zMod) {
this.xMod = xMod;
this.yMod = yMod;
this.zMod = zMod;
}
public double getX() {
return xMod / 2;
}
public double getY() {
return yMod;
}
public double getZ() {
return zMod / 2;
}
}

View File

@@ -1,8 +0,0 @@
package me.libraryaddict.disguise.utilities;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
public interface LibsProfileLookup {
public void onLookup(WrappedGameProfile gameProfile);
}

View File

@@ -1,24 +0,0 @@
package me.libraryaddict.disguise.utilities;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import net.minecraft.util.com.mojang.authlib.GameProfile;
import net.minecraft.util.com.mojang.authlib.ProfileLookupCallback;
public class LibsProfileLookupCaller implements ProfileLookupCallback {
private WrappedGameProfile gameProfile;
public WrappedGameProfile getGameProfile() {
return gameProfile;
}
@Override
public void onProfileLookupFailed(GameProfile gameProfile, Exception arg1) {
}
@Override
public void onProfileLookupSucceeded(GameProfile profile) {
gameProfile = WrappedGameProfile.fromHandle(profile);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,662 +0,0 @@
package me.libraryaddict.disguise.utilities;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.collect.ImmutableMap;
import org.bukkit.Art;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
public class ReflectionManager {
public enum LibVersion {
V1_6, V1_7, V1_7_10, V1_7_6, V1_8;
private static LibVersion currentVersion;
static {
String mcVersion = Bukkit.getVersion().split("MC: ")[1].replace(")", "");
if (mcVersion.startsWith("1.")) {
if (mcVersion.compareTo("1.7") < 0) {
currentVersion = LibVersion.V1_6;
} else if (mcVersion.startsWith("1.7")) {
if (mcVersion.equals("1.7.10")) {
currentVersion = LibVersion.V1_7_10;
} else {
currentVersion = mcVersion.compareTo("1.7.6") < 0 ? LibVersion.V1_7 : LibVersion.V1_7_6;
}
} else {
currentVersion = V1_8;
}
}
}
public static LibVersion getGameVersion() {
return currentVersion;
}
public static boolean is1_6() {
return getGameVersion() == V1_6;
}
public static boolean is1_7() {
return getGameVersion() == V1_7 || is1_7_6();
}
public static boolean is1_7_10() {
return getGameVersion() == V1_7_10 || is1_8();
}
public static boolean is1_7_6() {
return getGameVersion() == V1_7_6 || is1_7_10();
}
public static boolean is1_8() {
return getGameVersion() == V1_8;
}
}
private static final String bukkitVersion = Bukkit.getServer().getClass().getName().split("\\.")[3];
private static final Class<?> craftItemClass;
private static Method damageAndIdleSoundMethod;
private static final Field entitiesField;
/**
* Map of mc-dev simple class name to fully qualified Forge class name.
*/
private static Map<String, String> ForgeClassMappings;
/**
* Map of Forge fully qualified class names to a map from mc-dev field names to Forge field names.
*/
private static Map<String, Map<String, String>> ForgeFieldMappings;
/**
* Map of Forge fully qualified class names to a map from mc-dev method names to a map from method signatures to Forge method
* names.
*/
private static Map<String, Map<String, Map<String, String>>> ForgeMethodMappings;
private static final Method ihmGet;
private static HashMap<String, Boolean> is1_8 = new HashMap<String, Boolean>();
private static final boolean isForge = Bukkit.getServer().getName().contains("Cauldron")
|| Bukkit.getServer().getName().contains("MCPC-Plus");
private static final Field pingField;
private static Map<Class<?>, String> primitiveTypes;
private static final Field trackerField;
/*
* This portion of code is originally Copyright (C) 2014-2014 Kane York.
*
* In addition to the implicit license granted to libraryaddict to redistribuite the code, the
* code is also licensed to the public under the BSD 2-clause license.
*
* The publicly licensed version may be viewed here: https://gist.github.com/riking/2f330f831c30e2276df7
*/
static {
final String nameseg_class = "a-zA-Z0-9$_";
final String fqn_class = nameseg_class + "/";
primitiveTypes = ImmutableMap.<Class<?>, String> builder().put(boolean.class, "Z").put(byte.class, "B")
.put(char.class, "C").put(short.class, "S").put(int.class, "I").put(long.class, "J").put(float.class, "F")
.put(double.class, "D").put(void.class, "V").build();
if (isForge) {
// Initialize the maps by reading the srg file
ForgeClassMappings = new HashMap<String, String>();
ForgeFieldMappings = new HashMap<String, Map<String, String>>();
ForgeMethodMappings = new HashMap<String, Map<String, Map<String, String>>>();
try {
InputStream stream = Class.forName("net.minecraftforge.common.MinecraftForge").getClassLoader()
.getResourceAsStream("mappings/" + getBukkitVersion() + "/cb2numpkg.srg");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
// 1: cb-simpleName
// 2: forge-fullName (Needs dir2fqn())
Pattern classPattern = Pattern.compile("^CL: net/minecraft/server/([" + nameseg_class + "]+) ([" + fqn_class
+ "]+)$");
// 1: cb-simpleName
// 2: cb-fieldName
// 3: forge-fullName (Needs dir2fqn())
// 4: forge-fieldName
Pattern fieldPattern = Pattern.compile("^FD: net/minecraft/server/([" + nameseg_class + "]+)/([" + nameseg_class
+ "]+) ([" + fqn_class + "]+)/([" + nameseg_class + "]+)$");
// 1: cb-simpleName
// 2: cb-methodName
// 3: cb-signature-args
// 4: cb-signature-ret
// 5: forge-fullName (Needs dir2fqn())
// 6: forge-methodName
// 7: forge-signature-args
// 8: forge-signature-ret
Pattern methodPattern = Pattern.compile("^MD: net/minecraft/server/([" + fqn_class + "]+)/([" + nameseg_class
+ "]+) \\(([;\\[" + fqn_class + "]*)\\)([;\\[" + fqn_class + "]+) " + "([" + fqn_class + "]+)/(["
+ nameseg_class + "]+) \\(([;\\[" + fqn_class + "]*)\\)([;\\[" + fqn_class + "]+)$");
String line;
while ((line = reader.readLine()) != null) {
Matcher classMatcher = classPattern.matcher(line);
if (classMatcher.matches()) {
// by CB class name
ForgeClassMappings.put(classMatcher.group(1), dir2fqn(classMatcher.group(2)));
continue;
}
Matcher fieldMatcher = fieldPattern.matcher(line);
if (fieldMatcher.matches()) {
// by CB class name
Map<String, String> innerMap = ForgeFieldMappings.get(dir2fqn(fieldMatcher.group(3)));
if (innerMap == null) {
innerMap = new HashMap<String, String>();
ForgeFieldMappings.put(dir2fqn(fieldMatcher.group(3)), innerMap);
}
// by CB field name to Forge field name
innerMap.put(fieldMatcher.group(2), fieldMatcher.group(4));
continue;
}
Matcher methodMatcher = methodPattern.matcher(line);
if (methodMatcher.matches()) {
// get by CB class name
Map<String, Map<String, String>> middleMap = ForgeMethodMappings.get(dir2fqn(methodMatcher.group(5)));
if (middleMap == null) {
middleMap = new HashMap<String, Map<String, String>>();
ForgeMethodMappings.put(dir2fqn(methodMatcher.group(5)), middleMap);
}
// get by CB method name
Map<String, String> innerMap = middleMap.get(methodMatcher.group(2));
if (innerMap == null) {
innerMap = new HashMap<String, String>();
middleMap.put(methodMatcher.group(2), innerMap);
}
// store the parameter strings
innerMap.put(methodMatcher.group(3), methodMatcher.group(6));
innerMap.put(methodMatcher.group(7), methodMatcher.group(6));
}
}
System.out.println("[LibsDisguises] Loaded in Cauldron/Forge mode");
System.out.println("[LibsDisguises] Loaded " + ForgeClassMappings.size() + " Cauldron class mappings");
System.out.println("[LibsDisguises] Loaded " + ForgeFieldMappings.size() + " Cauldron field mappings");
System.out.println("[LibsDisguises] Loaded " + ForgeMethodMappings.size() + " Cauldron method mappings");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.err
.println("Warning: Running on Cauldron server, but couldn't load mappings file. LibsDisguises will likely crash!");
} catch (IOException e) {
e.printStackTrace();
System.err
.println("Warning: Running on Cauldron server, but couldn't load mappings file. LibsDisguises will likely crash!");
}
}
}
static {
for (Method method : getNmsClass("EntityLiving").getDeclaredMethods()) {
try {
if (method.getReturnType() == float.class && Modifier.isProtected(method.getModifiers())
&& method.getParameterTypes().length == 0) {
Object entity = createEntityInstance("Cow");
method.setAccessible(true);
float value = (Float) method.invoke(entity);
if (value == 0.4F) {
damageAndIdleSoundMethod = method;
break;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
craftItemClass = getCraftClass("inventory.CraftItemStack");
pingField = getNmsField("EntityPlayer", "ping");
trackerField = getNmsField("WorldServer", "tracker");
entitiesField = getNmsField("EntityTracker", "trackedEntities");
ihmGet = getNmsMethod("IntHashMap", "get", int.class);
}
public static Object createEntityInstance(String entityName) {
try {
Class<?> entityClass = getNmsClass("Entity" + entityName);
Object entityObject;
Object world = getWorld(Bukkit.getWorlds().get(0));
if (entityName.equals("Player")) {
Object minecraftServer = getNmsMethod("MinecraftServer", "getServer").invoke(null);
Object playerinteractmanager = getNmsClass("PlayerInteractManager").getConstructor(getNmsClass("World"))
.newInstance(world);
if (LibVersion.is1_7()) {
WrappedGameProfile gameProfile = getGameProfile(null, "LibsDisguises");
entityObject = entityClass.getConstructor(getNmsClass("MinecraftServer"), getNmsClass("WorldServer"),
gameProfile.getHandleType(), playerinteractmanager.getClass()).newInstance(minecraftServer, world,
gameProfile.getHandle(), playerinteractmanager);
} else {
entityObject = entityClass.getConstructor(getNmsClass("MinecraftServer"), getNmsClass("World"), String.class,
playerinteractmanager.getClass()).newInstance(minecraftServer, world, "LibsDisguises",
playerinteractmanager);
}
} else if (LibVersion.is1_8() && entityName.equals("EnderPearl")) {
entityObject = entityClass.getConstructor(getNmsClass("World"), getNmsClass("EntityLiving"))
.newInstance(world, createEntityInstance("Sheep"));
} else {
entityObject = entityClass.getConstructor(getNmsClass("World")).newInstance(world);
}
return entityObject;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String dir2fqn(String s) {
return s.replaceAll("/", ".");
}
public static FakeBoundingBox getBoundingBox(Entity entity) {
try {
Object boundingBox;
if (LibVersion.is1_8()) {
boundingBox = getNmsMethod("Entity", "getBoundingBox").invoke(getNmsEntity(entity));
} else {
boundingBox = getNmsField("Entity", "boundingBox").get(getNmsEntity(entity));
}
double x = 0, y = 0, z = 0;
int stage = 0;
for (Field field : boundingBox.getClass().getFields()) {
if (field.getType().getSimpleName().equals("double")) {
stage++;
switch (stage) {
case 1:
x -= field.getDouble(boundingBox);
break;
case 2:
y -= field.getDouble(boundingBox);
break;
case 3:
z -= field.getDouble(boundingBox);
break;
case 4:
x += field.getDouble(boundingBox);
break;
case 5:
y += field.getDouble(boundingBox);
break;
case 6:
z += field.getDouble(boundingBox);
break;
default:
throw new Exception("Error while setting the bounding box, more doubles than I thought??");
}
}
}
return new FakeBoundingBox(x, y, z);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Entity getBukkitEntity(Object nmsEntity) {
try {
return (Entity) getNmsMethod("Entity", "getBukkitEntity").invoke(nmsEntity);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static ItemStack getBukkitItem(Object nmsItem) {
try {
return (ItemStack) craftItemClass.getMethod("asBukkitCopy", getNmsClass("ItemStack")).invoke(null, nmsItem);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String getBukkitVersion() {
return bukkitVersion;
}
public static Class<?> getCraftClass(String className) {
try {
return Class.forName("org.bukkit.craftbukkit." + getBukkitVersion() + "." + className);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String getCraftSound(Sound sound) {
try {
return (String) getCraftClass("CraftSound").getMethod("getSound", Sound.class).invoke(null, sound);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Object getEntityTrackerEntry(Entity target) throws Exception {
Object world = getWorld(target.getWorld());
Object tracker = trackerField.get(world);
Object trackedEntities = entitiesField.get(tracker);
return ihmGet.invoke(trackedEntities, target.getEntityId());
}
public static String getEnumArt(Art art) {
try {
Object enumArt = getCraftClass("CraftArt").getMethod("BukkitToNotch", Art.class).invoke(null, art);
for (Field field : enumArt.getClass().getFields()) {
if (field.getType() == String.class) {
return (String) field.get(enumArt);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static WrappedGameProfile getGameProfile(Player player) {
if (LibVersion.is1_7() || LibVersion.is1_8()) {
return WrappedGameProfile.fromPlayer(player);
}
return null;
}
public static WrappedGameProfile getGameProfile(UUID uuid, String playerName) {
try {
return new WrappedGameProfile(uuid != null ? uuid : UUID.randomUUID(), playerName);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static WrappedGameProfile getGameProfileWithThisSkin(UUID uuid, String playerName, WrappedGameProfile profileWithSkin) {
try {
WrappedGameProfile gameProfile = new WrappedGameProfile(uuid != null ? uuid : UUID.randomUUID(), playerName);
if (LibVersion.is1_7_6()) {
gameProfile.getProperties().putAll(profileWithSkin.getProperties());
}
return gameProfile;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Class getNmsClass(String className) {
if (isForge) {
String forgeName = ForgeClassMappings.get(className);
if (forgeName != null) {
try {
return Class.forName(forgeName);
} catch (ClassNotFoundException ignored) {
}
} else {
// Throw, because the default cannot possibly work
throw new RuntimeException("Missing Forge mapping for " + className);
}
}
try {
return Class.forName("net.minecraft.server." + getBukkitVersion() + "." + className);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Object getNmsEntity(Entity entity) {
try {
return getCraftClass("entity.CraftEntity").getMethod("getHandle").invoke(entity);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Field getNmsField(Class clazz, String fieldName) {
if (isForge) {
try {
return clazz.getField(ForgeFieldMappings.get(clazz.getName()).get(fieldName));
} catch (NoSuchFieldException ex) {
ex.printStackTrace();
} catch (NullPointerException ignored) {
}
}
try {
return clazz.getField(fieldName);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return null;
}
public static Field getNmsField(String className, String fieldName) {
return getNmsField(getNmsClass(className), fieldName);
}
public static Object getNmsItem(ItemStack itemstack) {
try {
return craftItemClass.getMethod("asNMSCopy", ItemStack.class).invoke(null, itemstack);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Method getNmsMethod(Class<?> clazz, String methodName, Class<?>... parameters) {
if (isForge) {
try {
Map<String, String> innerMap = ForgeMethodMappings.get(clazz.getName()).get(methodName);
StringBuilder sb = new StringBuilder();
for (Class<?> cl : parameters) {
sb.append(methodSignaturePart(cl));
}
return clazz.getMethod(innerMap.get(sb.toString()), parameters);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (NullPointerException ignored) {
}
}
try {
return clazz.getMethod(methodName, parameters);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
public static Method getNmsMethod(String className, String methodName, Class<?>... parameters) {
return getNmsMethod(getNmsClass(className), methodName, parameters);
}
public static double getPing(Player player) {
try {
return (double) pingField.getInt(ReflectionManager.getNmsEntity(player));
} catch (Exception ex) {
ex.printStackTrace();
}
return 0D;
}
public static float[] getSize(Entity entity) {
try {
float length = getNmsField("Entity", "length").getFloat(getNmsEntity(entity));
float width = getNmsField("Entity", "width").getFloat(getNmsEntity(entity));
float height;
if (LibVersion.is1_8()) {
height = (Float) getNmsMethod("Entity", "getHeadHeight").invoke(getNmsEntity(entity));
} else {
height = getNmsField("Entity", "height").getFloat(getNmsEntity(entity));
}
return new float[] { length, width, height };
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static WrappedGameProfile getSkullBlob(WrappedGameProfile gameProfile) {
try {
Object minecraftServer = getNmsMethod("MinecraftServer", "getServer").invoke(null);
for (Method method : getNmsClass("MinecraftServer").getMethods()) {
if (method.getReturnType().getSimpleName().equals("MinecraftSessionService")) {
Object session = method.invoke(minecraftServer);
return WrappedGameProfile.fromHandle(session.getClass()
.getMethod("fillProfileProperties", gameProfile.getHandleType(), boolean.class)
.invoke(session, gameProfile.getHandle(), true));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Float getSoundModifier(Object entity) {
try {
damageAndIdleSoundMethod.setAccessible(true);
return (Float) damageAndIdleSoundMethod.invoke(entity);
} catch (Exception ex) {
}
return null;
}
public static Object getWorld(World world) {
try {
return getCraftClass("CraftWorld").getMethod("getHandle").invoke(world);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static WrappedGameProfile grabProfileAddUUID(String playername) {
try {
Object minecraftServer = getNmsMethod("MinecraftServer", "getServer").invoke(null);
for (Method method : getNmsClass("MinecraftServer").getMethods()) {
if (method.getReturnType().getSimpleName().equals("GameProfileRepository")) {
Object profileRepo = method.invoke(minecraftServer);
Object agent = Class.forName("net.minecraft.util.com.mojang.authlib.Agent").getField("MINECRAFT").get(null);
LibsProfileLookupCaller callback = new LibsProfileLookupCaller();
profileRepo
.getClass()
.getMethod("findProfilesByNames", String[].class, agent.getClass(),
Class.forName("net.minecraft.util.com.mojang.authlib.ProfileLookupCallback"))
.invoke(profileRepo, new String[] { playername }, agent, callback);
if (callback.getGameProfile() != null) {
return callback.getGameProfile();
}
return getGameProfile(null, playername);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static boolean is1_8(Player player) {
if (LibVersion.is1_8()) {
if (is1_8.containsKey(player.getName())) {
return is1_8.get(player.getName());
}
try {
Object nmsEntity = getNmsEntity(player);
Object connection = getNmsField(nmsEntity.getClass(), "playerConnection").get(nmsEntity);
Field networkManager = getNmsField(connection.getClass(), "networkManager");
Method getVersion = getNmsMethod(networkManager.getType(), "getVersion");
boolean is18 = (Integer) getVersion.invoke(networkManager.get(connection)) >= 28;
is1_8.put(player.getName(), is18);
return is18;
} catch (Exception ex) {
ex.printStackTrace();
}
}
return false;
}
public static boolean isForge() {
return isForge;
}
private static String methodSignaturePart(Class<?> param) {
if (param.isArray()) {
return "[" + methodSignaturePart(param.getComponentType());
} else if (param.isPrimitive()) {
return primitiveTypes.get(param);
} else {
return "L" + param.getName().replaceAll("\\.", "/") + ";";
}
}
public static void removePlayer(Player player) {
is1_8.remove(player.getName());
}
public static void setAllowSleep(Player player) {
try {
Object nmsEntity = getNmsEntity(player);
Object connection = getNmsField(nmsEntity.getClass(), "playerConnection").get(nmsEntity);
Field check = getNmsField(connection.getClass(), "checkMovement");
check.setBoolean(connection, true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void setBoundingBox(Entity entity, FakeBoundingBox newBox) {
try {
Object boundingBox;
if (LibVersion.is1_8()) {
boundingBox = getNmsMethod("Entity", "getBoundingBox").invoke(getNmsEntity(entity));
} else {
boundingBox = getNmsField("Entity", "boundingBox").get(getNmsEntity(entity));
}
int stage = 0;
Location loc = entity.getLocation();
for (Field field : boundingBox.getClass().getFields()) {
if (field.getType().getSimpleName().equals("double")) {
stage++;
switch (stage) {
case 1:
field.setDouble(boundingBox, loc.getX() - newBox.getX());
break;
case 2:
// field.setDouble(boundingBox, loc.getY() - newBox.getY());
break;
case 3:
field.setDouble(boundingBox, loc.getZ() - newBox.getZ());
break;
case 4:
field.setDouble(boundingBox, loc.getX() + newBox.getX());
break;
case 5:
field.setDouble(boundingBox, loc.getY() + newBox.getY());
break;
case 6:
field.setDouble(boundingBox, loc.getZ() + newBox.getZ());
break;
default:
throw new Exception("Error while setting the bounding box, more doubles than I thought??");
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

View File

@@ -1,58 +0,0 @@
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;
}
}