KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > puppycrawl > tools > checkstyle > Main


1 ////////////////////////////////////////////////////////////////////////////////
2
// checkstyle: Checks Java source code for adherence to a set of rules.
3
// Copyright (C) 2001-2005 Oliver Burn
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
package com.puppycrawl.tools.checkstyle;
20
21 import java.io.File JavaDoc;
22 import java.io.FileInputStream JavaDoc;
23 import java.io.FileNotFoundException JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.OutputStream JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.Properties JavaDoc;
29 import java.util.LinkedList JavaDoc;
30
31 import org.apache.commons.cli.CommandLine;
32 import org.apache.commons.cli.CommandLineParser;
33 import org.apache.commons.cli.HelpFormatter;
34 import org.apache.commons.cli.Options;
35 import org.apache.commons.cli.ParseException;
36 import org.apache.commons.cli.PosixParser;
37
38 import com.puppycrawl.tools.checkstyle.api.AuditListener;
39 import com.puppycrawl.tools.checkstyle.api.Configuration;
40
41 import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
42
43 /**
44  * Wrapper command line program for the Checker.
45  * @author Oliver Burn
46  **/

47 public final class Main
48 {
49     /** the options to the command line */
50     private static final Options OPTS = new Options();
51     static {
52         OPTS.addOption("c", true, "The check configuration file to use.");
53         OPTS.addOption("r", true, "Traverse the directory for source files");
54         OPTS.addOption("o", true, "Sets the output file. Defaults to stdout");
55         OPTS.addOption("p", true, "Loads the properties file");
56         OPTS.addOption("n", true, "Loads the package names file");
57         OPTS.addOption(
58             "f",
59             true,
60             "Sets the output format. (plain|xml). Defaults to plain");
61     }
62
63     /**
64      * Loops over the files specified checking them for errors. The exit code
65      * is the number of errors found in all the files.
66      * @param aArgs the command line arguments
67      **/

68     public static void main(String JavaDoc[] aArgs)
69     {
70         // parse the parameters
71
final CommandLineParser clp = new PosixParser();
72         CommandLine line = null;
73         try {
74             line = clp.parse(OPTS, aArgs);
75         }
76         catch (final ParseException e) {
77             e.printStackTrace();
78             usage();
79         }
80         assert line != null;
81
82         // setup the properties
83
final Properties JavaDoc props =
84             line.hasOption("p")
85                 ? loadProperties(new File JavaDoc(line.getOptionValue("p")))
86                 : System.getProperties();
87
88         // ensure a config file is specified
89
if (!line.hasOption("c")) {
90             System.out.println("Must specify a config XML file.");
91             usage();
92         }
93
94         final Configuration config = loadConfig(line, props);
95
96         //Load the set of package names
97
ModuleFactory moduleFactory = null;
98         if (line.hasOption("n")) {
99             moduleFactory = loadPackages(line);
100         }
101
102         // setup the output stream
103
OutputStream JavaDoc out = null;
104         boolean closeOut = false;
105         if (line.hasOption("o")) {
106             final String JavaDoc fname = line.getOptionValue("o");
107             try {
108                 out = new FileOutputStream JavaDoc(fname);
109                 closeOut = true;
110             }
111             catch (final FileNotFoundException JavaDoc e) {
112                 System.out.println("Could not find file: '" + fname + "'");
113                 System.exit(1);
114             }
115         }
116         else {
117             out = System.out;
118             closeOut = false;
119         }
120
121         final AuditListener listener = createListener(line, out, closeOut);
122         final List JavaDoc files = getFilesToProcess(line);
123         final Checker c = createChecker(config, moduleFactory, listener);
124
125         final File JavaDoc[] processedFiles = new File JavaDoc[files.size()];
126         files.toArray(processedFiles);
127         final int numErrs = c.process(processedFiles);
128         c.destroy();
129         System.exit(numErrs);
130     }
131
132     /**
133      * Creates the Checker object.
134      *
135      * @param aConfig the configuration to use
136      * @param aFactory the module factor to use
137      * @param aNosy the sticky beak to track what happens
138      * @return a nice new fresh Checker
139      */

140     private static Checker createChecker(Configuration aConfig,
141                                          ModuleFactory aFactory,
142                                          AuditListener aNosy)
143     {
144         Checker c = null;
145         try {
146             c = new Checker();
147             c.setModuleFactory(aFactory);
148             c.configure(aConfig);
149             c.addListener(aNosy);
150         }
151         catch (final Exception JavaDoc e) {
152             System.out.println("Unable to create Checker: "
153                                + e.getMessage());
154             e.printStackTrace(System.out);
155             System.exit(1);
156         }
157         return c;
158     }
159
160     /**
161      * Determines the files to process.
162      *
163      * @param aLine the command line options specifying what files to process
164      * @return list of files to process
165      */

166     private static List JavaDoc getFilesToProcess(CommandLine aLine)
167     {
168         final List JavaDoc files = new LinkedList JavaDoc();
169         if (aLine.hasOption("r")) {
170             final String JavaDoc[] values = aLine.getOptionValues("r");
171             for (int i = 0; i < values.length; i++) {
172                 traverse(new File JavaDoc(values[i]), files);
173             }
174         }
175
176         final String JavaDoc[] remainingArgs = aLine.getArgs();
177         for (int i = 0; i < remainingArgs.length; i++) {
178             files.add(new File JavaDoc(remainingArgs[i]));
179         }
180
181         if (files.isEmpty()) {
182             System.out.println("Must specify files to process");
183             usage();
184         }
185         return files;
186     }
187
188     /**
189      * Create the audit listener
190      *
191      * @param aLine command line options supplied
192      * @param aOut the stream to log to
193      * @param aCloseOut whether the stream should be closed
194      * @return a fresh new <code>AuditListener</code>
195      */

196     private static AuditListener createListener(CommandLine aLine,
197                                                 OutputStream JavaDoc aOut,
198                                                 boolean aCloseOut)
199     {
200         final String JavaDoc format =
201             aLine.hasOption("f") ? aLine.getOptionValue("f") : "plain";
202
203         AuditListener listener = null;
204         if ("xml".equals(format)) {
205             listener = new XMLLogger(aOut, aCloseOut);
206         }
207         else if ("plain".equals(format)) {
208             listener = new DefaultLogger(aOut, aCloseOut);
209         }
210         else {
211             System.out.println("Invalid format: (" + format
212                                + "). Must be 'plain' or 'xml'.");
213             usage();
214         }
215         return listener;
216     }
217
218     /**
219      * Loads the packages, or exists if unable to.
220      *
221      * @param aLine the supplied command line options
222      * @return a fresh new <code>ModuleFactory</code>
223      */

224     private static ModuleFactory loadPackages(CommandLine aLine)
225     {
226         try {
227             return PackageNamesLoader.loadModuleFactory(
228                 aLine.getOptionValue("n"));
229         }
230         catch (final CheckstyleException e) {
231             System.out.println("Error loading package names file");
232             e.printStackTrace(System.out);
233             System.exit(1);
234             return null; // never get here
235
}
236     }
237
238     /**
239      * Loads the configuration file. Will exit if unable to load.
240      *
241      * @param aLine specifies the location of the configuration
242      * @param aProps the properties to resolve with the configuration
243      * @return a fresh new configuration
244      */

245     private static Configuration loadConfig(CommandLine aLine,
246                                             Properties JavaDoc aProps)
247     {
248         try {
249             return ConfigurationLoader.loadConfiguration(
250                     aLine.getOptionValue("c"), new PropertiesExpander(aProps));
251         }
252         catch (final CheckstyleException e) {
253             System.out.println("Error loading configuration file");
254             e.printStackTrace(System.out);
255             System.exit(1);
256             return null; // can never get here
257
}
258     }
259
260     /** Prints the usage information. **/
261     private static void usage()
262     {
263         final HelpFormatter hf = new HelpFormatter();
264         hf.printHelp(
265             "java "
266                 + Main.class.getName()
267                 + " [options] -c <config.xml> file...",
268             OPTS);
269         System.exit(1);
270     }
271
272     /**
273      * Traverses a specified node looking for files to check. Found
274      * files are added to a specified list. Subdirectories are also
275      * traversed.
276      *
277      * @param aNode the node to process
278      * @param aFiles list to add found files to
279      */

280     private static void traverse(File JavaDoc aNode, List JavaDoc aFiles)
281     {
282         if (aNode.canRead()) {
283             if (aNode.isDirectory()) {
284                 final File JavaDoc[] nodes = aNode.listFiles();
285                 for (int i = 0; i < nodes.length; i++) {
286                     traverse(nodes[i], aFiles);
287                 }
288             }
289             else if (aNode.isFile()) {
290                 aFiles.add(aNode);
291             }
292         }
293     }
294
295     /**
296      * Loads properties from a File.
297      * @param aFile the properties file
298      * @return the properties in aFile
299      */

300     private static Properties JavaDoc loadProperties(File JavaDoc aFile)
301     {
302         final Properties JavaDoc properties = new Properties JavaDoc();
303         try {
304             FileInputStream JavaDoc fis = null;
305             fis = new FileInputStream JavaDoc(aFile);
306             properties.load(fis);
307             fis.close();
308         }
309         catch (final IOException JavaDoc ex) {
310             System.out.println("Unable to load properties from file: "
311                                + aFile.getAbsolutePath());
312             ex.printStackTrace(System.out);
313             System.exit(1);
314         }
315         return properties;
316     }
317 }
318
Popular Tags