KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Header: /home/cvs/jakarta-commons/cli/src/java/org/apache/commons/cli/Parser.java,v 1.7 2002/10/24 23:17:49 jkeyes Exp $
3  * $Revision: 1.7 $
4  * $Date: 2002/10/24 23:17:49 $
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
62 package org.apache.commons.cli;
63
64 import java.util.Arrays JavaDoc;
65 import java.util.Iterator JavaDoc;
66 import java.util.List JavaDoc;
67 import java.util.ListIterator JavaDoc;
68 import java.util.Map JavaDoc;
69
70 /**
71  * <p><code>Parser</code> creates {@link CommandLine}s.</p>
72  *
73  * @author John Keyes (john at integralsource.com)
74  * @see Parser
75  * @version $Revision: 1.7 $
76  */

77 public abstract class Parser implements CommandLineParser {
78
79     /** commandline instance */
80     private CommandLine cmd;
81     /** current Options */
82     private Options options;
83     /** list of required options strings */
84     private List JavaDoc requiredOptions;
85
86     /**
87      * <p>Subclasses must implement this method to reduce
88      * the <code>arguments</code> that have been passed to the parse
89      * method.</p>
90      *
91      * @param opts The Options to parse the arguments by.
92      * @param args The arguments that have to be flattened.
93      * @param stopAtNonOption specifies whether to stop
94      * flattening when a non option has been encountered
95      * @return a String array of the flattened arguments
96      */

97     abstract protected String JavaDoc[] flatten( Options opts,
98                                          String JavaDoc[] arguments,
99                                          boolean stopAtNonOption );
100
101     /**
102      * <p>Parses the specified <code>arguments</code>
103      * based on the specifed {@link Options}.</p>
104      *
105      * @param options the <code>Options</code>
106      * @param arguments the <code>arguments</code>
107      * @return the <code>CommandLine</code>
108      * @throws ParseException if an error occurs when parsing the
109      * arguments.
110      */

111     public CommandLine parse( Options options, String JavaDoc[] arguments )
112     throws ParseException
113     {
114         return parse( options, arguments, false );
115     }
116
117     /**
118      * <p>Parses the specified <code>arguments</code>
119      * based on the specifed {@link Options}.</p>
120      *
121      * @param options the <code>Options</code>
122      * @param arguments the <code>arguments</code>
123      * @param stopAtNonOption specifies whether to stop
124      * interpreting the arguments when a non option has
125      * been encountered and to add them to the CommandLines
126      * args list.
127      * @return the <code>CommandLine</code>
128      * @throws ParseException if an error occurs when parsing the
129      * arguments.
130      */

131     public CommandLine parse( Options opts,
132                               String JavaDoc[] arguments,
133                               boolean stopAtNonOption )
134     throws ParseException
135     {
136         // initialise members
137
options = opts;
138         requiredOptions = options.getRequiredOptions();
139         cmd = new CommandLine();
140
141         boolean eatTheRest = false;
142
143         List JavaDoc tokenList = Arrays.asList( flatten( opts, arguments, stopAtNonOption ) );
144         ListIterator JavaDoc iterator = tokenList.listIterator();
145
146         // process each flattened token
147
while( iterator.hasNext() ) {
148             String JavaDoc t = (String JavaDoc)iterator.next();
149
150             // the value is the double-dash
151
if( "--".equals( t ) ) {
152                 eatTheRest = true;
153             }
154             // the value is a single dash
155
else if( "-".equals( t ) ) {
156                 if( stopAtNonOption ) {
157                     eatTheRest = true;
158                 }
159                 else {
160                     cmd.addArg(t );
161                 }
162             }
163             // the value is an option
164
else if( t.startsWith( "-" ) ) {
165                 if ( stopAtNonOption && !options.hasOption( t ) ) {
166                     eatTheRest = true;
167                     cmd.addArg( t );
168                 }
169                 else {
170                     processOption( t, iterator );
171                 }
172             }
173             // the value is an argument
174
else {
175                 cmd.addArg( t );
176                 if( stopAtNonOption ) {
177                     eatTheRest = true;
178                 }
179             }
180
181             // eat the remaining tokens
182
if( eatTheRest ) {
183                 while( iterator.hasNext() ) {
184                     String JavaDoc str = (String JavaDoc)iterator.next();
185                     // ensure only one double-dash is added
186
if( !"--".equals( str ) ) {
187                         cmd.addArg( str );
188                     }
189                 }
190             }
191         }
192         checkRequiredOptions();
193         return cmd;
194     }
195
196     /**
197      * <p>Throws a {@link MissingOptionException} if all of the
198      * required options are no present.</p>
199      */

200     private void checkRequiredOptions()
201     throws MissingOptionException
202     {
203
204         // if there are required options that have not been
205
// processsed
206
if( requiredOptions.size() > 0 ) {
207             Iterator JavaDoc iter = requiredOptions.iterator();
208             StringBuffer JavaDoc buff = new StringBuffer JavaDoc();
209
210             // loop through the required options
211
while( iter.hasNext() ) {
212                 buff.append( iter.next() );
213             }
214
215             throw new MissingOptionException( buff.toString() );
216         }
217     }
218
219     public void processArgs( Option opt, ListIterator JavaDoc iter )
220     throws ParseException
221     {
222         // loop until an option is found
223
while( iter.hasNext() ) {
224             String JavaDoc var = (String JavaDoc)iter.next();
225
226             // found an Option
227
if( options.hasOption( var ) ) {
228                 iter.previous();
229                 break;
230             }
231             // found a value
232
else if( !opt.addValue( var ) ) {
233                 iter.previous();
234                 break;
235             }
236         }
237
238         if( opt.getValues() == null && !opt.hasOptionalArg() ) {
239             throw new MissingArgumentException( "no argument for:" + opt.getOpt() );
240         }
241     }
242
243     private void processOption( String JavaDoc arg, ListIterator JavaDoc iter )
244     throws ParseException
245     {
246         // get the option represented by arg
247
Option opt = null;
248
249         boolean hasOption = options.hasOption( arg );
250
251         // if there is no option throw an UnrecognisedOptionException
252
if( !hasOption ) {
253             throw new UnrecognizedOptionException("Unrecognized option: " + arg);
254         }
255         else {
256             opt = (Option) options.getOption( arg );
257         }
258
259         // if the option is a required option remove the option from
260
// the requiredOptions list
261
if ( opt.isRequired() ) {
262             requiredOptions.remove( "-" + opt.getOpt() );
263         }
264
265         // if the option is in an OptionGroup make that option the selected
266
// option of the group
267
if ( options.getOptionGroup( opt ) != null ) {
268             OptionGroup group = ( OptionGroup ) options.getOptionGroup( opt );
269             if( group.isRequired() ) {
270                 requiredOptions.remove( group );
271             }
272             group.setSelected( opt );
273         }
274
275         // if the option takes an argument value
276
if ( opt.hasArg() ) {
277             processArgs( opt, iter );
278         }
279
280         // set the option on the command line
281
cmd.addOption( opt );
282     }
283 }
Popular Tags