001// *************************************************************************************************************************** 002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * 003// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * 004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * 005// * with the License. You may obtain a copy of the License at * 006// * * 007// * http://www.apache.org/licenses/LICENSE-2.0 * 008// * * 009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * 010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * 011// * specific language governing permissions and limitations under the License. * 012// *************************************************************************************************************************** 013package org.apache.juneau.collections; 014 015import static org.apache.juneau.internal.StringUtils.*; 016 017import java.util.*; 018 019import org.apache.juneau.*; 020import org.apache.juneau.internal.*; 021 022/** 023 * Utility class to make it easier to work with command-line arguments pass in through a 024 * <c>main(String[] args)</c> method. 025 * 026 * <p> 027 * Used to parse command-line arguments of the form 028 * <js>"[zero or more main arguments] [zero or more optional arguments]"</js>. 029 * 030 * <p> 031 * The format of a main argument is a token that does not start with <js>'-'</js>. 032 * 033 * <p> 034 * The format of an optional argument is <js>"-argName [zero or more tokens]"</js>. 035 * 036 * <h5 class='topic'>Command-line examples</h5> 037 * <ul> 038 * <li><c>java com.sample.MyClass mainArg1</c> 039 * <li><c>java com.sample.MyClass mainArg1 mainArg2</c> 040 * <li><c>java com.sample.MyClass mainArg1 -optArg1</c> 041 * <li><c>java com.sample.MyClass -optArg1</c> 042 * <li><c>java com.sample.MyClass mainArg1 -optArg1 optArg1Val</c> 043 * <li><c>java com.sample.MyClass mainArg1 -optArg1 optArg1Val1 optArg1Val2</c> 044 * <li><c>java com.sample.MyClass mainArg1 -optArg1 optArg1Val1 -optArg1 optArg1Val2</c> 045 * </ul> 046 * 047 * <h5 class='section'>Example:</h5> 048 * <p class='bcode w800'> 049 * 050 * <jc>// Main method with arguments</jc> 051 * <jk>public static void</jk> <jsm>main</jsm>(String[] args) { 052 * 053 * <jc>// Wrap in Args</jc> 054 * Args a = new Args(args); 055 * 056 * <jc>// One main argument</jc> 057 * <jc>// a1</jc> 058 * String a1 = a.getArg(0); <jc>// "a1"</jc> 059 * String a2 = a.getArg(1); <jc>// null</jc> 060 * 061 * <jc>// Two main arguments</jc> 062 * <jc>// a1 a2</jc> 063 * String a1 = a.getArg(0); <jc>// "a1"</jc> 064 * String a2 = a.getArg(1); <jc>// "a2"</jc> 065 * 066 * <jc>// One main argument and one optional argument with no value</jc> 067 * <jc>// a1 -a2</jc> 068 * String a1 = a.getArg(0); 069 * <jk>boolean</jk> hasA2 = a.hasArg(<js>"a2"</js>); <jc>// true</jc> 070 * <jk>boolean</jk> hasA3 = a.hasArg(<js>"a3"</js>); <jc>// false</jc> 071 * 072 * <jc>// One main argument and one optional argument with one value</jc> 073 * <jc>// a1 -a2 v2</jc> 074 * String a1 = a.getArg(0); 075 * String a2 = a.getArg(<js>"a2"</js>); <jc>// "v2"</jc> 076 * String a3 = a.getArg(<js>"a3"</js>); <jc>// null</jc> 077 * 078 * <jc>// One main argument and one optional argument with two values</jc> 079 * <jc>// a1 -a2 v2a v2b</jc> 080 * String a1 = a.getArg(0); 081 * List<String> a2 = a.getArgs(<js>"a2"</js>); <jc>// Contains ["v2a","v2b"]</jc> 082 * List<String> a3 = a.getArgs(<js>"a3"</js>); <jc>// Empty list</jc> 083 * 084 * <jc>// Same as previous, except specify optional argument name multiple times</jc> 085 * <jc>// a1 -a2 v2a -a2 v2b</jc> 086 * String a1 = a.getArg(0); 087 * List<String> a2 = a.getArgs(<js>"a2"</js>); <jc>// Contains ["v2a","v2b"]</jc> 088 * } 089 * </p> 090 * 091 * <p> 092 * Main arguments are available through numeric string keys (e.g. <js>"0"</js>, <js>"1"</js>, ...). 093 * So you could use the {@link OMap} API to convert main arguments directly to POJOs, such as an <c>Enum</c> 094 * <p class='bcode w800'> 095 * <jc>// Get 1st main argument as an Enum</jc> 096 * MyEnum e = a.get(MyEnum.<jk>class</jk>, <js>"0"</js>); 097 * 098 * <jc>// Get 1st main argument as an integer</jc> 099 * int i = a.get(<jk>int</jk>.<jk>class</jk>, <js>"0"</js>); 100 * </p> 101 * 102 * <p> 103 * Equivalent operations are available on optional arguments through the {@link #getArg(Class, String)} method. 104 */ 105public final class Args extends OMap { 106 107 private static final long serialVersionUID = 1L; 108 109 /** 110 * Constructor. 111 * 112 * @param args Arguments passed in through a <c>main(String[] args)</c> method. 113 */ 114 public Args(String[] args) { 115 List<String> argList = new LinkedList<>(Arrays.asList(args)); 116 117 // Capture the main arguments. 118 Integer i = 0; 119 while (! argList.isEmpty()) { 120 String s = argList.get(0); 121 if (startsWith(s,'-')) 122 break; 123 put(i.toString(), argList.remove(0)); 124 i++; 125 } 126 127 // Capture the mapped arguments. 128 String key = null; 129 while (! argList.isEmpty()) { 130 String s = argList.remove(0); 131 if (startsWith(s, '-')) { 132 key = s.substring(1); 133 if (key.matches("\\d*")) 134 throw new BasicRuntimeException("Invalid optional key name ''{0}''", key); 135 if (! containsKey(key)) 136 put(key, new OList()); 137 } else { 138 ((OList)get(key)).add(s); 139 } 140 } 141 } 142 143 /** 144 * Constructor. 145 * 146 * @param args Arguments passed in as a raw command line. 147 */ 148 public Args(String args) { 149 this(StringUtils.splitQuoted(args)); 150 } 151 152 /** 153 * Returns main argument at the specified index, or <jk>null</jk> if the index is out of range. 154 * 155 * <p> 156 * Can be used in conjunction with {@link #hasArg(int)} to check for existence of arg. 157 * <p class='bcode w800'> 158 * <jc>// Check for no arguments</jc> 159 * <jk>if</jk> (! args.hasArg(0)) 160 * printUsageAndExit(); 161 * 162 * <jc>// Get the first argument</jc> 163 * String firstArg = args.getArg(0); 164 * </p> 165 * 166 * <p> 167 * Since main arguments are stored as numeric keys, this method is essentially equivalent to... 168 * <p class='bcode w800'> 169 * <jc>// Check for no arguments</jc> 170 * <jk>if</jk> (! args.containsKey(<js>"0"</js>)) 171 * printUsageAndExit(); 172 * 173 * <jc>// Get the first argument</jc> 174 * String firstArg = args.getString("0"); 175 * </p> 176 * 177 * @param i The index position of the main argument (zero-indexed). 178 * @return The main argument value, or <js>""</js> if argument doesn't exist at that position. 179 */ 180 public String getArg(int i) { 181 return getString(Integer.toString(i)); 182 } 183 184 /** 185 * Returns <jk>true</jk> if argument exists at specified index. 186 * 187 * @param i The zero-indexed position of the argument. 188 * @return <jk>true</jk> if argument exists at specified index. 189 */ 190 public boolean hasArg(int i) { 191 return containsKey(Integer.toString(i)); 192 } 193 194 /** 195 * Returns <jk>true</jk> if the named argument exists. 196 * 197 * @param name The argument name. 198 * @return <jk>true</jk> if the named argument exists. 199 */ 200 public boolean hasArg(String name) { 201 OList l = (OList)get(name); 202 return l != null; 203 } 204 205 /** 206 * Returns the optional argument value, or blank if the optional argument was not specified. 207 * 208 * <p> 209 * If the optional arg has multiple values, returns values as a comma-delimited list. 210 * 211 * @param name The optional argument name. 212 * @return The optional argument value, or blank if the optional argument was not specified. 213 */ 214 public String getArg(String name) { 215 OList l = (OList)get(name); 216 if (l == null || l.size() == 0) 217 return null; 218 if (l.size() == 1) 219 return l.get(0).toString(); 220 return Arrays.toString(l.toArray()).replaceAll("[\\[\\]]", ""); 221 } 222 223 /** 224 * Returns the optional argument value converted to the specified object type. 225 * 226 * <p> 227 * If the optional arg has multiple values, returns only the first converted value. 228 * 229 * <h5 class='section'>Example:</h5> 230 * <p class='bcode w800'> 231 * <jc>// Command: java com.sample.MyClass -verbose true -debug 5</jc> 232 * <jk>boolean</jk> b = args.getArg(<jk>boolean</jk>.<jk>class</jk>, <js>"verbose"</js>); 233 * <jk>int</jk> i = args.getArg(<jk>int</jk>.<jk>class</jk>, <js>"debug"</js>); 234 * </p> 235 * 236 * @param c The class type to convert the value to. 237 * @param <T> The class type to convert the value to. 238 * @param name The optional argument name. 239 * @return The optional argument value, or blank if the optional argument was not specified. 240 */ 241 public <T> T getArg(Class<T> c, String name) { 242 OList l = (OList)get(name); 243 if (l == null || l.size() == 0) 244 return null; 245 return l.get(0, c); 246 } 247 248 /** 249 * Returns the optional argument values as a list of strings. 250 * 251 * <h5 class='section'>Example:</h5> 252 * <p class='bcode w800'> 253 * <jc>// Command: java com.sample.MyClass -extraArgs foo bar baz</jc> 254 * List<String> l1 = args.getArgs(<js>"extraArgs"</js>); <jc>// ['foo','bar','baz']</jc> 255 * List<String> l2 = args.getArgs(<js>"nonExistentArgs"</js>); <jc>// An empty list</jc> 256 * </p> 257 * 258 * @param name The optional argument name. 259 * @return The optional argument values, or an empty list if the optional argument was not specified. 260 */ 261 @SuppressWarnings({"rawtypes", "unchecked"}) 262 public List<String> getArgs(String name) { 263 List l = (OList)get(name); 264 if (l == null) 265 return Collections.emptyList(); 266 return l; 267 } 268}