001package jargs.examples.gnu; 002 003import jargs.gnu.CmdLineParser; 004import java.text.DateFormat; 005import java.text.ParseException; 006import java.util.Locale; 007import java.util.Date; 008 009public class CustomOptionTest { 010 011 private static void printUsage() { 012 System.err.println("usage: prog [{-d,--date} date]"); 013 } 014 015 016 /** 017 * A custom type of command line option corresponding to a short 018 * date value, e.g. . 019 */ 020 public static class ShortDateOption extends CmdLineParser.Option { 021 public ShortDateOption( char shortForm, String longForm ) { 022 super(shortForm, longForm, true); 023 } 024 protected Object parseValue( String arg, Locale locale ) 025 throws CmdLineParser.IllegalOptionValueException { 026 try { 027 DateFormat dateFormat = 028 DateFormat.getDateInstance(DateFormat.SHORT, locale); 029 return dateFormat.parse(arg); 030 } 031 catch (ParseException e) { 032 throw new CmdLineParser.IllegalOptionValueException(this, arg); 033 } 034 } 035 } 036 037 public static void main( String[] args ) { 038 CmdLineParser parser = new CmdLineParser(); 039 CmdLineParser.Option date = 040 parser.addOption(new ShortDateOption('d', "date")); 041 042 try { 043 parser.parse(args); 044 } 045 catch ( CmdLineParser.OptionException e ) { 046 System.err.println(e.getMessage()); 047 printUsage(); 048 System.exit(2); 049 } 050 051 // Extract the values entered for the various options -- if the 052 // options were not specified, the corresponding values will be 053 // null. 054 Date dateValue = (Date)parser.getOptionValue(date); 055 056 // For testing purposes, we just print out the option values 057 System.out.println("date: " + dateValue); 058 059 // Extract the trailing command-line arguments ('a_number') in the 060 // usage string above. 061 String[] otherArgs = parser.getRemainingArgs(); 062 System.out.println("remaining args: "); 063 for ( int i = 0; i < otherArgs.length; ++i ) { 064 System.out.println(otherArgs[i]); 065 } 066 067 // In a real program, one would pass the option values and other 068 // arguments to a function that does something more useful. 069 070 System.exit(0); 071 } 072 073}