Listeners - adamtomi/grapefruit GitHub Wiki

Listeners are invoked when the execution process reaches certain stages. These stages are: tokenize, process and dispatch. Each stage has it's own listener interface. PreProcess listeners are invoked after the tokenize and before the process stage. This is a very early stage, so only the source and the command line itself is known.

public class MyPreProcessListener implements PreProcessListener<CommandSource> {
    
    @Override
    public boolean onPreProcess(final @NotNull CommandSource source, final @NotNull String commandLine) {
        System.out.println("PreProcessListener called");
        return true;
    }
}

The return type of onPreProcess is boolean. If one of the listeners return false, the execution of the command is cancelled.

PreDispatch listeners are called after the process and before the dispatch stage. At this stage the command itself is known and the context is ready to use. Each parameter has been mapped and stored.

public class MyPreDispatchListener implements PreDispatchListener<CommandSource> {

    @Override
    public boolean onPreDispatch(final @NotNull CommandContext<CommandSource> context,
                                 final @NotNull CommandRegistration<CommandSource> reg) {
        System.out.println("PreDispatchListener called");
        return true;
    }
}

Just as with the PreProcessListener, returning false in onPreDispatch will cancel the execution.

The last stage is dispatch after which the PostDispatchListeners are invoked. Unlike other listeners, these don't return a boolean, since there aren't any further execution stages that could be cancelled.

public class MyPostDispatchListener implements PostDispatchListener<CommandSource> {

    @Override
    public void onPostDispatch(final @NotNull CommandContext<CommandSource> context) {
       System.out.println("PostDispatchListener called");
    }
}

Registering a listeners is as easy as it gets:

final CommandDispatcher<CommandSource> dispatcher = //...
dispatcher.registerListener(new MyPostDispatchListener());
dispatcher.registerListener(new MyPreDispatchListener());
dispatcher.registerListener(new MyPreProcessListener());

The order in which the listeners are registeres doesn't really matter, unless there are more listeners of the same type. In that case they'll be invoked in the exact same order as they're registered.