Java Tutorial

Java Example:

The below text demonstrates some of the features of the library. This demo application is available in the GitHub repository.

In the command usage shown, "<argument>" represents a required parameter, and "[argument]" represents an optional parameter. Getting Started:

Getting started is very easy, first, create a parser object to parse your commands:

parser = CommandParser.createNew();

Customize the command prefix by using:

parser = CommandParser.createNew().usePrefix(string.Empty);

Let's also add a handler to provide messages when a parsing error occurs:

CommandParser.createNew().usePrefix("").onError(message -> onParseError(message));
...
private static void onParseError(string message) {
    System.out.println(message);
}

Now that the parser is set up, we can add a simple command. This command is called "Hello", and can be called by typing the alias "hello". Commands can have multiple aliases that will execute the action. In this case, the action will print out "Hello World" to the console.

parser.addCommand(Command
.create("Hello")
    .addAlias("hello")
    .setDescription("Prints: 'Hello World!'")
    .setAction((arguments, data) -> System.out.println("Hello World!"));

Now we have everything set up, so we can now call the Parser.Parse(input) method to handle the input. You would add this to your game or application's chat or console.

System.out.println("\nEnter command:\n");
while (true) {
      System.out.print("$ ");

     //Read input and parse command
     String input = scanner.nextLine();
     parser.parse(input);
}

Try typing into the console or your application now, you should be able to type "hello" if you are using an empty prefix, or "/hello" with the default prefix.

Now, lets make a simple ban command that makes use of an argument.

 parser.addCommand(Command
     .create("Ban User") 
     .addAlias("ban")
     .addAlias("banuser")
     .setDescription("Bans a user from the server.")
     .setAction((args, data) -> {
          //Retrieve the value of the argument named "user"
          System.out.println("%1$s has been banned!" + Argument.fromName(args, "user"));
     })
     .addArgument(Argument //Add an argument named "User"
         .create("User")));

Now, we can type "/ban Bob" to ban the user Bob. Of course, actual logic would be more than a simple console log. You can add multiple arguments to a command, and even nest them inside each other to create groups of optional arguments. Advanced Features:

Here are some helpful and more advanced features that will be useful for creating commands discussed below.

Optional Arguments:

Optional arguments can be created by calling the makeOptional() method on an argument. Note that optional arguments must come last. All arguments are required by default. Default Values:

Optional arguments can have default values specified in the case that they are not specified by using the setDefault(value) method on an argument. Note that optional arguments must come last.

Enum Arguments:

An "Enum" argument is an argument that is limited to a set of specific values. Instead of any value, they must be one of the defined choices set by the addOption(argument) method. This is most useful for creating different options within a command, such as "On" or "Off". Each option can have its own sub-arguments that vary depending on the option. Below is an example of an enum argument for a mail system that allows users to read, clear, and send mail in a game.

parser.addCommand(Command
    .create("Mail")
    .addAlias("mail")
    .setDescription("Allows users to send messages.")
    .setAction(onMailExecuted)
    //Note a deep nesting of arguments.
    .addArgument(Argument
        .create("type")
        .makeOptional()
        //Note command options. These turn the "type" argument into an enum style list of values.
        //The user has to type read, clear, or send (Which has it's own nested arguments).
        .addOption(Argument.create("read"))
        .addOption(Argument.create("clear"))
        .addOption(Argument.create("send")
            .addArgument((Argument.create("user")))
            .addArgument((Argument.create("message"))))));

Note how the send option contains nested "user" and "message" arguments, while the other options require no parameters

Argument Validation:

Arguments can be validated using the ValidationRule class. It comes with some handy rules such as email, IP, alphanumerical, etc. You can also define your own custom rules to validate arguments against. Below is an example use in a register command that only allows alphanumerical usernames and valid emails.

parser.addCommand(Command.create("Register").addAlias("register").setDescription("Create an     account")
    .setAction((arguments, data) ->
    {
        var user = Argument.fromName(arguments, "username");
        var email = Argument.fromName(arguments, "email");
        System.out.println("%1$s (%2$s) has registered.", user, email);
    })
    //Note argument validator.
    .addArgument(Argument.create("username").setValidator(ValidationRule.AlphaNumerical))
    .addArgument(Argument.create("password"))
    .addArgument(Argument.create("email").setValidator(ValidationRule.Email)));

Access Levels:

Commands can be restricted to certain users and situations by adding an access level through restrictAccess(int accessLevel) and calling the parser's parse(int level) method with the specified level. If a commands level is less than the specified level when parsing, it will not be allowed to run.

Command Pre-Conditions:

Commands can be given a condition using the setAction(Consumer<ArrayList<Argument>> action) { method. The action specified will be ran before the command is executed. If it fails, by returning an error in the form of a string, the error will call the parseError action, otherwise, the command will be executed. Command Data:

Data can be passed to the command by the calling code by using command data. For example, a username could be passed to the command so the command itself knows who sent it.

parser.parse(input, "Test")

The data "Test" can be used in the command through the data parameter.

command.setAction((arguments, data) -> { });

More Documentation:

We suggest you take a look at the demo application to learn a range of advanced commands that can be made. The parsing code is well documented and will be able to explain any other features that were not covered here. If you have any questions, feel free to make a post on our forums.