From 9fdf37e3032defc8ea11fd59722b487163381422 Mon Sep 17 00:00:00 2001 From: bculkin2442 Date: Wed, 13 Apr 2016 15:41:42 -0400 Subject: Implemented stream-based commands --- .../src/main/java/bjc/utils/cli/CLICommander.java | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) (limited to 'BJC-Utils2/src/main/java/bjc/utils/cli/CLICommander.java') 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."); + } } -- cgit v1.2.3