select from a small amount of options in spring shell

后端 未结 3 944
感情败类
感情败类 2021-01-23 15:53

I am currently trying to make an cli app with Spring Shell.

I want the user to able to fast pick one of 2-3 options. My current code works fine in eclipse but when I sta

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-23 16:12

    Facing a similar requirement, and not finding an example of such a thing anywhere in the JLine 3 or Spring-Shell 2 docs, I did some experimenting...

    Basically -- these components are not designed to work that way. Trying to get additional user input while already in the context of a @ShellMethod is simply not a supported feature.

    Any IO activity that you might do using System.out or System.in ends up being handled differently "under the hood" by JLine depending on what type of shell you first started from (hence your observation that your attempt behaves differently when the app is invoked from PowerShell vs being launched from within the IDE). I was able to get the desired behavior if I launched from GitBash on Windows, but not if I launched from CMD. In one case I just ended up crashing the application completely.

    However, I did find one way to prompt for input that worked for both GitBash and CMD. This example will not work in plain JLine, but appears to work in Spring-Shell 2.0 as long as you are using Spring Boot autoconfiguration (which gives you access to the same 'LineReader' instance that Spring initialized for your shell application).

    @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 speech recognition service. Type in the number and press enter:"
            + "\n 1. Google Speech API"
            + "\n 2. Bing Speech API";
    
            // Get Input
            String input = this.ask(question);
    
            // Select Service
            switch (input) {
            case "1":
                /*
                 * do something...
                 */
                console.write("Google Speech API selected");
                success = true;
                break;
            case "2":
                /*
                 * do something...
                 */
                console.write("Bing Speech API selected");
                success = true;
                break;
            default:
                this.console.error("Input not valid. Please type a number and press Enter to select a Service");
                break;
            }
        } while (!success);
    }
    

提交回复
热议问题