Skip to content

Instantly share code, notes, and snippets.

@chaozh
Created September 30, 2015 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chaozh/1eeb72346a13ccdde857 to your computer and use it in GitHub Desktop.
Save chaozh/1eeb72346a13ccdde857 to your computer and use it in GitHub Desktop.
A storage class for both command line options and shell commands. <code from ZK>
/**
* A storage class for both command line options and shell commands.
*
*/
static class CommandOptions {
private Map<String,String> options = new HashMap<String,String>();
private List<String> cmdArgs = null;
private String command = null;
public MyCommandOptions() {
options.put("server", "localhost:2181");
options.put("timeout", "30000");
}
public String getOption(String opt) {
return options.get(opt);
}
public String getCommand( ) {
return command;
}
public String getCmdArgument( int index ) {
return cmdArgs.get(index);
}
public int getNumArguments( ) {
return cmdArgs.size();
}
public String[] getArgArray() {
return cmdArgs.toArray(new String[0]);
}
/**
* Parses a command line that may contain one or more flags
* before an optional command string
* @param args command line arguments
* @return true if parsing succeeded, false otherwise.
*/
public boolean parseOptions(String[] args) {
List<String> argList = Arrays.asList(args);
Iterator<String> it = argList.iterator();
while (it.hasNext()) {
String opt = it.next();
try {
if (opt.equals("-server")) {
options.put("server", it.next());
} else if (opt.equals("-timeout")) {
options.put("timeout", it.next());
} else if (opt.equals("-r")) {
options.put("readonly", "true");
}
} catch (NoSuchElementException e){
System.err.println("Error: no argument found for option "
+ opt);
return false;
}
if (!opt.startsWith("-")) {
command = opt;
cmdArgs = new ArrayList<String>( );
cmdArgs.add( command );
while (it.hasNext()) {
cmdArgs.add(it.next());
}
return true;
}
}
return true;
}
/**
* Breaks a string into command + arguments.
* @param cmdstring string of form "cmd arg1 arg2..etc"
* @return true if parsing succeeded.
*/
public boolean parseCommand( String cmdstring ) {
StringTokenizer cmdTokens = new StringTokenizer(cmdstring, " ");
String[] args = new String[cmdTokens.countTokens()];
int tokenIndex = 0;
while (cmdTokens.hasMoreTokens()) {
args[tokenIndex] = cmdTokens.nextToken();
tokenIndex++;
}
if (args.length == 0){
return false;
}
command = args[0];
cmdArgs = Arrays.asList(args);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment