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.utils; 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 * <code>main(String[] args)</code> 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><code>java com.sample.MyClass mainArg1</code> 039 * <li><code>java com.sample.MyClass mainArg1 mainArg2</code> 040 * <li><code>java com.sample.MyClass mainArg1 -optArg1</code> 041 * <li><code>java com.sample.MyClass -optArg1</code> 042 * <li><code>java com.sample.MyClass mainArg1 -optArg1 optArg1Val</code> 043 * <li><code>java com.sample.MyClass mainArg1 -optArg1 optArg1Val1 optArg1Val2</code> 044 * <li><code>java com.sample.MyClass mainArg1 -optArg1 optArg1Val1 -optArg1 optArg1Val2</code> 045 * </ul> 046 * 047 * <h5 class='section'>Example:</h5> 048 * <p class='bcode'> 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 ObjectMap} API to convert main arguments directly to POJOs, such as an <code>Enum</code> 094 * <p class='bcode'> 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 ObjectMap { 106 107 private static final long serialVersionUID = 1L; 108 109 /** 110 * Constructor. 111 * 112 * @param args Arguments passed in through a <code>main(String[] args)</code> 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 FormattedRuntimeException("Invalid optional key name ''{0}''", key); 135 if (! containsKey(key)) 136 put(key, new ObjectList()); 137 } else { 138 ((ObjectList)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'> 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'> 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 the optional argument value, or blank if the optional argument was not specified. 196 * 197 * <p> 198 * If the optional arg has multiple values, returns values as a comma-delimited list. 199 * 200 * @param name The optional argument name. 201 * @return The optional argument value, or blank if the optional argument was not specified. 202 */ 203 public String getArg(String name) { 204 ObjectList l = (ObjectList)get(name); 205 if (l == null || l.size() == 0) 206 return null; 207 if (l.size() == 1) 208 return l.get(0).toString(); 209 return Arrays.toString(l.toArray()).replaceAll("[\\[\\]]", ""); 210 } 211 212 /** 213 * Returns the optional argument value converted to the specified object type. 214 * 215 * <p> 216 * If the optional arg has multiple values, returns only the first converted value. 217 * 218 * <h5 class='section'>Example:</h5> 219 * <p class='bcode'> 220 * <jc>// Command: java com.sample.MyClass -verbose true -debug 5</jc> 221 * <jk>boolean</jk> b = args.getArg(<jk>boolean</jk>.<jk>class</jk>, <js>"verbose"</js>); 222 * <jk>int</jk> i = args.getArg(<jk>int</jk>.<jk>class</jk>, <js>"debug"</js>); 223 * </p> 224 * 225 * @param c The class type to convert the value to. 226 * @param <T> The class type to convert the value to. 227 * @param name The optional argument name. 228 * @return The optional argument value, or blank if the optional argument was not specified. 229 */ 230 public <T> T getArg(Class<T> c, String name) { 231 ObjectList l = (ObjectList)get(name); 232 if (l == null || l.size() == 0) 233 return null; 234 return l.get(0, c); 235 } 236 237 /** 238 * Returns the optional argument values as a list of strings. 239 * 240 * <h5 class='section'>Example:</h5> 241 * <p class='bcode'> 242 * <jc>// Command: java com.sample.MyClass -extraArgs foo bar baz</jc> 243 * List<String> l1 = args.getArgs(<js>"extraArgs"</js>); <jc>// ['foo','bar','baz']</jc> 244 * List<String> l2 = args.getArgs(<js>"nonExistentArgs"</js>); <jc>// An empty list</jc> 245 * </p> 246 * 247 * @param name The optional argument name. 248 * @return The optional argument values, or an empty list if the optional argument was not specified. 249 */ 250 @SuppressWarnings({"rawtypes", "unchecked"}) 251 public List<String> getArgs(String name) { 252 List l = (ObjectList)get(name); 253 if (l == null) 254 return Collections.emptyList(); 255 return l; 256 } 257}