Author: [log in to unmask]
Date: Mon Nov 10 00:15:35 2014
New Revision: 1465
Log:
Add generic parsing to abstract class's execute method.
Modified:
java/trunk/conditions/src/main/java/org/hps/conditions/cli/AbstractCommand.java
Modified: java/trunk/conditions/src/main/java/org/hps/conditions/cli/AbstractCommand.java
=============================================================================
--- java/trunk/conditions/src/main/java/org/hps/conditions/cli/AbstractCommand.java (original)
+++ java/trunk/conditions/src/main/java/org/hps/conditions/cli/AbstractCommand.java Mon Nov 10 00:15:35 2014
@@ -1,12 +1,15 @@
package org.hps.conditions.cli;
+import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.Parser;
import org.apache.commons.cli.PosixParser;
/**
- * This is the API that sub-commands must implement in the conditions command line interface.
+ * This is the API that sub-commands must implement in the conditions command
+ * line interface.
*
* @author Jeremy McCormick <[log in to unmask]>
*/
@@ -16,20 +19,22 @@
String description;
Options options = new Options();
Parser parser = new PosixParser();
+ CommandLine commandLine;
boolean verbose = false;
/**
- * Class constructor.
+ * Class constructor.
* @param name The string that invokes this command.
* @param description The description of this command.
*/
AbstractCommand(String name, String description) {
this.name = name;
this.description = description;
+ options.addOption("h", false, "Print help for this command");
}
-
+
/**
- * Get the name of this command.
+ * Get the name of this command.
* @return A String of the name of this command.
*/
String getName() {
@@ -37,7 +42,7 @@
}
/**
- * Get the description of this command.
+ * Get the description of this command.
* @return A String of the description of this command.
*/
String getDescription() {
@@ -45,7 +50,7 @@
}
/**
- * Options for this command.
+ * Options for this command.
* @return Options object for this command.
*/
Options getOptions() {
@@ -60,7 +65,7 @@
HelpFormatter help = new HelpFormatter();
help.printHelp(getName(), getOptions());
}
-
+
/**
* Set whether verbose output is enabled.
* @param verbose True to enable verbose output.
@@ -70,9 +75,19 @@
}
/**
- * Execute the command with the arguments.
- * This is the only method that sub-classes must implement.
+ * Execute the command with the arguments. This is the only method that
+ * sub-classes must implement.
* @param arguments The sub-command's arguments.
*/
- abstract void execute(String[] arguments);
+ void execute(String[] arguments) {
+ try {
+ commandLine = parser.parse(options, arguments);
+ } catch (ParseException e) {
+ throw new RuntimeException(e);
+ }
+ if (commandLine.hasOption("h")) {
+ this.printUsage();
+ System.exit(0);
+ }
+ }
}
|