diff options
Diffstat (limited to 'openstack-console/src/main/java/com/woorea/openstack/console/CommandLineHelper.java')
-rw-r--r-- | openstack-console/src/main/java/com/woorea/openstack/console/CommandLineHelper.java | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/openstack-console/src/main/java/com/woorea/openstack/console/CommandLineHelper.java b/openstack-console/src/main/java/com/woorea/openstack/console/CommandLineHelper.java new file mode 100644 index 0000000..6e148ce --- /dev/null +++ b/openstack-console/src/main/java/com/woorea/openstack/console/CommandLineHelper.java @@ -0,0 +1,71 @@ +package com.woorea.openstack.console; + +import java.util.StringTokenizer; +import java.util.Vector; + +public class CommandLineHelper { + + public static String[] parse(String input) { + if (input == null || input.length() == 0) { + //no command? no string + return new String[0]; + } + // parse with a simple finite state machine + + final int normal = 0; + final int inQuote = 1; + final int inDoubleQuote = 2; + int state = normal; + StringTokenizer tok = new StringTokenizer(input, "\"\' ", true); + Vector v = new Vector(); + StringBuffer current = new StringBuffer(); + boolean lastTokenHasBeenQuoted = false; + + while (tok.hasMoreTokens()) { + String nextTok = tok.nextToken(); + switch (state) { + case inQuote: + if ("\'".equals(nextTok)) { + lastTokenHasBeenQuoted = true; + state = normal; + } else { + current.append(nextTok); + } + break; + case inDoubleQuote: + if ("\"".equals(nextTok)) { + lastTokenHasBeenQuoted = true; + state = normal; + } else { + current.append(nextTok); + } + break; + default: + if ("\'".equals(nextTok)) { + state = inQuote; + } else if ("\"".equals(nextTok)) { + state = inDoubleQuote; + } else if (" ".equals(nextTok)) { + if (lastTokenHasBeenQuoted || current.length() != 0) { + v.addElement(current.toString()); + current = new StringBuffer(); + } + } else { + current.append(nextTok); + } + lastTokenHasBeenQuoted = false; + break; + } + } + if (lastTokenHasBeenQuoted || current.length() != 0) { + v.addElement(current.toString()); + } + if (state == inQuote || state == inDoubleQuote) { + throw new RuntimeException("unbalanced quotes in " + input); + } + String[] args = new String[v.size()]; + v.copyInto(args); + return args; + } + +} |