01: package jargs.examples.gnu;
02:
03: import jargs.gnu.CmdLineParser;
04: import java.text.DateFormat;
05: import java.text.ParseException;
06: import java.util.Locale;
07: import java.util.Date;
08:
09: public class CustomOptionTest {
10:
11: private static void printUsage() {
12: System.err.println("usage: prog [{-d,--date} date]");
13: }
14:
15: /**
16: * A custom type of command line option corresponding to a short
17: * date value, e.g. .
18: */
19: public static class ShortDateOption extends CmdLineParser.Option {
20: public ShortDateOption(char shortForm, String longForm) {
21: super (shortForm, longForm, true);
22: }
23:
24: protected Object parseValue(String arg, Locale locale)
25: throws CmdLineParser.IllegalOptionValueException {
26: try {
27: DateFormat dateFormat = DateFormat.getDateInstance(
28: DateFormat.SHORT, locale);
29: return dateFormat.parse(arg);
30: } catch (ParseException e) {
31: throw new CmdLineParser.IllegalOptionValueException(
32: this , arg);
33: }
34: }
35: }
36:
37: public static void main(String[] args) {
38: CmdLineParser parser = new CmdLineParser();
39: CmdLineParser.Option date = parser
40: .addOption(new ShortDateOption('d', "date"));
41:
42: try {
43: parser.parse(args);
44: } catch (CmdLineParser.OptionException e) {
45: System.err.println(e.getMessage());
46: printUsage();
47: System.exit(2);
48: }
49:
50: // Extract the values entered for the various options -- if the
51: // options were not specified, the corresponding values will be
52: // null.
53: Date dateValue = (Date) parser.getOptionValue(date);
54:
55: // For testing purposes, we just print out the option values
56: System.out.println("date: " + dateValue);
57:
58: // Extract the trailing command-line arguments ('a_number') in the
59: // usage string above.
60: String[] otherArgs = parser.getRemainingArgs();
61: System.out.println("remaining args: ");
62: for (int i = 0; i < otherArgs.length; ++i) {
63: System.out.println(otherArgs[i]);
64: }
65:
66: // In a real program, one would pass the option values and other
67: // arguments to a function that does something more useful.
68:
69: System.exit(0);
70: }
71:
72: }
|