KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > optional > metamata > MMetrics


1 /*
2  * Copyright 2001-2002,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 package org.apache.tools.ant.taskdefs.optional.metamata;
18
19 import java.io.File JavaDoc;
20 import java.io.FileInputStream JavaDoc;
21 import java.io.FileOutputStream JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.util.Vector JavaDoc;
24 import org.apache.tools.ant.BuildException;
25 import org.apache.tools.ant.Project;
26 import org.apache.tools.ant.taskdefs.ExecuteStreamHandler;
27 import org.apache.tools.ant.taskdefs.LogStreamHandler;
28 import org.apache.tools.ant.types.EnumeratedAttribute;
29 import org.apache.tools.ant.types.Path;
30
31 /**
32  * Computes the metrics of a set of Java files and write the results to an XML
33  * file. As a convenience, a stylesheet is given in <tt>etc</tt> directory,
34  * so that an HTML report can be generated from the XML file.
35  * <p>
36  * You will not be able to use this task with the evaluation version since
37  * as of Metamata 2.0, Metrics does not support command line :-(
38  *
39  *
40  */

41 public class MMetrics extends AbstractMetamataTask {
42 /*
43     The command line options as of Metamata 2.0 are as follows:
44
45 Usage
46     mmetrics <option>... <path>...
47
48 Parameters
49     path File or directory to measure.
50
51 Options
52     -arguments -A <file> Includes command line arguments from file.
53     -classpath -cp <path> Sets class path (also source path unless one
54                                   explicitly set). Overrides METAPATH/CLASSPATH.
55     -compilation-units Measure compilation units.
56     -files Measure compilation units.
57     -format -f <format> Sets output format, default output file type.
58     -help -h Prints help and exits.
59     -indent -i <string> Sets string used to indent labels one level.
60     -methods Measure methods, types, and compilation units.
61     -output -o <file> Sets output file name.
62     -quiet -q Suppresses copyright message.
63     -sourcepath <path> Sets source path. Overrides SOURCEPATH.
64     -types Measure types and compilation units.
65     -verbose -v Prints all messages.
66     -version -V Prints version and exits.
67
68 Format Options
69     comma csv Format output as comma-separated text.
70     html htm Format output as an HTML table.
71     tab tab-separated tsv Format output as tab-separated text.
72     text txt Format output as space-aligned text.
73 */

74
75     /** the granularity mode. Should be one of 'files', 'methods' and 'types'. */
76     private String JavaDoc granularity = null;
77
78     /** the XML output file */
79     private File JavaDoc outFile = null;
80
81     /** the location of the temporary txt report */
82     private File JavaDoc tmpFile;
83
84     private Path path = null;
85
86     //--------------------------- PUBLIC METHODS -------------------------------
87

88     /** default constructor */
89     public MMetrics() {
90         super("com.metamata.sc.MMetrics");
91     }
92
93     /**
94      * Attributes for granularity.
95      */

96     public static class GranularityAttribute extends EnumeratedAttribute {
97         public String JavaDoc[] getValues() {
98             return new String JavaDoc[]{"compilation-units", "files", "methods", "types", "packages"};
99         }
100     }
101
102     /**
103      * set the granularity of the audit. Should be one of 'files', 'methods'
104      * or 'types'.
105      * @param granularity the audit reporting mode.
106      */

107     public void setGranularity(GranularityAttribute granularity) {
108         this.granularity = granularity.getValue();
109     }
110
111     /**
112      * Set the output XML file
113      * @param file the xml file to write the XML report to.
114      */

115     public void setTofile(File JavaDoc file) {
116         this.outFile = file;
117     }
118
119     /**
120      * Set a new path (directory) to measure metrics from.
121      * @return the path instance to use.
122      */

123     public Path createPath() {
124         if (path == null) {
125             path = new Path(getProject());
126         }
127         return path;
128
129     }
130
131     //------------------- PROTECTED / PRIVATE METHODS --------------------------
132

133
134     // check for existing options and outfile, all other are optional
135
protected void checkOptions() throws BuildException {
136         super.checkOptions();
137
138         if (outFile == null) {
139             throw new BuildException("Output XML file must be set via 'tofile' attribute.");
140         }
141         if (path == null && fileSets.size() == 0) {
142             throw new BuildException("Must set either paths (path element) "
143                 + "or files (fileset element)");
144         }
145         // I don't accept dirs and files at the same time,
146
// I cannot recognize the semantic in the result
147
if (path != null && fileSets.size() > 0) {
148             throw new BuildException("Cannot set paths (path element) and "
149                 + "files (fileset element) at the same time");
150         }
151         tmpFile = createTmpFile();
152     }
153
154     protected void execute0(ExecuteStreamHandler handler) throws BuildException {
155         super.execute0(handler);
156         transformFile();
157     }
158
159     /**
160      * transform the generated file via the handler
161      * This function can either be called if the result is written to the output
162      * file via -output or we could use the handler directly on stdout if not.
163      * @see #createStreamHandler()
164      */

165     protected void transformFile() throws BuildException {
166         FileInputStream JavaDoc tmpStream = null;
167         try {
168             tmpStream = new FileInputStream JavaDoc(tmpFile);
169         } catch (IOException JavaDoc e) {
170             throw new BuildException("Error reading temporary file: " + tmpFile, e);
171         }
172         FileOutputStream JavaDoc xmlStream = null;
173         try {
174             xmlStream = new FileOutputStream JavaDoc(outFile);
175             ExecuteStreamHandler xmlHandler = new MMetricsStreamHandler(this, xmlStream);
176             xmlHandler.setProcessOutputStream(tmpStream);
177             xmlHandler.start();
178             xmlHandler.stop();
179         } catch (IOException JavaDoc e) {
180             throw new BuildException("Error creating output file: " + outFile, e);
181         } finally {
182             if (xmlStream != null) {
183                 try {
184                     xmlStream.close();
185                 } catch (IOException JavaDoc ignored) {
186                 }
187             }
188             if (tmpStream != null) {
189                 try {
190                     tmpStream.close();
191                 } catch (IOException JavaDoc ignored) {
192                 }
193             }
194         }
195     }
196
197
198     /** cleanup the temporary txt report */
199     protected void cleanUp() throws BuildException {
200         try {
201             super.cleanUp();
202         } finally {
203             if (tmpFile != null) {
204                 tmpFile.delete();
205                 tmpFile = null;
206             }
207         }
208     }
209
210     /**
211      * if the report is transform via a temporary txt file we should use a
212      * a normal logger here, otherwise we could use the metrics handler
213      * directly to capture and transform the output on stdout to XML.
214      */

215     protected ExecuteStreamHandler createStreamHandler() {
216         // write the report directtly to an XML stream
217
// return new MMetricsStreamHandler(this, xmlStream);
218
return new LogStreamHandler(this, Project.MSG_INFO, Project.MSG_INFO);
219     }
220
221
222     protected Vector JavaDoc getOptions() {
223         Vector JavaDoc options = new Vector JavaDoc(512);
224         // there is a bug in Metamata 2.0 build 37. The sourcepath argument does
225
// not work. So we will use the sourcepath prepended to classpath. (order
226
// is important since Metamata looks at .class and .java)
227
if (sourcePath != null) {
228             sourcePath.append(classPath); // srcpath is prepended
229
classPath = sourcePath;
230             sourcePath = null; // prevent from using -sourcepath
231
}
232
233         // don't forget to modify the pattern if you change the options reporting
234
if (classPath != null) {
235             options.addElement("-classpath");
236             options.addElement(classPath.toString());
237         }
238         options.addElement("-output");
239         options.addElement(tmpFile.toString());
240
241         options.addElement("-" + granularity);
242
243         // display the metamata copyright
244
// options.addElement( "-quiet");
245
options.addElement("-format");
246
247         // need this because that's what the handler is using, it's
248
// way easier to process than any other separator
249
options.addElement("tab");
250
251         // specify a / as the indent character, used by the handler.
252
options.addElement("-i");
253         options.addElement("/");
254
255         // directories
256
String JavaDoc[] dirs = path.list();
257         for (int i = 0; i < dirs.length; i++) {
258             options.addElement(dirs[i]);
259         }
260         // files next.
261
addAllVector(options, includedFiles.keys());
262         return options;
263     }
264
265 }
266
Popular Tags