01: package jargs.examples.gnu;
02:
03: import jargs.gnu.CmdLineParser;
04:
05: import java.util.ArrayList;
06: import java.util.Iterator;
07: import java.util.List;
08:
09: /**
10: * This example shows how to dynamically create basic output for a --help option.
11: */
12: public class AutoHelpParser extends CmdLineParser {
13: List optionHelpStrings = new ArrayList();
14:
15: public Option addHelp(Option option, String helpString) {
16: optionHelpStrings.add(" -" + option.shortForm() + "/--"
17: + option.longForm() + ": " + helpString);
18: return option;
19: }
20:
21: public void printUsage() {
22: System.err.println("usage: prog [options]");
23: for (Iterator i = optionHelpStrings.iterator(); i.hasNext();) {
24: System.err.println(i.next());
25: }
26: }
27:
28: public static void main(String[] args) {
29: AutoHelpParser parser = new AutoHelpParser();
30: CmdLineParser.Option verbose = parser.addHelp(parser
31: .addBooleanOption('v', "verbose"),
32: "Print extra information");
33: CmdLineParser.Option size = parser.addHelp(parser
34: .addIntegerOption('s', "size"),
35: "The extent of the thing");
36: CmdLineParser.Option name = parser.addHelp(parser
37: .addStringOption('n', "name"),
38: "Name given to the widget");
39: CmdLineParser.Option fraction = parser.addHelp(parser
40: .addDoubleOption('f', "fraction"),
41: "What percentage should be discarded");
42: CmdLineParser.Option help = parser.addHelp(parser
43: .addBooleanOption('h', "help"),
44: "Show this help message");
45:
46: try {
47: parser.parse(args);
48: } catch (CmdLineParser.OptionException e) {
49: System.err.println(e.getMessage());
50: parser.printUsage();
51: System.exit(2);
52: }
53:
54: if (Boolean.TRUE.equals(parser.getOptionValue(help))) {
55: parser.printUsage();
56: System.exit(0);
57: }
58:
59: // Extract the values entered for the various options -- if the
60: // options were not specified, the corresponding values will be
61: // null.
62: Boolean verboseValue = (Boolean) parser.getOptionValue(verbose);
63: Integer sizeValue = (Integer) parser.getOptionValue(size);
64: String nameValue = (String) parser.getOptionValue(name);
65: Double fractionValue = (Double) parser.getOptionValue(fraction);
66:
67: // For testing purposes, we just print out the option values
68: System.out.println("verbose: " + verboseValue);
69: System.out.println("size: " + sizeValue);
70: System.out.println("name: " + nameValue);
71: System.out.println("fraction: " + fractionValue);
72:
73: // Extract the trailing command-line arguments ('a_nother') in the
74: // usage string above.
75: String[] otherArgs = parser.getRemainingArgs();
76: System.out.println("remaining args: ");
77: for (int i = 0; i < otherArgs.length; ++i) {
78: System.out.println(otherArgs[i]);
79: }
80:
81: // In a real program, one would pass the option values and other
82: // arguments to a function that does something more useful.
83:
84: System.exit(0);
85: }
86:
87: }
|