1

Is there an way for a spring-shell command to first ask for a confirmation message. For example

command

Do you want to proceed [y/n]

y

executing command

I did some research on internet but I don't find example of this type of command.

Community
  • 1
  • 1
KlezFromSpace
  • 53
  • 1
  • 10

3 Answers3

3

I am using jline.console.ConsoleReader (which spring-shell currently uses as well) for this, so the code looks something like:

public static boolean askYesNo(String question) {
    while (true) {
        String backup = ask(String.format("%s (y/n): ", question));
        if ("y".equals(backup)) {
            return true;
        }
        if ("n".equals(backup)) {
            return false;
        }
    }
}

public static String ask(String question) {
    question = "\n" + question + " > ";

    try {
        ConsoleReader consolereader = new ConsoleReader();
        return consolereader.readLine(question);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}
enem.dev
  • 124
  • 4
0

You can read from System.in and continue/abort execution of your command as you see fit.

ebottard
  • 1,997
  • 2
  • 12
  • 14
0
 try {

      System.out.println("** Press 'y' to delete  OR  'n' to cancel operation **");

        ConsoleReader consolereader = new ConsoleReader();


        int readCharacter = consolereader.readCharacter('y','n');//just can read 'y' and 'n' char. y=121 , n=110


        System.out.println(readCharacter);

       if (readCharacter == 121) {
          // do delete  operation
        } else if (readCharacter == 110) {
          // do cancel operation
        }


    } catch (Exception e) {
        e.printStackTrace();
    }

** Press 'y' to delete OR 'n' to cancel operation **

121

Sajad NasiriNezhad
  • 699
  • 1
  • 7
  • 27