summaryrefslogtreecommitdiff
path: root/3rdParty/jargs-1.0/examples/gnu/CustomOptionTest.java
blob: 2a1c45fd78c3c03c9b9f2b0bf2b6c58608b4b192 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package jargs.examples.gnu;

import jargs.gnu.CmdLineParser;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Locale;
import java.util.Date;

public class CustomOptionTest {

    private static void printUsage() {
        System.err.println("usage: prog [{-d,--date} date]");
    }


    /**
     * A custom type of command line option corresponding to a short
     * date value, e.g. .
     */
    public static class ShortDateOption extends CmdLineParser.Option {
        public ShortDateOption( char shortForm, String longForm ) {
            super(shortForm, longForm, true);
        }
        protected Object parseValue( String arg, Locale locale )
            throws CmdLineParser.IllegalOptionValueException {
            try {
                DateFormat dateFormat =
                    DateFormat.getDateInstance(DateFormat.SHORT, locale);
                return dateFormat.parse(arg);
            }
            catch (ParseException e) {
                throw new CmdLineParser.IllegalOptionValueException(this, arg);
            }
        }
    }

    public static void main( String[] args ) {
        CmdLineParser parser = new CmdLineParser();
        CmdLineParser.Option date =
            parser.addOption(new ShortDateOption('d', "date"));

        try {
            parser.parse(args);
        }
        catch ( CmdLineParser.OptionException e ) {
            System.err.println(e.getMessage());
            printUsage();
            System.exit(2);
        }

        // Extract the values entered for the various options -- if the
        // options were not specified, the corresponding values will be
        // null.
        Date dateValue = (Date)parser.getOptionValue(date);

        // For testing purposes, we just print out the option values
        System.out.println("date: " + dateValue);

        // Extract the trailing command-line arguments ('a_number') in the
        // usage string above.
        String[] otherArgs = parser.getRemainingArgs();
        System.out.println("remaining args: ");
        for ( int i = 0; i < otherArgs.length; ++i ) {
            System.out.println(otherArgs[i]);
        }

        // In a real program, one would pass the option values and other
        // arguments to a function that does something more useful.

        System.exit(0);
    }

}