Reputation: 53
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.
Upvotes: 1
Views: 946
Reputation: 779
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();
}
Upvotes: 0
Reputation: 124
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;
}
Upvotes: 3
Reputation: 1997
You can read from System.in
and continue/abort execution of your command as you see fit.
Upvotes: 0