KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > lib > cvsclient > commandLine > GetOpt


1 /*****************************************************************************
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14
15  * The Original Software is the CVS Client Library.
16  * The Initial Developer of the Original Software is Robert Greig.
17  * Portions created by Robert Greig are Copyright (C) 2000.
18  * All Rights Reserved.
19
20  * Contributor(s): Robert Greig.
21  *****************************************************************************/

22 package org.netbeans.lib.cvsclient.commandLine;
23
24 /**
25  * <h1>Overview</h1>
26  *
27  * GetOpt provides a general means for a Java program to parse command
28  * line arguments in accordance with the standard Unix conventions;
29  * it is analogous to, and based on, getopt(3) for C programs.
30  * (The following documentation is based on the man page for getopt(3).)
31
32  * <h1>Description</h1>
33  *
34  * GetOpt is a Java class that provides one method, getopt,
35  * and some variables that control behavior of or return additional
36  * information from getopt.
37  * <p>
38  * GetOpt interprets command arguments in accordance with the standard
39  * Unix conventions: option arguments of a command are introduced by "-"
40  * followed by a key character, and a non-option argument terminates
41  * the processing of options. GetOpt's option interpretation is controlled
42  * by its parameter optString, which specifies what characters designate
43  * legal options and which of them require associated values.
44  * <p>
45  * The getopt method returns the next, moving left to right, option letter
46  * in the command line arguments that matches a letter in optString.
47  * optString must contain the option letters the command using getopt
48  * will recognize. For example, getopt("ab") specifies that the command
49  * line should contain no options, only "-a", only "-b", or both "-a" and
50  * "-b" in either order. (The command line can also contain non-option
51  * arguments after any option arguments.) Multiple options per argument
52  * are allowed, e.g., "-ab" for the last case above.
53  * <p>
54  * If a letter in optString is followed by a colon, the option is expected
55  * to have an argument. The argument may or may not be separated by
56  * whitespace from the option letter. For example, getopt("w:") allows
57  * either "-w 80" or "-w80". The variable optArg is set to the option
58  * argument, e.g., "80" in either of the previous examples. Conversion
59  * functions such as Integer.parseInt(), etc., can then be applied to
60  * optArg.
61  * <p>
62  * getopt places in the variable optIndex the index of the next command
63  * line argument to be processed; optIndex is automatically initialized
64  * to 1 before the first call to getopt.
65  * <p>
66  * When all options have been processed (that is, up to the first
67  * non-option argument), getopt returns optEOF (-1). getopt recognizes the
68  * command line argument "--" (i.e., two dashes) to delimit the end of
69  * the options; getopt returns optEOF and skips "--". Subsequent,
70  * non-option arguments can be retrieved using the String array passed to
71  * main(), beginning with argument number optIndex.
72  *
73  * <h1>Diagnostics</h1>
74  *
75  * getopt prints an error message on System.stderr and returns a question
76  * mark ('?') when it encounters an option letter in a command line argument
77  * that is not included in optString. Setting the variable optErr to
78  * false disables this error message.
79
80  * <h1>Notes</h1>
81  *
82  * The following notes describe GetOpt's behavior in a few interesting
83  * or special cases; these behaviors are consistent with getopt(3)'s
84  * behaviors.
85  * -- A '-' by itself is treated as a non-option argument.
86  * -- If optString is "a:" and the command line arguments are "-a -x",
87  * then "-x" is treated as the argument associated with the "-a".
88  * -- Duplicate command line options are allowed; it is up to user to
89  * deal with them as appropriate.
90  * -- A command line option like "-b-" is considered as the two options
91  * "b" and "-" (so "-" should appear in option string); this differs
92  * from "-b --".
93  * -- Sun and DEC getopt(3)'s differ w.r.t. how "---" is handled.
94  * Sun treats "---" (or anything starting with "--") the same as "--"
95  * DEC treats "---" as two separate "-" options
96  * (so "-" should appear in option string).
97  * Java GetOpt follows the DEC convention.
98  * -- An option `letter' can be a letter, number, or most special character.
99  * Like getopt(3), GetOpt disallows a colon as an option letter.
100  *
101  * @author Anonymous
102  *****************************************************************************/

