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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/*
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */
package Apache.CLI;

import static Apache.CLI.Util.EMPTY_STRING_ARRAY;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

/**
 * Represents list of arguments parsed against a {@link Options} descriptor.
 *
 * <BR /><BR />It allows querying of a boolean {@link #hasOption(String opt)}, in addition to
 * retrieving the {@link #getOptionValue(String opt)} for options requiring arguments.
 * 
 * <BR /><BR />Additionally, any left-over or unrecognized arguments, are available for further
 * processing.
 */
@Torello.JavaDoc.JDHeaderBackgroundImg(EmbedTagFileID="LICENSE")
public class CommandLine implements Serializable {

    /** A nested builder class to create {@code CommandLine} instance using descriptive methods. */
    @Torello.JavaDoc.JDHeaderBackgroundImg(EmbedTagFileID="LICENSE")
    public static final class Builder
    {
        // CommandLine that is being build by this Builder.
        private final CommandLine commandLine = new CommandLine();

        /**
         * Adds left-over unrecognized option/argument.
         * @param arg the unrecognized option/argument.
         * @return this Builder instance for method chaining.
         */
        public Builder addArg(final String arg)
        {
            commandLine.addArg(arg);
            return this;
        }

        /**
         * Adds an option to the command line. The values of the option are stored.
         * @param opt the processed option.
         * @return this Builder instance for method chaining.
         */
        public Builder addOption(final Option opt)
        {
            commandLine.addOption(opt);
            return this;
        }

        /**
         * Returns the new instance.
         * @return the new instance.
         */
        public CommandLine build()
        { return commandLine; }
    }

    // The serial version UID.
    private static final long serialVersionUID = 1L;

    // The unrecognized options/arguments
    private final List<String> args = new LinkedList<>();

    // The processed options
    private final List<Option> options = new ArrayList<>();

    /** Creates a command line. */
    protected CommandLine()
    { /* nothing to do */ }

    /**
     * Adds left-over unrecognized option/argument.
     * @param arg the unrecognized option/argument.
     */
    protected void addArg(final String arg)
    { if (arg != null) args.add(arg); }

    /**
     * Adds an option to the command line. The values of the option are stored.
     * @param opt the processed option.
     */
    protected void addOption(final Option opt)
    { if (opt != null) options.add(opt); }

    /**
     * Gets any left-over non-recognized options and arguments
     * @return remaining items passed in but not parsed as a {@code List}.
     */
    public List<String> getArgList()
    { return args; }

    /**
     * Gets any left-over non-recognized options and arguments
     * @return remaining items passed in but not parsed as an array.
     */
    public String[] getArgs()
    { return args.toArray(Util.EMPTY_STRING_ARRAY); }

    /**
     * Gets the map of values associated to the option. This is convenient for options specifying
     * Java properties like <code>-Dparam1=value1 -Dparam2=value2</code>. The first argument of the
     * option is the key, and the 2nd argument is the value. If the option has only one argument
     * ({@code -Dfoo}) it is considered as a boolean flag and the value is {@code "true"}.
     *
     * @param option name of the option.
     * 
     * @return The Properties mapped by the option, never {@code null} even if the option doesn't
     * exists.
     */
    public Properties getOptionProperties(final Option option)
    {
        final Properties props = new Properties();

        for (final Option processedOption : options)
        {
            if (processedOption.equals(option))
            {
                final List<String> values = processedOption.getValuesList();

                if (values.size() >= 2)

                    // use the first 2 arguments as the key/value pair
                    props.put(values.get(0), values.get(1));

                else if (values.size() == 1)

                    // no explicit value, handle it as a boolean
                    props.put(values.get(0), "true");
            }
        }

        return props;
    }

    /**
     * Gets the map of values associated to the option. This is convenient for options specifying
     * Java properties like <code>-Dparam1=value1 -Dparam2=value2</code>. The first argument of the
     * option is the key, and the 2nd argument is the value. If the option has only one argument
     * ({@code -Dfoo}) it is considered as a boolean flag and the value is {@code "true"}.
     *
     * @param opt name of the option.
     * 
     * @return The Properties mapped by the option, never {@code null} even if the option doesn't
     * exists.
     */
    public Properties getOptionProperties(final String opt)
    {
        final Properties props = new Properties();

        for (final Option option : options)
        {
            if (opt.equals(option.getOpt()) || opt.equals(option.getLongOpt()))
            {
                final List<String> values = option.getValuesList();

                if (values.size() >= 2)

                    // use the first 2 arguments as the key/value pair
                    props.put(values.get(0), values.get(1));

                else if (values.size() == 1)

                    // no explicit value, handle it as a boolean
                    props.put(values.get(0), "true");
            }
        }

        return props;
    }

    /**
     * Gets an array of the processed {@link Option}'s.
     * @return an array of the processed {@link Option}s.
     */
    public Option[] getOptions()
    { return options.toArray(Option.EMPTY_ARRAY); }

    /**
     * Gets the first argument, if any, of this option.
     * @param opt the character name of the option.
     * @return Value of the argument if option is set, and has an argument, otherwise null.
     */
    public String getOptionValue(final char opt)
    { return getOptionValue(String.valueOf(opt)); }

