Search code examples
spring-shell

Spring Shell - capturing user input in middle of executing ShellMethod


Is the a way to capture user input in middle of executing @ShellMethod. Basically stoping executing of the method to ask for the user input and carrying on after capturing it.


Solution

  • Use Spring Shell UI Components, now that we're in the future.

    "Starting from 2.1.x there is a new component model which provides easier way to create higher level user interaction for usual use cases like asking input in a various forms. These usually are just plain text input or choosing something from a list."

    @ShellComponent
    public class ComponentCommands extends AbstractShellComponent {
    
        @ShellMethod(key = "component string", value = "String input", group = "Components")
        public String stringInput(boolean mask) {
            StringInput component = new StringInput(getTerminal(), "Enter value", "myvalue");
            component.setResourceLoader(getResourceLoader());
            component.setTemplateExecutor(getTemplateExecutor());
            if (mask) {
                component.setMaskCharater('*');
            }
            StringInputContext context = component.run(StringInputContext.empty());
            return "Got value " + context.getResultValue();
        }
    }
    

    https://docs.spring.io/spring-shell/docs/2.1.0-SNAPSHOT/site/reference/htmlsingle/#_build_in_components