KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > cli > CommandLine


1 /*
2  * $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/CommandLine.java,v 1.4 2002/06/06 22:32:37 bayard Exp $
3  * $Revision: 1.4 $
4  * $Date: 2002/06/06 22:32:37 $
5  *
6  * ====================================================================
7  *
8  * The Apache Software License, Version 1.1
9  *
10  * Copyright (c) 1999-2001 The Apache Software Foundation. All rights
11  * reserved.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  *
17  * 1. Redistributions of source code must retain the above copyright
18  * notice, this list of conditions and the following disclaimer.
19  *
20  * 2. Redistributions in binary form must reproduce the above copyright
21  * notice, this list of conditions and the following disclaimer in
22  * the documentation and/or other materials provided with the
23  * distribution.
24  *
25  * 3. The end-user documentation included with the redistribution, if
26  * any, must include the following acknowlegement:
27  * "This product includes software developed by the
28  * Apache Software Foundation (http://www.apache.org/)."
29  * Alternately, this acknowlegement may appear in the software itself,
30  * if and wherever such third-party acknowlegements normally appear.
31  *
32  * 4. The names "The Jakarta Project", "Commons", and "Apache Software
33  * Foundation" must not be used to endorse or promote products derived
34  * from this software without prior written permission. For written
35  * permission, please contact apache@apache.org.
36  *
37  * 5. Products derived from this software may not be called "Apache"
38  * nor may "Apache" appear in their names without prior written
39  * permission of the Apache Group.
40  *
41  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
42  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
43  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
44  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
45  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
46  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
47  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
48  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
49  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
50  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
51  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52  * SUCH DAMAGE.
53  * ====================================================================
54  *
55  * This software consists of voluntary contributions made by many
56  * individuals on behalf of the Apache Software Foundation. For more
57  * information on the Apache Software Foundation, please see
58  * <http://www.apache.org/>.
59  *
60  */

61 package org.apache.commons.cli;
62
63 import java.util.ArrayList JavaDoc;
64 import java.util.Collection JavaDoc;
65 import java.util.HashMap JavaDoc;
66 import java.util.Iterator JavaDoc;
67 import java.util.List JavaDoc;
68 import java.util.LinkedList JavaDoc;
69 import java.util.Map JavaDoc;
70
71 /**
72  * <p>Represents list of arguments parsed against
73  * a {@link Options} descriptor.<p>
74  *
75  * <p>It allows querying of a boolean {@link #hasOption(String opt)},
76  * in addition to retrieving the {@link #getOptionValue(String opt)}
77  * for options requiring arguments.</p>
78  *
79  * <p>Additionally, any left-over or unrecognized arguments,
80  * are available for further processing.</p>
81  *
82  * @author bob mcwhirter (bob @ werken.com)
83  * @author <a HREF="mailto:jstrachan@apache.org">James Strachan</a>
84  * @author John Keyes (john at integralsource.com)
85  */

