KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/Option.java,v 1.6 2002/06/06 22:50:14 bayard Exp $
3  * $Revision: 1.6 $
4  * $Date: 2002/06/06 22:50:14 $
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 /*
63  * Copyright (C) The Apache Software Foundation. All rights reserved.
64  *
65  * This software is published under the terms of the Apache Software License
66  * version 1.1, a copy of which has been included with this distribution in
67  * the LICENSE file.
68  *
69  * $Id: Option.java,v 1.6 2002/06/06 22:50:14 bayard Exp $
70  */

71
72 package org.apache.commons.cli;
73
74 import java.util.ArrayList JavaDoc;
75
76 /** <p>Describes a single command-line option. It maintains
77  * information regarding the short-name of the option, the long-name,
78  * if any exists, a flag indicating if an argument is required for
79  * this option, and a self-documenting description of the option.</p>
80  *
81  * <p>An Option is not created independantly, but is create through
82  * an instance of {@link Options}.<p>
83  *
84  * @see org.apache.commons.cli.Options
85  * @see org.apache.commons.cli.CommandLine
86  *
87  * @author bob mcwhirter (bob @ werken.com)
88  * @author <a HREF="mailto:jstrachan@apache.org">James Strachan</a>
89  * @version $Revision: 1.6 $
90  */

