KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > util > cmdline > lib > DefaultCommandLine


1 /*====================================================================
2
3 ObjectWeb Util CommandLine Package.
4 Copyright (C) 2004 INRIA & USTL - LIFL - GOAL
5 Contact: architecture@objectweb.org
6
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or any later version.
11
12 This library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public
18 License along with this library; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20 USA
21
22 Initial developer(s): Philippe Merle.
23 Contributor(s): ______________________________________.
24
25 ====================================================================*/

26
27 package org.objectweb.util.cmdline.lib;
28
29 import java.util.Iterator JavaDoc;
30
31 import org.objectweb.util.cmdline.api.Option;
32 import org.objectweb.util.cmdline.api.Console;
33 import org.objectweb.util.cmdline.api.CommandLine;
34
35 /**
36  * This provides a default implementation of the interface
37  * org.objectweb.util.CommandLine.
38  *
39  * @author <a HREF="mailto:Philippe.Merle@lifl.fr">Philippe Merle</a>
40  *
41  * @version 0.2
42  */

43
44 public class DefaultCommandLine
45      extends DefaultUsage
46   implements CommandLine
47 {
48     // ==================================================================
49
//
50
// Internal state.
51
//
52
// ==================================================================
53

54     /** The associated console. */
55     private Console console_;
56
57     /** To store command line options. */
58     private java.util.Vector JavaDoc options_;
59
60     /** To store the maximun option length. */
61     private int maxOptionLength_;
62
63     /** To check arguments. */
64     private boolean checkingArguments_;
65     
66     // ==================================================================
67
//
68
// Constructors.
69
//
70
// ==================================================================
71

72     /**
73      * The default constructor.
74      *
75      * It inits the Labels, Arguments, and Description usage properties
76      * with an empty string.
77      */

78     public
79     DefaultCommandLine()
80     {
81         this("", "", (String JavaDoc[])null, false);
82     }
83
84     /**
85      * The constructor with or without help.
86      *
87      * It inits the Labels, Arguments, and Description usage properties
88      * with an empty string.
89      *
90      * @param with_help true if default help option is required.
91      */

92     public
93     DefaultCommandLine(boolean with_help)
94     {
95         this("", "", (String JavaDoc[])null, with_help);
96     }
97
98     /**
99      * The constructor with the initial values for the Labels,
100      * Arguments, and Description usage properties.
101      *
102      * @param label The usage label.
103      * @param arguments The usage arguments.
104      * @param description The usage description.
105      * @param with_help true if default help option is required.
106      */

107     public
108     DefaultCommandLine(String JavaDoc label,
109                        String JavaDoc arguments,
110                        String JavaDoc description,
111                        boolean with_help)
112     {
113         this(label, arguments, new String JavaDoc[] { description }, with_help);
114     }
115
116     /**
117      * The constructor with the initial values for the Labels,
118      * Arguments, and Description usage properties.
119      *
120      * @param labels The usage labels.
121      * @param arguments The usage arguments.
122      * @param description The usage description.
123      * @param with_help true if default help option is required.
124      */

125     public
126     DefaultCommandLine(String JavaDoc[] labels,
127                        String JavaDoc arguments,
128                        String JavaDoc description,
129                        boolean with_help)
130     {
131         this(labels, arguments, new String JavaDoc[] { description }, with_help);
132     }
133
134     /**
135      * The constructor with the initial values for the Labels,
136      * Arguments, and Description usage properties.
137      *
138      * @param label The usage label.
139      * @param arguments The usage arguments.
140      * @param description The usage description.
141      * @param with_help true if default help option is required.
142      */

143     public
144     DefaultCommandLine(String JavaDoc label,
145                        String JavaDoc arguments,
146                        String JavaDoc[] description,
147                        boolean with_help)
148     {
149         this(new String JavaDoc[] { label }, arguments, description, with_help);
150     }
151
152     /**
153      * The constructor with the initial values for the Labels,
154      * Arguments, and Description usage properties.
155      *
156      * @param labels The usage labels.
157      * @param arguments The usage arguments.
158      * @param description The usage description.
159      * @param with_help true if default help option is required.
160      */

161     public
162     DefaultCommandLine(String JavaDoc[] labels,
163                        String JavaDoc arguments,
164                        String JavaDoc[] description,
165                        boolean with_help)
166     {
167         this(labels, new String JavaDoc[] { arguments }, description, with_help);
168     }
169
170     /**
171      * The constructor with the initial values for the Labels,
172      * Arguments, and Description usage properties.
173      *
174      * @param labels The usage labels.
175      * @param arguments The usage arguments.
176      * @param description The usage description.
177      * @param with_help true if default help option is required.
178      */

179     public
180     DefaultCommandLine(String JavaDoc[] labels,
181                        String JavaDoc[] arguments,
182                        String JavaDoc[] description,
183                        boolean with_help)
184     {
185         this(labels,arguments,false,description,with_help);
186     }
187
188     /**
189      * The constructor with the initial values for the Labels,
190      * Arguments, and Description usage properties.
191      *
192      * @param labels The usage labels.
193      * @param arguments The usage arguments.
194      * @param additional Additional arguments.
195      * @param description The usage description.
196      * @param with_help true if default help option is required.
197      */

198     public DefaultCommandLine(String JavaDoc[] labels,
199                               String JavaDoc[] arguments,
200                               boolean additional,
201                               String JavaDoc[] description,
202                               boolean with_help)
203     {
204         super(labels, arguments, additional, description);
205             
206         options_ = new java.util.Vector JavaDoc();
207         maxOptionLength_ = 0;
208
209         if(with_help) {
210             addOption(new DefaultOptionHelp());
211         }
212         console_ = null;
213         
214         // By default, arguments are checked.
215
checkingArguments_ = true;
216     }
217     
218     
219     // ==================================================================
220
//
221
// Internal methods.
222
//
223
// ==================================================================
224
/**
225      * Exists when error.
226      *
227      * @param message The error message.
228      */

229     protected void
230     exit(String JavaDoc message) {
231         console_.getErrorStream().println(getLabels()[0] + ": " + message + '!');
232         print(console_.getErrorStream());
233         System.exit(-1);
234     }
235
236     /**
237      * Sums the length of a set of strings.
238      *
239      * @param strings The string array.
240      *
241      * @return The sum of the length of a set of strings.
242      */

243     static protected int
244     sumStringLength(String JavaDoc[] strings) {
245         int result = 0;
246         for(int i=0; i<strings.length; i++)
247             result += strings[i].length();
248         return result;
249     }
250
251     /**
252      * Prints a set of strings.
253      *
254      * @param stream The output stream.
255      * @param strings The string array.
256      * @param sep_first The separator.
257      * @param sep_next The separator.
258      */

259     static protected void
260     print(java.io.PrintStream JavaDoc stream,
261           String JavaDoc[] strings,
262           String JavaDoc sep_first,
263           String JavaDoc sep_next)
264     {
265         if(strings.length > 0)
266         {
267             stream.print(sep_first);
268             stream.print(strings[0]);
269             for(int i=1; i<strings.length; i++)
270             {
271                 stream.print(sep_next);
272                 stream.print(strings[i]);
273             }
274         }
275     }
276
277     // ==================================================================
278
//
279
// Public methods for interface org.objectweb.util.api.Printable
280
//
281
// ==================================================================
282

283     /**
284      * Prints the target object to a java.io.PrintStream output stream.
285      *
286      * @param stream The java.io.PrintStream output stream.
287      */

288     public void
289     print(java.io.PrintStream JavaDoc stream) {
290         //
291
// Prints the Usage part.
292
//
293
stream.print("Usage: ");
294         stream.print(getLabels()[0]);
295
296         // Iterate over all the command line options.
297
for(Iterator JavaDoc iterator=options_.iterator();iterator.hasNext();)
298         {
299             stream.print(' ');
300
301             Option option = (Option)iterator.next();
302
303             if(!option.isMandatory())
304                 stream.print('[');
305
306             print(stream, option.getLabels(), "", "|");
307
308             print(stream, option.getArguments(), " ", " ");
309
310             if(!option.isMandatory())
311                 stream.print(']');
312         }
313
314         if (getAdditionalArguments())
315             print(stream, new String JavaDoc[]{"[Additional]"}, " ", " ");
316
317         print(stream, getArguments(), " ", " ");
318
319         //
320
// Prints the Options part.
321
//
322
stream.println("\n\nOptions:");
323
324         // Iterate over all the command line options.
325
for(Iterator JavaDoc iterator=options_.iterator();iterator.hasNext();)
326         {
327             int nb_characters = 0;
328
329             Option option = (Option)iterator.next();
330
331             String JavaDoc[] labels = option.getLabels();
332             print(stream, labels, " ", ", ");
333             nb_characters = nb_characters +
334                 sumStringLength(labels) +
335                 labels.length * 2;
336
337             String JavaDoc[] arguments = option.getArguments();
338             print(stream, arguments, " ", " ");
339             nb_characters = nb_characters +
340                 sumStringLength(arguments) +
341                 arguments.length;
342             
343             String JavaDoc[] description = option.getDescription();
344             for(int i=0; i<description.length; i++)
345             {
346                 for(int j = nb_characters;
347                     j <= maxOptionLength_; j++)
348                 {
349                     stream.print(' ');
350                 }
351                 stream.println(description[i]);
352                 nb_characters = 0;
353             }
354         }
355         stream.println("");
356
357         //
358
// Prints the Description part.
359
//
360
stream.println("Description: ");
361         print(stream, getDescription(), " ", "\n ");
362
363         stream.println("\n");
364     }
365
366     // ==================================================================
367
//
368
// Public methods for interface org.objectweb.util.cmdline.api.CommandLine
369
//
370
// ==================================================================
371

372     /**
373      * Obtains the CheckingArguments flag.
374      *
375      * @return The CheckingArguments flag.
376      */

377     public boolean
378     isCheckingArguments() {
379         return checkingArguments_;
380     }
381     
382     /**
383      * Sets the CheckingArguments flag.
384      *
385      * @param checkingArguments The CheckingArguments flag.
386      */

387     public void
388     setCheckingArguments(boolean checkingArguments){
389         checkingArguments_ = checkingArguments;
390     }
391     
392     /**
393      * Gets the command line options.
394      *
395      * @return The command line options.
396      */

397     public Option[]
398     getOptions()
399     {
400         return ((Option[])(options_.toArray(new Option[0])));
401     }
402
403     /**
404      * Adds a command line option.
405      *
406      * @param option The command line option object.
407      */

408     public void
409     addOption(Option option)
410     {
411         options_.addElement(option);
412
413         int size = sumStringLength(option.getLabels()) +
414             option.getLabels().length * 2 +
415             sumStringLength(option.getArguments()) +
416             option.getArguments().length;
417
418         if(size > maxOptionLength_) {
419             maxOptionLength_ = size;
420         }
421     }
422
423     /**
424      * Parses given command line arguments and
425      * feeds the command line option objects.
426      *
427      * @param args The command line arguments.
428      *
429      * @return The command line arguments not parsed.
430      */

431     public String JavaDoc[]
432     parse(String JavaDoc[] args) {
433         // Creates a command line arguments iterator.
434
DefaultIterator argumentsIterator = new DefaultIterator(args, this);
435
436         // Iterates over all command line arguments.
437
for(;argumentsIterator.hasNext();) {
438             String JavaDoc currentArgument = argumentsIterator.next();
439             
440             // Iterates over all command line options.
441
for(Iterator JavaDoc iterator=options_.iterator();iterator.hasNext();) {
442                 Option option = (Option)iterator.next();
443                 if(option.check(currentArgument)) {
444                     argumentsIterator.remove();
445                     try {
446                         option.consume(argumentsIterator);
447                     } catch(Error JavaDoc exc) {
448                         exit(exc.getMessage() + " for option " + OptionHelper.toString(option));
449                     }
450                     break;
451                 }
452             }
453         }
454
455         // Checks if all mandatory options are set during parsing.
456
//
457
// Iterates over all command line options.
458
//
459
for(Iterator JavaDoc iterator=options_.iterator();iterator.hasNext();) {
460             Option option = (Option)iterator.next();
461
462             // Checks if the option is mandatory and not set.
463
if(option.isMandatory() && !option.isSet()) {
464                 exit("Missed mandatory option " +
465                      OptionHelper.toString(option));
466             }
467         }
468
469         // Obtains unparsed command line arguments.
470
String JavaDoc[] arguments = argumentsIterator.getUnparsedArguments();
471         
472         // Checks arguments if required.
473
if (isCheckingArguments()) {
474             // Checks if enough.
475
if(arguments.length < getArguments().length)
476                 exit("Not enough arguments");
477
478             if((!getAdditionalArguments())&&(arguments.length > getArguments().length))
479                 exit("Too many arguments");
480         }
481         // Returns unparsed command line arguments.
482
return arguments;
483     }
484
485     // ==================================================================
486
//
487
// Public methods for org.objectweb.util.cmdline.api.ConsoleHolder
488
//
489
// ==================================================================
490

491     /**
492      * Obtains the associated console.
493      *
494      * @return The associated console.
495      */

496     public Console
497     getConsole()
498     {
499         return console_;
500     }
501
502     /**
503      * Sets the associated console.
504      *
505      * @param console The associated console.
506      */

507     public void
508     setConsole(Console console)
509     {
510         console_ = console;
511     }
512
513     // ==================================================================
514
//
515
// Other public methods.
516
//
517
// ==================================================================
518

519 }
520
Popular Tags