Clean up code, change ParamInfos to display better information. DisguiseHelp is more readable. Parse disguises code is more readable

This commit is contained in:
libraryaddict
2018-09-07 14:35:38 +12:00
parent ef1b69302c
commit 03e50e9d07
34 changed files with 1785 additions and 1580 deletions

View File

@@ -0,0 +1,18 @@
package me.libraryaddict.disguise.utilities.parser;
import me.libraryaddict.disguise.utilities.LibsMsg;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class DisguiseParseException extends Exception {
private static final long serialVersionUID = 1276971370793124510L;
public DisguiseParseException() {
super();
}
public DisguiseParseException(LibsMsg message, String... params) {
super(message.get((Object[]) params));
}
}

View File

@@ -0,0 +1,745 @@
package me.libraryaddict.disguise.utilities.parser;
import me.libraryaddict.disguise.DisguiseConfig;
import me.libraryaddict.disguise.disguisetypes.*;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
import me.libraryaddict.disguise.utilities.LibsMsg;
import me.libraryaddict.disguise.utilities.TranslateType;
import me.libraryaddict.disguise.utilities.parser.params.ParamInfo;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.permissions.PermissionAttachmentInfo;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DisguiseParser {
public static class DisguisePerm {
private DisguiseType disguiseType;
private String permName;
public DisguisePerm(DisguiseType disguiseType) {
this.disguiseType = disguiseType;
}
public DisguisePerm(DisguiseType disguiseType, String disguisePerm) {
this.disguiseType = disguiseType;
permName = disguisePerm;
}
public Class getEntityClass() {
return getType().getEntityClass();
}
public EntityType getEntityType() {
return getType().getEntityType();
}
public DisguiseType getType() {
return disguiseType;
}
public Class<? extends FlagWatcher> getWatcherClass() {
return getType().getWatcherClass();
}
public boolean isMisc() {
return getType().isMisc();
}
public boolean isMob() {
return getType().isMob();
}
public boolean isPlayer() {
return getType().isPlayer();
}
public boolean isUnknown() {
return getType().isUnknown();
}
public String toReadable() {
return permName == null ? getType().toReadable() : permName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((disguiseType == null) ? 0 : disguiseType.hashCode());
result = prime * result + ((permName == null) ? 0 : permName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof DisguisePerm))
return false;
DisguisePerm other = (DisguisePerm) obj;
if (disguiseType != other.disguiseType)
return false;
return Objects.equals(permName, other.permName);
}
}
private static void doCheck(CommandSender sender, HashMap<ArrayList<String>, Boolean> optionPermissions,
ArrayList<String> usedOptions) throws DisguiseParseException {
if (!passesCheck(sender, optionPermissions, usedOptions)) {
throw new DisguiseParseException(LibsMsg.D_PARSE_NOPERM, usedOptions.get(usedOptions.size() - 1));
}
}
private static HashMap<String, Boolean> getDisguiseOptions(CommandSender sender, String permNode,
DisguisePerm type) {
switch (type.getType()) {
case PLAYER:
case FALLING_BLOCK:
case PAINTING:
case SPLASH_POTION:
case FISHING_HOOK:
case DROPPED_ITEM:
HashMap<String, Boolean> returns = new HashMap<>();
String beginning = "libsdisguises.options." + permNode + ".";
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.toReadable().toLowerCase().replace(" ", ""))) {
for (int i = 1; i < split.length; i++) {
returns.put(split[i], permission.getValue());
}
}
}
}
}
return returns;
default:
return new HashMap<>();
}
}
public static DisguisePerm getDisguisePerm(String name) {
for (DisguisePerm perm : getDisguisePerms()) {
if (!perm.toReadable().replaceAll("[ |_]", "").equalsIgnoreCase(name.replaceAll("[ |_]", "")))
continue;
return perm;
}
if (name.equalsIgnoreCase("p"))
return getDisguisePerm(DisguiseType.PLAYER.toReadable());
return null;
}
public static DisguisePerm[] getDisguisePerms() {
DisguisePerm[] perms = new DisguisePerm[DisguiseType.values().length +
DisguiseConfig.getCustomDisguises().size()];
int i = 0;
for (DisguiseType disguiseType : DisguiseType.values()) {
perms[i++] = new DisguisePerm(disguiseType);
}
for (Entry<String, Disguise> entry : DisguiseConfig.getCustomDisguises().entrySet()) {
perms[i++] = new DisguisePerm(entry.getValue().getType(), entry.getKey());
}
return perms;
}
private static HashMap<ArrayList<String>, Boolean> getOptions(String perm) {
ArrayList<String> list = new ArrayList<>();
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<>();
options.put(list, isRemove);
return options;
}
/**
* Get perms for the node. Returns a hashmap of allowed disguisetypes and their options
*/
public static HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> getPermissions(CommandSender sender,
String permissionNode) {
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> singleDisguises = new HashMap<>();
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> rangeDisguises = new HashMap<>();
HashMap<String, Boolean> perms = new HashMap<>();
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];
DisguisePerm dPerm = DisguiseParser.getDisguisePerm(disguiseType);
if (dPerm != null) {
HashMap<ArrayList<String>, Boolean> list;
if (singleDisguises.containsKey(dPerm)) {
list = singleDisguises.get(dPerm);
} else {
list = new HashMap<>();
singleDisguises.put(dPerm, list);
}
HashMap<ArrayList<String>, Boolean> map1 = getOptions(perm);
list.put(map1.keySet().iterator().next(), map1.values().iterator().next());
} else {
for (DisguisePerm type : getDisguisePerms()) {
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<>();
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];
DisguisePerm dType = DisguiseParser.getDisguisePerm(disguiseType);
if (dType != null) {
singleDisguises.remove(dType);
rangeDisguises.remove(dType);
} else {
for (DisguisePerm type : getDisguisePerms()) {
boolean foundHim = false;
Class entityClass = type.getEntityClass();
switch (disguiseType) {
case "mob":
if (type.isMob()) {
foundHim = true;
}
break;
case "animal":
case "animals":
if (Animals.class.isAssignableFrom(entityClass)) {
foundHim = true;
}
break;
case "monster":
case "monsters":
if (Monster.class.isAssignableFrom(entityClass)) {
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);
}
}
}
}
}
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> map = new HashMap<>();
for (DisguisePerm type : getDisguisePerms()) {
HashMap<ArrayList<String>, 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;
}
private static boolean isDouble(String string) {
try {
Float.parseFloat(string);
return true;
}
catch (Exception ex) {
return false;
}
}
private static boolean isInteger(String string) {
try {
Integer.parseInt(string);
return true;
}
catch (Exception ex) {
return false;
}
}
/**
* Splits a string while respecting quotes
*/
public static String[] split(String string) {
Matcher matcher = Pattern.compile("\"(?:\"(?=\\S)|\\\\\"|[^\"])*(?:[^\\\\]\"(?=\\s|$))|\\S+").matcher(string);
List<String> list = new ArrayList<>();
while (matcher.find()) {
list.add(matcher.group());
}
return list.toArray(new String[0]);
}
/**
* 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.
*/
public static Disguise parseDisguise(CommandSender sender, String permNode, String[] args,
HashMap<DisguisePerm, HashMap<ArrayList<String>, Boolean>> permissionMap) throws DisguiseParseException,
IllegalAccessException, InvocationTargetException {
if (sender instanceof Player) {
DisguiseUtilities.setCommandsUsed();
}
if (permissionMap.isEmpty()) {
throw new DisguiseParseException(LibsMsg.NO_PERM);
}
if (args.length == 0) {
throw new DisguiseParseException(LibsMsg.PARSE_NO_ARGS);
}
// 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<>();
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(LibsMsg.PARSE_NO_REF, args[0]);
}
} else {
throw new DisguiseParseException(LibsMsg.PARSE_NO_PERM_REF);
}
optionPermissions = (permissionMap.containsKey(new DisguisePerm(disguise.getType())) ?
permissionMap.get(new DisguisePerm(disguise.getType())) :
new HashMap<ArrayList<String>, Boolean>());
} else {
DisguisePerm disguisePerm = getDisguisePerm(args[0]);
Entry<String, Disguise> customDisguise = DisguiseConfig.getCustomDisguise(args[0]);
if (customDisguise != null) {
disguise = customDisguise.getValue().clone();
}
if (disguisePerm == null) {
throw new DisguiseParseException(LibsMsg.PARSE_DISG_NO_EXIST, args[0]);
}
if (disguisePerm.isUnknown()) {
throw new DisguiseParseException(LibsMsg.PARSE_CANT_DISG_UNKNOWN);
}
if (disguisePerm.getEntityType() == null) {
throw new DisguiseParseException(LibsMsg.PARSE_CANT_LOAD);
}
if (!permissionMap.containsKey(disguisePerm)) {
throw new DisguiseParseException(LibsMsg.NO_PERM_DISGUISE);
}
optionPermissions = permissionMap.get(disguisePerm);
HashMap<String, Boolean> disguiseOptions = getDisguiseOptions(sender, permNode, disguisePerm);
if (disguise == null) {
if (disguisePerm.isPlayer()) {
// If he is doing a player disguise
if (args.length == 1) {
// He needs to give the player name
throw new DisguiseParseException(LibsMsg.PARSE_SUPPLY_PLAYER);
} else {
if (!disguiseOptions.isEmpty() && (!disguiseOptions.containsKey(args[1].toLowerCase()) ||
!disguiseOptions.get(args[1].toLowerCase()))) {
throw new DisguiseParseException(LibsMsg.PARSE_NO_PERM_NAME);
}
args[1] = args[1].replace("\\_", " ");
// Construct the player disguise
disguise = new PlayerDisguise(ChatColor.translateAlternateColorCodes('&', args[1]));
toSkip++;
}
} else if (disguisePerm.isMob()) { // Its a mob, use the mob constructor
boolean adult = true;
if (args.length > 1) {
if (args[1].equalsIgnoreCase(TranslateType.DISGUISE_OPTIONS.get("baby")) ||
args[1].equalsIgnoreCase(TranslateType.DISGUISE_OPTIONS.get("adult"))) {
usedOptions.add("setbaby");
doCheck(sender, optionPermissions, usedOptions);
adult = args[1].equalsIgnoreCase(TranslateType.DISGUISE_OPTIONS.get("adult"));
toSkip++;
}
}
disguise = new MobDisguise(disguisePerm.getType(), adult);
} else if (disguisePerm.isMisc()) {
// Its a misc, we are going to use the MiscDisguise constructor.
ItemStack itemStack = new ItemStack(Material.STONE);
int miscId = -1;
int miscData = -1;
String secondArg = null;
if (args.length > 1) {
// They have defined more arguments!
// If the first arg is a number
if (args[1].contains(":")) {
String[] split = args[1].split(":");
if (isInteger(split[1])) {
secondArg = split[1];
}
args[1] = split[0];
}
if (isInteger(args[1])) {
miscId = Integer.parseInt(args[1]);
} else {
if (disguisePerm.getType() == DisguiseType.FALLING_BLOCK ||
disguisePerm.getType() == DisguiseType.DROPPED_ITEM) {
for (Material mat : Material.values()) {
if (mat.name().replace("_", "").equalsIgnoreCase(args[1].replace("_", ""))) {
itemStack = new ItemStack(mat);
miscId = mat.getId();
break;
}
}
}
}
if (miscId != -1) {
switch (disguisePerm.getType()) {
case PAINTING:
case FALLING_BLOCK:
case SPLASH_POTION:
case DROPPED_ITEM:
case FISHING_HOOK:
case ARROW:
case TIPPED_ARROW:
case SPECTRAL_ARROW:
case SMALL_FIREBALL:
case FIREBALL:
case WITHER_SKULL:
case TRIDENT:
break;
default:
throw new DisguiseParseException(LibsMsg.PARSE_TOO_MANY_ARGS,
disguisePerm.toReadable(), args[1]);
}
toSkip++;
// If they also defined a data value
if (args.length > 2 && secondArg == null && isInteger(args[2])) {
secondArg = args[2];
toSkip++;
}
if (secondArg != null) {
if (disguisePerm.getType() != DisguiseType.FALLING_BLOCK &&
disguisePerm.getType() != DisguiseType.DROPPED_ITEM) {
throw new DisguiseParseException(LibsMsg.PARSE_USE_SECOND_NUM,
DisguiseType.FALLING_BLOCK.toReadable(),
DisguiseType.DROPPED_ITEM.toReadable());
}
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(LibsMsg.PARSE_NO_PERM_PARAM, toCheck,
disguisePerm.toReadable());
}
}
if (miscId != -1) {
if (disguisePerm.getType() == DisguiseType.FALLING_BLOCK) {
usedOptions.add("setblock");
doCheck(sender, optionPermissions, usedOptions);
} else if (disguisePerm.getType() == DisguiseType.PAINTING) {
usedOptions.add("setpainting");
doCheck(sender, optionPermissions, usedOptions);
} else if (disguisePerm.getType() == DisguiseType.SPLASH_POTION) {
usedOptions.add("setpotionid");
doCheck(sender, optionPermissions, usedOptions);
}
}
// Construct the disguise
if (disguisePerm.getType() == DisguiseType.DROPPED_ITEM) {
disguise = new MiscDisguise(itemStack);
} else {
disguise = new MiscDisguise(disguisePerm.getType(), miscId, miscData);
}
}
}
}
// Copy strings to their new range
String[] newArgs = new String[args.length - toSkip];
System.arraycopy(args, toSkip, newArgs, 0, args.length - toSkip);
callMethods(sender, disguise, optionPermissions, usedOptions, newArgs);
// Alright. We've constructed our disguise.
return disguise;
}
public static void callMethods(CommandSender sender, Disguise disguise,
HashMap<ArrayList<String>, Boolean> optionPermissions, ArrayList<String> usedOptions,
String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException,
DisguiseParseException {
Method[] methods = ParamInfoManager.getDisguiseWatcherMethods(disguise.getWatcher().getClass());
List<String> list = new ArrayList<>(Arrays.asList(args));
for (int argIndex = 0; argIndex < args.length; argIndex++) {
// This is the method name they provided
String methodNameProvided = list.remove(0);
// Translate the name they provided, to a name we recognize
String methodNameJava = TranslateType.DISGUISE_OPTIONS.reverseGet(methodNameProvided);
// The method we'll use
Method methodToUse = null;
Object valueToSet = null;
DisguiseParseException parseException = null;
for (Method method : methods) {
if (!method.getName().equalsIgnoreCase(methodNameJava)) {
continue;
}
Class paramType = method.getParameterTypes()[0];
ParamInfo paramInfo = ParamInfoManager.getParamInfo(paramType);
try {
// Store how many args there were before calling the param
int argCount = list.size();
if (argCount < paramInfo.getMinArguments()) {
throw new DisguiseParseException(LibsMsg.PARSE_NO_OPTION_VALUE,
TranslateType.DISGUISE_OPTIONS.reverseGet(method.getName()));
}
valueToSet = paramInfo.fromString(list);
if (valueToSet == null && !paramInfo.canReturnNull()) {
throw new IllegalStateException();
}
// Skip ahead as many args as were consumed on successful parse
argIndex += argCount - list.size();
methodToUse = method;
// We've found a method which will accept a valid value, break
break;
}
catch (Exception ignored) {
ignored.printStackTrace();
parseException = new DisguiseParseException(LibsMsg.PARSE_EXPECTED_RECEIVED,
paramInfo.getDescriptiveName(), list.isEmpty() ? null : list.get(0),
TranslateType.DISGUISE_OPTIONS.reverseGet(method.getName()));
}
}
if (methodToUse == null) {
if (parseException != null) {
throw parseException;
}
throw new DisguiseParseException(LibsMsg.PARSE_OPTION_NA, methodNameProvided);
}
if (!usedOptions.contains(methodToUse.getName().toLowerCase())) {
usedOptions.add(methodToUse.getName().toLowerCase());
}
doCheck(sender, optionPermissions, usedOptions);
if (FlagWatcher.class.isAssignableFrom(methodToUse.getDeclaringClass())) {
methodToUse.invoke(disguise.getWatcher(), valueToSet);
} else {
methodToUse.invoke(disguise, valueToSet);
}
}
}
public static boolean passesCheck(CommandSender sender, HashMap<ArrayList<String>, Boolean> theirPermissions,
ArrayList<String> usedOptions) {
if (theirPermissions == null)
return false;
boolean hasPermission = false;
for (ArrayList<String> list : theirPermissions.keySet()) {
boolean myPerms = true;
for (String option : usedOptions) {
if (!sender.getName().equals("CONSOLE") && option.equalsIgnoreCase("setInvisible") &&
DisguiseConfig.isDisabledInvisibility()) {
myPerms = false;
}
if (!(theirPermissions.get(list) && list.contains("*")) &&
(list.contains(option) != theirPermissions.get(list))) {
myPerms = false;
break;
}
}
if (myPerms) {
hasPermission = true;
}
}
return hasPermission;
}
}