91
92 public class Option implements Cloneable JavaDoc {
93
94     /** constant that specifies the number of argument values has not been specified */
95     public final static int UNINITIALIZED = -1;
96     
97     /** constant that specifies the number of argument values is infinite */
98     public final static int UNLIMITED_VALUES = -2;
99     
100     /** opt the single character representation of the option */
101     private String JavaDoc opt;
102
103     /** longOpt is the long representation of the option */
104     private String JavaDoc longOpt;
105
106     /** hasArg specifies whether this option has an associated argument */
107     private boolean hasArg;
108
109     /** argName specifies the name of the argument for this option */
110     private String JavaDoc argName;
111
112     /** description of the option */
113     private String JavaDoc description;
114
115     /** required specifies whether this option is required to be present */
116     private boolean required;
117
118     /** specifies whether the argument value of this Option is optional */
119     private boolean optionalArg;
120
121     /**
122      * numberOfArgs specifies the number of argument values this option
123      * can have
124      */

125     private int numberOfArgs = UNINITIALIZED;
126
127     /** the type of this Option */
128     private Object JavaDoc type;
129
130     /** the list of argument values **/
131     private ArrayList JavaDoc values = new ArrayList JavaDoc();
132     
133     /** option char (only valid for single character options) */
134     private char id;
135
136     /** the character that is the value separator */
137     private char valuesep;
138
139     /**
140      * <p>Validates whether <code>opt</code> is a permissable Option
141      * shortOpt. The rules that specify if the <code>opt</code>
142      * is valid are:</p>
143      * <ul>
144      * <li><code>opt</code> is not NULL</li>
145      * <li>a single character <code>opt</code> that is either
146      * ' '(special case), '?', '@' or a letter</li>
147      * <li>a multi character <code>opt</code> that only contains
148      * letters.</li>
149      * </ul>
150      *
151      * @param opt The option string to validate
152      * @throws IllegalArgumentException if the Option is not valid.
153      */

154     private void validateOption( String JavaDoc opt )
155     throws IllegalArgumentException JavaDoc
156     {
157         // check that opt is not NULL
158
if( opt == null ) {
159             throw new IllegalArgumentException JavaDoc( "opt is null" );
160         }
161         // handle the single character opt
162
else if( opt.length() == 1 ) {
163             char ch = opt.charAt( 0 );
164             if ( !isValidOpt( ch ) ) {
165                 throw new IllegalArgumentException JavaDoc( "illegal option value '"
166                                                     + ch + "'" );
167             }
168             id = ch;
169         }
170         // handle the multi character opt
171
else {
172             char[] chars = opt.toCharArray();
173             for( int i = 0; i < chars.length; i++ ) {
174                 if( !isValidChar( chars[i] ) ) {
175                     throw new IllegalArgumentException JavaDoc( "opt contains illegal character value '" + chars[i] + "'" );
176                 }
177             }
178         }
179     }
180
181     /**
182      * <p>Returns whether the specified character is a valid Option.</p>
183      *
184      * @param c the option to validate
185      * @return true if <code>c</code> is a letter, ' ', '?' or '@', otherwise false.
186      */

187     private boolean isValidOpt( char c ) {
188         return ( isValidChar( c ) || c == ' ' || c == '?' || c == '@' );
189     }
190
191     /**
192      * <p>Returns whether the specified character is a valid character.</p>
193      *
194      * @param c the character to validate
195      * @return true if <code>c</code> is a letter.
196      */

197     private boolean isValidChar( char c ) {
198         return Character.isJavaIdentifierPart( c );
199     }
200
201     /**
202      * <p>Returns the id of this Option. This is only set when the
203      * Option shortOpt is a single character. This is used for switch
204      * statements.</p>
205      *
206      * @return the id of this Option
207      */

208     public int getId( ) {
209         return id;
210     }
211
212     /**
213      * Creates an Option using the specified parameters.
214      *
215      * @param opt short representation of the option
216      * @param hasArg specifies whether the Option takes an argument or not
217      * @param description describes the function of the option
218      */

219     public Option( String JavaDoc opt, String JavaDoc description )
220     throws IllegalArgumentException JavaDoc
221     {
222         this( opt, null, false, description );
223     }
224
225     /**
226      * Creates an Option using the specified parameters.
227      *
228      * @param opt short representation of the option
229      * @param hasArg specifies whether the Option takes an argument or not
230      * @param description describes the function of the option
231      */

232     public Option( String JavaDoc opt, boolean hasArg, String JavaDoc description )
233     throws IllegalArgumentException JavaDoc
234     {
235         this( opt, null, hasArg, description );
236     }
237     
238     /**
239      * <p>Creates an Option using the specified parameters.</p>
240      *
241      * @param opt short representation of the option
242      * @param longOpt the long representation of the option
243      * @param hasArg specifies whether the Option takes an argument or not
244      * @param description describes the function of the option
245      */

246     public Option( String JavaDoc opt, String JavaDoc longOpt, boolean hasArg, String JavaDoc description )
247     throws IllegalArgumentException JavaDoc
248     {
249         // ensure that the option is valid
250
validateOption( opt );
251
252         this.opt = opt;
253         this.longOpt = longOpt;
254
255         // if hasArg is set then the number of arguments is 1
256
if( hasArg ) {
257             this.numberOfArgs = 1;
258         }
259
260         this.hasArg = hasArg;
261         this.description = description;
262     }
263     
264     /** <p>Retrieve the name of this Option.</p>
265      *
266      * <p>It is this String which can be used with
267      * {@link CommandLine#hasOption(String opt)} and
268      * {@link CommandLine#getOptionValue(String opt)} to check
269      * for existence and argument.<p>
270      *
271      * @return The name of this option
272      */

273     public String JavaDoc getOpt() {
274         return this.opt;
275     }
276
277     /**
278      * <p>Retrieve the type of this Option.</p>
279      *
280      * @return The type of this option
281      */

282     public Object JavaDoc getType() {
283         return this.type;
284     }
285
286     /**
287      * <p>Sets the type of this Option.</p>
288      *
289      * @param type the type of this Option
290      */

291     public void setType( Object JavaDoc type ) {
292         this.type = type;
293     }
294     
295     /**
296      * <p>Retrieve the long name of this Option.</p>
297      *
298      * @return Long name of this option, or null, if there is no long name
299      */

300     public String JavaDoc getLongOpt() {
301         return this.longOpt;
302     }
303
304     /**
305      * <p>Sets the long name of this Option.</p>
306      *
307      * @param longOpt the long name of this Option
308      */

309     public void setLongOpt( String JavaDoc longOpt ) {
310         this.longOpt = longOpt;
311     }
312
313     /**
314      * <p>Sets whether this Option can have an optional argument.</p>
315      *
316      * @param optionalArg specifies whether the Option can have
317      * an optional argument.
318      */

319     public void setOptionalArg( boolean optionalArg ) {
320         this.optionalArg = optionalArg;
321     }
322
323     /**
324      * @return whether this Option can have an optional argument
325      */

326     public boolean hasOptionalArg( ) {
327         return this.optionalArg;
328     }
329     
330     /** <p>Query to see if this Option has a long name</p>
331      *
332      * @return boolean flag indicating existence of a long name
333      */

334     public boolean hasLongOpt() {
335         return ( this.longOpt != null );
336     }
337     
338     /** <p>Query to see if this Option requires an argument</p>
339      *
340      * @return boolean flag indicating if an argument is required
341      */

342     public boolean hasArg() {
343         return this.numberOfArgs > 0 || numberOfArgs == UNLIMITED_VALUES;
344     }
345     
346     /** <p>Retrieve the self-documenting description of this Option</p>
347      *
348      * @return The string description of this option
349      */

350     public String JavaDoc getDescription() {
351         return this.description;
352     }
353
354      /**
355       * <p>Query to see if this Option requires an argument</p>
356       *
357       * @return boolean flag indicating if an argument is required
358       */

359      public boolean isRequired() {
360          return this.required;
361      }
362
363      /**
364       * <p>Sets whether this Option is mandatory.</p>
365       *
366       * @param required specifies whether this Option is mandatory
367       */

368      public void setRequired( boolean required ) {
369          this.required = required;
370      }
371
372      /**
373       * <p>Sets the display name for the argument value.</p>
374       *
375       * @param argName the display name for the argument value.
376       */

377      public void setArgName( String JavaDoc argName ) {
378          this.argName = argName;
379      }
380
381      /**
382       * <p>Gets the display name for the argument value.</p>
383       *
384       * @return the display name for the argument value.
385       */

386      public String JavaDoc getArgName() {
387          return this.argName;
388      }
389
390      /**
391       * <p>Returns whether the display name for the argument value
392       * has been set.</p>
393       *
394       * @return if the display name for the argument value has been
395       * set.
396       */

397      public boolean hasArgName() {
398          return (this.argName != null && this.argName.length() > 0 );
399      }
400
401      /**
402       * <p>Query to see if this Option can take many values</p>
403       *
404       * @return boolean flag indicating if multiple values are allowed
405       */

406      public boolean hasArgs() {
407          return ( this.numberOfArgs > 1 || this.numberOfArgs == UNLIMITED_VALUES );
408      }
409
410      /**
411       * <p>Sets the number of argument values this Option can take.</p>
412       *
413       * @param num the number of argument values
414       */

415      public void setArgs( int num ) {
416          this.numberOfArgs = num;
417      }
418
419      /**
420       * <p>Sets the value separator. For example if the argument value
421       * was a Java property, the value separator would be '='.</p>
422       *
423       * @param sep The value separator.
424       */

425      public void setValueSeparator( char sep ) {
426          this.valuesep = sep;
427      }
428
429      /**
430       * <p>Returns the value separator character.</p>
431       *
432       * @return the value separator character.
433       */

434      public char getValueSeparator() {
435          return this.valuesep;
436      }
437
438      /**
439       * <p>Returns the number of argument values this Option can take.</p>
440       *
441       * @return num the number of argument values
442       */

443      public int getArgs( ) {
444          return this.numberOfArgs;
445      }
446
447     /**
448      * <p>Dump state, suitable for debugging.</p>
449      *
450      * @return Stringified form of this object
451      */

452     public String JavaDoc toString() {
453         StringBuffer JavaDoc buf = new StringBuffer JavaDoc().append("[ option: ");
454         
455         buf.append( this.opt );
456         
457         if ( this.longOpt != null ) {
458             buf.append(" ")
459             .append(this.longOpt);
460         }
461         
462         buf.append(" ");
463         
464         if ( hasArg ) {
465             buf.append( "+ARG" );
466         }
467         
468         buf.append(" :: ")
469         .append( this.description );
470         
471         if ( this.type != null ) {
472             buf.append(" :: ")
473             .append( this.type );
474         }
475
476         buf.append(" ]");
477         return buf.toString();
478     }
479
480     /**
481      * <p>Adds the specified value to this Option.</p>
482      *
483      * @param value is a/the value of this Option
484      */

485     public boolean addValue( String JavaDoc value ) {
486
487         switch( numberOfArgs ) {
488             case UNINITIALIZED:
489                 return false;
490             case UNLIMITED_VALUES:
491                 if( getValueSeparator() > 0 ) {
492                     int index = 0;
493                     while( (index = value.indexOf( getValueSeparator() ) ) != -1 ) {
494                         this.values.add( value.substring( 0, index ) );
495                         value = value.substring( index+1 );
496                     }
497                 }
498                 this.values.add( value );
499                 return true;
500             default:
501                 if( getValueSeparator() > 0 ) {
502                     int index = 0;
503                     while( (index = value.indexOf( getValueSeparator() ) ) != -1 ) {
504                         if( values.size() > numberOfArgs-1 ) {
505                             return false;
506                         }
507                         this.values.add( value.substring( 0, index ) );
508                         value = value.substring( index+1 );
509                     }
510                 }
511                 if( values.size() > numberOfArgs-1 ) {
512                     return false;
513                 }
514                 this.values.add( value );
515                 return true;
516         }
517     }
518
519     /**
520      * @return the value/first value of this Option or
521      * <code>null</code> if there are no values.
522      */

523     public String JavaDoc getValue() {
524         return this.values.size()==0 ? null : (String JavaDoc)this.values.get( 0 );
525     }
526
527     /**
528      * @return the specified value of this Option or
529      * <code>null</code> if there are no values.
530      */

531     public String JavaDoc getValue( int index )
532     throws IndexOutOfBoundsException JavaDoc
533     {
534         return ( this.values.size()==0 ) ? null : (String JavaDoc)this.values.get( index );
535     }
536
537     /**
538      * @return the value/first value of this Option or the
539      * <code>defaultValue</code> if there are no values.
540      */

541     public String JavaDoc getValue( String JavaDoc defaultValue ) {
542         String JavaDoc value = getValue( );
543         return ( value != null ) ? value : defaultValue;
544     }
545
546     /**
547      * @return the values of this Option as a String array
548      * or null if there are no values
549      */

550     public String JavaDoc[] getValues() {
551         return this.values.size()==0 ? null : (String JavaDoc[])this.values.toArray(new String JavaDoc[]{});
552     }
553
554     /**
555      * @return the values of this Option as a List
556      * or null if there are no values
557      */

558     public java.util.List JavaDoc getValuesList() {
559         return this.values;
560     }
561
562     /**
563      * @return a copy of this Option
564      */

565     public Object JavaDoc clone() {
566         Option option = new Option( getOpt(), getDescription() );
567         option.setArgs( getArgs() );
568         option.setOptionalArg( hasOptionalArg() );
569         option.setRequired( isRequired() );
570         option.setLongOpt( getLongOpt() );
571         option.setType( getType() );
572         option.setValueSeparator( getValueSeparator() );
573         return option;
574     }
575 }
576
Popular Tags