86 public class CommandLine {
87     
88     /** the unrecognised options/arguments */
89     private List JavaDoc args = new LinkedList JavaDoc();
90
91     /** the processed options */
92     private Map JavaDoc options = new HashMap JavaDoc();
93
94     /** Map of unique options for ease to get complete list of options */
95     private Map JavaDoc hashcodeMap = new HashMap JavaDoc();
96
97     /** the processed options */
98     private Option[] optionsArray;
99
100     /**
101      * <p>Creates a command line.</p>
102      */

103     CommandLine() {
104     }
105     
106     /**
107      * <p>Query to see if an option has been set.</p>
108      *
109      * @param opt Short name of the option
110      * @return true if set, false if not
111      */

112     public boolean hasOption(String JavaDoc opt) {
113         return options.containsKey( opt );
114     }
115
116     /**
117      * <p>Query to see if an option has been set.</p>
118      *
119      * @param opt character name of the option
120      * @return true if set, false if not
121      */

122     public boolean hasOption( char opt ) {
123         return hasOption( String.valueOf( opt ) );
124     }
125
126     /**
127      * <p>Return the <code>Object</code> type of this <code>Option</code>.</p>
128      *
129      * @param opt the name of the option
130      * @return the type of this <code>Option</code>
131      */

132     public Object JavaDoc getOptionObject( String JavaDoc opt ) {
133         String JavaDoc res = getOptionValue( opt );
134         
135         Object JavaDoc type = ((Option)((List JavaDoc)options.get(opt)).iterator().next()).getType();
136         return res == null ? null : TypeHandler.createValue(res, type);
137     }
138
139     /**
140      * <p>Return the <code>Object</code> type of this <code>Option</code>.</p>
141      *
142      * @param opt the name of the option
143      * @return the type of opt
144      */

145     public Object JavaDoc getOptionObject( char opt ) {
146         return getOptionObject( String.valueOf( opt ) );
147     }
148
149     /**
150      * <p>Retrieve the argument, if any, of this option.</p>
151      *
152      * @param opt the name of the option
153      * @return Value of the argument if option is set, and has an argument,
154      * otherwise null.
155      */

156     public String JavaDoc getOptionValue( String JavaDoc opt ) {
157         String JavaDoc[] values = getOptionValues(opt);
158         return (values == null) ? null : values[0];
159     }
160
161     /**
162      * <p>Retrieve the argument, if any, of this option.</p>
163      *
164      * @param opt the character name of the option
165      * @return Value of the argument if option is set, and has an argument,
166      * otherwise null.
167      */

168     public String JavaDoc getOptionValue( char opt ) {
169         return getOptionValue( String.valueOf( opt ) );
170     }
171
172     /**
173      * <p>Retrieves the array of values, if any, of an option.</p>
174      *
175      * @param opt string name of the option
176      * @return Values of the argument if option is set, and has an argument,
177      * otherwise null.
178      */

179     public String JavaDoc[] getOptionValues( String JavaDoc opt ) {
180         List JavaDoc values = new java.util.ArrayList JavaDoc();
181
182         if( options.containsKey( opt ) ) {
183             List JavaDoc opts = (List JavaDoc)options.get( opt );
184             Iterator JavaDoc iter = opts.iterator();
185
186             while( iter.hasNext() ) {
187                 Option optt = (Option)iter.next();
188                 values.addAll( optt.getValuesList() );
189             }
190         }
191         return (values.size() == 0) ? null : (String JavaDoc[])values.toArray(new String JavaDoc[]{});
192     }
193
194     /**
195      * <p>Retrieves the array of values, if any, of an option.</p>
196      *
197      * @param opt character name of the option
198      * @return Values of the argument if option is set, and has an argument,
199      * otherwise null.
200      */

201     public String JavaDoc[] getOptionValues( char opt ) {
202         return getOptionValues( String.valueOf( opt ) );
203     }
204     
205     /**
206      * <p>Retrieve the argument, if any, of an option.</p>
207      *
208      * @param opt name of the option
209      * @param defaultValue is the default value to be returned if the option is not specified
210      * @return Value of the argument if option is set, and has an argument,
211      * otherwise <code>defaultValue</code>.
212      */

213     public String JavaDoc getOptionValue( String JavaDoc opt, String JavaDoc defaultValue ) {
214         String JavaDoc answer = getOptionValue( opt );
215         return ( answer != null ) ? answer : defaultValue;
216     }
217     
218     /**
219      * <p>Retrieve the argument, if any, of an option.</p>
220      *
221      * @param opt character name of the option
222      * @param defaultValue is the default value to be returned if the option is not specified
223      * @return Value of the argument if option is set, and has an argument,
224      * otherwise <code>defaultValue</code>.
225      */

226     public String JavaDoc getOptionValue( char opt, String JavaDoc defaultValue ) {
227         return getOptionValue( String.valueOf( opt ), defaultValue );
228     }
229
230     /**
231      * <p>Retrieve any left-over non-recognized options and arguments</p>
232      *
233      * @return remaining items passed in but not parsed as an array
234      */

235     public String JavaDoc[] getArgs() {
236         String JavaDoc[] answer = new String JavaDoc[ args.size() ];
237         args.toArray( answer );
238         return answer;
239     }
240     
241     /**
242      * <p>Retrieve any left-over non-recognized options and arguments</p>
243      *
244      * @return remaining items passed in but not parsed as a <code>List</code>.
245      */

246     public List JavaDoc getArgList() {
247         return args;
248     }
249     
250     /**
251      * jkeyes
252      * - commented out until it is implemented properly
253      * <p>Dump state, suitable for debugging.</p>
254      *
255      * @return Stringified form of this object
256      */

257     /*
258     public String toString() {
259         StringBuffer buf = new StringBuffer();
260         
261         buf.append( "[ CommandLine: [ options: " );
262         buf.append( options.toString() );
263         buf.append( " ] [ args: ");
264         buf.append( args.toString() );
265         buf.append( " ] ]" );
266         
267         return buf.toString();
268     }
269     */

270
271     /**
272      * <p>Add left-over unrecognized option/argument.</p>
273      *
274      * @param arg the unrecognised option/argument.
275      */

276     void addArg(String JavaDoc arg) {
277         args.add( arg );
278     }
279         
280     /**
281      * <p>Add an option to the command line. The values of
282      * the option are stored.</p>
283      *
284      * @param opt the processed option
285      */

286     void addOption( Option opt ) {
287         hashcodeMap.put( new Integer JavaDoc( opt.hashCode() ), opt );
288
289         String JavaDoc key = opt.getOpt();
290         if( " ".equals(key) ) {
291             key = opt.getLongOpt();
292         }
293
294         if( options.get( key ) != null ) {
295             ((java.util.List JavaDoc)options.get( key )).add( opt );
296         }
297         else {
298             options.put( key, new java.util.ArrayList JavaDoc() );
299             ((java.util.List JavaDoc)options.get( key ) ).add( opt );
300         }
301     }
302
303     /**
304      * <p>Returns an iterator over the Option members of CommandLine.</p>
305      *
306      * @return an <code>Iterator</code> over the processed {@link Option}
307      * members of this {@link CommandLine}
308      */

309     public Iterator JavaDoc iterator( ) {
310         return hashcodeMap.values().iterator();
311     }
312
313     /**
314      * <p>Returns an array of the processed {@link Option}s.</p>
315      *
316      * @return an array of the processed {@link Option}s.
317      */

318     public Option[] getOptions( ) {
319         Collection JavaDoc processed = hashcodeMap.values();
320
321         // reinitialise array
322
optionsArray = new Option[ processed.size() ];
323
324         // return the array
325
return (Option[]) processed.toArray( optionsArray );
326     }
327
328 }
329
Popular Tags