1 22 23 24 package com.mchange.v2.cmdline; 25 26 import java.util.*; 27 28 class ParsedCommandLineImpl implements ParsedCommandLine 29 { 30 String [] argv; 31 String switchPrefix; 32 33 String [] unswitchedArgs; 34 35 HashMap foundSwitches = new HashMap(); 38 39 ParsedCommandLineImpl(String [] argv, 40 String switchPrefix, 41 String [] validSwitches, 42 String [] requiredSwitches, 43 String [] argSwitches) 44 throws BadCommandLineException 45 { 46 this.argv = argv; 47 this.switchPrefix = switchPrefix; 48 49 List unswitchedArgsList = new LinkedList(); 50 int sp_len = switchPrefix.length(); 51 52 for (int i = 0; i < argv.length; ++i) 53 { 54 if (argv[i].startsWith(switchPrefix)) { 56 String sw = argv[i].substring( sp_len ); 57 String arg = null; 58 59 int eq = sw.indexOf('='); 60 if ( eq >= 0 ) { 62 arg = sw.substring( eq + 1 ); 63 sw = sw.substring( 0, eq ); 64 } 65 else if ( contains( sw, argSwitches ) ) { 67 if (i < argv.length - 1 && !argv[i + 1].startsWith( switchPrefix) ) 68 arg = argv[++i]; 69 } 70 71 if (validSwitches != null && ! contains( sw, validSwitches ) ) 72 throw new UnexpectedSwitchException("Unexpected Switch: " + sw, sw); 73 if (argSwitches != null && arg != null && ! contains( sw, argSwitches )) 74 throw new UnexpectedSwitchArgumentException("Switch \"" + sw + 75 "\" should not have an " + 76 "argument. Argument \"" + 77 arg + "\" found.", sw, arg); 78 foundSwitches.put( sw, arg ); 79 } 80 else 81 unswitchedArgsList.add( argv[i] ); 82 } 83 84 if (requiredSwitches != null) 85 { 86 for (int i = 0; i < requiredSwitches.length; ++i) 87 if (! foundSwitches.containsKey( requiredSwitches[i] )) 88 throw new MissingSwitchException("Required switch \"" + requiredSwitches[i] + 89 "\" not found.", requiredSwitches[i]); 90 } 91 92 unswitchedArgs = new String [ unswitchedArgsList.size() ]; 93 unswitchedArgsList.toArray( unswitchedArgs ); 94 } 95 96 public String getSwitchPrefix() 97 { return switchPrefix; } 98 99 public String [] getRawArgs() 100 { return (String []) argv.clone(); } 101 102 public boolean includesSwitch(String sw) 103 { return foundSwitches.containsKey( sw ); } 104 105 public String getSwitchArg(String sw) 106 { return (String ) foundSwitches.get(sw); } 107 108 public String [] getUnswitchedArgs() 109 { return (String []) unswitchedArgs.clone(); } 110 111 private static boolean contains(String string, String [] list) 112 { 113 for (int i = list.length; --i >= 0;) 114 if (list[i].equals(string)) return true; 115 return false; 116 } 117 118 } 119 120 121 122 123 124 125 | Popular Tags |