0

Reformatted code.

This commit is contained in:
Logan Fick
2019-02-08 16:53:55 -05:00
parent 50f53a63d1
commit 619c603a4f
24 changed files with 554 additions and 581 deletions

View File

@@ -5,16 +5,14 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
@Target(ElementType.METHOD) @Target (ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) @Retention (RetentionPolicy.RUNTIME)
public @interface Command public @interface Command {
{ String hook();
enum AsyncType
{ AsyncType async() default AsyncType.NEVER;
enum AsyncType {
NEVER, ALWAYS; NEVER, ALWAYS;
} }
String hook();
AsyncType async() default AsyncType.NEVER;
} }

View File

@@ -1,11 +1,13 @@
//@noformat //@noformat
package com.nemez.cmdmgr; package com.nemez.cmdmgr;
import java.io.BufferedReader; import com.nemez.cmdmgr.component.*;
import java.io.File; import com.nemez.cmdmgr.util.*;
import java.io.FileReader; import org.bukkit.Bukkit;
import java.io.InputStream; import org.bukkit.command.CommandMap;
import java.io.InputStreamReader; import org.bukkit.plugin.java.JavaPlugin;
import java.io.*;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
@@ -15,81 +17,50 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.logging.Level; import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandMap;
import org.bukkit.plugin.java.JavaPlugin;
import com.nemez.cmdmgr.component.ArgumentComponent;
import com.nemez.cmdmgr.component.BooleanComponent;
import com.nemez.cmdmgr.component.ByteComponent;
import com.nemez.cmdmgr.component.ChainComponent;
import com.nemez.cmdmgr.component.ConstantComponent;
import com.nemez.cmdmgr.component.DoubleComponent;
import com.nemez.cmdmgr.component.EmptyComponent;
import com.nemez.cmdmgr.component.FloatComponent;
import com.nemez.cmdmgr.component.ICommandComponent;
import com.nemez.cmdmgr.component.IntegerComponent;
import com.nemez.cmdmgr.component.LongComponent;
import com.nemez.cmdmgr.component.OptionalComponent;
import com.nemez.cmdmgr.component.ShortComponent;
import com.nemez.cmdmgr.component.StringComponent;
import com.nemez.cmdmgr.util.BranchStack;
import com.nemez.cmdmgr.util.Executable;
import com.nemez.cmdmgr.util.HelpPageCommand;
import com.nemez.cmdmgr.util.Property;
import com.nemez.cmdmgr.util.Type;
/** /**
* Example command.cmd * Example command.cmd
* * <p>
* command home: * command home:
* set [string:name]: * set [string:name]:
* run home_set name * run home_set name
* help Set a new home * help Set a new home
* perm home.set * perm home.set
* del [string:name]: * del [string:name]:
* run home_del name * run home_del name
* help Delete home\n&CCannot be undone! * help Delete home\n&CCannot be undone!
* perm home.del * perm home.del
* list: * list:
* run home_list * run home_list
* help Show all homes * help Show all homes
* perm home.list * perm home.list
* [string:name]: * [string:name]:
* run home_tp name * run home_tp name
* help Teleport to specified home * help Teleport to specified home
* perm home.tp * perm home.tp
* <p>
* Generated in-game command structure:
* (will only show commands the user has permission to execute)
* <p>
* /home set <name>
* /home del <name>
* /home list
* /home <name>
* /home help
* <p>
* Java code:
* *
* Generated in-game command structure: * @Command(hook="home_set") public void executeHomeSet(String name) {
* (will only show commands the user has permission to execute) * ...
* * }
* /home set <name> * @Command(hook="home_del") public void executeHomeDelete(String name) {
* /home del <name> * ...
* /home list * }
* /home <name> * @Command(hook="home_list") public void executeHomeList() {
* /home help * ...
* * }
* Java code: * @Command(hook="home_tp") public void executeHomeTeleport(String name) {
* * ...
* @Command(hook="home_set") * }
* public void executeHomeSet(String name) {
* ...
* }
*
* @Command(hook="home_del")
* public void executeHomeDelete(String name) {
* ...
* }
*
* @Command(hook="home_list")
* public void executeHomeList() {
* ...
* }
*
* @Command(hook="home_tp")
* public void executeHomeTeleport(String name) {
* ...
* }
*/ */
public class CommandManager { public class CommandManager {
@@ -97,27 +68,28 @@ public class CommandManager {
/* Debugging toggle to generate help pages with types, e.g: str, i8, i32, fp64, etc. */ /* Debugging toggle to generate help pages with types, e.g: str, i8, i32, fp64, etc. */
public static boolean debugHelpMenu = false; public static boolean debugHelpMenu = false;
/* Internal boolean to keep track of errors during resolving */ /* Internal boolean to keep track of errors during resolving */
public static boolean errors = false; public static boolean errors = false;
/* Switches for color and formatting in the built-in help message and pagination text */ /* Switches for color and formatting in the built-in help message and pagination text */
public static String helpDescriptionFormatting = "&b"; public static String helpDescriptionFormatting = "&b";
public static String helpUsageFormatting = "&6"; public static String helpUsageFormatting = "&6";
public static String helpPageHeaderFormatting = "&a"; public static String helpPageHeaderFormatting = "&a";
public static String helpInvalidPageFormatting = "&c"; public static String helpInvalidPageFormatting = "&c";
public static String noPermissionFormatting = "&c"; public static String noPermissionFormatting = "&c";
public static String notAllowedFormatting = "&c"; public static String notAllowedFormatting = "&c";
/* List of all commands that can be invoked async */ /* List of all commands that can be invoked async */
public static ArrayList<Executable> asyncExecutables = new ArrayList<Executable>(); public static ArrayList<Executable> asyncExecutables = new ArrayList<Executable>();
public static HashMap<Object, ArrayList<String>> commands = new HashMap<Object, ArrayList<String>>(); public static HashMap<Object, ArrayList<String>> commands = new HashMap<Object, ArrayList<String>>();
/* */ /* */
/** /**
* Registers a command from a String of source code * Registers a command from a String of source code
* *
* @param cmdSourceCode source code * @param cmdSourceCode source code
* @param commandHandler instance of a class where your java functions are located * @param commandHandler instance of a class where your java functions are located
* @param plugin your plugin class * @param plugin your plugin class
*
* @return success - if command was processed and registered successfully * @return success - if command was processed and registered successfully
*/ */
public static boolean registerCommand(String cmdSourceCode, Object commandHandler, JavaPlugin plugin) { public static boolean registerCommand(String cmdSourceCode, Object commandHandler, JavaPlugin plugin) {
@@ -125,7 +97,7 @@ public class CommandManager {
return false; return false;
} }
/* get the class definition of the 'commandHandler' and get its functions */ /* get the class definition of the 'commandHandler' and get its functions */
Method[] methods = commandHandler.getClass().getMethods(); Method[] methods = commandHandler.getClass().getMethods();
ArrayList<Method> finalMethods = new ArrayList<Method>(); ArrayList<Method> finalMethods = new ArrayList<Method>();
/* extract all the functions annotated with @Command that are not static */ /* extract all the functions annotated with @Command that are not static */
@@ -136,18 +108,19 @@ public class CommandManager {
} }
return parse(cmdSourceCode, finalMethods, plugin, commandHandler); return parse(cmdSourceCode, finalMethods, plugin, commandHandler);
} }
/** /**
* Registers a command from a source File * Registers a command from a source File
* *
* @param sourceFile file containing source code * @param sourceFile file containing source code
* @param commandHandler instance of a class where your java functions are located * @param commandHandler instance of a class where your java functions are located
* @param plugin your plugin class * @param plugin your plugin class
*
* @return success - if command was processed and registered successfully * @return success - if command was processed and registered successfully
*/ */
public static boolean registerCommand(File sourceFile, Object commandHandler, JavaPlugin plugin) { public static boolean registerCommand(File sourceFile, Object commandHandler, JavaPlugin plugin) {
StringBuilder src = new StringBuilder(); StringBuilder src = new StringBuilder();
String buf = ""; String buf = "";
try { try {
BufferedReader reader = new BufferedReader(new FileReader(sourceFile)); BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
while ((buf = reader.readLine()) != null) { while ((buf = reader.readLine()) != null) {
@@ -163,18 +136,19 @@ public class CommandManager {
} }
return registerCommand(src.toString(), commandHandler, plugin); return registerCommand(src.toString(), commandHandler, plugin);
} }
/** /**
* Registers a command from an InputStream * Registers a command from an InputStream
* *
* @param sourceStream input stream containing source code * @param sourceStream input stream containing source code
* @param commandHandler instance of a class where your java functions are located * @param commandHandler instance of a class where your java functions are located
* @param plugin your plugin class * @param plugin your plugin class
*
* @return success - if command was processed and registered successfully * @return success - if command was processed and registered successfully
*/ */
public static boolean registerCommand(InputStream sourceStream, Object commandHandler, JavaPlugin plugin) { public static boolean registerCommand(InputStream sourceStream, Object commandHandler, JavaPlugin plugin) {
StringBuilder src = new StringBuilder(); StringBuilder src = new StringBuilder();
String buf = ""; String buf = "";
try { try {
BufferedReader reader = new BufferedReader(new InputStreamReader(sourceStream)); BufferedReader reader = new BufferedReader(new InputStreamReader(sourceStream));
while ((buf = reader.readLine()) != null) { while ((buf = reader.readLine()) != null) {
@@ -189,16 +163,16 @@ public class CommandManager {
} }
return registerCommand(src.toString(), commandHandler, plugin); return registerCommand(src.toString(), commandHandler, plugin);
} }
/** /**
* Unregisters all commands from a source File * Unregisters all commands from a source File
* *
* @param sourceFile file containing source code * @param sourceFile file containing source code
* @param plugin your plugin class * @param plugin your plugin class
*/ */
public static void unregisterCommands(File sourceFile, JavaPlugin plugin) { public static void unregisterCommands(File sourceFile, JavaPlugin plugin) {
StringBuilder src = new StringBuilder(); StringBuilder src = new StringBuilder();
String buf = ""; String buf = "";
try { try {
BufferedReader reader = new BufferedReader(new FileReader(sourceFile)); BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
while ((buf = reader.readLine()) != null) { while ((buf = reader.readLine()) != null) {
@@ -212,33 +186,10 @@ public class CommandManager {
} }
unregisterCommands(src.toString()); unregisterCommands(src.toString());
} }
/**
* Unregisters all commands from an InputStream
*
* @param sourceStream input stream containing source code
* @param plugin your plugin class
*/
public static void unregisterCommands(InputStream sourceStream, JavaPlugin plugin) {
StringBuilder src = new StringBuilder();
String buf = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(sourceStream));
while ((buf = reader.readLine()) != null) {
src.append(buf + '\n');
}
reader.close();
} catch (Exception e) {
plugin.getLogger().log(Level.WARNING, "Error while loading command file. (" + sourceStream.toString() + ")");
plugin.getLogger().log(Level.WARNING, e.getCause().toString());
return;
}
unregisterCommands(src.toString());
}
/** /**
* Unregisters all commands from a String of source code * Unregisters all commands from a String of source code
* *
* @param cmdSourceCode source code * @param cmdSourceCode source code
*/ */
public static void unregisterCommands(String cmdSourceCode) { public static void unregisterCommands(String cmdSourceCode) {
@@ -247,15 +198,15 @@ public class CommandManager {
} }
parseUnregister(cmdSourceCode); parseUnregister(cmdSourceCode);
} }
public static void parseUnregister(String src) { public static void parseUnregister(String src) {
char[] chars = src.toCharArray(); char[] chars = src.toCharArray();
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
int nesting = 0; int nesting = 0;
for (int i = 0; i < chars.length; i++) { for (int i = 0; i < chars.length; i++) {
char c = chars[i]; char c = chars[i];
if (c == ';') { if (c == ';') {
if (nesting == 1) { if (nesting == 1) {
String[] alias = buffer.toString().trim().split("\\ "); String[] alias = buffer.toString().trim().split("\\ ");
@@ -264,7 +215,7 @@ public class CommandManager {
} }
} }
buffer = new StringBuilder(); buffer = new StringBuilder();
}else if (c == '{') { } else if (c == '{') {
if (nesting == 0) { if (nesting == 0) {
String[] command = buffer.toString().trim().split("\\ "); String[] command = buffer.toString().trim().split("\\ ");
if (command.length == 2 && command[0].equals("command")) { if (command.length == 2 && command[0].equals("command")) {
@@ -275,10 +226,10 @@ public class CommandManager {
nesting++; nesting++;
} }
buffer = new StringBuilder(); buffer = new StringBuilder();
}else if (c == '}') { } else if (c == '}') {
nesting--; nesting--;
buffer = new StringBuilder(); buffer = new StringBuilder();
}else { } else {
buffer.append(c); buffer.append(c);
} }
} }
@@ -286,7 +237,7 @@ public class CommandManager {
/** /**
* Unregisters a command specified by its name or alias * Unregisters a command specified by its name or alias
* *
* @param name name or alias of command * @param name name or alias of command
*/ */
public static void unregisterCommand(String name) { public static void unregisterCommand(String name) {
@@ -294,10 +245,10 @@ public class CommandManager {
try { try {
final Field mapField = Bukkit.getServer().getClass().getDeclaredField("commandMap"); final Field mapField = Bukkit.getServer().getClass().getDeclaredField("commandMap");
mapField.setAccessible(true); mapField.setAccessible(true);
CommandMap map = (CommandMap) mapField.get(Bukkit.getServer()); CommandMap map = (CommandMap) mapField.get(Bukkit.getServer());
final Field knownCommandsField = mapField.getClass().getSuperclass().getDeclaredField("knownCommands"); final Field knownCommandsField = mapField.getClass().getSuperclass().getDeclaredField("knownCommands");
knownCommandsField.setAccessible(true); knownCommandsField.setAccessible(true);
@SuppressWarnings("unchecked") @SuppressWarnings ("unchecked")
Map<String, Command> knownCommands = (Map<String, Command>) knownCommandsField.get(map); Map<String, Command> knownCommands = (Map<String, Command>) knownCommandsField.get(map);
knownCommands.remove(name); knownCommands.remove(name);
map.register(name, empty); map.register(name, empty);
@@ -305,19 +256,40 @@ public class CommandManager {
e.printStackTrace(); e.printStackTrace();
} }
} }
public static void unregisterAll(String[] commands) /**
{ * Unregisters all commands from an InputStream
for (String name : commands) *
{ * @param sourceStream input stream containing source code
* @param plugin your plugin class
*/
public static void unregisterCommands(InputStream sourceStream, JavaPlugin plugin) {
StringBuilder src = new StringBuilder();
String buf = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(sourceStream));
while ((buf = reader.readLine()) != null) {
src.append(buf + '\n');
}
reader.close();
} catch (Exception e) {
plugin.getLogger().log(Level.WARNING, "Error while loading command file. (" + sourceStream.toString() + ")");
plugin.getLogger().log(Level.WARNING, e.getCause().toString());
return;
}
unregisterCommands(src.toString());
}
public static void unregisterAll(String[] commands) {
for (String name : commands) {
EmptyCommand emptyCommand = new EmptyCommand(name); EmptyCommand emptyCommand = new EmptyCommand(name);
try { try {
final Field cmdMap = Bukkit.getServer().getClass().getDeclaredField("commandMap"); final Field cmdMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
cmdMap.setAccessible(true); cmdMap.setAccessible(true);
CommandMap map = (CommandMap) cmdMap.get(Bukkit.getServer()); CommandMap map = (CommandMap) cmdMap.get(Bukkit.getServer());
final Field knownCommandsField = map.getClass().getSuperclass().getDeclaredField("knownCommands"); final Field knownCommandsField = map.getClass().getSuperclass().getDeclaredField("knownCommands");
knownCommandsField.setAccessible(true); knownCommandsField.setAccessible(true);
@SuppressWarnings("unchecked") @SuppressWarnings ("unchecked")
Map<String, Command> knownCommands = (Map<String, Command>) knownCommandsField.get(map); Map<String, Command> knownCommands = (Map<String, Command>) knownCommandsField.get(map);
knownCommands.remove(name); knownCommands.remove(name);
map.register(name, emptyCommand); map.register(name, emptyCommand);
@@ -326,26 +298,26 @@ public class CommandManager {
} }
} }
} }
public static void unregisterAllWithFallback(String fallback) { public static void unregisterAllWithFallback(String fallback) {
try { try {
final Field cmdMap = Bukkit.getServer().getClass().getDeclaredField("commandMap"); final Field cmdMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
cmdMap.setAccessible(true); cmdMap.setAccessible(true);
CommandMap map = (CommandMap) cmdMap.get(Bukkit.getServer()); CommandMap map = (CommandMap) cmdMap.get(Bukkit.getServer());
final Field knownCommandsField = map.getClass().getSuperclass().getDeclaredField("knownCommands"); final Field knownCommandsField = map.getClass().getSuperclass().getDeclaredField("knownCommands");
knownCommandsField.setAccessible(true); knownCommandsField.setAccessible(true);
@SuppressWarnings("unchecked") @SuppressWarnings ("unchecked")
Map<String, org.bukkit.command.Command> knownCommands = (Map<String, org.bukkit.command.Command>) knownCommandsField.get(map); Map<String, org.bukkit.command.Command> knownCommands = (Map<String, org.bukkit.command.Command>) knownCommandsField.get(map);
fallback = fallback.toLowerCase(); fallback = fallback.toLowerCase();
List<String> toRemove = new ArrayList<>(); List<String> toRemove = new ArrayList<>();
for (String key: knownCommands.keySet()) { for (String key : knownCommands.keySet()) {
org.bukkit.command.Command value = knownCommands.get(key); org.bukkit.command.Command value = knownCommands.get(key);
if ((value instanceof Executable) && ((Executable)value).getMethodContainerName().equals(fallback)) { if ((value instanceof Executable) && ((Executable) value).getMethodContainerName().equals(fallback)) {
toRemove.add(key); toRemove.add(key);
value.unregister(map); value.unregister(map);
} }
} }
for (String key : toRemove) { for (String key : toRemove) {
@@ -353,20 +325,21 @@ public class CommandManager {
knownCommands.remove(key); knownCommands.remove(key);
map.register(key, emptyCommand); map.register(key, emptyCommand);
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* Parses the source code into an abstract command syntax * Parses the source code into an abstract command syntax
* *
* @param source String containing command source code * @param source String containing command source code
* @param methods ArrayList of methods gathered from the plugin's handler class * @param methods ArrayList of methods gathered from the plugin's handler class
* @param plugin plugin to register commands as * @param plugin plugin to register commands as
* @param methodContainer class containing method handles * @param methodContainer class containing method handles
*
* @return success - if command parsing and registration was successful * @return success - if command parsing and registration was successful
*/ */
private static boolean parse(String source, ArrayList<Method> methods, JavaPlugin plugin, Object methodContainer) { private static boolean parse(String source, ArrayList<Method> methods, JavaPlugin plugin, Object methodContainer) {
@@ -398,7 +371,7 @@ public class CommandManager {
int line = 0; int line = 0;
// buffer for '...' and '"' properties of string types // buffer for '...' and '"' properties of string types
StringBuilder sideBuffer = new StringBuilder(); StringBuilder sideBuffer = new StringBuilder();
/* iterate over all characters */ /* iterate over all characters */
for (int i = 0; i < chars.length; i++) { for (int i = 0; i < chars.length; i++) {
/* get current char */ /* get current char */
@@ -421,7 +394,7 @@ public class CommandManager {
plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": Already defining a type."); plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": Already defining a type.");
errors = true; errors = true;
return false; return false;
}else{ } else {
/* okay, resolve what type this is */ /* okay, resolve what type this is */
currentArgComp = resolveComponentType(buffer.toString()); currentArgComp = resolveComponentType(buffer.toString());
buffer = new StringBuilder(); buffer = new StringBuilder();
@@ -432,18 +405,18 @@ public class CommandManager {
return false; return false;
} }
} }
}else{ } else {
/* not inside a type, probably just a string in the help property */ /* not inside a type, probably just a string in the help property */
buffer.append(':'); buffer.append(':');
} }
/* current is a semicolon, we just finished a property line */ /* current is a semicolon, we just finished a property line */
/* help this is an example; */ /* help this is an example; */
/* ^ */ /* ^ */
}else if (current == ';') { } else if (current == ';') {
/* semicolon is backslash escaped, treat it as a normal character */ /* semicolon is backslash escaped, treat it as a normal character */
if (previous == '\\') { if (previous == '\\') {
buffer.append(';'); buffer.append(';');
}else{ } else {
/* there is nothing on the stack, we are defining properties of 'nothing', throw an error */ /* there is nothing on the stack, we are defining properties of 'nothing', throw an error */
if (stack.get() == null) { if (stack.get() == null) {
plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": Not in code section."); plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": Not in code section.");
@@ -454,25 +427,27 @@ public class CommandManager {
if (gettingAlias) { if (gettingAlias) {
stack.get().aliases.add(buffer.toString()); stack.get().aliases.add(buffer.toString());
gettingAlias = false; gettingAlias = false;
}else if (currentProp == Property.HELP) { } else if (currentProp == Property.HELP) {
stack.get().help = buffer.toString(); stack.get().help = buffer.toString();
/* same as above, except its the function to run */ /* same as above, except its the function to run */
}else if (currentProp == Property.EXECUTE) { } else if (currentProp == Property.EXECUTE) {
stack.get().execute = buffer.toString(); stack.get().execute = buffer.toString();
/* same again, but with the permission, and as that should not contain spaces, trim it */ /* same again, but with the permission, and as that should not contain spaces, trim it */
}else if (currentProp == Property.PERMISSION) { } else if (currentProp == Property.PERMISSION) {
stack.get().permission = buffer.toString().trim(); stack.get().permission = buffer.toString().trim();
/* execution type, check if its a valid one and set it */ /* execution type, check if its a valid one and set it */
}else if (currentProp == Property.TYPE) { } else if (currentProp == Property.TYPE) {
stack.get().type = resolveExecutionType(buffer.toString().trim()); stack.get().type = resolveExecutionType(buffer.toString().trim());
/* not a valid type, throw an error */ /* not a valid type, throw an error */
if (stack.get().type == null) { if (stack.get().type == null) {
plugin.getLogger().log(Level.WARNING, "Attribute error at line " + line + ": Invalid attribute value. (" + buffer.toString().trim() + ")."); plugin
.getLogger()
.log(Level.WARNING, "Attribute error at line " + line + ": Invalid attribute value. (" + buffer.toString().trim() + ").");
errors = true; errors = true;
return false; return false;
} }
/* currently not defining anything, throw an error */ /* currently not defining anything, throw an error */
}else{ } else {
plugin.getLogger().log(Level.WARNING, "Attribute error at line " + line + ": Invalid attribute type."); plugin.getLogger().log(Level.WARNING, "Attribute error at line " + line + ": Invalid attribute type.");
errors = true; errors = true;
return false; return false;
@@ -481,8 +456,8 @@ public class CommandManager {
currentProp = Property.NONE; currentProp = Property.NONE;
buffer = new StringBuilder(); buffer = new StringBuilder();
} }
/* current is an opening curly bracket, we just entered a sub-command property definition */ /* current is an opening curly bracket, we just entered a sub-command property definition */
}else if (current == '{') { } else if (current == '{') {
/* increment bracket counter */ /* increment bracket counter */
bracketCounter++; bracketCounter++;
/* are we getting the name of the command? */ /* are we getting the name of the command? */
@@ -490,14 +465,14 @@ public class CommandManager {
/* set the command name to what we just gathered (trimmed) */ /* set the command name to what we just gathered (trimmed) */
cmdName = buffer.toString().trim(); cmdName = buffer.toString().trim();
gettingName = false; gettingName = false;
}else{ } else {
/* are we currently in an argument? */ /* are we currently in an argument? */
if (currentArgComp == null) { if (currentArgComp == null) {
/* no, but if there is something that looks like text, put it into the current subcommand as a constant */ /* no, but if there is something that looks like text, put it into the current subcommand as a constant */
if (buffer.toString().trim().length() > 0) { if (buffer.toString().trim().length() > 0) {
currentChain.append(new ConstantComponent(buffer.toString().trim())); currentChain.append(new ConstantComponent(buffer.toString().trim()));
} }
}else{ } else {
/* yes, put it into the current subcommand */ /* yes, put it into the current subcommand */
/* could happen when there are no 'spaces' */ /* could happen when there are no 'spaces' */
/* [str:example]{ */ /* [str:example]{ */
@@ -518,8 +493,8 @@ public class CommandManager {
stack.push(currentChain); stack.push(currentChain);
/* reset our current sub-command */ /* reset our current sub-command */
currentChain = new ChainComponent(); currentChain = new ChainComponent();
/* current is a closing curly bracket, we just finished a property section */ /* current is a closing curly bracket, we just finished a property section */
}else if (current == '}') { } else if (current == '}') {
/* decrement the bracket counter */ /* decrement the bracket counter */
bracketCounter--; bracketCounter--;
/* pop whatever was on the stack */ /* pop whatever was on the stack */
@@ -558,42 +533,42 @@ public class CommandManager {
continue; continue;
} }
currentChain = new ChainComponent(); currentChain = new ChainComponent();
/* current is a space, we just finished defining which property we are about to set */ /* current is a space, we just finished defining which property we are about to set */
}else if (current == ' ') { } else if (current == ' ') {
/* we are already defining a property, append it as text */ /* we are already defining a property, append it as text */
if (currentProp != Property.NONE) { if (currentProp != Property.NONE) {
buffer.append(' '); buffer.append(' ');
}else{ } else {
/* we got the 'command' definition, the name of the command will follow */ /* we got the 'command' definition, the name of the command will follow */
if (buffer.toString().equals("command") && !gettingName && !gettingAlias && cmdName == null) { if (buffer.toString().equals("command") && !gettingName && !gettingAlias && cmdName == null) {
gettingName = true; gettingName = true;
/* we got other properties, their values will follow */ /* we got other properties, their values will follow */
}else if (buffer.toString().equals("alias") && !gettingAlias && !gettingName) { } else if (buffer.toString().equals("alias") && !gettingAlias && !gettingName) {
gettingAlias = true; gettingAlias = true;
}else if (buffer.toString().equals("help")) { } else if (buffer.toString().equals("help")) {
currentProp = Property.HELP; currentProp = Property.HELP;
}else if (buffer.toString().equals("run")) { } else if (buffer.toString().equals("run")) {
currentProp = Property.EXECUTE; currentProp = Property.EXECUTE;
}else if (buffer.toString().equals("perm")) { } else if (buffer.toString().equals("perm")) {
currentProp = Property.PERMISSION; currentProp = Property.PERMISSION;
}else if (buffer.toString().equals("type")) { } else if (buffer.toString().equals("type")) {
currentProp = Property.TYPE; currentProp = Property.TYPE;
/* we didn't get any of those, we are probably in the middle of a sub-command definition */ /* we didn't get any of those, we are probably in the middle of a sub-command definition */
/* example [int:value] { */ /* example [int:value] { */
/* ^ ^ */ /* ^ ^ */
}else{ } else {
/* we are getting the name and we didn't set it yet, set it */ /* we are getting the name and we didn't set it yet, set it */
if (gettingName && cmdName == null) { if (gettingName && cmdName == null) {
cmdName = buffer.toString().trim(); cmdName = buffer.toString().trim();
gettingName = false; gettingName = false;
}else{ } else {
/* we aren't defining a type, put the current text into the sub-command as a constant */ /* we aren't defining a type, put the current text into the sub-command as a constant */
if (currentArgComp == null) { if (currentArgComp == null) {
if (buffer.toString().trim().length() > 0) { if (buffer.toString().trim().length() > 0) {
currentChain.append(new ConstantComponent(buffer.toString().trim())); currentChain.append(new ConstantComponent(buffer.toString().trim()));
} }
/* we are defining a command, put it into the sub-command */ /* we are defining a command, put it into the sub-command */
}else{ } else {
currentChain.append(currentArgComp); currentChain.append(currentArgComp);
currentArgComp = null; currentArgComp = null;
} }
@@ -602,41 +577,41 @@ public class CommandManager {
/* reset the buffer */ /* reset the buffer */
buffer = new StringBuilder(); buffer = new StringBuilder();
} }
/* current is an opening square bracket, we just started a type definition */ /* current is an opening square bracket, we just started a type definition */
}else if (current == '[') { } else if (current == '[') {
/* we are defining a property, treat it as text */ /* we are defining a property, treat it as text */
if (currentProp != Property.NONE) { if (currentProp != Property.NONE) {
buffer.append('['); buffer.append('[');
/* we are already inside of a type definition, throw an error */ /* we are already inside of a type definition, throw an error */
}else if (insideType) { } else if (insideType) {
plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": Invalid type declaration."); plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": Invalid type declaration.");
errors = true; errors = true;
return false; return false;
}else{ } else {
/* we just entered a type definition */ /* we just entered a type definition */
insideType = true; insideType = true;
} }
/* current is a closing square bracket, we just finished a type definition */ /* current is a closing square bracket, we just finished a type definition */
}else if (current == ']') { } else if (current == ']') {
/* we are defining a property, treat it as text */ /* we are defining a property, treat it as text */
if (currentProp != Property.NONE) { if (currentProp != Property.NONE) {
buffer.append(']'); buffer.append(']');
/* we are inside of a type */ /* we are inside of a type */
}else if (insideType) { } else if (insideType) {
insideType = false; insideType = false;
/* current argument type is null, throw an error */ /* current argument type is null, throw an error */
if (currentArgComp == null) { if (currentArgComp == null) {
currentArgComp = resolveComponentType(buffer.toString()); currentArgComp = resolveComponentType(buffer.toString());
buffer = new StringBuilder(); buffer = new StringBuilder();
if (currentArgComp instanceof EmptyComponent) { if (currentArgComp instanceof EmptyComponent) {
}else{ } else {
/* should never happen */ /* should never happen */
plugin.getLogger().log(Level.WARNING, "Type error at line " + line + ": Type has no type?"); plugin.getLogger().log(Level.WARNING, "Type error at line " + line + ": Type has no type?");
errors = true; errors = true;
return false; return false;
} }
}else{ } else {
/* set the value of the current type and reset the buffer */ /* set the value of the current type and reset the buffer */
currentArgComp.argName = buffer.toString(); currentArgComp.argName = buffer.toString();
buffer = new StringBuilder(); buffer = new StringBuilder();
@@ -646,109 +621,111 @@ public class CommandManager {
} }
sideBuffer = new StringBuilder(); sideBuffer = new StringBuilder();
} }
}else{ } else {
/* we are not defining a type, throw an error */ /* we are not defining a type, throw an error */
plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": Not in type declaration."); plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": Not in type declaration.");
errors = true; errors = true;
return false; return false;
} }
/* typical escape sequences and such */ /* typical escape sequences and such */
}else if (current == 'n' && currentProp == Property.HELP) { } else if (current == 'n' && currentProp == Property.HELP) {
if (previous == '\\') { if (previous == '\\') {
buffer.append('\n'); buffer.append('\n');
}else{ } else {
buffer.append('n'); buffer.append('n');
} }
}else if (current == 't' && currentProp == Property.HELP) { } else if (current == 't' && currentProp == Property.HELP) {
if (previous == '\\') { if (previous == '\\') {
buffer.append('\t'); buffer.append('\t');
}else{ } else {
buffer.append('t'); buffer.append('t');
} }
}else if (current == '\\' && currentProp == Property.HELP) { } else if (current == '\\' && currentProp == Property.HELP) {
if (previous == '\\') { if (previous == '\\') {
buffer.append('\\'); buffer.append('\\');
} }
}else if (current != '\r' && current != '\n' && current != '\t') { } else if (current != '\r' && current != '\n' && current != '\t') {
if (currentArgComp != null && current == '.') { if (currentArgComp != null && current == '.') {
if (currentArgComp instanceof StringComponent) { if (currentArgComp instanceof StringComponent) {
sideBuffer.append(current); sideBuffer.append(current);
}else{ } else {
plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": '...' is invalid for non-string types."); plugin.getLogger().log(Level.WARNING, "Syntax error at line " + line + ": '...' is invalid for non-string types.");
errors = true; errors = true;
return false; return false;
} }
}else{ } else {
buffer.append(current); buffer.append(current);
} }
} }
previous = current; previous = current;
} }
return true; return true;
} }
/** /**
* Resolves the string into a type, or null if invalid * Resolves the string into a type, or null if invalid
* *
* @param type string you want to evaluate * @param type string you want to evaluate
*
* @return the type class or null if invalid * @return the type class or null if invalid
*/ */
private static ArgumentComponent resolveComponentType(String type) { private static ArgumentComponent resolveComponentType(String type) {
switch (type) { switch (type) {
case "string": case "string":
return new StringComponent(); return new StringComponent();
case "int": case "int":
case "integer": case "integer":
return new IntegerComponent(); return new IntegerComponent();
case "short": case "short":
return new ShortComponent(); return new ShortComponent();
case "long": case "long":
return new LongComponent(); return new LongComponent();
case "byte": case "byte":
return new ByteComponent(); return new ByteComponent();
case "float": case "float":
return new FloatComponent(); return new FloatComponent();
case "double": case "double":
return new DoubleComponent(); return new DoubleComponent();
case "bool": case "bool":
case "boolean": case "boolean":
return new BooleanComponent(); return new BooleanComponent();
case "optional": case "optional":
case "opt": case "opt":
case "flag": case "flag":
return new OptionalComponent(); return new OptionalComponent();
case "empty": case "empty":
case "null": case "null":
return new EmptyComponent(); return new EmptyComponent();
} }
return null; return null;
} }
/** /**
* Resolves the string into a property, or null if invalid * Resolves the string into a property, or null if invalid
* *
* @param type string you want to evaluate * @param type string you want to evaluate
*
* @return the property enum or null if invalid * @return the property enum or null if invalid
*/ */
private static Type resolveExecutionType(String type) { private static Type resolveExecutionType(String type) {
switch (type) { switch (type) {
case "player": case "player":
return Type.PLAYER; return Type.PLAYER;
case "both": case "both":
case "any": case "any":
case "all": case "all":
return Type.BOTH; return Type.BOTH;
case "server": case "server":
case "console": case "console":
return Type.CONSOLE; return Type.CONSOLE;
case "none": case "none":
case "nobody": case "nobody":
return Type.NOBODY; return Type.NOBODY;
} }
return null; return null;
} }
private static void postProcess(String cmdName, ChainComponent components, ArrayList<Method> methods, JavaPlugin plugin, Object methodContainer) { private static void postProcess(String cmdName, ChainComponent components, ArrayList<Method> methods, JavaPlugin plugin, Object methodContainer) {
components.execute = null; components.execute = null;
components.help = null; components.help = null;
@@ -757,21 +734,21 @@ public class CommandManager {
Executable cmd = new Executable(cmdName, constructHelpPages(cmdName, components), methodContainer.getClass().getSimpleName()); Executable cmd = new Executable(cmdName, constructHelpPages(cmdName, components), methodContainer.getClass().getSimpleName());
cmd.register(methods, plugin, methodContainer, components.getAliases()); cmd.register(methods, plugin, methodContainer, components.getAliases());
} }
private static ArrayList<HelpPageCommand[]> constructHelpPages(String cmdName, ChainComponent root) { private static ArrayList<HelpPageCommand[]> constructHelpPages(String cmdName, ChainComponent root) {
String[] rawLines = constructHelpPagesRecursive(root).split("\r"); String[] rawLines = constructHelpPagesRecursive(root).split("\r");
ArrayList<HelpPageCommand[]> pages = new ArrayList<HelpPageCommand[]>(); ArrayList<HelpPageCommand[]> pages = new ArrayList<HelpPageCommand[]>();
ArrayList<String> lines = new ArrayList<String>(); ArrayList<String> lines = new ArrayList<String>();
HelpPageCommand[] page = new HelpPageCommand[5]; HelpPageCommand[] page = new HelpPageCommand[5];
for (int i = 0; i < rawLines.length; i++) { for (int i = 0; i < rawLines.length; i++) {
if (rawLines[i].length() > 0 && !rawLines[i].equals("\0null\0null\0null\0null\0")) { if (rawLines[i].length() > 0 && !rawLines[i].equals("\0null\0null\0null\0null\0")) {
lines.add(rawLines[i]); lines.add(rawLines[i]);
} }
} }
boolean firstPass = true; boolean firstPass = true;
int i; int i;
for (i = 0; i < lines.size(); i++) { for (i = 0; i < lines.size(); i++) {
if (i % 5 == 0 && !firstPass) { if (i % 5 == 0 && !firstPass) {
pages.add(page); pages.add(page);
@@ -787,35 +764,37 @@ public class CommandManager {
} }
page[i % 5] = new HelpPageCommand(cmdName + ".help", "/" + cmdName + " help <page:i32>", "Shows help.", null, Type.BOTH); page[i % 5] = new HelpPageCommand(cmdName + ".help", "/" + cmdName + " help <page:i32>", "Shows help.", null, Type.BOTH);
pages.add(page); pages.add(page);
return pages; return pages;
} }
private static String constructHelpPagesRecursive(ICommandComponent component) { private static String constructHelpPagesRecursive(ICommandComponent component) {
String data = ""; String data = "";
if (component instanceof ChainComponent) { if (component instanceof ChainComponent) {
ChainComponent comp = (ChainComponent) component; ChainComponent comp = (ChainComponent) component;
ArrayList<String> leaves = new ArrayList<String>(); ArrayList<String> leaves = new ArrayList<String>();
String chain = ""; String chain = "";
data += "\r"; data += "\r";
for (ICommandComponent c : comp.getComponents()) { for (ICommandComponent c : comp.getComponents()) {
String temp = constructHelpPagesRecursive(c); String temp = constructHelpPagesRecursive(c);
if (c instanceof ChainComponent) { if (c instanceof ChainComponent) {
temp = temp.replaceAll("\r", "\r" + chain); temp = temp.replaceAll("\r", "\r" + chain);
leaves.add(temp); leaves.add(temp);
}else{ } else {
chain += temp; chain += temp;
} }
} }
data += chain + "\0" + ((comp.permission == null || comp.permission.equals("-none-")) ? null : comp.permission) + "\0" + comp.execute + "\0" + comp.help + "\0" + Type.get(comp.type) + "\0"; data += chain + "\0" + ((comp.permission == null || comp.permission.equals("-none-"))
? null
: comp.permission) + "\0" + comp.execute + "\0" + comp.help + "\0" + Type.get(comp.type) + "\0";
for (String s : leaves) { for (String s : leaves) {
data += s; data += s;
} }
}else{ } else {
data += component.getComponentInfo() + " "; data += component.getComponentInfo() + " ";
} }
return data; return data;
} }
}//@format }//@format

View File

@@ -1,19 +1,15 @@
package com.nemez.cmdmgr; package com.nemez.cmdmgr;
import com.nemez.cmdmgr.util.Executable;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.nemez.cmdmgr.util.Executable; public class EmptyCommand extends Executable {
public EmptyCommand(String name) {
public class EmptyCommand extends Executable
{
public EmptyCommand(String name)
{
super(name, null, ""); super(name, null, "");
} }
@Override @Override
public boolean execute(CommandSender sender, String name, String[] args_) public boolean execute(CommandSender sender, String name, String[] args_) {
{
sender.sendMessage("§cCommand no longer Exists. Use §e/help§c, §e/plugins§c or ask a mod."); sender.sendMessage("§cCommand no longer Exists. Use §e/help§c, §e/plugins§c or ask a mod.");
return true; return true;
} }

View File

@@ -3,7 +3,7 @@ package com.nemez.cmdmgr.component;
public abstract class ArgumentComponent implements ICommandComponent { public abstract class ArgumentComponent implements ICommandComponent {
public String argName; public String argName;
public int position; public int position;
@Override @Override
public String argName() { public String argName() {

View File

@@ -1,7 +1,7 @@
package com.nemez.cmdmgr.component; package com.nemez.cmdmgr.component;
public class BooleanComponent extends ArgumentComponent { public class BooleanComponent extends ArgumentComponent {
@Override @Override
public Object get(String input) { public Object get(String input) {
if (input.toLowerCase().equals("true") || input.toLowerCase().equals("yes")) { if (input.toLowerCase().equals("true") || input.toLowerCase().equals("yes")) {
@@ -12,14 +12,16 @@ public class BooleanComponent extends ArgumentComponent {
@Override @Override
public boolean valid(String input) { public boolean valid(String input) {
if (input.toLowerCase().equals("true") || input.toLowerCase().equals("false") || input.toLowerCase().equals("yes") || input.toLowerCase().equals("no")) { if (input.toLowerCase().equals("true") || input.toLowerCase().equals("false") || input.toLowerCase().equals("yes") || input
.toLowerCase()
.equals("no")) {
return true; return true;
} }
return false; return false;
} }
@Override @Override
public String getComponentInfo() { public String getComponentInfo() {
return "<" + argName + ":bool>"; return "<" + argName + ":bool>";
} }
} }

View File

@@ -1,7 +1,7 @@
package com.nemez.cmdmgr.component; package com.nemez.cmdmgr.component;
public class ByteComponent extends ArgumentComponent { public class ByteComponent extends ArgumentComponent {
@Override @Override
public Object get(String input) { public Object get(String input) {
try { try {
@@ -20,9 +20,9 @@ public class ByteComponent extends ArgumentComponent {
return false; return false;
} }
} }
@Override @Override
public String getComponentInfo() { public String getComponentInfo() {
return "<" + argName + ":i8>"; return "<" + argName + ":i8>";
} }
} }

View File

@@ -1,22 +1,22 @@
package com.nemez.cmdmgr.component; package com.nemez.cmdmgr.component;
import java.util.ArrayList;
import com.nemez.cmdmgr.util.Type; import com.nemez.cmdmgr.util.Type;
import java.util.ArrayList;
public class ChainComponent implements ICommandComponent { public class ChainComponent implements ICommandComponent {
public String permission;
public String help;
public String execute;
public Type type;
public ArrayList<String> aliases = new ArrayList<String>();
private ArrayList<ICommandComponent> components; private ArrayList<ICommandComponent> components;
public String permission;
public String help;
public String execute;
public Type type;
public ArrayList<String> aliases = new ArrayList<String>();
public ChainComponent() { public ChainComponent() {
components = new ArrayList<ICommandComponent>(); components = new ArrayList<ICommandComponent>();
} }
public void append(ICommandComponent comp) { public void append(ICommandComponent comp) {
components.add(comp); components.add(comp);
} }
@@ -35,21 +35,21 @@ public class ChainComponent implements ICommandComponent {
public String argName() { public String argName() {
return null; return null;
} }
@Override @Override
public String getComponentInfo() { public String getComponentInfo() {
return "chain[" + components.size() + "]"; return "chain[" + components.size() + "]";
} }
public int capacity() { public int capacity() {
return components.size(); return components.size();
} }
public ArrayList<ICommandComponent> getComponents() { public ArrayList<ICommandComponent> getComponents() {
return components; return components;
} }
public ArrayList<String> getAliases() { public ArrayList<String> getAliases() {
return aliases; return aliases;
} }
} }

View File

@@ -3,11 +3,11 @@ package com.nemez.cmdmgr.component;
public class ConstantComponent implements ICommandComponent { public class ConstantComponent implements ICommandComponent {
private String component; private String component;
public ConstantComponent(String comp) { public ConstantComponent(String comp) {
component = comp; component = comp;
} }
@Override @Override
public Object get(String input) { public Object get(String input) {
if (input.equals(component)) { if (input.equals(component)) {
@@ -25,7 +25,7 @@ public class ConstantComponent implements ICommandComponent {
public String argName() { public String argName() {
return null; return null;
} }
@Override @Override
public String getComponentInfo() { public String getComponentInfo() {
return component; return component;

View File

@@ -20,7 +20,7 @@ public class DoubleComponent extends ArgumentComponent {
return false; return false;
} }
} }
@Override @Override
public String getComponentInfo() { public String getComponentInfo() {
return "<" + argName + ":fp64>"; return "<" + argName + ":fp64>";

View File

@@ -11,7 +11,7 @@ public class EmptyComponent extends ArgumentComponent {
public boolean valid(String input) { public boolean valid(String input) {
return true; return true;
} }
@Override @Override
public String getComponentInfo() { public String getComponentInfo() {
return "<empty>"; return "<empty>";

View File

@@ -20,7 +20,7 @@ public class FloatComponent extends ArgumentComponent {
return false; return false;
} }
} }
@Override @Override
public String getComponentInfo() { public String getComponentInfo() {
return "<" + argName + ":fp32>"; return "<" + argName + ":fp32>";

View File

@@ -3,7 +3,10 @@ package com.nemez.cmdmgr.component;
public interface ICommandComponent { public interface ICommandComponent {
public Object get(String input); public Object get(String input);
public boolean valid(String input); public boolean valid(String input);
public String argName(); public String argName();
public String getComponentInfo(); public String getComponentInfo();
} }

View File

@@ -20,7 +20,7 @@ public class IntegerComponent extends ArgumentComponent {
return false; return false;
} }
} }
@Override @Override
public String getComponentInfo() { public String getComponentInfo() {
return "<" + argName + ":i32>"; return "<" + argName + ":i32>";

View File

@@ -20,7 +20,7 @@ public class LongComponent extends ArgumentComponent {
return false; return false;
} }
} }
@Override @Override
public String getComponentInfo() { public String getComponentInfo() {
return "<" + argName + ":i64>"; return "<" + argName + ":i64>";

View File

@@ -1,7 +1,7 @@
package com.nemez.cmdmgr.component; package com.nemez.cmdmgr.component;
public class OptionalComponent extends ArgumentComponent { public class OptionalComponent extends ArgumentComponent {
@Override @Override
public Object get(String input) { public Object get(String input) {
return input.equals(argName); return input.equals(argName);

View File

@@ -20,7 +20,7 @@ public class ShortComponent extends ArgumentComponent {
return false; return false;
} }
} }
@Override @Override
public String getComponentInfo() { public String getComponentInfo() {
return "<" + argName + ":i16>"; return "<" + argName + ":i16>";

View File

@@ -3,7 +3,7 @@ package com.nemez.cmdmgr.component;
public class StringComponent extends ArgumentComponent { public class StringComponent extends ArgumentComponent {
public boolean infinite = false; public boolean infinite = false;
@Override @Override
public Object get(String input) { public Object get(String input) {
return input; return input;
@@ -13,7 +13,7 @@ public class StringComponent extends ArgumentComponent {
public boolean valid(String input) { public boolean valid(String input) {
return true; return true;
} }
@Override @Override
public String getComponentInfo() { public String getComponentInfo() {
return "<" + (infinite ? "..." : "") + argName + ":str>"; return "<" + (infinite ? "..." : "") + argName + ":str>";

View File

@@ -1,29 +1,23 @@
package com.nemez.cmdmgr.util; package com.nemez.cmdmgr.util;
import com.nemez.cmdmgr.component.ICommandComponent;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import org.bukkit.command.CommandSender; public class AsyncExecutableDefinition extends ExecutableDefinition {
import org.bukkit.plugin.java.JavaPlugin;
import com.nemez.cmdmgr.component.ICommandComponent;
public class AsyncExecutableDefinition extends ExecutableDefinition
{
public AsyncExecutableDefinition(ArrayList<ICommandComponent> cmd, ArrayList<Integer> paramLinks, String perm, public AsyncExecutableDefinition(ArrayList<ICommandComponent> cmd, ArrayList<Integer> paramLinks, String perm,
Method method, Object methodContainer, Type type) Method method, Object methodContainer, Type type) {
{
super(cmd, paramLinks, perm, method, methodContainer, type); super(cmd, paramLinks, perm, method, methodContainer, type);
} }
@Override @Override
public boolean invoke(Object[] args, CommandSender sender, JavaPlugin plugin) public boolean invoke(Object[] args, CommandSender sender, JavaPlugin plugin) {
{ Thread t = new Thread(new Runnable() {
Thread t = new Thread(new Runnable()
{
@Override @Override
public void run() public void run() {
{
invokeFromThread(args, sender, plugin); invokeFromThread(args, sender, plugin);
} }
}); });
@@ -31,9 +25,8 @@ public class AsyncExecutableDefinition extends ExecutableDefinition
t.start(); t.start();
return true; return true;
} }
private final void invokeFromThread(Object[] args, CommandSender sender, JavaPlugin plugin) private final void invokeFromThread(Object[] args, CommandSender sender, JavaPlugin plugin) {
{
super.invoke(args, sender, plugin); super.invoke(args, sender, plugin);
} }
} }

View File

@@ -1,21 +1,21 @@
package com.nemez.cmdmgr.util; package com.nemez.cmdmgr.util;
import java.util.ArrayList;
import com.nemez.cmdmgr.component.ChainComponent; import com.nemez.cmdmgr.component.ChainComponent;
import java.util.ArrayList;
public class BranchStack { public class BranchStack {
private ArrayList<ChainComponent> components; private ArrayList<ChainComponent> components;
public BranchStack() { public BranchStack() {
components = new ArrayList<ChainComponent>(); components = new ArrayList<ChainComponent>();
} }
public void push(ChainComponent comp) { public void push(ChainComponent comp) {
components.add(comp); components.add(comp);
} }
public ChainComponent pop() { public ChainComponent pop() {
if (components.size() > 0) { if (components.size() > 0) {
ChainComponent toPop = components.remove(components.size() - 1); ChainComponent toPop = components.remove(components.size() - 1);
@@ -23,7 +23,7 @@ public class BranchStack {
} }
return null; return null;
} }
public ChainComponent get() { public ChainComponent get() {
if (components.size() > 0) { if (components.size() > 0) {
return components.get(components.size() - 1); return components.get(components.size() - 1);

View File

@@ -1,6 +1,17 @@
//@noformat //@noformat
package com.nemez.cmdmgr.util; package com.nemez.cmdmgr.util;
import com.nemez.cmdmgr.Command;
import com.nemez.cmdmgr.Command.AsyncType;
import com.nemez.cmdmgr.CommandManager;
import com.nemez.cmdmgr.component.*;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
@@ -8,36 +19,14 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.logging.Level; import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import com.nemez.cmdmgr.Command;
import com.nemez.cmdmgr.Command.AsyncType;
import com.nemez.cmdmgr.CommandManager;
import com.nemez.cmdmgr.component.BooleanComponent;
import com.nemez.cmdmgr.component.ByteComponent;
import com.nemez.cmdmgr.component.ConstantComponent;
import com.nemez.cmdmgr.component.DoubleComponent;
import com.nemez.cmdmgr.component.FloatComponent;
import com.nemez.cmdmgr.component.ICommandComponent;
import com.nemez.cmdmgr.component.IntegerComponent;
import com.nemez.cmdmgr.component.LongComponent;
import com.nemez.cmdmgr.component.OptionalComponent;
import com.nemez.cmdmgr.component.ShortComponent;
import com.nemez.cmdmgr.component.StringComponent;
public class Executable extends org.bukkit.command.Command { public class Executable extends org.bukkit.command.Command {
private ArrayList<ExecutableDefinition> commands; private ArrayList<ExecutableDefinition> commands;
private ArrayList<HelpPageCommand[]> help; private ArrayList<HelpPageCommand[]> help;
private String name; private String name;
private String methodContainerName; private String methodContainerName;
private JavaPlugin plugin; private JavaPlugin plugin;
public Executable(String name, ArrayList<HelpPageCommand[]> help, String methodContainerName) { public Executable(String name, ArrayList<HelpPageCommand[]> help, String methodContainerName) {
super(name); super(name);
this.help = help; this.help = help;
@@ -45,43 +34,43 @@ public class Executable extends org.bukkit.command.Command {
this.commands = new ArrayList<ExecutableDefinition>(); this.commands = new ArrayList<ExecutableDefinition>();
this.methodContainerName = methodContainerName; this.methodContainerName = methodContainerName;
} }
public String getMethodContainerName() { public String getMethodContainerName() {
return methodContainerName; return methodContainerName;
} }
public void register(ArrayList<Method> methods, JavaPlugin plugin, Object methodContainer, ArrayList<String> aliases) { public void register(ArrayList<Method> methods, JavaPlugin plugin, Object methodContainer, ArrayList<String> aliases) {
methodContainerName = methodContainer.getClass().getSimpleName().toLowerCase(); methodContainerName = methodContainer.getClass().getSimpleName().toLowerCase();
for (HelpPageCommand[] page : help) { for (HelpPageCommand[] page : help) {
for (HelpPageCommand cmd : page) { for (HelpPageCommand cmd : page) {
if (cmd != null) { if (cmd != null) {
processLine(cmd.usage.split("\\ "), cmd.permission, cmd.method, methods, methodContainer, plugin, cmd.type); processLine(cmd.usage.split("\\ "), cmd.permission, cmd.method, methods, methodContainer, plugin, cmd.type);
String newUsage = ""; String newUsage = "";
String buffer = ""; String buffer = "";
String typeBuffer = ""; String typeBuffer = "";
boolean ignore = false; boolean ignore = false;
boolean toBuffer = false; boolean toBuffer = false;
for (char c : cmd.usage.toCharArray()) { for (char c : cmd.usage.toCharArray()) {
if (c == '<') { if (c == '<') {
toBuffer = true; toBuffer = true;
}else if (c == ':') { } else if (c == ':') {
toBuffer = false; toBuffer = false;
ignore = true; ignore = true;
}else if (c == '>') { } else if (c == '>') {
ignore = false; ignore = false;
if (typeBuffer.equals("flag")) { if (typeBuffer.equals("flag")) {
newUsage += '[' + buffer + (CommandManager.debugHelpMenu ? ':' + typeBuffer : "") + ']'; newUsage += '[' + buffer + (CommandManager.debugHelpMenu ? ':' + typeBuffer : "") + ']';
}else{ } else {
newUsage += '<' + buffer + (CommandManager.debugHelpMenu ? ':' + typeBuffer : "") + '>'; newUsage += '<' + buffer + (CommandManager.debugHelpMenu ? ':' + typeBuffer : "") + '>';
} }
buffer = ""; buffer = "";
typeBuffer = ""; typeBuffer = "";
}else{ } else {
if (toBuffer) { if (toBuffer) {
buffer += c; buffer += c;
}else if (ignore) { } else if (ignore) {
typeBuffer += c; typeBuffer += c;
}else{ } else {
newUsage += c; newUsage += c;
} }
} }
@@ -90,37 +79,38 @@ public class Executable extends org.bukkit.command.Command {
} }
} }
} }
this.plugin = plugin; this.plugin = plugin;
try { try {
final Field cmdMap = Bukkit.getServer().getClass().getDeclaredField("commandMap"); final Field cmdMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
cmdMap.setAccessible(true); cmdMap.setAccessible(true);
CommandMap map = (CommandMap) cmdMap.get(Bukkit.getServer()); CommandMap map = (CommandMap) cmdMap.get(Bukkit.getServer());
final Field knownCommandsField = map.getClass().getSuperclass().getDeclaredField("knownCommands"); final Field knownCommandsField = map.getClass().getSuperclass().getDeclaredField("knownCommands");
knownCommandsField.setAccessible(true); knownCommandsField.setAccessible(true);
@SuppressWarnings("unchecked") @SuppressWarnings ("unchecked")
Map<String, Command> knownCommands = (Map<String, Command>) knownCommandsField.get(map); Map<String, Command> knownCommands = (Map<String, Command>) knownCommandsField.get(map);
knownCommands.remove(name); knownCommands.remove(name);
map.register(methodContainerName, this); map.register(methodContainerName, this);
for (String alias : aliases) { for (String alias : aliases) {
Executable cmd = new Executable(alias, this.help, methodContainerName); Executable cmd = new Executable(alias, this.help, methodContainerName);
cmd.commands = this.commands; cmd.commands = this.commands;
cmd.plugin = this.plugin; cmd.plugin = this.plugin;
knownCommands.remove(alias); knownCommands.remove(alias);
map.register(methodContainerName, cmd); map.register(methodContainerName, cmd);
} }
} catch (Exception e) { } catch (Exception e) {
plugin.getLogger().log(Level.SEVERE, "Failed to register command '" + name + "'!"); plugin.getLogger().log(Level.SEVERE, "Failed to register command '" + name + "'!");
e.printStackTrace(); e.printStackTrace();
} }
if (CommandManager.errors) { if (CommandManager.errors) {
plugin.getLogger().log(Level.WARNING, "There were parser errors, some commands may not function properly!"); plugin.getLogger().log(Level.WARNING, "There were parser errors, some commands may not function properly!");
CommandManager.errors = false; CommandManager.errors = false;
} }
} }
private void processLine(String[] line, String permission, String method, ArrayList<Method> methods, Object methodContainer, JavaPlugin plugin, Type etype) { private void processLine(String[] line, String permission, String method, ArrayList<Method> methods, Object methodContainer, JavaPlugin plugin,
Type etype) {
ArrayList<ICommandComponent> command = new ArrayList<ICommandComponent>(); ArrayList<ICommandComponent> command = new ArrayList<ICommandComponent>();
if (method == null && line[1].equals("help")) { if (method == null && line[1].equals("help")) {
command.add(new ConstantComponent("help")); command.add(new ConstantComponent("help"));
@@ -133,75 +123,75 @@ public class Executable extends org.bukkit.command.Command {
} }
HashMap<Integer, ICommandComponent> methodParams = new HashMap<Integer, ICommandComponent>(); HashMap<Integer, ICommandComponent> methodParams = new HashMap<Integer, ICommandComponent>();
method = method.trim() + " "; method = method.trim() + " ";
String[] methodArray = method.split(" "); String[] methodArray = method.split(" ");
Method target = null; Method target = null;
ArrayList<Integer> links = new ArrayList<Integer>(); ArrayList<Integer> links = new ArrayList<Integer>();
for (String s : line) { for (String s : line) {
if (s.contains("/")) { if (s.contains("/")) {
continue; continue;
} }
if (s.contains(":")) { if (s.contains(":")) {
String[] type = s.split(":"); String[] type = s.split(":");
String paramName = ""; String paramName = "";
switch (type[1].substring(0, type[1].length() - 1)) { switch (type[1].substring(0, type[1].length() - 1)) {
case "i8": case "i8":
ByteComponent comp1 = new ByteComponent(); ByteComponent comp1 = new ByteComponent();
comp1.argName = type[0].substring(1); comp1.argName = type[0].substring(1);
paramName = comp1.argName; paramName = comp1.argName;
command.add(comp1); command.add(comp1);
break; break;
case "i16": case "i16":
ShortComponent comp2 = new ShortComponent(); ShortComponent comp2 = new ShortComponent();
comp2.argName = type[0].substring(1); comp2.argName = type[0].substring(1);
paramName = comp2.argName; paramName = comp2.argName;
command.add(comp2); command.add(comp2);
break; break;
case "i32": case "i32":
IntegerComponent comp3 = new IntegerComponent(); IntegerComponent comp3 = new IntegerComponent();
comp3.argName = type[0].substring(1); comp3.argName = type[0].substring(1);
paramName = comp3.argName; paramName = comp3.argName;
command.add(comp3); command.add(comp3);
break; break;
case "i64": case "i64":
LongComponent comp4 = new LongComponent(); LongComponent comp4 = new LongComponent();
comp4.argName = type[0].substring(1); comp4.argName = type[0].substring(1);
paramName = comp4.argName; paramName = comp4.argName;
command.add(comp4); command.add(comp4);
break; break;
case "fp32": case "fp32":
FloatComponent comp5 = new FloatComponent(); FloatComponent comp5 = new FloatComponent();
comp5.argName = type[0].substring(1); comp5.argName = type[0].substring(1);
paramName = comp5.argName; paramName = comp5.argName;
command.add(comp5); command.add(comp5);
break; break;
case "fp64": case "fp64":
DoubleComponent comp6 = new DoubleComponent(); DoubleComponent comp6 = new DoubleComponent();
comp6.argName = type[0].substring(1); comp6.argName = type[0].substring(1);
paramName = comp6.argName; paramName = comp6.argName;
command.add(comp6); command.add(comp6);
break; break;
case "str": case "str":
StringComponent comp7 = new StringComponent(); StringComponent comp7 = new StringComponent();
comp7.argName = type[0].substring(1).replace("...", ""); comp7.argName = type[0].substring(1).replace("...", "");
comp7.infinite = type[0].substring(1).contains("..."); comp7.infinite = type[0].substring(1).contains("...");
paramName = comp7.argName; paramName = comp7.argName;
command.add(comp7); command.add(comp7);
break; break;
case "bool": case "bool":
BooleanComponent comp8 = new BooleanComponent(); BooleanComponent comp8 = new BooleanComponent();
comp8.argName = type[0].substring(1); comp8.argName = type[0].substring(1);
paramName = comp8.argName; paramName = comp8.argName;
command.add(comp8); command.add(comp8);
break; break;
case "flag": case "flag":
OptionalComponent comp9 = new OptionalComponent(); OptionalComponent comp9 = new OptionalComponent();
comp9.argName = type[0].substring(1); comp9.argName = type[0].substring(1);
paramName = comp9.argName; paramName = comp9.argName;
command.add(comp9); command.add(comp9);
break; break;
default: default:
return; return;
} }
int index = 0; int index = 0;
for (int i = 1; i < methodArray.length; i++) { for (int i = 1; i < methodArray.length; i++) {
@@ -214,29 +204,29 @@ public class Executable extends org.bukkit.command.Command {
index++; index++;
} }
} }
}else{ } else {
if (s.equals("<empty>")) { if (s.equals("<empty>")) {
}else{ } else {
command.add(new ConstantComponent(s)); command.add(new ConstantComponent(s));
} }
} }
} }
for (Method m : methods) { for (Method m : methods) {
Command[] annotations = m.getAnnotationsByType(Command.class); Command[] annotations = m.getAnnotationsByType(Command.class);
if (annotations == null || annotations.length != 1) { if (annotations == null || annotations.length != 1) {
plugin.getLogger().log(Level.WARNING, "Invalid method (" + methodArray[0] + ")"); plugin.getLogger().log(Level.WARNING, "Invalid method (" + methodArray[0] + ")");
CommandManager.errors = true; CommandManager.errors = true;
return; return;
}else{ } else {
if (annotations[0].hook().equals(methodArray[0])) { if (annotations[0].hook().equals(methodArray[0])) {
Class<?>[] params = m.getParameterTypes(); Class<?>[] params = m.getParameterTypes();
if (params.length -1 != methodParams.size()) { if (params.length - 1 != methodParams.size()) {
plugin.getLogger().log(Level.WARNING, "Invalid method (" + methodArray[0] + "): Arguments don't match"); plugin.getLogger().log(Level.WARNING, "Invalid method (" + methodArray[0] + "): Arguments don't match");
CommandManager.errors = true; CommandManager.errors = true;
return; return;
}else{ } else {
for (int i = 0; i < params.length; i++) { for (int i = 0; i < params.length; i++) {
if (i == 0) { if (i == 0) {
if (params[0] != CommandSender.class) { if (params[0] != CommandSender.class) {
@@ -244,27 +234,27 @@ public class Executable extends org.bukkit.command.Command {
CommandManager.errors = true; CommandManager.errors = true;
return; return;
} }
}else{ } else {
ICommandComponent comp = methodParams.get(i - 1); ICommandComponent comp = methodParams.get(i - 1);
if (comp instanceof ByteComponent && params[i] == byte.class) { if (comp instanceof ByteComponent && params[i] == byte.class) {
}else if (comp instanceof ShortComponent && params[i] == short.class) { } else if (comp instanceof ShortComponent && params[i] == short.class) {
}else if (comp instanceof IntegerComponent && params[i] == int.class) { } else if (comp instanceof IntegerComponent && params[i] == int.class) {
}else if (comp instanceof LongComponent && params[i] == long.class) { } else if (comp instanceof LongComponent && params[i] == long.class) {
}else if (comp instanceof FloatComponent && params[i] == float.class) { } else if (comp instanceof FloatComponent && params[i] == float.class) {
}else if (comp instanceof DoubleComponent && params[i] == double.class) { } else if (comp instanceof DoubleComponent && params[i] == double.class) {
}else if (comp instanceof StringComponent && params[i] == String.class) { } else if (comp instanceof StringComponent && params[i] == String.class) {
}else if (comp instanceof BooleanComponent && params[i] == boolean.class) { } else if (comp instanceof BooleanComponent && params[i] == boolean.class) {
}else if (comp instanceof OptionalComponent && params[i] == boolean.class) { } else if (comp instanceof OptionalComponent && params[i] == boolean.class) {
}else{ } else {
plugin.getLogger().log(Level.WARNING, "Invalid method (" + methodArray[0] + "): Invalid method arguments"); plugin.getLogger().log(Level.WARNING, "Invalid method (" + methodArray[0] + "): Invalid method arguments");
CommandManager.errors = true; CommandManager.errors = true;
return; return;
@@ -286,7 +276,7 @@ public class Executable extends org.bukkit.command.Command {
etype = Type.BOTH; etype = Type.BOTH;
} }
ExecutableDefinition def; ExecutableDefinition def;
AsyncType type = target.getAnnotation(Command.class).async(); AsyncType type = target.getAnnotation(Command.class).async();
if (type == AsyncType.ALWAYS) if (type == AsyncType.ALWAYS)
def = new AsyncExecutableDefinition(command, links, permission, target, methodContainer, etype); def = new AsyncExecutableDefinition(command, links, permission, target, methodContainer, etype);
else else
@@ -295,27 +285,27 @@ public class Executable extends org.bukkit.command.Command {
if (def instanceof AsyncExecutableDefinition) if (def instanceof AsyncExecutableDefinition)
CommandManager.asyncExecutables.add(this); CommandManager.asyncExecutables.add(this);
} }
@Override @Override
public boolean execute(CommandSender sender, String name, String[] args_) { public boolean execute(CommandSender sender, String name, String[] args_) {
String[] args; String[] args;
if (args_.length == 0) { if (args_.length == 0) {
args = new String[0]; args = new String[0];
}else{ } else {
ArrayList<String> tempArgs = new ArrayList<String>(); ArrayList<String> tempArgs = new ArrayList<String>();
String temp = ""; String temp = "";
int counter = 0; int counter = 0;
for (String s : args_) { for (String s : args_) {
if (s.endsWith("\\")) { if (s.endsWith("\\")) {
if ((s.length() > 1 && s.charAt(s.length() - 2) == '\\') || counter + 1 == args_.length) { if ((s.length() > 1 && s.charAt(s.length() - 2) == '\\') || counter + 1 == args_.length) {
// escaped \ // escaped \
tempArgs.add(temp + s.replace("\\\\", "\\")); tempArgs.add(temp + s.replace("\\\\", "\\"));
temp = ""; temp = "";
}else{ } else {
// unescaped \ // unescaped \
temp += s.substring(0, s.length() - 1).replace("\\\\", "\\") + " "; temp += s.substring(0, s.length() - 1).replace("\\\\", "\\") + " ";
} }
}else{ } else {
tempArgs.add(temp + s); tempArgs.add(temp + s);
temp = ""; temp = "";
} }
@@ -327,7 +317,7 @@ public class Executable extends org.bukkit.command.Command {
} }
} }
ArrayList<ExecutableDefinition> defs = new ArrayList<ExecutableDefinition>(); ArrayList<ExecutableDefinition> defs = new ArrayList<ExecutableDefinition>();
if (args.length == 0) { if (args.length == 0) {
for (ExecutableDefinition d : commands) { for (ExecutableDefinition d : commands) {
if (d.getLength(0) == 0) { if (d.getLength(0) == 0) {
@@ -335,9 +325,10 @@ public class Executable extends org.bukkit.command.Command {
break; break;
} }
} }
}else{ } else {
defs.addAll(commands); defs.addAll(commands);
defLoop: for (int j = 0; j < defs.size(); j++) { defLoop:
for (int j = 0; j < defs.size(); j++) {
if (defs.get(j).getLength(args.length) == 0) { if (defs.get(j).getLength(args.length) == 0) {
defs.remove(j); defs.remove(j);
j--; j--;
@@ -350,7 +341,7 @@ public class Executable extends org.bukkit.command.Command {
defs.remove(j); defs.remove(j);
j--; j--;
continue defLoop; continue defLoop;
}else{ } else {
i--; i--;
continue; continue;
} }
@@ -364,7 +355,7 @@ public class Executable extends org.bukkit.command.Command {
} }
if (defs.size() == 0) { if (defs.size() == 0) {
printPage(sender, 1); printPage(sender, 1);
}else{ } else {
ExecutableDefinition def = defs.get(0); ExecutableDefinition def = defs.get(0);
for (ExecutableDefinition d : defs) { for (ExecutableDefinition d : defs) {
if (d.isHelp() && args[0].equals("help")) { if (d.isHelp() && args[0].equals("help")) {
@@ -378,20 +369,24 @@ public class Executable extends org.bukkit.command.Command {
} }
} }
if (def.getPermission() != null && !def.getPermission().equals("null") && !sender.hasPermission(def.getPermission())) { if (def.getPermission() != null && !def.getPermission().equals("null") && !sender.hasPermission(def.getPermission())) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', CommandManager.noPermissionFormatting + "You do not have permission to execute this command.")); sender.sendMessage(ChatColor.translateAlternateColorCodes('&',
CommandManager.noPermissionFormatting + "You do not have permission to execute this command."
));
return true; return true;
} }
if (def.getExecType() == Type.PLAYER) { if (def.getExecType() == Type.PLAYER) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', CommandManager.notAllowedFormatting + "Only players are allowed to run this command.")); sender.sendMessage(
ChatColor.translateAlternateColorCodes('&', CommandManager.notAllowedFormatting + "Only players are allowed to run this command."));
return true; return true;
} }
}else if (def.getExecType() == Type.CONSOLE) { } else if (def.getExecType() == Type.CONSOLE) {
if (sender instanceof Player) { if (sender instanceof Player) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', CommandManager.notAllowedFormatting + "Only console is allowed to run this command.")); sender.sendMessage(
ChatColor.translateAlternateColorCodes('&', CommandManager.notAllowedFormatting + "Only console is allowed to run this command."));
return true; return true;
} }
}else if (def.getExecType() == Type.NOBODY) { } else if (def.getExecType() == Type.NOBODY) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', CommandManager.notAllowedFormatting + "Nobody can run this command.")); sender.sendMessage(ChatColor.translateAlternateColorCodes('&', CommandManager.notAllowedFormatting + "Nobody can run this command."));
return true; return true;
} }
@@ -400,7 +395,7 @@ public class Executable extends org.bukkit.command.Command {
if (def.isArgument(j)) { if (def.isArgument(j)) {
if (def.valid(j, args[i])) { if (def.valid(j, args[i])) {
arguments.add(def.get(j, args[i])); arguments.add(def.get(j, args[i]));
}else if (def.isOptional(j)) { } else if (def.isOptional(j)) {
arguments.add(false); arguments.add(false);
i--; i--;
} }
@@ -411,7 +406,7 @@ public class Executable extends org.bukkit.command.Command {
int link = def.getLink(i) + 1; int link = def.getLink(i) + 1;
if (linkedArgs[link] != null) { if (linkedArgs[link] != null) {
linkedArgs[link] = linkedArgs[link].toString() + " " + arguments.get(i).toString(); linkedArgs[link] = linkedArgs[link].toString() + " " + arguments.get(i).toString();
}else{ } else {
linkedArgs[link] = arguments.get(i); linkedArgs[link] = arguments.get(i);
} }
} }
@@ -421,14 +416,19 @@ public class Executable extends org.bukkit.command.Command {
} }
return true; return true;
} }
private void printPage(CommandSender sender, int page) { private void printPage(CommandSender sender, int page) {
page--; page--;
if (page < 0 || page >= help.size()) { if (page < 0 || page >= help.size()) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', CommandManager.helpInvalidPageFormatting + "Non-existant page (" + (page + 1) + ").\nThere are " + help.size() + " pages.")); sender.sendMessage(ChatColor.translateAlternateColorCodes('&',
}else{ CommandManager.helpInvalidPageFormatting + "Non-existant page (" + (page + 1) + ").\nThere are " + help
.size() + " pages."
));
} else {
HelpPageCommand[] pageData = help.get(page); HelpPageCommand[] pageData = help.get(page);
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', CommandManager.helpPageHeaderFormatting + "### Help Page " + (page + 1) + "/" + (help.size()) + " ###")); sender.sendMessage(ChatColor.translateAlternateColorCodes('&',
CommandManager.helpPageHeaderFormatting + "### Help Page " + (page + 1) + "/" + (help.size()) + " ###"
));
for (HelpPageCommand c : pageData) { for (HelpPageCommand c : pageData) {
if (c != null) { if (c != null) {
if (c.type == null || c.type == Type.BOTH || (c.type == Type.CONSOLE && !(sender instanceof Player)) || (c.type == Type.PLAYER && sender instanceof Player)) { if (c.type == null || c.type == Type.BOTH || (c.type == Type.CONSOLE && !(sender instanceof Player)) || (c.type == Type.PLAYER && sender instanceof Player)) {

View File

@@ -1,29 +1,29 @@
package com.nemez.cmdmgr.util; package com.nemez.cmdmgr.util;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import com.nemez.cmdmgr.CommandManager; import com.nemez.cmdmgr.CommandManager;
import com.nemez.cmdmgr.component.ArgumentComponent; import com.nemez.cmdmgr.component.ArgumentComponent;
import com.nemez.cmdmgr.component.ICommandComponent; import com.nemez.cmdmgr.component.ICommandComponent;
import com.nemez.cmdmgr.component.OptionalComponent; import com.nemez.cmdmgr.component.OptionalComponent;
import com.nemez.cmdmgr.component.StringComponent; import com.nemez.cmdmgr.component.StringComponent;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.logging.Level;
public class ExecutableDefinition { public class ExecutableDefinition {
private ArrayList<ICommandComponent> components; private ArrayList<ICommandComponent> components;
private String permission; private String permission;
private Method target; private Method target;
private Object methodContainer; private Object methodContainer;
private Type type; private Type type;
private ArrayList<Integer> paramLinks; private ArrayList<Integer> paramLinks;
public ExecutableDefinition(ArrayList<ICommandComponent> cmd, ArrayList<Integer> paramLinks, String perm, Method method, Object methodContainer, Type type) { public ExecutableDefinition(ArrayList<ICommandComponent> cmd, ArrayList<Integer> paramLinks, String perm, Method method, Object methodContainer,
Type type) {
this.components = cmd; this.components = cmd;
this.permission = perm; this.permission = perm;
this.target = method; this.target = method;
@@ -31,7 +31,7 @@ public class ExecutableDefinition {
this.type = type; this.type = type;
this.paramLinks = paramLinks; this.paramLinks = paramLinks;
} }
public boolean valid(int index, String arg) { public boolean valid(int index, String arg) {
if (index < 0) { if (index < 0) {
return false; return false;
@@ -41,10 +41,10 @@ public class ExecutableDefinition {
StringComponent strComp = (StringComponent) components.get(components.size() - 1); StringComponent strComp = (StringComponent) components.get(components.size() - 1);
if (strComp.infinite) { if (strComp.infinite) {
return strComp.valid(arg); return strComp.valid(arg);
}else{ } else {
return false; return false;
} }
}else{ } else {
return false; return false;
} }
} }
@@ -60,16 +60,16 @@ public class ExecutableDefinition {
StringComponent strComp = (StringComponent) components.get(components.size() - 1); StringComponent strComp = (StringComponent) components.get(components.size() - 1);
if (strComp.infinite) { if (strComp.infinite) {
return strComp.get(arg); return strComp.get(arg);
}else{ } else {
return null; return null;
} }
}else{ } else {
return null; return null;
} }
} }
return components.get(index).get(arg); return components.get(index).get(arg);
} }
public boolean isArgument(int index) { public boolean isArgument(int index) {
if (index < 0) { if (index < 0) {
return false; return false;
@@ -79,35 +79,35 @@ public class ExecutableDefinition {
StringComponent strComp = (StringComponent) components.get(components.size() - 1); StringComponent strComp = (StringComponent) components.get(components.size() - 1);
if (strComp.infinite) { if (strComp.infinite) {
return true; return true;
}else{ } else {
return false; return false;
} }
}else{ } else {
return false; return false;
} }
} }
return components.get(index) instanceof ArgumentComponent; return components.get(index) instanceof ArgumentComponent;
} }
public boolean isOptional(int index) { public boolean isOptional(int index) {
if (index < 0 || index >= components.size()) { if (index < 0 || index >= components.size()) {
return false; return false;
} }
return components.get(index) instanceof OptionalComponent; return components.get(index) instanceof OptionalComponent;
} }
public boolean isHelp() { public boolean isHelp() {
return target == null && components.get(0).valid("help") && components.get(1).getComponentInfo().equals("<page:i32>"); return target == null && components.get(0).valid("help") && components.get(1).getComponentInfo().equals("<page:i32>");
} }
public String getPermission() { public String getPermission() {
return permission; return permission;
} }
public Type getExecType() { public Type getExecType() {
return type; return type;
} }
public int getLength(int argSize) { public int getLength(int argSize) {
if (components.size() == 0) { if (components.size() == 0) {
return 0; return 0;
@@ -122,7 +122,7 @@ public class ExecutableDefinition {
} }
return components.size(); return components.size();
} }
public int getNumOfArgs() { public int getNumOfArgs() {
int counter = 0; int counter = 0;
for (ICommandComponent c : components) { for (ICommandComponent c : components) {
@@ -132,7 +132,7 @@ public class ExecutableDefinition {
} }
return counter; return counter;
} }
public int getLink(int i) { public int getLink(int i) {
if (i < 0) { if (i < 0) {
return i; return i;
@@ -142,16 +142,16 @@ public class ExecutableDefinition {
StringComponent strComp = (StringComponent) components.get(components.size() - 1); StringComponent strComp = (StringComponent) components.get(components.size() - 1);
if (strComp.infinite) { if (strComp.infinite) {
return paramLinks.get(paramLinks.size() - 1); return paramLinks.get(paramLinks.size() - 1);
}else{ } else {
return i; return i;
} }
}else{ } else {
return i; return i;
} }
} }
return paramLinks.get(i); return paramLinks.get(i);
} }
public boolean invoke(Object[] args, CommandSender sender, JavaPlugin plugin) { public boolean invoke(Object[] args, CommandSender sender, JavaPlugin plugin) {
if (target == null) { if (target == null) {
return false; return false;
@@ -161,11 +161,13 @@ public class ExecutableDefinition {
if (target.getReturnType() == void.class) { if (target.getReturnType() == void.class) {
target.invoke(methodContainer, args); target.invoke(methodContainer, args);
return true; return true;
}else if (target.getReturnType() == boolean.class) { } else if (target.getReturnType() == boolean.class) {
return (boolean) target.invoke(methodContainer, args); return (boolean) target.invoke(methodContainer, args);
} }
} catch (Exception e) { } catch (Exception e) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', CommandManager.helpInvalidPageFormatting + "An internal error occured, please contact the server administrator and/or report a bug.")); sender.sendMessage(ChatColor.translateAlternateColorCodes('&',
CommandManager.helpInvalidPageFormatting + "An internal error occured, please contact the server administrator and/or report a bug."
));
plugin.getLogger().log(Level.WARNING, "Runtime Error: invalid method"); plugin.getLogger().log(Level.WARNING, "Runtime Error: invalid method");
e.printStackTrace(); e.printStackTrace();
return true; return true;

View File

@@ -6,8 +6,8 @@ public class HelpPageCommand {
public String usage; public String usage;
public String description; public String description;
public String method; public String method;
public Type type; public Type type;
public HelpPageCommand(String perm, String usage, String description, String method, Type type) { public HelpPageCommand(String perm, String usage, String description, String method, Type type) {
this.permission = perm; this.permission = perm;
this.usage = usage.replaceAll("<empty>", ""); this.usage = usage.replaceAll("<empty>", "");

View File

@@ -3,5 +3,5 @@ package com.nemez.cmdmgr.util;
public enum Property { public enum Property {
NONE, PERMISSION, HELP, EXECUTE, TYPE; NONE, PERMISSION, HELP, EXECUTE, TYPE;
} }

View File

@@ -3,34 +3,34 @@ package com.nemez.cmdmgr.util;
public enum Type { public enum Type {
BOTH, PLAYER, CONSOLE, NOBODY; BOTH, PLAYER, CONSOLE, NOBODY;
public static Type parse(String string) { public static Type parse(String string) {
if (string.equals("both")) { if (string.equals("both")) {
return BOTH; return BOTH;
}else if (string.equals("player")) { } else if (string.equals("player")) {
return PLAYER; return PLAYER;
}else if (string.equals("console")) { } else if (string.equals("console")) {
return CONSOLE; return CONSOLE;
}else if (string.equals("nobody")) { } else if (string.equals("nobody")) {
return NOBODY; return NOBODY;
}else{ } else {
return null; return null;
} }
} }
public static String get(Type t) { public static String get(Type t) {
if (t == null) { if (t == null) {
return "null"; return "null";
} }
switch (t) { switch (t) {
case BOTH: case BOTH:
return "both"; return "both";
case PLAYER: case PLAYER:
return "player"; return "player";
case CONSOLE: case CONSOLE:
return "console"; return "console";
case NOBODY: case NOBODY:
return "nobody"; return "nobody";
} }
return "null"; return "null";
} }