View File

@@ -0,0 +1,135 @@
package me.libraryaddict.disguise.utilities.parser;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
import me.libraryaddict.disguise.disguisetypes.watchers.LivingWatcher;
import me.libraryaddict.disguise.utilities.parser.DisguiseParser.DisguisePerm;
import me.libraryaddict.disguise.utilities.parser.params.ParamInfo;
import me.libraryaddict.disguise.utilities.parser.params.ParamInfoTypes;
import org.bukkit.ChatColor;
import javax.annotation.Nullable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class ParamInfoManager {
private static List<ParamInfo> paramList;
public static List<ParamInfo> getParamInfos() {
return paramList;
}
public static ParamInfo getParamInfo(Class c) {
for (ParamInfo info : getParamInfos()) {
if (!info.isParam(c)) {
continue;
}
return info;
}
return null;
}
public static ParamInfo getParamInfo(DisguisePerm disguiseType, String methodName) {
return getParamInfo(disguiseType.getType(), methodName);
}
public static ParamInfo getParamInfo(DisguiseType disguiseType, String methodName) {
for (Method method : getDisguiseWatcherMethods(disguiseType.getWatcherClass())) {
if (!method.getName().toLowerCase().equals(methodName.toLowerCase()))
continue;
if (method.getParameterTypes().length != 1)
continue;
if (method.getAnnotation(Deprecated.class) != null)
continue;
return getParamInfo(method.getParameterTypes()[0]);
}
return null;
}
static {
paramList = new ParamInfoTypes().getParamInfos();
//paramList.sort((o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getName(), o2.getName()));
}
public static Method[] getDisguiseWatcherMethods(@Nullable Class<? extends FlagWatcher> watcherClass) {
if (watcherClass == null) {
return new Method[0];
}
ArrayList<Method> methods = new ArrayList<>(Arrays.asList(watcherClass.getMethods()));
Iterator<Method> itel = methods.iterator();
while (itel.hasNext()) {
Method method = itel.next();
if (method.getParameterTypes().length != 1) {
itel.remove();
} else if (method.getName().startsWith("get")) {
itel.remove();
} else if (method.isAnnotationPresent(Deprecated.class)) {
itel.remove();
} else if (getParamInfo(method.getParameterTypes()[0]) == null) {
itel.remove();
} else if (!method.getReturnType().equals(Void.TYPE)) {
itel.remove();
} else if (method.getName().equals("removePotionEffect")) {
itel.remove();
}
}
// Order first by their declaring class, the top class (SheepWatcher) goes before (FlagWatcher)
// Order methods in the same watcher by their name from A to Z
methods.sort((m1, m2) -> {
int v1 = getValue(m1);
int v2 = getValue(m2);
if (v1 != v2) {
return v1 - v2;
}
return String.CASE_INSENSITIVE_ORDER.compare(m1.getName(), m2.getName());
});
// Add these last as it's what we want to present to be called the least
for (String methodName : new String[]{"setViewSelfDisguise", "setHideHeldItemFromSelf", "setHideArmorFromSelf",
"setHearSelfDisguise", "setHidePlayer"}) {
try {
methods.add(Disguise.class.getMethod(methodName, boolean.class));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
return methods.toArray(new Method[0]);
}
/**
* Value of the method, used namely for displaying the more unique methods to a disguise
*/
public static int getValue(Method method) {
ChatColor methodColor = ChatColor.YELLOW;
Class<?> declaring = method.getDeclaringClass();
if (declaring == LivingWatcher.class) {
return 1;
} else if (!(FlagWatcher.class.isAssignableFrom(declaring)) || declaring == FlagWatcher.class) {
return 2;
}
return 0;
}
}

View File

@@ -0,0 +1,8 @@
package me.libraryaddict.disguise.utilities.parser;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParsedDisguise {
private String[] arguments;
}

View File

@@ -0,0 +1,140 @@
package me.libraryaddict.disguise.utilities.parser.params;
import me.libraryaddict.disguise.utilities.TranslateType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by libraryaddict on 7/09/2018.
*/
public abstract class ParamInfo {
private Class paramClass;
private String descriptiveName;
private String name;
private Map<String, Object> possibleValues;
/**
* Used for translations, namely ItemStack and it's 'Glowing' and 'null' counterparts
*/
private String[] otherValues;
private String description;
public ParamInfo(Class paramClass, String name, String description) {
this(paramClass, name, name, description);
}
public ParamInfo(Class paramClass, String name, String descriptiveName, String description) {
this.name = name;
this.paramClass = paramClass;
this.descriptiveName = descriptiveName;
this.description = description;
}
public ParamInfo(Class paramClass, String name, String description, Enum[] possibleValues) {
this(paramClass, name, name, description);
}
public ParamInfo(Class paramClass, String name, String descriptiveName, String description, Enum[] possibleValues) {
this(paramClass, name, descriptiveName, description);
this.possibleValues = new HashMap<>();
for (Enum anEnum : possibleValues) {
this.getValues().put(anEnum.name(), anEnum);
}
}
public ParamInfo(Class paramClass, String name, String description, String[] possibleValues) {
this(paramClass, name, name, description);
}
public ParamInfo(Class paramClass, String name, String descriptiveName, String description,
String[] possibleValues) {
this(paramClass, name, descriptiveName, description);
this.possibleValues = new HashMap<>();
for (String value : possibleValues) {
getValues().put(value, value);
}
}
public boolean canTranslateValues() {
return getValues() != null;
}
public String[] getOtherValues() {
return this.otherValues;
}
public void setOtherValues(String... otherValues) {
this.otherValues = otherValues;
}
public boolean canReturnNull() {
return false;
}
protected abstract Object fromString(String string);
public Object fromString(List<String> arguments) {
// Don't consume a string immediately, if it errors we need to check other param types
String string = arguments.get(0);
Object value = fromString(string);
arguments.remove(0);
return value;
}
public int getMinArguments() {
return 1;
}
public boolean hasValues() {
return getValues() != null;
}
private Class getParamClass() {
return paramClass;
}
public boolean isParam(Class paramClass) {
return getParamClass() == paramClass;
}
public String getName() {
return TranslateType.DISGUISE_OPTIONS_PARAMETERS.get(getRawName());
}
public String getDescriptiveName() {
return TranslateType.DISGUISE_OPTIONS_PARAMETERS.get(getRawDescriptiveName());
}
public String getRawName() {
return this.name;
}
public String getRawDescriptiveName() {
return descriptiveName;
}
public String getDescription() {
return TranslateType.DISGUISE_OPTIONS_PARAMETERS.get(getRawDescription());
}
public String getRawDescription() {
return description;
}
public Map<String, Object> getValues() {
return this.possibleValues;
}
public Set<String> getEnums(String tabComplete) {
return getValues().keySet();
}
}

View File

@@ -0,0 +1,162 @@
package me.libraryaddict.disguise.utilities.parser.params;
import com.comphenix.protocol.wrappers.BlockPosition;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import me.libraryaddict.disguise.disguisetypes.AnimalColor;
import me.libraryaddict.disguise.disguisetypes.RabbitType;
import me.libraryaddict.disguise.utilities.parser.params.types.ParamInfoEnum;
import me.libraryaddict.disguise.utilities.parser.params.types.base.*;
import me.libraryaddict.disguise.utilities.parser.params.types.custom.*;
import org.apache.commons.lang.StringUtils;
import org.bukkit.*;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.MainHand;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.EulerAngle;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParamInfoTypes {
/**
* Constructor values are listed here for continuity
*/
public List<ParamInfo> getParamInfos() {
List<ParamInfo> paramInfos = new ArrayList<>();
// Register enum types
paramInfos.add(new ParamInfoEnum(AnimalColor.class, "Animal Color",
"View all the colors you can use for an animal color"));
paramInfos
.add(new ParamInfoEnum(Art.class, "Art", "View all the paintings you can use for a painting disguise"));
paramInfos.add(new ParamInfoEnum(Horse.Color.class, "Horse Color",
"View all the colors you can use for a horses color"));
paramInfos.add(new ParamInfoEnum(Ocelot.Type.class, "Ocelot Type",
"View all the ocelot types you can use for ocelots"));
paramInfos.add(new ParamInfoEnum(Villager.Profession.class, "Villager Profession",
"View all the professions you can set on a Zombie and Normal Villager"));
paramInfos.add(new ParamInfoEnum(BlockFace.class, "Direction", "Direction (North, East, South, West, Up, Down)",
"View the directions usable on player setSleeping and shulker direction",
Arrays.copyOf(BlockFace.values(), 6)));
paramInfos
.add(new ParamInfoEnum(RabbitType.class, "Rabbit Type", "View the kinds of rabbits you can turn into"));
paramInfos
.add(new ParamInfoEnum(TreeSpecies.class, "Tree Species", "View the different types of tree species"));
paramInfos.add(new ParamInfoEnum(MainHand.class, "Main Hand", "Set the main hand for an entity"));
paramInfos.add(new ParamInfoEnum(Llama.Color.class, "Llama Color",
"View all the colors you can use for a llama color"));
paramInfos.add(new ParamInfoEnum(Parrot.Variant.class, "Parrot Variant",
"View the different colors a parrot can be"));
paramInfos.add(new ParamInfoEnum(Particle.class, "Particle", "The different particles of Minecraft"));
paramInfos.add(new ParamInfoEnum(TropicalFish.Pattern.class, "Pattern", "Patterns of a tropical fish"));
paramInfos.add(new ParamInfoEnum(DyeColor.class, "DyeColor", "Dye colors of many different colors"));
paramInfos.add(new ParamInfoEnum(Horse.Style.class, "Horse Style",
"Horse style which is the patterns on the horse"));
// Register custom types
paramInfos.add(new ParamInfoEulerAngle(EulerAngle.class, "Euler Angle", "Euler Angle (X,Y,Z)",
"Set the X,Y,Z directions on an armorstand"));
paramInfos.add(new ParamInfoEnum(Color.class, "Color", "Colors that can also be defined through RGB",
getColors()));
paramInfos.add(new ParamInfoEnum(Material.class, "Material", "A material used for blocks and items",
getMaterials()));
paramInfos.add(new ParamInfoItemStack(ItemStack.class, "ItemStack", "ItemStack (Material:Amount?:Glow?)",
"An ItemStack compromised of Material:Amount:Glow, only requires Material", getMaterials()));
paramInfos.add(new ParamInfoItemStackArray(ItemStack[].class, "ItemStack[]",
"Four ItemStacks (Material:Amount?:Glow?,Material:Amount?:Glow?..)",
"Four ItemStacks separated by a comma", getMaterials()));
paramInfos.add(new ParamInfoPotionType(PotionEffectType.class, "Potion Effect",
"View all the potion effects you can add", getPotions()));
paramInfos.add(new ParamInfoBlockPosition(BlockPosition.class, "Block Position", "Block Position (num,num,num)",
"Three numbers separated by a ,"));
paramInfos.add(new ParamInfoGameProfile(WrappedGameProfile.class, "GameProfile",
"Get the gameprofile here https://sessionserver.mojang" +
".com/session/minecraft/profile/PLAYER_UUID_GOES_HERE?unsigned=false"));
// Register base types
paramInfos.add(new ParamInfoBoolean("Boolean", "True/False", "True or False", new String[]{"true", "false"}));
paramInfos.add(new ParamInfoString(String.class, "Text", "A line of text"));
paramInfos.add(new ParamInfoInteger("Number", "A whole number without decimals"));
paramInfos.add(new ParamInfoFloat("Number.0", "A number which can have decimal places"));
paramInfos.add(new ParamInfoDouble("Number.0", "A number which can have decimal places"));
return paramInfos;
}
private String[] getColors() {
try {
List<String> colors = new ArrayList<>();
Class cl = Class.forName("org.bukkit.Color");
for (Field field : cl.getFields()) {
if (field.getType() != cl) {
continue;
}
colors.add(field.getName());
}
return colors.toArray(new String[0]);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
private Material[] getMaterials() {
List<Material> list = new ArrayList<>();
for (Material material : Material.values()) {
try {
Field field = Material.class.getField(material.name());
// Ignore all legacies materials
if (field.isAnnotationPresent(Deprecated.class)) {
continue;
}
list.add(material);
}
catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
return list.toArray(new Material[0]);
}
private String[] getPotions() {
List<String> potionEnums = new ArrayList<>();
for (PotionEffectType effectType : PotionEffectType.values()) {
if (effectType == null)
continue;
potionEnums.add(toReadable(effectType.getName()));
}
return potionEnums.toArray(new String[0]);
}
private 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, "_");
}
}

View File

@@ -0,0 +1,41 @@
package me.libraryaddict.disguise.utilities.parser.params.types;
import me.libraryaddict.disguise.utilities.parser.params.ParamInfo;
import java.util.Map;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParamInfoEnum extends ParamInfo {
public ParamInfoEnum(Class<? extends Enum> paramClass, String name, String description) {
super(paramClass, name, name, description, paramClass.getEnumConstants());
}
public ParamInfoEnum(Class paramClass, String name, String valueType, String description, Enum[] possibleValues) {
super(paramClass, name, valueType, description);
}
public ParamInfoEnum(Class paramClass, String name, String description, Enum[] possibleValues) {
super(paramClass, name, name, description);
}
public ParamInfoEnum(Class paramClass, String name, String description, String[] possibleValues) {
super(paramClass, name, name, description);
}
@Override
protected Object fromString(String string) {
string = string.replace("_", "");
for (Map.Entry<String, Object> entry : getValues().entrySet()) {
if (!entry.getKey().replace("_", "").equalsIgnoreCase(string)) {
continue;
}
return entry.getValue();
}
return null;
}
}

View File

@@ -0,0 +1,48 @@
package me.libraryaddict.disguise.utilities.parser.params.types.base;
import me.libraryaddict.disguise.utilities.TranslateType;
import me.libraryaddict.disguise.utilities.parser.params.ParamInfo;
import java.util.List;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParamInfoBoolean extends ParamInfo {
public ParamInfoBoolean(String name, String valueType, String description, String[] possibleValues) {
super(Boolean.class, name, valueType, description, possibleValues);
}
@Override
public boolean isParam(Class classType) {
return classType == Boolean.class || classType == Boolean.TYPE;
}
@Override
public Object fromString(List<String> list) {
if (list.isEmpty()) {
return true;
}
String string = list.get(0);
if (string.equalsIgnoreCase(TranslateType.DISGUISE_OPTIONS_PARAMETERS.get("true"))) {
list.remove(0);
} else if (string.equalsIgnoreCase(TranslateType.DISGUISE_OPTIONS_PARAMETERS.get("false"))) {
list.remove(0);
return false;
}
return true;
}
@Override
protected Object fromString(String string) {
throw new IllegalStateException("This shouldn't be called");
}
@Override
public int getMinArguments() {
return 0;
}
}

View File

@@ -0,0 +1,22 @@
package me.libraryaddict.disguise.utilities.parser.params.types.base;
import me.libraryaddict.disguise.utilities.parser.params.ParamInfo;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParamInfoDouble extends ParamInfo {
public ParamInfoDouble(String name, String description) {
super(null, name, description);
}
@Override
public boolean isParam(Class classType) {
return classType == Double.class || classType == Double.TYPE;
}
@Override
protected Object fromString(String string) {
return Double.parseDouble(string);
}
}

View File

@@ -0,0 +1,22 @@
package me.libraryaddict.disguise.utilities.parser.params.types.base;
import me.libraryaddict.disguise.utilities.parser.params.ParamInfo;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParamInfoFloat extends ParamInfo {
public ParamInfoFloat(String name, String description) {
super(Number.class, name, description);
}
@Override
public boolean isParam(Class classType) {
return classType == Float.class || classType == Float.TYPE;
}
@Override
protected Object fromString(String string) {
return Float.parseFloat(string);
}
}

View File

@@ -0,0 +1,22 @@
package me.libraryaddict.disguise.utilities.parser.params.types.base;
import me.libraryaddict.disguise.utilities.parser.params.ParamInfo;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParamInfoInteger extends ParamInfo {
public ParamInfoInteger(String name, String description) {
super(null, name, description);
}
@Override
public boolean isParam(Class classType) {
return classType == Integer.class || classType == Integer.TYPE;
}
@Override
protected Object fromString(String string) {
return Integer.parseInt(string);
}
}

View File

@@ -0,0 +1,18 @@
package me.libraryaddict.disguise.utilities.parser.params.types.base;
import me.libraryaddict.disguise.utilities.parser.params.ParamInfo;
import org.bukkit.ChatColor;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParamInfoString extends ParamInfo {
public ParamInfoString(Class paramClass, String name, String description) {
super(paramClass, name, description);
}
@Override
protected Object fromString(String string) {
return ChatColor.translateAlternateColorCodes('&', string);
}
}

View File

@@ -0,0 +1,24 @@
package me.libraryaddict.disguise.utilities.parser.params.types.custom;
import com.comphenix.protocol.wrappers.BlockPosition;
import me.libraryaddict.disguise.utilities.parser.params.ParamInfo;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParamInfoBlockPosition extends ParamInfo {
public ParamInfoBlockPosition(Class paramClass, String name, String valueType, String description) {
super(paramClass, name, valueType, description);
}
@Override
protected Object fromString(String string) {
String[] split = string.split(",");
if (split.length != 3) {
return null;
}
return new BlockPosition(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
}
}

View File

@@ -0,0 +1,24 @@
package me.libraryaddict.disguise.utilities.parser.params.types.custom;
import me.libraryaddict.disguise.utilities.parser.params.ParamInfo;
import org.bukkit.util.EulerAngle;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParamInfoEulerAngle extends ParamInfo {
public ParamInfoEulerAngle(Class paramClass, String name, String valueType, String description) {
super(paramClass, name, valueType, description);
}
@Override
protected Object fromString(String string) {
String[] split = string.split(",");
if (split.length != 3) {
return null;
}
return new EulerAngle(Double.parseDouble(split[0]), Double.parseDouble(split[1]), Double.parseDouble(split[2]));
}
}

View File

@@ -0,0 +1,21 @@
package me.libraryaddict.disguise.utilities.parser.params.types.custom;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import me.libraryaddict.disguise.utilities.DisguiseUtilities;
import me.libraryaddict.disguise.utilities.parser.params.ParamInfo;
import java.lang.reflect.Method;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParamInfoGameProfile extends ParamInfo {
public ParamInfoGameProfile(Class paramClass, String name, String description) {
super(paramClass, name, description);
}
@Override
protected Object fromString( String string) {
return DisguiseUtilities.getGson().fromJson(string, WrappedGameProfile.class);
}
}

View File

@@ -0,0 +1,71 @@
package me.libraryaddict.disguise.utilities.parser.params.types.custom;
import me.libraryaddict.disguise.utilities.TranslateType;
import me.libraryaddict.disguise.utilities.parser.params.types.ParamInfoEnum;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParamInfoItemStack extends ParamInfoEnum {
public ParamInfoItemStack(Class paramClass, String name, String valueType, String description,
Enum[] possibleValues) {
super(paramClass, name, valueType, description, possibleValues);
setOtherValues("null", "glow");
}
@Override
public boolean canTranslateValues() {
return false;
}
@Override
public boolean canReturnNull() {
return true;
}
@Override
public Object fromString(String string) {
return parseToItemstack(string);
}
protected ItemStack parseToItemstack(String string) {
String[] split = string.split(":", -1);
if (split[0].isEmpty() || split[0].equalsIgnoreCase(TranslateType.DISGUISE_OPTIONS_PARAMETERS.get("null"))) {
return null;
}
Material material = Material.getMaterial(split[0]);
if (material == null) {
throw new IllegalArgumentException();
}
Integer amount = null;
boolean enchanted = false;
for (int i = 1; i < split.length; i++) {
String s = split[i];
if (!enchanted && s.equalsIgnoreCase(TranslateType.DISGUISE_OPTIONS_PARAMETERS.get("glow"))) {
enchanted = true;
} else if (s.matches("\\d+") && amount == null) {
amount = Integer.parseInt(s);
} else {
throw new IllegalArgumentException();
}
}
ItemStack itemStack = new ItemStack(material, amount == null ? 1 : amount);
if (enchanted) {
itemStack.addUnsafeEnchantment(Enchantment.DURABILITY, 1);
}
return itemStack;
}
}

View File

@@ -0,0 +1,51 @@
package me.libraryaddict.disguise.utilities.parser.params.types.custom;
import org.bukkit.inventory.ItemStack;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParamInfoItemStackArray extends ParamInfoItemStack {
public ParamInfoItemStackArray(Class paramClass, String name, String valueType, String description,
Enum[] possibleValues) {
super(paramClass, name, valueType, description, possibleValues);
}
@Override
public Set<String> getEnums(String tabComplete) {
String beginning = tabComplete.substring(0, tabComplete.contains(",") ? tabComplete.lastIndexOf(",") + 1 : 0);
String end = tabComplete.substring(tabComplete.contains(",") ? tabComplete.lastIndexOf(",") + 1 : 0);
Set<String> toReturn = new LinkedHashSet<>();
for (String material : super.getEnums(null)) {
if (!material.toLowerCase().startsWith(end.toLowerCase()))
continue;
toReturn.add(beginning + material);
}
return toReturn;
}
@Override
public Object fromString(String string) {
String[] split = string.split(",", -1);
if (split.length != 4) {
return null;
}
// Parse to itemstack array
ItemStack[] items = new ItemStack[4];
for (int a = 0; a < 4; a++) {
items[a] = parseToItemstack(split[a]);
}
return items;
}
}

View File

@@ -0,0 +1,18 @@
package me.libraryaddict.disguise.utilities.parser.params.types.custom;
import me.libraryaddict.disguise.utilities.parser.params.types.ParamInfoEnum;
import org.bukkit.potion.PotionEffectType;
/**
* Created by libraryaddict on 7/09/2018.
*/
public class ParamInfoPotionType extends ParamInfoEnum {
public ParamInfoPotionType(Class paramClass, String name, String description, String[] possibleValues) {
super(paramClass, name, description, possibleValues);
}
@Override
public Object fromString(String string) {
return PotionEffectType.getByName(string);
}
}