KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > xalan > internal > xsltc > cmdline > getopt > GetOpt


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 /*
17  * $Id: GetOpt.java,v 1.5 2004/02/16 21:21:06 minchau Exp $
18  */

19
20 package com.sun.org.apache.xalan.internal.xsltc.cmdline.getopt;
21
22 import java.util.ArrayList JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.ListIterator JavaDoc;
25
26 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
27
28
29 /**
30 * GetOpt is a Java equivalent to the C getopt() library function
31 * discussed in man page getopt(3C). It provides command line
32 * parsing for Java applications. It supports the most rules of the
33 * command line standard (see man page intro(1)) including stacked
34 * options such as '-sxm' (which is equivalent to -s -x -m); it
35 * handles special '--' option that signifies the end of options.
36 * Additionally this implementation of getopt will check for
37 * mandatory arguments to options such as in the case of
38 * '-d <file>' it will throw a MissingOptArgException if the
39 * option argument '<file>' is not included on the commandline.
40 * getopt(3C) does not check for this.
41  * @author G Todd Miller
42 */

43 public class GetOpt{
44     public GetOpt(String JavaDoc[] args, String JavaDoc optString){
45     theOptions = new ArrayList JavaDoc();
46     int currOptIndex = 0;
47     theCmdArgs = new ArrayList JavaDoc();
48     theOptionMatcher = new OptionMatcher(optString);
49     // fill in the options list
50
for(int i=0; i<args.length; i++){
51         String JavaDoc token = args[i];
52         int tokenLength = token.length();
53         if(token.equals("--")){ // end of opts
54
currOptIndex = i+1; // set index of first operand
55
break; // end of options
56
}
57         else if(token.startsWith("-") && tokenLength == 2){
58         // simple option token such as '-s' found
59
theOptions.add(new Option(token.charAt(1)));
60         }
61         else if(token.startsWith("-") && tokenLength > 2){
62         // stacked options found, such as '-shm'
63
// iterate thru the tokens after the dash and
64
// add them to theOptions list
65
for(int j=1; j<tokenLength; j++){
66             theOptions.add(new Option(token.charAt(j)));
67         }
68         }
69         else if(!token.startsWith("-")){
70         // case 1- there are not options stored yet therefore
71
// this must be an command argument, not an option argument
72
if(theOptions.size() == 0){
73             currOptIndex = i;
74             break; // stop processing options
75
}
76         else {
77             // case 2-
78
// there are options stored, check to see if
79
// this arg belong to the last arg stored
80
int indexoflast=0;
81             indexoflast = theOptions.size()-1;
82             Option op = (Option)theOptions.get(indexoflast);
83             char opLetter = op.getArgLetter();
84             if(!op.hasArg() && theOptionMatcher.hasArg(opLetter)){
85                 op.setArg(token);
86             }
87             else{
88                 // case 3 -
89
// the last option stored does not take
90
// an argument, so again, this argument
91
// must be a command argument, not
92
// an option argument
93
currOptIndex = i;
94                 break; // end of options
95
}
96         }
97         }// end option does not start with "-"
98
} // end for args loop
99

100         // attach an iterator to list of options
101
theOptionsIterator = theOptions.listIterator();
102
103     // options are done, now fill out cmd arg list with remaining args
104
for(int i=currOptIndex; i<args.length; i++){
105         String JavaDoc token = args[i];
106         theCmdArgs.add(token);
107     }
108     }
109
110
111     /**
112     * debugging routine to print out all options collected
113     */

114     public void printOptions(){
115     for(ListIterator JavaDoc it=theOptions.listIterator(); it.hasNext();){
116         Option opt = (Option)it.next();
117         System.out.print("OPT =" + opt.getArgLetter());
118         String JavaDoc arg = opt.getArgument();
119         if(arg != null){
120            System.out.print(" " + arg);
121         }
122         System.out.println();
123     }
124     }
125
126     /**
127     * gets the next option found in the commandline. Distinguishes
128     * between two bad cases, one case is when an illegal option
129     * is found, and then other case is when an option takes an
130     * argument but no argument was found for that option.
131     * If the option found was not declared in the optString, then
132     * an IllegalArgumentException will be thrown (case 1).
133     * If the next option found has been declared to take an argument,
134     * and no such argument exists, then a MissingOptArgException
135     * is thrown (case 2).
136     * @param none
137     * @return int - the next option found.
138     * @throws IllegalArgumentException, MissingOptArgException.
139     */

140     public int getNextOption() throws IllegalArgumentException JavaDoc,
141     MissingOptArgException
142     {
143     int retval = -1;
144     if(theOptionsIterator.hasNext()){
145         theCurrentOption = (Option)theOptionsIterator.next();
146         char c = theCurrentOption.getArgLetter();
147         boolean shouldHaveArg = theOptionMatcher.hasArg(c);
148         String JavaDoc arg = theCurrentOption.getArgument();
149         if(!theOptionMatcher.match(c)) {
150                 ErrorMsg msg = new ErrorMsg(ErrorMsg.ILLEGAL_CMDLINE_OPTION_ERR,
151                                             new Character JavaDoc(c));
152         throw (new IllegalArgumentException JavaDoc(msg.toString()));
153         }
154         else if(shouldHaveArg && (arg == null)) {
155                 ErrorMsg msg = new ErrorMsg(ErrorMsg.CMDLINE_OPT_MISSING_ARG_ERR,
156                                             new Character JavaDoc(c));
157         throw (new MissingOptArgException(msg.toString()));
158         }
159         retval = c;
160     }
161     return retval;
162     }
163
164     /**
165     * gets the argument for the current parsed option. For example,
166     * in case of '-d <file>', if current option parsed is 'd' then
167     * getOptionArg() would return '<file>'.
168     * @param none
169     * @return String - argument for current parsed option.
170     */

171     public String JavaDoc getOptionArg(){
172     String JavaDoc retval = null;
173     String JavaDoc tmp = theCurrentOption.getArgument();
174     char c = theCurrentOption.getArgLetter();
175     if(theOptionMatcher.hasArg(c)){
176         retval = tmp;
177     }
178     return retval;
179     }
180
181     /**
182     * gets list of the commandline arguments. For example, in command
183     * such as 'cmd -s -d file file2 file3 file4' with the usage
184     * 'cmd [-s] [-d <file>] <file>...', getCmdArgs() would return
185     * the list {file2, file3, file4}.
186     * @params none
187     * @return String[] - list of command arguments that may appear
188     * after options and option arguments.
189     */

190     public String JavaDoc[] getCmdArgs(){
191     String JavaDoc[] retval = new String JavaDoc[theCmdArgs.size()];
192     int i=0;
193         for(ListIterator JavaDoc it=theCmdArgs.listIterator(); it.hasNext();){
194             retval[i++] = (String JavaDoc)it.next();
195         }
196     return retval;
197     }
198
199
200     private Option theCurrentOption = null;
201     private ListIterator JavaDoc theOptionsIterator;
202     private List JavaDoc theOptions = null;
203     private List JavaDoc theCmdArgs = null;
204     private OptionMatcher theOptionMatcher = null;
205
206     ///////////////////////////////////////////////////////////
207
//
208
// Inner Classes
209
//
210
///////////////////////////////////////////////////////////
211

212     // inner class to model an option
213
class Option{
214         private char theArgLetter;
215         private String JavaDoc theArgument = null;
216         public Option(char argLetter) { theArgLetter = argLetter; }
217         public void setArg(String JavaDoc arg) {
218         theArgument = arg;
219         }
220         public boolean hasArg() { return (theArgument != null); }
221         public char getArgLetter() { return theArgLetter; }
222         public String JavaDoc getArgument() { return theArgument; }
223     } // end class Option
224

225
226     // inner class to query optString for a possible option match,
227
// and whether or not a given legal option takes an argument.
228
//
229
class OptionMatcher{
230         public OptionMatcher(String JavaDoc optString){
231         theOptString = optString;
232         }
233         public boolean match(char c){
234         boolean retval = false;
235         if(theOptString.indexOf(c) != -1){
236             retval = true;
237         }
238         return retval;
239         }
240         public boolean hasArg(char c){
241         boolean retval = false;
242         int index = theOptString.indexOf(c)+1;
243         if (index == theOptString.length()){
244             // reached end of theOptString
245
retval = false;
246         }
247             else if(theOptString.charAt(index) == ':'){
248                 retval = true;
249             }
250             return retval;
251         }
252         private String JavaDoc theOptString = null;
253     } // end class OptionMatcher
254
}// end class GetOpt
255

256
Popular Tags