    /**
     * Gets the argument, if any, of an option.
     * @param opt character name of the option
     * @param defaultValue is the default value to be returned if the option is not specified.
     * 
     * @return Value of the argument if option is set, and has an argument, otherwise
     * {@code defaultValue}.
     */
    public String getOptionValue(final char opt, final String defaultValue)
    { return getOptionValue(String.valueOf(opt), defaultValue); }

    /**
     * Gets the first argument, if any, of this option.
     * @param option the name of the option.
     * @return Value of the argument if option is set, and has an argument, otherwise null.
     */
    public String getOptionValue(final Option option)
    {
        if (option == null) return null;

        final String[] values = getOptionValues(option);

        return values == null ? null : values[0];
    }

    /**
     * Gets the first argument, if any, of an option.
     * @param option name of the option.
     * @param defaultValue is the default value to be returned if the option is not specified.
     * 
     * @return Value of the argument if option is set, and has an argument, otherwise
     * {@code defaultValue}.
     */
    public String getOptionValue(final Option option, final String defaultValue)
    {
        final String answer = getOptionValue(option);
        return answer != null ? answer : defaultValue;
    }

    /**
     * Gets the first argument, if any, of this option.
     * @param opt the name of the option.
     * @return Value of the argument if option is set, and has an argument, otherwise null.
     */
    public String getOptionValue(final String opt)
    { return getOptionValue(resolveOption(opt)); }

    /**
     * Gets the first argument, if any, of an option.
     * @param opt name of the option.
     * @param defaultValue is the default value to be returned if the option is not specified.
     * 
     * @return Value of the argument if option is set, and has an argument, otherwise
     * {@code defaultValue}.
     */
    public String getOptionValue(final String opt, final String defaultValue)
    { return getOptionValue(resolveOption(opt), defaultValue); }

    /**
     * Gets the array of values, if any, of an option.
     * @param opt character name of the option.
     * @return Values of the argument if option is set, and has an argument, otherwise null.
     */
    public String[] getOptionValues(final char opt)
    { return getOptionValues(String.valueOf(opt)); }

    /**
     * Gets the array of values, if any, of an option.
     * @param option string name of the option.
     * @return Values of the argument if option is set, and has an argument, otherwise null.
     */
    public String[] getOptionValues(final Option option)
    {
        final List<String> values = new ArrayList<>();

        for (final Option processedOption : options)
            if (processedOption.equals(option))
                values.addAll(processedOption.getValuesList());

        return values.isEmpty() ? null : values.toArray(EMPTY_STRING_ARRAY);
    }

    /**
     * Gets the array of values, if any, of an option.
     * @param opt string name of the option.
     * @return Values of the argument if option is set, and has an argument, otherwise null.
     */
    public String[] getOptionValues(final String opt)
    { return getOptionValues(resolveOption(opt)); }

    /**
     * Gets a version of this {@code Option} converted to a particular type.
     * @param opt the name of the option.
     * @return the value parsed into a particular object.
     * @throws ParseException if there are problems turning the option value into the desired type
     * @see PatternOptionBuilder
     */
    public Object getParsedOptionValue(final char opt) throws ParseException
    { return getParsedOptionValue(String.valueOf(opt)); }

    /**
     * Gets a version of this {@code Option} converted to a particular type.
     * @param option the name of the option.
     * @return the value parsed into a particular object.
     * @throws ParseException if there are problems turning the option value into the desired type
     * @see PatternOptionBuilder
     */
    public Object getParsedOptionValue(final Option option) throws ParseException
    {
        if (option == null) return null;

        final String res = getOptionValue(option);

        if (res == null) return null;

        return TypeHandler.createValue(res, option.getType());
    }

    /**
     * Gets a version of this {@code Option} converted to a particular type.
     * @param opt the name of the option.
     * @return the value parsed into a particular object.
     * @throws ParseException if there are problems turning the option value into the desired type
     * @see PatternOptionBuilder
     */
    public Object getParsedOptionValue(final String opt) throws ParseException
    { return getParsedOptionValue(resolveOption(opt)); }

    /**
     * Tests to see if an option has been set.
     * @param opt character name of the option.
     * @return true if set, false if not.
     */
    public boolean hasOption(final char opt)
    { return hasOption(String.valueOf(opt)); }

    /**
     * Tests to see if an option has been set.
     * @param opt the option to check.
     * @return true if set, false if not.
     */
    public boolean hasOption(final Option opt)
    { return options.contains(opt); }

    /**
     * Tests to see if an option has been set.
     * @param opt Short name of the option.
     * @return true if set, false if not.
     */
    public boolean hasOption(final String opt)
    { return hasOption(resolveOption(opt)); }

    /**
     * Returns an iterator over the Option members of CommandLine.
     *
     * @return an {@code Iterator} over the processed {@link Option} members of this
     * {@link CommandLine}.
     */
    public Iterator<Option> iterator()
    { return options.iterator(); }

    /**
     * Retrieves the option object given the long or short option as a String
     * @param opt short or long name of the option, may be null.
     * @return Canonicalized option.
     */
    private Option resolveOption(final String opt)
    {
        final String actual = Util.stripLeadingHyphens(opt);

        if (actual != null)
            for (final Option option : options)
                if (actual.equals(option.getOpt()) || actual.equals(option.getLongOpt()))
                    return option;

        return null;
    }
}