KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > umd > cs > findbugs > config > CommandLine


1 /*
2  * FindBugs - Find bugs in Java programs
3  * Copyright (C) 2004, University of Maryland
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  */

19
20 package edu.umd.cs.findbugs.config;
21
22 import java.io.BufferedReader JavaDoc;
23 import java.io.FileInputStream JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStreamReader JavaDoc;
26 import java.io.OutputStream JavaDoc;
27 import java.io.PrintStream JavaDoc;
28 import java.nio.charset.Charset JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.HashSet JavaDoc;
32 import java.util.LinkedList JavaDoc;
33 import java.util.List JavaDoc;
34 import java.util.Map JavaDoc;
35 import java.util.Set JavaDoc;
36
37 import edu.umd.cs.findbugs.annotations.SuppressWarnings;
38
39
40 /**
41  * Helper class for parsing command line arguments.
42  */

43 public abstract class CommandLine {
44     private List JavaDoc<String JavaDoc> optionList;
45     private Set JavaDoc<String JavaDoc> requiresArgumentSet;
46     private Map JavaDoc<String JavaDoc, String JavaDoc> optionDescriptionMap;
47     private Map JavaDoc<String JavaDoc, String JavaDoc> optionExtraPartSynopsisMap;
48     private Map JavaDoc<String JavaDoc, String JavaDoc> argumentDescriptionMap;
49     int maxWidth;
50
51     public CommandLine() {
52         this.optionList = new LinkedList JavaDoc<String JavaDoc>();
53         this.requiresArgumentSet = new HashSet JavaDoc<String JavaDoc>();
54         this.optionDescriptionMap = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
55         this.optionExtraPartSynopsisMap = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
56         this.argumentDescriptionMap = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
57         this.maxWidth = 0;
58     }
59
60     /**
61      * Add a command line switch.
62      * This method is for adding options that do not require
63      * an argument.
64      *
65      * @param option the option, must start with "-"
66      * @param description single line description of the option
67      */

68     public void addSwitch(String JavaDoc option, String JavaDoc description) {
69         optionList.add(option);
70         optionDescriptionMap.put(option, description);
71
72         if (option.length() > maxWidth)
73             maxWidth = option.length();
74     }
75
76     /**
77      * Add a command line switch that allows optional extra
78      * information to be specified as part of it.
79      *
80      * @param option the option, must start with "-"
81      * @param optionExtraPartSynopsis synopsis of the optional extra information
82      * @param description single-line description of the option
83      */

84     public void addSwitchWithOptionalExtraPart(String JavaDoc option, String JavaDoc optionExtraPartSynopsis,
85             String JavaDoc description) {
86         optionList.add(option);
87         optionExtraPartSynopsisMap.put(option, optionExtraPartSynopsis);
88         optionDescriptionMap.put(option, description);
89
90         // Option will display as -foo[:extraPartSynopsis]
91
int length = option.length() + optionExtraPartSynopsis.length() + 3;
92         if (length > maxWidth)
93             maxWidth = length;
94     }
95
96     /**
97      * Add an option requiring an argument.
98      *
99      * @param option the option, must start with "-"
100      * @param argumentDesc brief (one or two word) description of the argument
101      * @param description single line description of the option
102      */

103     public void addOption(String JavaDoc option, String JavaDoc argumentDesc, String JavaDoc description) {
104         optionList.add(option);
105         optionDescriptionMap.put(option, description);
106         requiresArgumentSet.add(option);
107         argumentDescriptionMap.put(option, argumentDesc);
108
109         int width = option.length() + 3 + argumentDesc.length();
110         if (width > maxWidth)
111             maxWidth = width;
112     }
113
114     /**
115      * Expand option files in given command line.
116      * Any token beginning with "@" is assumed to be an option file.
117      * Option files contain one command line option per line.
118      *
119      * @param argv the original command line
120      * @param ignoreComments ignore comments (lines starting with "#")
121      * @param ignoreBlankLines ignore blank lines
122      * @return the expanded command line
123      */

124     public static String JavaDoc[] expandOptionFiles(
125                 String JavaDoc[] argv, boolean ignoreComments, boolean ignoreBlankLines)
126                 throws IOException JavaDoc {
127         ArrayList JavaDoc<String JavaDoc> resultList = new ArrayList JavaDoc<String JavaDoc>();
128
129         for (String JavaDoc arg : argv) {
130             if (!arg.startsWith("@")) {
131                 resultList.add(arg);
132                 continue;
133             }
134
135             BufferedReader JavaDoc reader = null;
136             try {
137                 reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(
138                         new FileInputStream JavaDoc(arg.substring(1)), Charset.forName("UTF-8")));
139                 String JavaDoc line;
140                 while ((line = reader.readLine()) != null) {
141                     line = line.trim();
142
143                     if (ignoreComments && line.startsWith("#"))
144                         continue;
145
146                     if (ignoreBlankLines && line.equals(""))
147                         continue;
148
149                     resultList.add(line);
150                 }
151             } finally {
152                 if (reader != null) {
153                     try {
154                         reader.close();
155                     } catch (IOException JavaDoc ignore) {
156                         // Ignore
157
}
158                 }
159             }
160         }
161
162         return resultList.toArray(new String JavaDoc[resultList.size()]);
163     }
164
165     public static class HelpRequestedException extends Exception JavaDoc {
166         
167     }
168     @SuppressWarnings JavaDoc("DM_EXIT")
169     public int parse(String JavaDoc argv[], int minArgs, int maxArgs, String JavaDoc usage) {
170         try {
171         int count = parse(argv);
172         int remaining = argv.length - count;
173         if (remaining < minArgs || remaining > maxArgs) {
174             System.out.println(usage);
175             System.out.println("Expected " +minArgs + "..." + maxArgs
176                     + " file arguments, found " + remaining);
177             System.out.println("Options:");
178             printUsage(System.out);
179             System.exit(1);
180         }
181         return count;
182         } catch (HelpRequestedException e) {
183             // fall through
184

185         } catch (RuntimeException JavaDoc e) {
186             e.printStackTrace();
187         } catch (IOException JavaDoc e) {
188             e.printStackTrace();
189         }
190         System.out.println(usage);
191         System.out.println("Options:");
192         printUsage(System.out);
193         System.exit(1);
194         return -1;
195     }
196     /**
197      * Parse a command line.
198      * Calls down to handleOption() and handleOptionWithArgument() methods.
199      * Stops parsing when it reaches the end of the command line,
200      * or when a command line argument not starting with "-" is seen.
201      *
202      * @param argv the arguments
203      * @return the number of arguments parsed; if equal to
204      * argv.length, then the entire command line was parsed
205      * @throws HelpRequestedException
206      */

