summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java
diff options
context:
space:
mode:
Diffstat (limited to 'BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java')
-rw-r--r--BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java48
1 files changed, 48 insertions, 0 deletions
diff --git a/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java b/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java
index f48f08e..e816b78 100644
--- a/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java
+++ b/BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java
@@ -2,6 +2,9 @@ package bjc.utils.cli;
import java.io.InputStream;
import java.io.OutputStream;
+import java.io.PrintStream;
+import java.util.Arrays;
+import java.util.Scanner;
/**
* Runs a CLI interface from the provided set of streams
@@ -13,6 +16,7 @@ public class CLICommander {
private InputStream input;
private OutputStream output;
private OutputStream error;
+
private ICommandMode initialMode;
/**
@@ -57,4 +61,48 @@ public class CLICommander {
this.initialMode = initialMode;
}
+
+ /**
+ * Run a set of commands through this commander
+ */
+ public void runCommands() {
+ PrintStream normalOutput = new PrintStream(output);
+ PrintStream errorOutput = new PrintStream(error);
+
+ @SuppressWarnings("resource")
+ // We might use this stream multiple times. Don't close it
+ Scanner inputSource = new Scanner(input);
+
+ ICommandMode currentMode = initialMode;
+
+ while (currentMode != null) {
+ if (currentMode.useCustomPrompt()) {
+ normalOutput.print(currentMode.getCustomPrompt());
+ } else {
+ normalOutput.print(currentMode.getName() + ">> ");
+ }
+
+ String ln = inputSource.nextLine();
+
+ if (currentMode.canHandleCommand(ln)) {
+ String[] commandTokens = ln.split(" ");
+
+ String[] commandArgs;
+
+ if (commandTokens.length > 1) {
+ commandArgs = Arrays.copyOfRange(commandTokens, 1,
+ commandTokens.length);
+ } else {
+ commandArgs = null;
+ }
+
+ currentMode = currentMode.processCommand(commandTokens[0],
+ commandArgs);
+ } else {
+ errorOutput.print("Error: Unrecognized command " + ln);
+ }
+ }
+
+ normalOutput.print("Exiting now.");
+ }
}