hamid
hamid

Reputation: 2079

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.

Upvotes: 2

Views: 2901

Answers (3)

Alexander Taylor
Alexander Taylor

Reputation: 17652

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

Upvotes: 2

Evgenii Terekhov
Evgenii Terekhov

Reputation: 61

There is possible solution here: https://stackoverflow.com/a/50954716, authored by ZachOfAllTrades

It works only when your app is SpringBoot-based, so you'll have access to the LineReader object, configured by SpringBoot.

@Autowired
LineReader reader;

public String ask(String question) {
    return this.reader.readLine("\n" + question + " > ");
}

@ShellMethod(key = { "setService", "select" }, value = "Choose a Speech to Text Service")
public void setService() {
    boolean success = false;
    do {
        String question = "Please select a service.";

        // Get Input
        String input = this.ask(question);

        // Input handling
        /*
         * do something with input variable
         */
        success = true;

        }
    } while (!success);
}

I didn't try it myself, though.

Upvotes: 3

ebottard
ebottard

Reputation: 1997

You should be able to interact directly with System.in although it is not really what Spring Shell is about: commands should be self contained.

Upvotes: 0

Related Questions