### Gradle Installation for Brigadier Source: https://github.com/mojang/brigadier/blob/master/README.md This snippet shows how to add the Brigadier library to your Gradle project. It requires including a custom Maven repository and then specifying the dependency with the latest version. ```groovy maven { url "https://libraries.minecraft.net" } compile 'com.mojang:brigadier:(the latest version)' ``` -------------------------------- ### Maven Installation for Brigadier Source: https://github.com/mojang/brigadier/blob/master/README.md This snippet demonstrates how to integrate Brigadier into a Maven project. It involves configuring the repository and declaring the dependency, ensuring you replace '(the latest version)' with the actual latest version. ```xml minecraft-libraries Minecraft Libraries https://libraries.minecraft.net com.mojang brigadier (the latest version) ``` -------------------------------- ### Brigadier Exception Handling Example in Java Source: https://context7.com/mojang/brigadier/llms.txt A Java example demonstrating custom exception types (SimpleCommandExceptionType, DynamicCommandExceptionType, Dynamic2CommandExceptionType) and their usage within a Brigadier CommandDispatcher. It covers scenarios like player not found, player offline, and invalid range inputs, along with testing and outputting error messages. ```java import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.LiteralMessage; import com.mojang.brigadier.exceptions.*; import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal; import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; import static com.mojang.brigadier.arguments.StringArgumentType.*; public class ExceptionHandlingExample { // Custom exception types private static final SimpleCommandExceptionType PLAYER_NOT_FOUND = new SimpleCommandExceptionType(new LiteralMessage("Player not found")); private static final DynamicCommandExceptionType PLAYER_OFFLINE = new DynamicCommandExceptionType(name -> new LiteralMessage("Player '" + name + "' is offline")); private static final Dynamic2CommandExceptionType INVALID_RANGE = new Dynamic2CommandExceptionType((min, max) -> new LiteralMessage("Value must be between " + min + " and " + max)); public static void main(String[] args) { CommandDispatcher dispatcher = new CommandDispatcher<>(); Object source = new Object(); dispatcher.register( literal("kick") .then(argument("player", word()) .executes(ctx -> { String player = getString(ctx, "player"); // Simulate player lookup if (player.equals("nobody")) { throw PLAYER_NOT_FOUND.create(); } if (player.equals("offline_player")) { throw PLAYER_OFFLINE.create(player); } System.out.println("Kicked " + player); return 1; })) ); dispatcher.register( literal("setlevel") .then(argument("level", integer()) .executes(ctx -> { int level = getInteger(ctx, "level"); if (level < 0 || level > 100) { throw INVALID_RANGE.create(0, 100); } System.out.println("Level set to " + level); return 1; })) ); // Test error handling testCommand(dispatcher, "kick Steve", source); // Success testCommand(dispatcher, "kick nobody", source); // Player not found testCommand(dispatcher, "kick offline_player", source); // Player 'offline_player' is offline testCommand(dispatcher, "setlevel 50", source); // Success testCommand(dispatcher, "setlevel 150", source); // Value must be between 0 and 100 testCommand(dispatcher, "unknown_command", source); // Unknown command testCommand(dispatcher, "kick", source); // Incomplete command testCommand(dispatcher, "setlevel abc", source); // Invalid integer } private static void testCommand(CommandDispatcher dispatcher, String command, Object source) { System.out.println("\nExecuting: '" + command + "'\n"); try { int result = dispatcher.execute(command, source); System.out.println("Success! Result: " + result); } catch (CommandSyntaxException e) { System.out.println("Error: " + e.getMessage()); if (e.getInput() != null) { System.out.println("Context: " + e.getContext()); } } } } ``` -------------------------------- ### Register and Execute Commands with CommandDispatcher in Java Source: https://context7.com/mojang/brigadier/llms.txt Demonstrates how to use Brigadier's CommandDispatcher to register literal and argument-based commands, define their execution logic, and then execute them against a custom source object. This example showcases basic command registration, argument parsing (integers), and command execution flow. ```java import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.exceptions.CommandSyntaxException; import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal; import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument; import static com.mojang.brigadier.arguments.IntegerArgumentType.integer; import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger; import static com.mojang.brigadier.arguments.StringArgumentType.word; import static com.mojang.brigadier.arguments.StringArgumentType.getString; public class CommandExample { public static void main(String[] args) throws CommandSyntaxException { // Create dispatcher with custom source type (e.g., Player, User, or any object) CommandDispatcher dispatcher = new CommandDispatcher<>(); // Register a simple command: /greet dispatcher.register( literal("greet") .executes(context -> { System.out.println("Hello, " + context.getSource().getName() + "!"); return 1; // Return value indicates success (non-zero) }) ); // Register command with subcommand and argument: /teleport dispatcher.register( literal("teleport") .then( argument("x", integer()) .then( argument("y", integer()) .then( argument("z", integer()) .executes(context -> { int x = getInteger(context, "x"); int y = getInteger(context, "y"); int z = getInteger(context, "z"); System.out.println("Teleporting to: " + x + ", " + y + ", " + z); return 1; }) ) ) ) ); // Execute commands User source = new User("Steve"); dispatcher.execute("greet", source); // Output: Hello, Steve! dispatcher.execute("teleport 100 64 200", source); // Output: Teleporting to: 100, 64, 200 } } class User { private final String name; public User(String name) { this.name = name; } public String getName() { return name; } } ``` -------------------------------- ### Brigadier Command Redirects and Aliases in Java Source: https://context7.com/mojang/brigadier/llms.txt Demonstrates how to use Brigadier's `redirect()` and `fork()` methods in Java for command aliasing, chaining with source modification, and branching execution contexts. This example requires the Brigadier library. ```java import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.tree.LiteralCommandNode; import java.util.Arrays; import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal; import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; public class RedirectExample { public static void main(String[] args) throws CommandSyntaxException { CommandDispatcher dispatcher = new CommandDispatcher<>(); // Register base command LiteralCommandNode runNode = dispatcher.register( literal("run") .executes(ctx -> { int source = ctx.getSource(); System.out.println("Running with source value: " + source); return source; }) ); // Simple alias: /execute -> /run dispatcher.register( literal("execute") .redirect(runNode) ); // Redirect to root with source modification: /add ... // This allows chaining: /add 5 add 3 run dispatcher.register( literal("add") .then(argument("value", integer()) .redirect(dispatcher.getRoot(), ctx -> ctx.getSource() + getInteger(ctx, "value"))) ); // Fork to multiple sources: /broadcast ... // Executes the following command for each source in the list dispatcher.register( literal("broadcast") .fork(dispatcher.getRoot(), ctx -> Arrays.asList(1, 2, 3, 4, 5)) ); // Execute examples System.out.println("--- Simple execution ---"); dispatcher.execute("run", 10); // Output: Running with source value: 10 System.out.println("\n--- Alias execution ---"); dispatcher.execute("execute", 20); // Output: Running with source value: 20 System.out.println("\n--- Chained redirect with source modification ---"); dispatcher.execute("add 5 run", 10); // Output: Running with source value: 15 dispatcher.execute("add 5 add 3 run", 0); // Output: Running with source value: 8 System.out.println("\n--- Fork to multiple sources ---"); int count = dispatcher.execute("broadcast run", 0); // Output: // Running with source value: 1 // Running with source value: 2 // Running with source value: 3 // Running with source value: 4 // Running with source value: 5 System.out.println("Commands executed: " + count); // Output: Commands executed: 5 } } ``` -------------------------------- ### Java Command Suggestions with Tooltips using Brigadier Source: https://context7.com/mojang/brigadier/llms.txt This Java code demonstrates how to implement custom suggestion providers in Brigadier for command auto-completion. It shows how to attach providers to argument nodes, generate suggestions based on input, and include tooltips for each suggestion. This example requires the Brigadier library. ```java import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.ParseResults; import com.mojang.brigadier.suggestion.Suggestion; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionProvider; import com.mojang.brigadier.LiteralMessage; import java.util.concurrent.CompletableFuture; import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal; import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument; import static com.mojang.brigadier.arguments.StringArgumentType.*; public class SuggestionsExample { public static void main(String[] args) throws Exception { CommandDispatcher dispatcher = new CommandDispatcher<>(); Object source = new Object(); // Custom suggestion provider with tooltips SuggestionProvider playerSuggestions = (context, builder) -> { String remaining = builder.getRemainingLowerCase(); // Simulate player list String[] players = {"Alice", "Bob", "Charlie", "David"}; for (String player : players) { if (player.toLowerCase().startsWith(remaining)) { builder.suggest(player, new LiteralMessage("Online player")); } } return builder.buildFuture(); }; // Suggestions for game modes SuggestionProvider gameModeSuggestions = (context, builder) -> { builder.suggest("survival", new LiteralMessage("Default gameplay")); builder.suggest("creative", new LiteralMessage("Unlimited resources")); builder.suggest("adventure", new LiteralMessage("Map exploration")); builder.suggest("spectator", new LiteralMessage("Observer mode")); return builder.buildFuture(); }; dispatcher.register( literal("tp") .then(argument("player", word()) .suggests(playerSuggestions) .executes(ctx -> { System.out.println("Teleporting to: " + getString(ctx, "player")); return 1; })) ); dispatcher.register( literal("gamemode") .then(argument("mode", word()) .suggests(gameModeSuggestions) .executes(ctx -> { System.out.println("Setting gamemode: " + getString(ctx, "mode")); return 1; })) ); // Get suggestions for partial input ParseResults parse = dispatcher.parse("tp A", source); CompletableFuture suggestionsFuture = dispatcher.getCompletionSuggestions(parse); Suggestions suggestions = suggestionsFuture.get(); System.out.println("Suggestions for 'tp A':"); for (Suggestion suggestion : suggestions.getList()) { System.out.println(" - " + suggestion.getText() + (suggestion.getTooltip() != null ? " (" + suggestion.getTooltip().getString() + ")" : "")); } // Output: // Suggestions for 'tp A': // - Alice (Online player) // Suggestions for gamemode ParseResults gmParse = dispatcher.parse("gamemode ", source); Suggestions gmSuggestions = dispatcher.getCompletionSuggestions(gmParse).get(); System.out.println("\nSuggestions for 'gamemode ':"); for (Suggestion s : gmSuggestions.getList()) { System.out.println(" - " + s.getText()); } // Output: // Suggestions for 'gamemode ': // - survival // - creative // - adventure // - spectator } } ``` -------------------------------- ### Registering Commands with Brigadier in Java Source: https://github.com/mojang/brigadier/blob/master/README.md This Java code example illustrates how to register commands using Brigadier's `CommandDispatcher`. It showcases registering a literal command 'foo' with an argument 'bar' (integer) and an alternative execution for 'foo' without arguments. ```java CommandDispatcher dispatcher = new CommandDispatcher<>(); dispatcher.register( literal("foo") .then( argument("bar", integer()) .executes(c -> { System.out.println("Bar is " + getInteger(c, "bar")); return 1; }) ) .executes(c -> { System.out.println("Called foo with no arguments"); return 1; }) ); ``` -------------------------------- ### Brigadier Built-in Argument Types Example (Java) Source: https://context7.com/mojang/brigadier/llms.txt Demonstrates the usage of Brigadier's built-in argument types like Integer, Long, Float, Double, Boolean, and String. It shows how to register commands with these argument types and extract their values from the command context. This example requires the Brigadier library. ```java import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.exceptions.CommandSyntaxException; import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal; import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; import static com.mojang.brigadier.arguments.LongArgumentType.*; import static com.mojang.brigadier.arguments.FloatArgumentType.*; import static com.mojang.brigadier.arguments.DoubleArgumentType.*; import static com.mojang.brigadier.arguments.BoolArgumentType.*; import static com.mojang.brigadier.arguments.StringArgumentType.*; public class ArgumentTypesExample { public static void main(String[] args) throws CommandSyntaxException { CommandDispatcher dispatcher = new CommandDispatcher<>(); Object source = new Object(); // IntegerArgumentType: integer(), integer(min), integer(min, max) dispatcher.register(literal("int") .then(argument("value", integer(-100, 100)) .executes(ctx -> { System.out.println("Integer: " + getInteger(ctx, "value")); return 1; }))); // LongArgumentType: longArg(), longArg(min), longArg(min, max) dispatcher.register(literal("long") .then(argument("value", longArg(0L, 1000000000000L)) .executes(ctx -> { System.out.println("Long: " + getLong(ctx, "value")); return 1; }))); // FloatArgumentType: floatArg(), floatArg(min), floatArg(min, max) dispatcher.register(literal("float") .then(argument("value", floatArg(0.0f, 1.0f)) .executes(ctx -> { System.out.println("Float: " + getFloat(ctx, "value")); return 1; }))); // DoubleArgumentType: doubleArg(), doubleArg(min), doubleArg(min, max) dispatcher.register(literal("double") .then(argument("value", doubleArg()) .executes(ctx -> { System.out.println("Double: " + getDouble(ctx, "value")); return 1; }))); // BoolArgumentType: bool() - parses "true" or "false" dispatcher.register(literal("bool") .then(argument("value", bool()) .executes(ctx -> { System.out.println("Boolean: " + getBool(ctx, "value")); return 1; }))); // StringArgumentType variants: // word() - single word (no spaces) // string() - quoted phrase or single word // greedyString() - consumes all remaining input dispatcher.register(literal("word") .then(argument("value", word()) .executes(ctx -> { System.out.println("Word: " + getString(ctx, "value")); return 1; }))); dispatcher.register(literal("quoted") .then(argument("value", string()) .executes(ctx -> { System.out.println("String: " + getString(ctx, "value")); return 1; }))); dispatcher.register(literal("message") .then(argument("text", greedyString()) .executes(ctx -> { System.out.println("Message: " + getString(ctx, "text")); return 1; }))); // Execute examples dispatcher.execute("int 42", source); // Output: Integer: 42 dispatcher.execute("long 9876543210", source); // Output: Long: 9876543210 dispatcher.execute("float 0.75", source); // Output: Float: 0.75 dispatcher.execute("double 3.14159", source); // Output: Double: 3.14159 dispatcher.execute("bool true", source); // Output: Boolean: true dispatcher.execute("word hello", source); // Output: Word: hello dispatcher.execute("quoted \"hello world\"", source); // Output: String: hello world dispatcher.execute("message This is a long message!", source); // Output: Message: This is a long message! } } ``` -------------------------------- ### Get All Command Usage Strings Source: https://github.com/mojang/brigadier/blob/master/README.md Retrieves a list of all possible command paths under a given node. Optionally filters commands based on source restrictions. The output format is a list of strings representing command paths. ```java getAllUsage(node, source, restricted) ``` -------------------------------- ### Get Smart Command Usage Strings Source: https://github.com/mojang/brigadier/blob/master/README.md Retrieves a map of child nodes to their 'smart usage' strings. This method attempts to condense future nodes and display optional and typed information for a more user-friendly representation. ```java getSmartUsage(node, source) ``` -------------------------------- ### Java Result Consumer Example for Brigadier Commands Source: https://context7.com/mojang/brigadier/llms.txt This Java code demonstrates how to implement and set a ResultConsumer for a Brigadier CommandDispatcher. The consumer logs the success status and return value of each command execution, including forked commands. It requires the Brigadier library and standard Java utilities. ```java import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.ResultConsumer; import com.mojang.brigadier.exceptions.CommandSyntaxException; import java.util.Arrays; import java.util.ArrayList; import java.util.List; import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal; import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; public class ResultConsumerExample { public static void main(String[] args) throws CommandSyntaxException { CommandDispatcher dispatcher = new CommandDispatcher<>(); // Track all command results List log = new ArrayList<>(); ResultConsumer consumer = (context, success, result) -> { String entry = String.format("User '%s': %s (result=%d)", context.getSource(), success ? "SUCCESS" : "FAILED", result); log.add(entry); System.out.println("[LOG] " + entry); }; dispatcher.setConsumer(consumer); // Simple command dispatcher.register( literal("points") .then(argument("amount", integer(1, 100)) .executes(ctx -> { int points = getInteger(ctx, "amount"); System.out.println(ctx.getSource() + " earned " + points + " points!"); return points; })) ); // Command that executes for multiple sources (fork) dispatcher.register( literal("broadcast") .fork(dispatcher.getRoot(), ctx -> Arrays.asList("Alice", "Bob", "Charlie")) ); // Command that might fail dispatcher.register( literal("risky") .executes(ctx -> { if (Math.random() > 0.5) { throw new RuntimeException("Random failure!"); } return 42; }) ); System.out.println("=== Normal execution ==="); dispatcher.execute("points 50", "Player1"); // Output: // Player1 earned 50 points! // [LOG] User 'Player1': SUCCESS (result=50) System.out.println("\n=== Forked execution (broadcasts to multiple users) ==="); int count = dispatcher.execute("broadcast points 25", "System"); System.out.println("Total executions: " + count); // Output: // Alice earned 25 points! // [LOG] User 'Alice': SUCCESS (result=25) // Bob earned 25 points! // [LOG] User 'Bob': SUCCESS (result=25) // Charlie earned 25 points! // [LOG] User 'Charlie': SUCCESS (result=25) // Total executions: 3 System.out.println("\n=== Command log ==="); for (String entry : log) { System.out.println(" " + entry); } } } ``` -------------------------------- ### Parse and Execute Commands in Java using Brigadier Source: https://context7.com/mojang/brigadier/llms.txt Demonstrates parsing a command string using Brigadier's CommandDispatcher, inspecting the parse results, executing the parsed command, handling syntax errors during parsing, and caching parse results for efficient repeated execution. ```java import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.ParseResults; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.tree.CommandNode; import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal; import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; public class ParseExecuteExample { public static void main(String[] args) throws CommandSyntaxException { CommandDispatcher dispatcher = new CommandDispatcher<>(); Object source = new Object(); dispatcher.register( literal("add") .then(argument("a", integer()) .then(argument("b", integer()) .executes(ctx -> { int result = getInteger(ctx, "a") + getInteger(ctx, "b"); System.out.println("Result: " + result); return result; }))) ); // Parse command without executing ParseResults parseResult = dispatcher.parse("add 5 3", source); // Check if parsing was successful (no remaining input) if (!parseResult.getReader().canRead()) { System.out.println("Command parsed successfully!"); // Inspect parsed nodes parseResult.getContext().getNodes().forEach(node -> System.out.println("Node: " + node.getNode().getName()) ); // Execute the parsed command (can be called multiple times) int result = dispatcher.execute(parseResult); // Output: Result: 8 System.out.println("Returned: " + result); // Output: Returned: 8 } // Handle parse errors ParseResults badParse = dispatcher.parse("add five three", source); if (badParse.getReader().canRead()) { System.out.println("Parse failed at position: " + badParse.getReader().getCursor()); System.out.println("Remaining input: " + badParse.getReader().getRemaining()); // Check exceptions for each node that failed for (var entry : badParse.getExceptions().entrySet()) { CommandNode node = entry.getKey(); CommandSyntaxException ex = entry.getValue(); System.out.println("Error at '" + node.getName() + "': " + ex.getMessage()); } } // Cache parsed commands for repeated execution ParseResults cached = dispatcher.parse("add 10 20", source); for (int i = 0; i < 3; i++) { dispatcher.execute(cached); // Executes 3 times without re-parsing } } } ``` -------------------------------- ### Create Integer, String, and Boolean Arguments with Brigadier Source: https://context7.com/mojang/brigadier/llms.txt Demonstrates how to register commands with typed arguments (integer, string, boolean) using Brigadier's builder pattern. It shows how to define argument ranges and retrieve parsed values from the command context. This requires the Brigadier library. ```java import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.suggestion.SuggestionProvider; import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal; import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; import static com.mojang.brigadier.arguments.StringArgumentType.*; import static com.mojang.brigadier.arguments.BoolArgumentType.*; import static com.mojang.brigadier.arguments.DoubleArgumentType.*; public class ArgumentExample { public static void main(String[] args) throws CommandSyntaxException { CommandDispatcher dispatcher = new CommandDispatcher<>(); // Integer argument with range validation: /give (1-64) dispatcher.register( literal("give") .then(argument("amount", integer(1, 64)) // Min 1, max 64 .executes(ctx -> { int amount = getInteger(ctx, "amount"); System.out.println("Giving " + amount + " items"); return amount; })) ); // Multiple argument types in one command: /setblock dispatcher.register( literal("setblock") .then(argument("x", integer()) .then(argument("y", integer(0, 256)) // Y constrained to world height .then(argument("z", integer()) .then(argument("block", word()) .then(argument("solid", bool()) .executes(ctx -> { int x = getInteger(ctx, "x"); int y = getInteger(ctx, "y"); int z = getInteger(ctx, "z"); String block = getString(ctx, "block"); boolean solid = getBool(ctx, "solid"); System.out.printf("Setting %s at (%d,%d,%d), solid=%b%n", block, x, y, z, solid); return 1; })))))) // Removed extra closing parenthesis ); // Custom suggestion provider for auto-completion SuggestionProvider blockSuggestions = (context, builder) -> { builder.suggest("stone"); builder.suggest("dirt"); builder.suggest("grass_block"); builder.suggest("oak_planks"); return builder.buildFuture(); }; dispatcher.register( literal("place") .then(argument("blocktype", word()) .suggests(blockSuggestions) .executes(ctx -> { System.out.println("Placing: " + getString(ctx, "blocktype")); return 1; })) ); Object source = new Object(); dispatcher.execute("give 32", source); // Output: Giving 32 items dispatcher.execute("setblock 10 64 20 stone true", source); // Output: Setting stone at (10,64,20), solid=true dispatcher.execute("place oak_planks", source); // Output: Placing: oak_planks } } ``` -------------------------------- ### Generate Command Usage Strings with Brigadier Source: https://context7.com/mojang/brigadier/llms.txt This Java code demonstrates how to register commands with Brigadier's CommandDispatcher and then generate both detailed and compact usage strings. It covers registering literal and argument commands, and then uses `getAllUsage()` and `getSmartUsage()` to produce help text. Dependencies include the Brigadier library. ```java import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.tree.CommandNode; import java.util.Map; import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal; import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument; import static com.mojang.brigadier.arguments.IntegerArgumentType.integer; import static com.mojang.brigadier.arguments.StringArgumentType.*; public class UsageExample { public static void main(String[] args) { CommandDispatcher dispatcher = new CommandDispatcher<>(); Object source = new Object(); // Register commands with various structures dispatcher.register( literal("help") .executes(ctx -> { System.out.println("Showing help"); return 1; }) ); dispatcher.register( literal("give") .then(argument("player", word()) .then(argument("item", word()) .executes(ctx -> 1) .then(argument("count", integer(1, 64)) .executes(ctx -> 1)))) ); dispatcher.register( literal("time") .then(literal("set") .then(literal("day").executes(ctx -> 1)) .then(literal("night").executes(ctx -> 1)) .then(argument("value", integer()).executes(ctx -> 1))) .then(literal("query") .then(literal("daytime").executes(ctx -> 1)) .then(literal("gametime").executes(ctx -> 1))) ); // Get all usage strings (detailed) System.out.println("=== All Usage (Detailed) ==="); String[] allUsage = dispatcher.getAllUsage(dispatcher.getRoot(), source, true); for (String usage : allUsage) { System.out.println(" " + usage); } // Output: // help // give // give // time set day // time set night // time set // time query daytime // time query gametime // Get smart usage (compact) System.out.println("\n=== Smart Usage (Compact) ==="); Map, String> smartUsage = dispatcher.getSmartUsage(dispatcher.getRoot(), source); for (var entry : smartUsage.entrySet()) { System.out.println(" " + entry.getKey().getName() + ": " + entry.getValue()); } // Output: // help: help // give: give [] // time: time (set|query) ... // Generate help for specific command node System.out.println("\n=== Usage for 'time' subcommand ==="); CommandNode timeNode = dispatcher.findNode(java.util.List.of("time")); if (timeNode != null) { String[] timeUsage = dispatcher.getAllUsage(timeNode, source, true); for (String usage : timeUsage) { System.out.println(" time " + usage); } } } } ``` -------------------------------- ### Create Literal Command Nodes with LiteralArgumentBuilder in Java Source: https://context7.com/mojang/brigadier/llms.txt Demonstrates how to use LiteralArgumentBuilder to create literal command nodes. This includes building nested subcommands, setting permission requirements, and defining multiple execution handlers for a single literal command. It utilizes the CommandDispatcher and various argument types. ```java import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.exceptions.CommandSyntaxException; import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal; import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument; import static com.mojang.brigadier.arguments.StringArgumentType.greedyString; import static com.mojang.brigadier.arguments.StringArgumentType.getString; public class LiteralExample { public static void main(String[] args) throws CommandSyntaxException { CommandDispatcher dispatcher = new CommandDispatcher<>(); // Nested literals create subcommand structure: /game start, /game stop, /game pause dispatcher.register( literal("game") .then(literal("start") .executes(ctx -> { System.out.println("Game started!"); return 1; })) .then(literal("stop") .executes(ctx -> { System.out.println("Game stopped!"); return 1; })) .then(literal("pause") .executes(ctx -> { System.out.println("Game paused!"); return 1; })) ); // Command with permission requirement dispatcher.register( literal("admin") .requires(source -> source instanceof AdminUser) // Only AdminUser can execute .then(literal("reset") .executes(ctx -> { System.out.println("System reset!"); return 1; })) ); // Multiple execution points: /say or /say dispatcher.register( literal("say") .executes(ctx -> { System.out.println("You said nothing"); return 1; }) .then(argument("message", greedyString()) .executes(ctx -> { System.out.println("You said: " + getString(ctx, "message")); return 1; })) ); Object source = new Object(); dispatcher.execute("game start", source); // Output: Game started! dispatcher.execute("say", source); // Output: You said nothing dispatcher.execute("say Hello world!", source); // Output: You said: Hello world! } } class AdminUser {} ``` -------------------------------- ### Implement Custom Color ArgumentType in Java Source: https://context7.com/mojang/brigadier/llms.txt Demonstrates the implementation of a custom `ColorArgumentType` in Java for Brigadier. This type parses color strings (hex or named) into a `Color` object, provides validation, and offers suggestions for valid color inputs. It requires the Brigadier library. ```java import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import com.mojang.brigadier.LiteralMessage; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.regex.Pattern; import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal; import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument; // Custom Color argument type class ColorArgumentType implements ArgumentType { private static final Collection EXAMPLES = Arrays.asList("#FF0000", "#00FF00", "red", "blue"); private static final Pattern HEX_PATTERN = Pattern.compile("#[0-9A-Fa-f]{6}"); private static final SimpleCommandExceptionType INVALID_COLOR = new SimpleCommandExceptionType(new LiteralMessage("Invalid color format")); public static ColorArgumentType color() { return new ColorArgumentType(); } public static Color getColor(CommandContext context, String name) { return context.getArgument(name, Color.class); } @Override public Color parse(StringReader reader) throws CommandSyntaxException { int start = reader.getCursor(); String input = reader.readUnquotedString(); // Try hex format if (HEX_PATTERN.matcher(input).matches()) { int r = Integer.parseInt(input.substring(1, 3), 16); int g = Integer.parseInt(input.substring(3, 5), 16); int b = Integer.parseInt(input.substring(5, 7), 16); return new Color(r, g, b); } // Try named colors switch (input.toLowerCase()) { case "red": return new Color(255, 0, 0); case "green": return new Color(0, 255, 0); case "blue": return new Color(0, 0, 255); case "white": return new Color(255, 255, 255); case "black": return new Color(0, 0, 0); default: reader.setCursor(start); throw INVALID_COLOR.createWithContext(reader); } } @Override public CompletableFuture listSuggestions( CommandContext context, SuggestionsBuilder builder) { String remaining = builder.getRemainingLowerCase(); for (String color : Arrays.asList("red", "green", "blue", "white", "black")) { if (color.startsWith(remaining)) { builder.suggest(color); } } if ("#".startsWith(remaining) || remaining.startsWith("#")) { builder.suggest("#FF0000", new LiteralMessage("Hex format")); } return builder.buildFuture(); } @Override public Collection getExamples() { return EXAMPLES; } } class Color { public final int r, g, b; public Color(int r, int g, int b) { this.r = r; this.g = g; this.b = b; } @Override public String toString() { return String.format("RGB(%d,%d,%d)", r, g, b); } } public class CustomArgumentExample { public static void main(String[] args) throws CommandSyntaxException { CommandDispatcher dispatcher = new CommandDispatcher<>(); Object source = new Object(); dispatcher.register( literal("setcolor") .then(argument("color", ColorArgumentType.color()) .executes(ctx -> { Color color = ColorArgumentType.getColor(ctx, "color"); System.out.println("Color set to: " + color); return 1; })) ); dispatcher.execute("setcolor red", source); // Output: Color set to: RGB(255,0,0) dispatcher.execute("setcolor #00FF00", source); // Output: Color set to: RGB(0,255,0) dispatcher.execute("setcolor blue", source); // Output: Color set to: RGB(0,0,255) // Test suggestions var suggestions = dispatcher.getCompletionSuggestions( dispatcher.parse("setcolor r", source)).join(); System.out.println("Suggestions: " + suggestions.getList()); // Output: [red] } } ``` -------------------------------- ### Execute Command with Brigadier Source: https://github.com/mojang/brigadier/blob/master/README.md Executes a command directly using the dispatcher. The result is an integer returned by the command, and a source object provides context. CommandSyntaxException or RuntimeException may be thrown on failure. ```java final ParseResults parse = dispatcher.parse("foo 123", source); final int result = execute(parse); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.