### Example Command Line Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/syntax.adoc Provides an example of a command line invocation demonstrating the use of subcommands, options with values, and arguments in various orders. ```shell $>mycommand mysubcommand --optionA=value1 arg1 -b=value2 arg2 --optionC value3 -d value4 ``` -------------------------------- ### Path Input Component Example Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/components/ui/pathinput.adoc This Java snippet demonstrates the usage of the path input component. It requires no specific setup beyond standard Spring Shell component imports. ```java package org.springframework.shell.docs; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.shell.component.PathInput; import org.springframework.shell.component.PathInputContext; import org.springframework.shell.component.TextComponentContext; import java.nio.file.Path; @Configuration public class UiComponentSnippets { @Bean public PathInput pathInput() { return new PathInput() { @Override protected PathInputContext createContext(Path value) { return super.createContext(value).setModel(new TextComponentContext() { @Override public String getPrompt() { return "Enter path:"; } }); } }; } } ``` -------------------------------- ### Simple SearchMatch Example Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/appendices/techintro/searchalgorithm.adoc A basic example showing how to use a configured SearchMatch to find matches within a given text. ```java SearchMatch searchMatch = SearchMatch.builder() .withCaseSensitivity(CaseSensitivity.CASE_INSENSITIVE) .withDirection(Direction.FORWARD) .withNormalization(true) .build(); List texts = List.of("hello", "world", "foo", "bar"); List results = searchMatch.search(texts, "o"); results.forEach(System.out::println); ``` -------------------------------- ### Basic ListView Initialization Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/views/list.adoc Shows how to initialize a basic ListView with items. This is a starting point for displaying lists. ```java var list = new ListView(); list.setItems(List.of("one", "two", "three")); ``` -------------------------------- ### InputView Sample Code Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/views/input.adoc Provides a basic example of InputView usage. Ensure the 'snippets' property is defined to include this example. ```java package org.springframework.shell.docs; import org.springframework.shell.component.view.screen.Screen; import org.springframework.shell.component.view.screen.Screen.Window; import org.springframework.shell.component.view.screen.Screen.Window.Input; import org.springframework.shell.component.view.screen.Screen.Window.Input.InputView; import org.springframework.shell.component.view.screen.Screen.Window.Input.InputView.InputViewTextChangeEvent; import org.springframework.shell.component.view.screen.Screen.Window.Input.InputView.InputViewTextChangeEvent.InputViewTextChange; import org.springframework.shell.component.view.screen.Screen.Window.Input.InputView.InputViewTextChangeEvent.InputViewTextChange.InputViewTextChangeType; public class InputViewSnippets { public void sample(Screen screen) { Window window = screen.createWindow("input-view-sample"); Input input = window.input(); InputView inputView = input.newInputView("my-input", "Hello World"); inputView.addInputViewTextChangeListener(new InputViewTextChangeListener() { @Override public void onInputViewTextChange(InputViewTextChangeEvent event) { InputViewTextChange change = event.getChange(); InputViewTextChangeType type = change.getType(); String text = change.getText(); System.out.println("Input changed: " + type + ", text: " + text); } }); } } ``` -------------------------------- ### Spring Shell Interactive Session Example Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/getting-started.adoc Demonstrates an interactive session with the Spring Shell application, showing available commands and executing the 'hello' command. ```text $>help Available commands: Built-In Commands clear: Clear the terminal screen help: Display help about available commands version: Show version info Greetings hello: Say hello to a given name $>hello --name=foo Hello foo! $>exit Exiting the shell ``` -------------------------------- ### Basic String Input Example Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/components/ui/stringinput.adoc Demonstrates a basic string input component. This snippet shows how to configure a simple text input field. ```java StringInputContext.builder() // .text("Enter your name") // .required(true) // .build() ``` -------------------------------- ### Command Not Available Example Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/availability.adoc Demonstrates the user-facing message when a command is invoked but not available due to application state. ```shell shell:>download Command 'download' exists but is not currently available because you are not connected. ``` -------------------------------- ### Dialog Layout Example Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/views/dialog.adoc Illustrates the typical layout structure of a DialogView, including main content and buttons. ```text ┌──────────────────┐ │ │ │
│ │ │ ├──────────────────┤ │ │ └──────────────────┘ ``` -------------------------------- ### AppView Layout Example Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/views/app.adoc Illustrates the typical layout of an AppView, including menu, main content, and status sections. ```text ┌──────────────────────────┐ │ Menu │ ├──────────────────────────┤ │ │ │ Main │ │ │ ├──────────────────────────┤ │ Status │ └──────────────────────────┘ ``` -------------------------------- ### Run Spring Shell Hello World Application Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/getting-started.adoc Execute the Spring Shell sample application using Maven to start the interactive shell. ```shell ./mvnw -pl org.springframework.shell:spring-shell-sample-hello-world exec:java -Dexec.mainClass=org.springframework.shell.samples.helloworld.SpringShellApplication ``` -------------------------------- ### Custom Command Completion Provider Example Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/completion.adoc This example demonstrates how to define a custom completion provider for a Spring Shell command. It includes an enum for gender options and a composite provider that handles both name and gender completions. ```java public enum Gender { MALE, FEMALE } @Command(name = "hello", description = "Say hello to a given name", group = "Greetings", help = "A command that greets the user with 'Hello [Mr.|Ms.] ${name}!'. Usage: hello [-n | --name]= [-g | --gender]=", completionProvider = "helloCompletionProvider") public void sayHello( @Option(shortName = 'n', longName = "name", description = "the name of the person to greet", defaultValue = "World") String name, @Option(shortName = 'g', longName = "gender", description = "the gender of the person to greet") Gender gender) { String prefix = switch (gender) { case MALE -> "Mr. "; case FEMALE -> "Ms. "; }; System.out.println("Hello " + prefix + name + "!"); } @Bean public CompletionProvider helloCompletionProvider() { EnumCompletionProvider genderCompletionProvider = new EnumCompletionProvider(Gender.class, "--gender"); CompletionProvider nameCompletionProvider = completionContext -> List.of(new CompletionProposal("--name=Bob"), new CompletionProposal("--name=Alice")); return new CompositeCompletionProvider(nameCompletionProvider, genderCompletionProvider); } ``` -------------------------------- ### Number Input Example Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/components/ui/numberinput.adoc Demonstrates how to use the number input component to ask a user for numerical input. It can be configured to use any implementation of Number.class. ```java String value = "10"; NumberInputContext context = NumberInputContext.builder() .defaultValue(value) .defaultClass(Integer.class) .required(true) .build(); return context; ``` -------------------------------- ### Validation Error Example Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/validation.adoc Demonstrates the command-line output when the @Size constraint on the --password option is violated. ```bash $>change-password --password=hello The following constraints were not met: --password: size must be between 8 and 40 Error while executing command change-password: USAGE_ERROR ``` -------------------------------- ### Color and RGB Style Specifications Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/appendices/techintro/theming.adoc Examples of foreground and background color specifications, including named colors and RGB formats. ```text fg-red fg-r fg-rgb:red fg-rgb:xff3333 fg-rgb:#ff3333 ``` -------------------------------- ### Confirmation Component Example Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/components/ui/confirmation.adoc Demonstrates the basic usage of the confirmation component. This snippet shows how to integrate it within a Spring Shell application to ask for user confirmation. ```java confirmation.promptForConfirm(new ConfirmationInputContext("Are you sure?")) ``` -------------------------------- ### Run the Secure Input Application Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-samples/spring-shell-sample-secure-input/README.md Execute the packaged JAR file to start the Spring Shell application. This command launches the interactive shell environment. ```bash java -jar spring-shell-samples/spring-shell-sample-secure-input/target/secure-input.jar ``` -------------------------------- ### Multi Select Component Example Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/components/ui/multiselect.adoc Demonstrates the usage of the multi select component. This snippet requires the UiComponentSnippets.java class and tag 'snippet7'. ```java public class UiComponentSnippets { @Snippet public void snippet7() { // tag::snippet7[] MultiItemSelectorContext context = new MultiItemSelectorContext<>("Select items", "Select items", "Select items"); context.add("Item 1", false, true, true); context.add("Item 2", false, true, true); context.add("Item 3", false, true, true); context.add("Item 4", false, true, true); context.add("Item 5", false, true, true); context.add("Item 6", false, true, true); context.add("Item 7", false, true, true); context.add("Item 8", false, true, true); context.add("Item 9", false, true, true); context.add("Item 10", false, true, true); context.add("Item 11", false, true, true); context.add("Item 12", false, true, true); context.add("Item 13", false, true, true); context.add("Item 14", false, true, true); context.add("Item 15", false, true, true); context.add("Item 16", false, true, true); context.add("Item 17", false, true, true); context.add("Item 18", false, true, true); context.add("Item 19", false, true, true); context.add("Item 20", false, true, true); context.add("Item 21", false, true, true); context.add("Item 22", false, true, true); context.add("Item 23", false, true, true); context.add("Item 24", false, true, true); context.add("Item 25", false, true, true); context.add("Item 26", false, true, true); context.add("Item 27", false, true, true); context.add("Item 28", false, true, true); context.add("Item 29", false, true, true); context.add("Item 30", false, true, true); context.add("Item 31", false, true, true); context.add("Item 32", false, true, true); context.add("Item 33", false, true, true); context.add("Item 34", false, true, true); context.add("Item 35", false, true, true); context.add("Item 36", false, true, true); context.add("Item 37", false, true, true); context.add("Item 38", false, true, true); context.add("Item 39", false, true, true); context.add("Item 40", false, true, true); context.add("Item 41", false, true, true); context.add("Item 42", false, true, true); context.add("Item 43", false, true, true); context.add("Item 44", false, true, true); context.add("Item 45", false, true, true); context.add("Item 46", false, true, true); context.add("Item 47", false, true, true); context.add("Item 48", false, true, true); context.add("Item 49", false, true, true); context.add("Item 50", false, true, true); // end::snippet7[] } } ``` -------------------------------- ### Access Command Context Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/context.adoc Demonstrates how to access the CommandContext to get parsed command input and other relevant information. ```java import org.springframework.shell.context.CommandContext; // ... public void myCommand(CommandContext context) { // Access parsed command input, command registry, etc. System.out.println(context.getParsedCommand()); } ``` -------------------------------- ### Run the Spring Shell Application Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-samples/spring-shell-sample-hello-world/README.md Executes the built Spring Shell Hello World application. This command starts the CLI, allowing user interaction. ```bash java -jar spring-shell-samples/spring-shell-sample-hello-world/target/hello-world.jar ``` -------------------------------- ### Simple StatusBarView Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/views/statusbar.adoc Creates a basic status bar with a single item. This is a foundational example for status bar creation. ```java var view = new StatusBarView(new StatusItem("Item1")); view.open(); ``` -------------------------------- ### Style Attribute Specifications Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/appendices/techintro/theming.adoc Examples of applying style attributes like bold in conjunction with color specifications. ```text bold bold,fg:red ``` -------------------------------- ### Example Spring Shell Application with Multiple Commands Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/testing.adoc Defines a simple Spring Shell application with 'hi' and 'bye' commands. This serves as the application under test. ```java @SpringBootApplication public class GreetingShellApplication { public static void main(String[] args) { SpringApplication.run(GreetingShellApplication.class, args); } @Command public void hi(CommandContext context) { context.outputWriter().println("Hello world!"); } @Command public void bye(CommandContext context) { context.outputWriter().println("Goodbye world!"); } } ``` -------------------------------- ### Spring Shell Interactive Mode Example Source: https://github.com/spring-projects/spring-shell/blob/main/README.adoc Illustrates the interactive prompt of a Spring Shell application after execution. Shows available commands and how to invoke the custom 'hi' command. ```bash shell:>help AVAILABLE COMMANDS Built-In Commands history: Display or save the history of previously run commands clear: Clear the terminal screen help: Display help about available commands quit, exit: Exit the shell version: Show version info script: Execute commands from a script file SpringShellApplication Commands hi: N/A shell:>hi hi ``` -------------------------------- ### Custom PromptProvider Bean Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/customization/custom-prompt.adoc Implement PromptProvider to define a custom shell prompt. This example sets the prompt text to 'myprompt:>' and colors it yellow. ```java @SpringBootApplication static class SpringShellApplication { @Command public void hi() { System.out.println("Hello world!"); } @Bean public PromptProvider myPromptProvider() { return () -> new AttributedString("myprompt:>", AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW)); } } ``` -------------------------------- ### GridView Layout Example Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/views/grid.adoc Demonstrates the basic layout structure created by GridView. This snippet shows how GridView arranges child elements in a grid. ```java package org.springframework.shell.docs; import org.springframework.shell.component.view.screen.Screen; import org.springframework.shell.component.view.screen.Screen.Window; import org.springframework.shell.component.view.screen.Screen.Window.Pane; import org.springframework.shell.component.view.screen.Screen.Window.Pane.Border; import org.springframework.shell.component.view.screen.Screen.Window.Pane.Border.Style; import org.springframework.shell.component.view.screen.Screen.Window.Pane.Border.Type; import org.springframework.shell.component.view.screen.Screen.Window.Pane.Grid; import org.springframework.shell.component.view.screen.Screen.Window.Pane.Grid.Row; import org.springframework.shell.component.view.screen.Screen.Window.Pane.Grid.Column; public class GridViewSnippets { public static void snippet1(Screen screen) { Window window = screen.createWindow("window"); Pane pane = window.createPane("pane", 10, 10, 0, 0); pane.setBorder(new Border(Style.DOUBLE, Type.LEFT, Type.RIGHT, Type.TOP, Type.BOTTOM)); Grid grid = pane.getGrid(); grid.set(new Row(0, 10), new Column(0, 10)); grid.set(new Row(1, 10), new Column(0, 10)); grid.set(new Row(0, 10), new Column(1, 10)); grid.set(new Row(1, 10), new Column(1, 10)); } } ``` -------------------------------- ### Run Spring Petclinic Application Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-samples/spring-shell-sample-petclinic/README.md Executes the built Spring Petclinic application JAR file. This command starts the application and presents a command prompt. ```bash java -jar spring-shell-samples/spring-shell-sample-petclinic/target/petclinic.jar ``` -------------------------------- ### Get Detailed Help for a Specific Command Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/builtin/help.adoc Shows detailed help information for a specific command, including its synopsis, options, and parameter details. Use this for in-depth understanding of a command's functionality. ```bash my-shell:>help version NAME version - Show version info SYNOPSIS version --help OPTIONS --help or -h help for version [Optional] ``` -------------------------------- ### Run the Spring Boot Application Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-samples/spring-shell-sample-spring-boot/README.md Execute the built Spring Boot application to start the Spring Shell interactive prompt. Ensure you are in the correct directory to reference the JAR file. ```bash java -jar spring-shell-samples/spring-shell-sample-spring-boot/target/hello-world-boot.jar ``` -------------------------------- ### Spring Shell Integration Test Setup Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/testing.adoc Shows how to set up an integration test for a Spring Shell application using the @ShellTest annotation. This requires a Spring Boot application class and @ContextConfiguration. ```java @SpringBootApplication public class ExampleShellApplication { @Command(name = "hi", description = "Says hello") public String hello() { return "hello"; } } @ShellTest @ContextConfiguration(classes = ExampleShellApplication.class) class ShellTestIntegrationTests { @Test void testCommandExecution(@Autowired ShellTestClient client) throws Exception { // when ShellScreen shellScreen = client.sendCommand("hi"); // then ShellAssertions.assertThat(shellScreen).containsText("hello"); } @Test void testUnknownCommandExecution(@Autowired ShellTestClient client) { Assertions.assertThatThrownBy(() -> client.sendCommand("foo")) .isInstanceOf(CommandNotFoundException.class); } } ``` -------------------------------- ### Spring Shell v4 Multi-valued Arguments Example Source: https://github.com/spring-projects/spring-shell/wiki/v4-migration-guide Shows how to define multi-valued input for command arguments using the @Arguments annotation with a specified arity. This allows commands to accept multiple values for a single argument. ```java @Command(name = "real-part", description = "Calculate the real part of the product of two complex numbers", group = "math", help = "Calculate the real part of the product of two complex numbers. Example usage: real-part 1 2 3 4") public double realPartOfComplexProduct(@Arguments(arity = 2) double[] realParts, @Arguments(arity = 2) double[] imaginaryParts) { return realParts[0] * realParts[1] - imaginaryParts[0] * imaginaryParts[1]; } ``` -------------------------------- ### Get InputReader from Command Context Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/reading.adoc Obtain the InputReader instance from the command context to read user input. This is the standard way to interact with the shell for input. ```java import org.springframework.shell.context.StandardShellContext; import org.springframework.shell.InputReader; public class ReadingSnippets { // tag::input-reader public void readInput(StandardShellContext context) { InputReader inputReader = context.getInputReader(); String name = inputReader.readLine("Your name: "); System.out.println("Hello " + name); } // end::input-reader } ``` -------------------------------- ### Command Grouping in Spring Shell v3 (Legacy) Source: https://github.com/spring-projects/spring-shell/wiki/v4-migration-guide This example shows the legacy approach to grouping commands using the @Command annotation on a class in Spring Shell v3. ```java //v3 @Command(command = "github auth", group = "Github Authentication Commands") public class GitHubCommands { @Command(command = "login", description = "Login to GitHub.") public void login() { // ... } @Command(command = "logout", description = "Logout from GitHub.") public void logout() { // ... } } ``` -------------------------------- ### Command Grouping in Spring Shell v4 using @CommandGroup Source: https://github.com/spring-projects/spring-shell/wiki/v4-migration-guide This example demonstrates the new approach to grouping commands in Spring Shell v4 using the @CommandGroup annotation on a class and @Command on methods. ```java //v4 @CommandGroup(prefix = "github auth", name = "Github Authentication Commands") public class GitHubCommands { @Command(name = "login", description = "Login to GitHub.") public void login() { // ... } @Command(name = "logout", description = "Logout from GitHub.") public void logout() { // ... } } ``` -------------------------------- ### Defining Commands with @Command in Spring Shell v4 Source: https://github.com/spring-projects/spring-shell/wiki/v4-migration-guide This example demonstrates how to define commands within a Spring-managed bean using the @Command annotation for methods. It shows how to define multiple command names and descriptions, and how to access the CommandContext for output. ```java @Component public class GitHubCommands { private boolean loggedIn = false; @Command(name = { "github", "auth", "login" }, description = "Login to GitHub", group = "GitHub Authentication Commands") public void githubLogin(CommandContext commandContext) { PrintWriter writer = commandContext.outputWriter(); writer.println("Logging in to GitHub..."); writer.flush(); // Simulate login process this.loggedIn = true; } @Command(name = { "github", "auth", "logout" }, description = "Logout from GitHub", group = "GitHub Authentication Commands") public void githubLogout(CommandContext commandContext) { PrintWriter writer = commandContext.outputWriter(); writer.println("Logging out from GitHub..."); writer.flush(); // Simulate logout process this.loggedIn = false; } } ``` -------------------------------- ### Build the Project with Maven Wrapper Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-samples/spring-shell-sample-hello-world/README.md Builds the Spring Shell Hello World sample project using the Maven wrapper. Ensure you are in the project's root directory before executing. ```bash ./mvnw clean install ``` -------------------------------- ### Define Command Options and Arguments Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/syntax.adoc Demonstrates how to define command options using `@Option` and arguments using `@Argument` annotations on method parameters. ```java public void commandWithOptionAndArgument(@Option String option, @Argument String argument) { // ... } ``` -------------------------------- ### ButtonView Sample Usage Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/views/button.adoc Demonstrates setting text and an action for a button when selected. ```java ButtonView button = new ButtonView(); button.setText("My Button"); button.setRunnable(() -> System.out.println("Button clicked!")); ``` -------------------------------- ### List All Commands with Help Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/builtin/help.adoc Displays a list of all available commands and their descriptions known to the shell. This is the basic usage of the help command. ```bash my-shell:>help Available commands: Built-In Commands clear: Clear the terminal screen help: Show help about available commands version: Show version info ``` -------------------------------- ### ANSI Escape Code Specifications Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/appendices/techintro/theming.adoc Examples of using numbers to specify ANSI escape codes for styling. ```text 31 31;1 ``` -------------------------------- ### Simulating User Input with ShellInputProvider Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/testing.adoc Demonstrates how to use ShellInputProvider to simulate user input for commands that read from the input stream. The provider is built using a fluent API. ```java @Bean public Command ask() { return new AbstractCommand("ask", "Ask for user input") { @Override public ExitStatus doExecute(CommandContext commandContext) throws Exception { String message = commandContext.inputReader().readInput(); commandContext.outputWriter().println("You said: " + message); return ExitStatus.OK; } }; } @Test void testCommandExecutionWithReadingInput(@Autowired ShellTestClient client) throws Exception { // given ShellInputProvider inputProvider = ShellInputProvider.providerFor("ask").withInput("hi").build(); // when ShellScreen screen = client.sendCommand(inputProvider); // then ShellAssertions.assertThat(screen).containsText("You said: hi"); } ``` -------------------------------- ### Spring Shell Sample Selection Menu Source: https://github.com/spring-projects/spring-shell/blob/main/README.adoc The interactive menu presented by the `./run-sample.sh` script. Users select a sample application to run by entering a number. ```text Spring Shell Samples ==================== Select a sample to run: 1) hello-world — Simple greeting shell application 2) non-interactive — Non-interactive sample (runs 'hi' and exits) 3) petclinic — Spring PetClinic shell application 4) secure-input — Secure input / password prompt sample 5) spring-boot — Spring Boot-based shell application Enter your choice [1-5]: ``` -------------------------------- ### MenuBarView Constructor with MenuBarItems Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/views/menubar.adoc Demonstrates how to construct a MenuBarView with MenuBarItems, which in turn use MenuItems to define styles, actions, and hot keys. ```java var menuBarView = new MenuBarView( new MenuBarItem( new MenuItem("File", "F", "File menu", "file-menu", Optional.empty(), Optional.empty()), new MenuItem("Help", "H", "Help menu", "help-menu", Optional.empty(), Optional.empty()) ), new MenuBarItem( new MenuItem("Save", "S", "Save current file", "save-file", Optional.of(KeyStroke.parse("control s")), Optional.empty()), new MenuItem("Exit", "X", "Exit application", "exit-app", Optional.of(KeyStroke.parse("control x")), Optional.empty()) ) ); ``` -------------------------------- ### Simple Hello World App Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/intro/index.adoc This snippet demonstrates a basic 'hello world' application using Terminal UI. It shows the fundamental structure for creating a view. ```java package org.springframework.shell.docs; import org.springframework.shell.component.view.TerminalUI; import org.springframework.shell.component.view.View; import org.springframework.stereotype.Component; @Component public class IntroSample { private final TerminalUI ui; public IntroSample(TerminalUI ui) { this.ui = ui; } public void run() { ui.run(new View() { @Override protected void onMount() { ui.println("hello world"); } }); } } ``` -------------------------------- ### Construct SearchMatch using Builder Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/appendices/techintro/searchalgorithm.adoc Demonstrates how to construct a SearchMatch instance using its builder, allowing configuration of case sensitivity, search direction, and text normalization. ```java SearchMatch searchMatch = SearchMatch.builder() .withCaseSensitivity(CaseSensitivity.CASE_INSENSITIVE) .withDirection(Direction.FORWARD) .withNormalization(true) .build(); ``` -------------------------------- ### Implement Custom ExitStatusExceptionMapper Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/exception-handling.adoc Implement the ExitStatusExceptionMapper to map exceptions to specific exit codes and messages. This example maps any exception to exit code 42. ```java @Bean public ExitStatusExceptionMapper myCustomExceptionMapper() { return exception -> new ExitStatus(42, "42! The answer to life, the universe and everything!"); } ``` -------------------------------- ### Build Spring Shell from Source Source: https://github.com/spring-projects/spring-shell/blob/main/README.adoc Clone the Spring Shell repository and build the project using Maven. ```bash $>git clone git@github.com:spring-projects/spring-shell.git $>cd spring-shell $>./mvnw install ``` -------------------------------- ### Basic Component Flow Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/components/flow/index.adoc Demonstrates a basic component flow where components are executed in the order they are defined. ```java package org.springframework.shell.docs; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.shell.command.CommandRegistration; import org.springframework.shell.component.flow.ComponentFlow; import org.springframework.shell.component.flow.ComponentFlowResult; @Configuration public class FlowComponentSnippets { @Bean public CommandRegistration flowCommands(ComponentFlow.Builder componentFlowBuilder) { return CommandRegistration.builder() .withTarget() .registration("flow1", "Run basic flow") .withDescription("Runs a simple flow") .and() .withAction(ctx -> { ComponentFlowResult result = componentFlowBuilder .withComponent("comp1", String.class) .withComponent("comp2", String.class) .withComponent("comp3", String.class) .build() .run(); return result; }) .build(); } } ``` -------------------------------- ### Launch Spring Shell Sample Application Source: https://github.com/spring-projects/spring-shell/blob/main/README.adoc Convenience script to launch sample Spring Shell applications from the repository root. This script presents an interactive menu for selecting and running different samples. ```bash $>./run-sample.sh ``` -------------------------------- ### Build Spring Shell Documentation Source: https://github.com/spring-projects/spring-shell/blob/main/README.adoc Build the project's documentation using the Antora Maven plugin. The documentation will be available in `spring-shell-docs/target/site`. ```bash $>./mvnw antora -pl spring-shell-docs ``` -------------------------------- ### Unsupported Top-Level @Command Annotation in Spring Shell v4 Source: https://github.com/spring-projects/spring-shell/wiki/v4-migration-guide This example shows a usage pattern that is no longer supported in Spring Shell v4, where @Command was applied to a top-level class. ```java @Command class Example { @Command(command = "example") public String example() { return "Hello"; } } ``` -------------------------------- ### Run Spring Shell Application Interactively Source: https://github.com/spring-projects/spring-shell/blob/main/README.adoc Executes the built Spring Shell application as an executable JAR. This command starts the shell in interactive mode, allowing users to enter commands. ```bash $>java -jar target/demo-0.0.1-SNAPSHOT.jar ``` -------------------------------- ### ListView with Checkbox Style Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/views/list.adoc Demonstrates initializing a ListView with a CHECK style, allowing items to have selectable checked states. ```java var list = new ListView(ListViewStyle.CHECK); list.setItems(List.of("one", "two", "three")); ``` -------------------------------- ### Spring Shell Application with Hello Command Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/getting-started.adoc Defines a Spring Shell application with a 'hello' command that greets a given name. The main method bootstraps the Spring context and runs the shell. ```java @EnableCommand(SpringShellApplication.class) public class SpringShellApplication { public static void main(String[] args) throws Exception { ApplicationContext context = new AnnotationConfigApplicationContext(SpringShellApplication.class); ShellRunner runner = context.getBean(ShellRunner.class); runner.run(args); } @Command(name = "hello", description = "Say hello to a given name", group = "Greetings", help = "A command that greets the user with 'Hello ${name}!'. Usage: hello [-n | --name]=") public void sayHello(@Option(shortName = 'n', longName = "name", description = "the name of the person to greet", defaultValue = "World") String name) { System.out.println("Hello " + name + "!"); } } ``` -------------------------------- ### Create TerminalUI with AutoConfiguration Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/intro/terminalui.adoc Use TerminalUIBuilder for autoconfigured services when building TerminalUI. This is the recommended approach. ```java TerminalUI terminalUI = TerminalUIBuilder.build(); ``` -------------------------------- ### Custom Theme Class Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/customization/styling.adoc Create a new theme by implementing ThemeSettings and providing your own style and figure implementations. This offers complete control over the shell's appearance. ```java package org.springframework.shell.docs; import org.springframework.shell.style.ThemeSettings; public class CustomThemeClass extends ThemeSettings { public CustomThemeClass() { super("custom-theme", new CustomStyleClass(), new CustomFigureClass()); } } ``` -------------------------------- ### Define Command using AbstractCommand Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/registration.adoc Simplifies command definition using the AbstractCommand class, which provides utilities for help options and output. ```java package com.example.shell; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.shell.command.AbstractCommand; import org.springframework.shell.command.Command; import org.springframework.shell.standard.ShellMethod; @Configuration public class CommandRegistrationBeanSnippets { @Bean public Command abstractCommand() { return AbstractCommand.of("my-abstract-command", new Object() { @ShellMethod public void myAbstractCommand() { System.out.println("Hello from my-abstract-command!"); } }); } } ``` -------------------------------- ### Basic Shell Command Test Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/testing.adoc Demonstrates a basic test case using ShellTestClient to send a command and ShellAssertions to verify the output. Requires SpringExtension and autowired ShellTestClient. ```java @ExtendWith(SpringExtension.class) class ShellTestClientTests { @Test void testCommandExecution(@Autowired ShellTestClient shellTestClient) throws Exception { // when ShellScreen shellScreen = shellTestClient.sendCommand("test"); // then ShellAssertions.assertThat(shellScreen).containsText("Test command executed"); } } ``` -------------------------------- ### Spring Shell Application with SystemShellRunner Source: https://github.com/spring-projects/spring-shell/wiki/v4-migration-guide Demonstrates a basic Spring Shell application using the default SystemShellRunner, which is interactive and based on the standard Java Console. Requires the @EnableCommand annotation. ```java import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.shell.core.ShellRunner; import org.springframework.shell.core.command.annotation.Command; import org.springframework.shell.core.command.annotation.EnableCommand; @EnableCommand(SpringShellApplication.class) public class SpringShellApplication { public static void main(String[] args) throws Exception { ApplicationContext context = new AnnotationConfigApplicationContext(SpringShellApplication.class); ShellRunner runner = context.getBean(ShellRunner.class); runner.run(args); } @Command public void hi() { System.out.println("Hello world!"); } } ``` -------------------------------- ### Build Spring Shell Application with Maven Source: https://github.com/spring-projects/spring-shell/blob/main/README.adoc Command to package a Spring Shell application using Maven, skipping tests. This is a standard build step before running the application. ```bash $>./mvnw package -DskipTests ``` -------------------------------- ### Using PrintWriter for Console Output Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/writing.adoc Obtain a PrintWriter from the command context to write output to the console. This is the recommended approach over using System.out directly. ```java PrintWriter printWriter = context.get(PrintWriter.class); printWriter.println("Hello World!"); ``` -------------------------------- ### BoxView Sample Drawing Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/views/box.adoc Demonstrates a basic usage of BoxView's drawFunction for simple drawing operations within a bounded rectangle. ```java BoxView boxView = new BoxView() { @Override protected void drawFunction(Context context) { // Simple drawing logic here context.writer().text("Hello BoxView!"); } }; // Example usage within a Shell context (not shown) // boxView.draw(context); ``` -------------------------------- ### Default ProgressView Implementation Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/views/progress.adoc This snippet shows the default configuration of ProgressView, which includes text, spinner, and percentage display. It is used to set up the basic progress bar. ```java ProgressView.of(ProgressViewItem.text(), ProgressViewItem.spinner(), ProgressViewItem.percent()) ``` -------------------------------- ### Enable Native Access in MANIFEST.MF Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/building.adoc Add this attribute to your JAR's META-INF/MANIFEST.MF file to enable native access for the FFM provider. ```text Enable-Native-Access: ALL-UNNAMED ``` -------------------------------- ### End-to-End Test for Multiple Commands in Spring Shell Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/testing.adoc Demonstrates end-to-end testing of multiple commands ('help', 'hi', 'bye') using Spring Shell's testing utilities. It utilizes `@ShellTest` and `ShellTestClient` for command execution and assertion. ```java @ShellTest @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, useMainMethod = SpringBootTest.UseMainMethod.ALWAYS, classes = { GreetingShellApplication.class }, properties = { "spring.shell.interactive.enabled=false" }) public class ShellApplicationEndToEndMultipleCommandsTests { @Test void testCommandExecution(@Autowired ShellTestClient client) throws Exception { // when ShellScreen shellScreen = client.sendCommand("help"); // then ShellAssertions.assertThat(shellScreen).containsText("AVAILABLE COMMANDS"); } @Test void testHiCommandExecution(@Autowired ShellTestClient client) throws Exception { // when ShellScreen shellScreen = client.sendCommand("hi"); // then ShellAssertions.assertThat(shellScreen).containsText("Hello world!"); } @Test void testByeCommandExecution(@Autowired ShellTestClient client) throws Exception { // when ShellScreen shellScreen = client.sendCommand("bye"); // then ShellAssertions.assertThat(shellScreen).containsText("Goodbye world!"); } } ``` -------------------------------- ### Configure Views in TerminalUI Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/intro/terminalui.adoc The configure method on TerminalUI integrates views with the event loop and other necessary services. ```java terminalUI.configure(view); ``` -------------------------------- ### Custom CellFactory for ListView Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/views/list.adoc Illustrates how to create and use a custom CellFactory to control how individual list items are rendered. ```java class MyCellFactory implements CellFactory { @Override public CharSequence generate(String item) { return "Custom: " + item; } } ``` -------------------------------- ### Path Search Component Configuration Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/components/ui/pathsearch.adoc Configuration for the path search UI component. This snippet shows how to set up the component with a base directory and an optional search expression. ```java PathSearchConfig.builder() .baseDirectory(Path.of("/")) .searchExpression("*.java") .build() ``` -------------------------------- ### Execute Script File Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/builtin/script.adoc Use the 'script' command with the --file option to specify the absolute path to a script file containing commands to execute. ```shell $>script --file /absolute/path/to/your/script.txt ``` -------------------------------- ### Define Multi-Valued Arguments Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/syntax.adoc Shows how to define multi-valued arguments using the `@Arguments` annotation on an array or collection type. All remaining command line tokens are collected into this collection. ```java @Arguments public void multiValuedArgument(List values) { // ... } ``` -------------------------------- ### Enable Native Access for FFM Provider Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/building.adoc Use this JVM option to enable native access when using the FFM terminal provider with JDK 22+. ```bash --enable-native-access=ALL-UNNAMED ``` -------------------------------- ### Enable Command Registration with @EnableCommand Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/registration.adoc Enables command registration for target classes. This is automatically handled by Spring Boot auto-configuration. ```java package com.example.shell; import org.springframework.context.annotation.Configuration; import org.springframework.shell.command.annotation.EnableCommand; @Configuration @EnableCommand(CommandAnnotationSnippets.class) public class EnableCommandConfiguration { } ``` -------------------------------- ### Configure Enable Native Access in Gradle Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/building.adoc Configure the bootJar task in your Gradle build script to include the 'Enable-Native-Access' manifest attribute. ```groovy tasks.named("bootJar") { manifest { attributes 'Enable-Native-Access': 'ALL-UNNAMED' } } ``` -------------------------------- ### Spring Boot Application with JLineShellRunner Source: https://github.com/spring-projects/spring-shell/wiki/v4-migration-guide Configures a Spring Boot application to use the JLine-based interactive shell. This is achieved by using the Spring Boot starter, which automatically configures JLineShellRunner. ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.shell.core.command.annotation.Command; @SpringBootApplication public class SpringShellApplication { public static void main(String[] args) { // This will start the JLine-based interactive shell SpringApplication.run(SpringShellApplication.class, args); } @Command public void hi() { System.out.println("Hello world!"); } } ``` -------------------------------- ### Maven Build for Native Compilation Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/building.adoc This snippet shows the Maven configuration for building a Spring Shell application, specifically enabling native compilation. ```xml org.springframework.experimental spring-native-maven-plugin ${experiments.native.version} native-agent-image build-native ``` -------------------------------- ### Subscribe to All Key Events Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/events/key.adoc Use this snippet to subscribe to all key events. The KeyEvent record contains information about bindings from the terminal. ```java KeyEvent event = new KeyEvent(new KeyStroke(new Character('a'), null, null)); context.subscribe("all", event -> { System.out.println("Key event: " + event.keyStroke().character()); }); context.write("a"); ``` -------------------------------- ### Programmatic Component Rendering with Function Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/components/ui/render.adoc Implement custom component rendering by creating a Function that accepts a Context and returns a list of AttributedString. This approach offers flexibility for complex rendering logic. ```java Function> renderer = context -> { // Custom rendering logic here return List.of(new AttributedString("Rendered by code")); }; ``` -------------------------------- ### Plain Events as Spring Messages Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/tui/events/eventloop.adoc Demonstrates how events are represented as Spring Messages within the EventLoop. This is the fundamental way events are handled. ```java plainevents ``` -------------------------------- ### Add a Command to a Spring Shell Application Source: https://github.com/spring-projects/spring-shell/blob/main/README.adoc Demonstrates how to add a simple 'hi' command to a Spring Boot application using Spring Shell annotations. This snippet shows the basic structure for defining a command within the main application class. ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.shell.core.command.annotation.Command; @SpringBootApplication public class DemoApplication { @Command public String hi() { return "hi"; } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` -------------------------------- ### Define Command Method with @Command Annotation Source: https://github.com/spring-projects/spring-shell/blob/main/spring-shell-docs/modules/ROOT/pages/commands/registration.adoc Marks a method for command registration. If no command name is provided, the method name is used. Return values are printed to the shell. ```java package com.example.shell; import org.springframework.shell.standard.ShellComponent; import org.springframework.shell.standard.ShellMethod; @ShellComponent public class CommandAnnotationSnippets { @ShellMethod(key = "example") public String commandAnnoInMethod() { return "This is an example command"; } } ```