207     public int parse(String JavaDoc argv[]) throws IOException JavaDoc, HelpRequestedException {
208         int arg = 0;
209
210         while (arg < argv.length) {
211             String JavaDoc option = argv[arg];
212             if (option.equals("-help"))
213                 throw new HelpRequestedException();
214             if (!option.startsWith("-"))
215                 break;
216
217             String JavaDoc optionExtraPart = "";
218             int colon = option.indexOf(':');
219             if (colon >= 0) {
220                 optionExtraPart = option.substring(colon + 1);
221                 option = option.substring(0, colon);
222             }
223
224             if (optionDescriptionMap.get(option) == null)
225                 throw new IllegalArgumentException JavaDoc("Unknown option: " + option);
226
227             if (requiresArgumentSet.contains(option)) {
228                 ++arg;
229                 if (arg >= argv.length)
230                     throw new IllegalArgumentException JavaDoc("Option " + option + " requires an argument");
231                 String JavaDoc argument = argv[arg];
232                 handleOptionWithArgument(option, argument);
233                 ++arg;
234             } else {
235                 handleOption(option, optionExtraPart);
236                 ++arg;
237             }
238         }
239
240         return arg;
241     }
242
243     /**
244      * Callback method for handling an option.
245      *
246      * @param option the option
247      * @param optionExtraPart the "extra" part of the option (everything after the
248      * colon: e.g., "withMessages" in "-xml:withMessages");
249      * the empty string if there was no extra part
250      */

251     protected abstract void handleOption(String JavaDoc option, String JavaDoc optionExtraPart)
252         throws IOException JavaDoc;
253
254     /**
255      * Callback method for handling an option with an argument.
256      *
257      * @param option the option
258      * @param argument the argument
259      */

260     protected abstract void handleOptionWithArgument(String JavaDoc option, String JavaDoc argument) throws IOException JavaDoc;
261
262     /**
263      * Print command line usage information to given stream.
264      *
265      * @param os the output stream
266      */

267     public void printUsage(OutputStream JavaDoc os) {
268         PrintStream JavaDoc out = new PrintStream JavaDoc(os);
269         for (String JavaDoc option : optionList) {
270             out.print(" ");
271
272             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
273             buf.append(option);
274             if (optionExtraPartSynopsisMap.get(option) != null) {
275                 String JavaDoc optionExtraPartSynopsis = optionExtraPartSynopsisMap.get(option);
276                 buf.append("[:");
277                 buf.append(optionExtraPartSynopsis);
278                 buf.append("]");
279             }
280             if (requiresArgumentSet.contains(option)) {
281                 buf.append(" <");
282                 buf.append(argumentDescriptionMap.get(option));
283                 buf.append(">");
284             }
285             printField(out, buf.toString(), maxWidth + 1);
286
287             out.println(optionDescriptionMap.get(option));
288         }
289         out.flush();
290     }
291
292     private static final String JavaDoc SPACES = " ";
293
294     private static void printField(PrintStream JavaDoc out, String JavaDoc s, int width) {
295         if (s.length() > width) throw new IllegalArgumentException JavaDoc();
296         int nSpaces = width - s.length();
297         out.print(s);
298         while (nSpaces > 0) {
299             int n = Math.min(SPACES.length(), nSpaces);
300             out.print(SPACES.substring(0, n));
301             nSpaces -= n;
302         }
303     }
304 }
305
306 // vim:ts=3
307
Popular Tags