103 public class GetOpt {
104
105     private String JavaDoc[] theArgs = null;
106     private int argCount = 0;
107     private String JavaDoc optString = null;
108
109     public GetOpt(String JavaDoc[] args, String JavaDoc opts) {
110         theArgs = args;
111         argCount = theArgs.length;
112         optString = opts;
113     }
114
115     // user can toggle this to control printing of error messages
116
public boolean optErr = false;
117
118     public int processArg(String JavaDoc arg, int n) {
119         int value;
120         try {
121             value = Integer.parseInt(arg);
122         }
123         catch (NumberFormatException JavaDoc e) {
124             if (optErr)
125                 System.err.println("processArg cannot process " + arg //NOI18N
126
+ " as an integer"); //NOI18N
127
return n;
128         }
129         return value;
130     }
131
132     public int tryArg(int k, int n) {
133         int value;
134         try {
135             value = processArg(theArgs[k], n);
136         }
137         catch (ArrayIndexOutOfBoundsException JavaDoc e) {
138             if (optErr)
139                 System.err.println("tryArg: no theArgs[" + k + "]"); //NOI18N
140
return n;
141         }
142         return value;
143     }
144
145     public long processArg(String JavaDoc arg, long n) {
146         long value;
147         try {
148             value = Long.parseLong(arg);
149         }
150         catch (NumberFormatException JavaDoc e) {
151             if (optErr)
152                 System.err.println("processArg cannot process " + arg //NOI18N
153
+ " as a long"); //NOI18N
154
return n;
155         }
156         return value;
157     }
158
159     public long tryArg(int k, long n) {
160         long value;
161         try {
162             value = processArg(theArgs[k], n);
163         }
164         catch (ArrayIndexOutOfBoundsException JavaDoc e) {
165             if (optErr)
166                 System.err.println("tryArg: no theArgs[" + k + "]"); //NOI18N
167
return n;
168         }
169         return value;
170     }
171
172     public double processArg(String JavaDoc arg, double d) {
173         double value;
174         try {
175             value = Double.valueOf(arg).doubleValue();
176         }
177         catch (NumberFormatException JavaDoc e) {
178             if (optErr)
179                 System.err.println("processArg cannot process " + arg //NOI18N
180
+ " as a double"); //NOI18N
181
return d;
182         }
183         return value;
184     }
185
186     public double tryArg(int k, double d) {
187         double value;
188         try {
189             value = processArg(theArgs[k], d);
190         }
191         catch (ArrayIndexOutOfBoundsException JavaDoc e) {
192             if (optErr)
193                 System.err.println("tryArg: no theArgs[" + k + "]"); //NOI18N
194
return d;
195         }
196         return value;
197     }
198
199     public float processArg(String JavaDoc arg, float f) {
200         float value;
201         try {
202             value = Float.valueOf(arg).floatValue();
203         }
204         catch (NumberFormatException JavaDoc e) {
205             if (optErr)
206                 System.err.println("processArg cannot process " + arg //NOI18N
207
+ " as a float"); //NOI18N
208
return f;
209         }
210         return value;
211     }
212
213     public float tryArg(int k, float f) {
214         float value;
215         try {
216             value = processArg(theArgs[k], f);
217         }
218         catch (ArrayIndexOutOfBoundsException JavaDoc e) {
219             if (optErr)
220                 System.err.println("tryArg: no theArgs[" + k + "]"); //NOI18N
221
return f;
222         }
223         return value;
224     }
225
226     public boolean processArg(String JavaDoc arg, boolean b) {
227         // `true' in any case mixture is true; anything else is false
228
return Boolean.valueOf(arg).booleanValue();
229     }
230
231     public boolean tryArg(int k, boolean b) {
232         boolean value;
233         try {
234             value = processArg(theArgs[k], b);
235         }
236         catch (ArrayIndexOutOfBoundsException JavaDoc e) {
237             if (optErr)
238                 System.err.println("tryArg: no theArgs[" + k + "]"); //NOI18N
239
return b;
240         }
241         return value;
242     }
243
244     public String JavaDoc tryArg(int k, String JavaDoc s) {
245         String JavaDoc value;
246         try {
247             value = theArgs[k];
248         }
249         catch (ArrayIndexOutOfBoundsException JavaDoc e) {
250             if (optErr)
251                 System.err.println("tryArg: no theArgs[" + k + "]"); //NOI18N
252
return s;
253         }
254         return value;
255     }
256
257     private static void writeError(String JavaDoc msg, char ch) {
258         System.err.println("GetOpt: " + msg + " -- " + ch); //NOI18N
259
}
260
261     public static final int optEOF = -1;
262
263     private int optIndex = 0;
264
265     public int optIndexGet() {
266         return optIndex;
267     }
268
269     public void optIndexSet(int i) {
270         optIndex = i;
271     }
272
273     private String JavaDoc optArg = null;
274
275     public String JavaDoc optArgGet() {
276         return optArg;
277     }
278
279     private int optPosition = 1;
280
281     public int getopt() {
282         optArg = null;
283         if (theArgs == null || optString == null)
284             return optEOF;
285         if (optIndex < 0 || optIndex >= argCount)
286             return optEOF;
287         String JavaDoc thisArg = theArgs[optIndex];
288         int argLength = thisArg.length();
289         // handle special cases
290
if (argLength <= 1 || thisArg.charAt(0) != '-') {
291             // e.g., "", "a", "abc", or just "-"
292
return optEOF;
293         }
294         else if (thisArg.equals("--")) {//NOI18N
295
// end of non-option args
296
optIndex++;
297             return optEOF;
298         }
299         // get next "letter" from option argument
300
char ch = thisArg.charAt(optPosition);
301         // find this option in optString
302
int pos = optString.indexOf(ch);
303         if (pos == -1 || ch == ':') {
304             if (optErr) {
305                 writeError("illegal option", ch); //NOI18N
306
}
307             ch = '?';
308         }
309         else { // handle colon, if present
310
if (pos < optString.length() - 1 && optString.charAt(pos + 1) == ':') {
311                 if (optPosition != argLength - 1) {
312                     // take rest of current arg as optArg
313
optArg = thisArg.substring(optPosition + 1);
314                     optPosition = argLength - 1; // force advance to next arg below
315
}
316                 else { // take next arg as optArg
317
optIndex++;
318                     if (optIndex < argCount
319                             && (theArgs[optIndex].charAt(0) != '-' ||
320                             theArgs[optIndex].length() >= 2 &&
321                             (optString.indexOf(theArgs[optIndex].charAt(1)) == -1
322                             || theArgs[optIndex].charAt(1) == ':'))) {
323                         optArg = theArgs[optIndex];
324                     }
325                     else {
326                         if (optErr) {
327                             writeError("option requires an argument", ch); //NOI18N
328
}
329                         optArg = null;
330                         ch = ':'; // Linux man page for getopt(3) says : not ?
331
}
332                 }
333             }
334         }
335         // advance to next option argument,
336
// which might be in thisArg or next arg
337
optPosition++;
338         if (optPosition >= argLength) {
339             optIndex++;
340             optPosition = 1;
341         }
342         return ch;
343     }
344
345     public static void main(String JavaDoc[] args) { // test the class
346
GetOpt go = new GetOpt(args, "Uab:f:h:w:");
347         go.optErr = true;
348         int ch = -1;
349         // process options in command line arguments
350
boolean usagePrint = false; // set
351
int aflg = 0; // default
352
boolean bflg = false; // values
353
String JavaDoc filename = "out"; // of
354
int width = 80; // options
355
double height = 1; // here
356
while ((ch = go.getopt()) != go.optEOF) {
357             if ((char)ch == 'U')
358                 usagePrint = true;
359             else if ((char)ch == 'a')
360                 aflg++;
361             else if ((char)ch == 'b')
362                 bflg = go.processArg(go.optArgGet(), bflg);
363             else if ((char)ch == 'f')
364                 filename = go.optArgGet();
365             else if ((char)ch == 'h')
366                 height = go.processArg(go.optArgGet(), height);
367             else if ((char)ch == 'w')
368                 width = go.processArg(go.optArgGet(), width);
369             else
370                 System.exit(1); // undefined option
371
} // getopt() returns '?'
372
if (usagePrint) {
373             System.out.println("Usage: -a -b bool -f file -h height -w width"); //NOI18N
374
System.exit(0);
375         }
376         System.out.println("These are all the command line arguments " + //NOI18N
377
"before processing with GetOpt:"); //NOI18N
378
for (int i = 0; i < args.length; i++) {
379             System.out.print(" " + args[i]); //NOI18N
380
}
381         System.out.println();
382         System.out.println("-U " + usagePrint); //NOI18N
383
System.out.println("-a " + aflg); //NOI18N
384
System.out.println("-b " + bflg); //NOI18N
385
System.out.println("-f " + filename); //NOI18N
386
System.out.println("-h " + height); //NOI18N
387
System.out.println("-w " + width); //NOI18N
388
// process non-option command line arguments
389
for (int k = go.optIndexGet(); k < args.length; k++) {
390             System.out.println("normal argument " + k + " is " + args[k]); //NOI18N
391
}
392     }
393 }
394
395 /* ............... Example compile and run(s)
396
397 D:\>javac GetOpt.java
398
399 D:\>java GetOpt -aaa -b true -f theFile -w -80 -h3.33 arg1 arg2
400
401 These are all the command line arguments before processing with GetOpt:
402  -aaa -b true -f theFile -w -80 -h3.33 arg1 arg2
403  -U false
404  -a 3
405  -b true
406  -f theFile
407  -h 3.33
408  -w -80
409  normal argument 8 is arg1
410  normal argument 9 is arg2
411
412 D:\>java GetOpt -aaa -x -w90
413
414 GetOpt: illegal option -- x
415
416 D:\>java GetOpt -af theFile -w -b true
417
418 GetOpt: option requires an argument -- w
419                                             ... end of example run(s) */

420
421
Popular Tags