KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > optional > sitraka > CovReport


1 /*
2  * Copyright 2001-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
18 package org.apache.tools.ant.taskdefs.optional.sitraka;
19
20 import java.io.File JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.util.Vector JavaDoc;
23 import javax.xml.transform.OutputKeys JavaDoc;
24 import javax.xml.transform.Result JavaDoc;
25 import javax.xml.transform.Source JavaDoc;
26 import javax.xml.transform.Transformer JavaDoc;
27 import javax.xml.transform.TransformerFactory JavaDoc;
28 import javax.xml.transform.dom.DOMSource JavaDoc;
29 import javax.xml.transform.stream.StreamResult JavaDoc;
30 import org.apache.tools.ant.BuildException;
31 import org.apache.tools.ant.Project;
32 import org.apache.tools.ant.taskdefs.Execute;
33 import org.apache.tools.ant.taskdefs.LogStreamHandler;
34 import org.apache.tools.ant.types.Commandline;
35 import org.apache.tools.ant.types.EnumeratedAttribute;
36 import org.apache.tools.ant.types.Path;
37 import org.w3c.dom.Document JavaDoc;
38
39
40 /**
41  * Runs the JProbe Coverage 3.0 snapshot merge utility.
42  *
43  * @ant.task name="jpcovreport" category="metrics"
44  */

45 public class CovReport extends CovBase {
46     /*
47       jpcoverport [options] -output=file -snapshot=snapshot.jpc
48       jpcovreport [options] [-paramfile=file] -output=<fileName> -snapshot=<fileName>
49
50       Generate a report based on the indicated snapshot
51
52       -paramfile=file
53       A text file containing the report generation options.
54
55       -format=(html|text|xml) defaults to html
56       The format of the generated report.
57
58       -type=(executive|summary|detailed|verydetailed) defaults to detailed
59       The type of report to be generated. For -format=xml,
60       use -type=verydetailed to include source code lines.
61
62       Note: A very detailed report can be VERY large.
63
64       -percent=num Min 1 Max 101 Default 101
65       An integer representing a percentage of coverage.
66       Only methods with test case coverage less than the
67       percentage are included in reports.
68
69       -filters=string
70       A comma-separated list of filters in the form
71       <package>.<class>:V, where V can be I for Include or
72       E for Exclude. For the default package, omit <package>.
73
74       -filters_method=string
75       Optional. A comma-separated list of methods that
76       correspond one-to-one with the entries in -filters.
77
78       -output=string Must be specified
79       The absolute path and file name for the generated
80       report file.
81
82       -snapshot=string Must be specified
83       The absolute path and file name of the snapshot file.
84
85       -inc_src_text=(on|off) defaults to on
86       Include text of the source code lines.
87       Only applies for -format=xml and -type=verydetailed.
88
89       -sourcepath=string defaults to .
90       A semicolon-separated list of source paths.
91
92       /*
93
94     /** format of generated report, optional */

95     private String JavaDoc format = null;
96
97     /** the name of the output snapshot, mandatory */
98     private File JavaDoc tofile = null;
99
100     /** type of report, optional */
101     private String JavaDoc type = null;
102
103     /** threshold value for printing methods, optional */
104     private Integer JavaDoc percent = null;
105
106     /** comma separated list of filters (???)*/
107     private String JavaDoc filters = null;
108
109     /** name of the snapshot file to create report from */
110     private File JavaDoc snapshot = null;
111
112     /** sourcepath to use */
113     private Path sourcePath = null;
114
115     /** include the text for each line of code (xml report verydetailed)*/
116     private boolean includeSource = true;
117
118     private Path coveragePath = null;
119
120     /** */
121     private Reference reference = null;
122
123
124     public static class ReportFormat extends EnumeratedAttribute {
125         public String JavaDoc[] getValues() {
126             return new String JavaDoc[]{"html", "text", "xml"};
127         }
128     }
129
130     /**
131      * set the format of the report: "html", "text", or "xml"
132      */

133     public void setFormat(ReportFormat value) {
134         this.format = value.getValue();
135     }
136
137     public static class ReportType extends EnumeratedAttribute {
138         public String JavaDoc[] getValues() {
139             return new String JavaDoc[]{"executive", "summary", "detailed", "verydetailed"};
140         }
141     }
142
143     /**
144      * The type of report to be generated: "executive", "summary",
145      * "detailed" or "verydetailed".
146      */

147     public void setType(ReportType value) {
148         this.type = value.getValue();
149     }
150
151     /**
152      * If true, include text of the source code lines.
153      * Only applies to format="xml" and type="verydetailed"
154      */

155     public void setIncludesource(boolean value) {
156         this.includeSource = value;
157     }
158
159     /**
160      * A numeric value for the threshold for printing methods.
161      * Must be between 0 and 100.
162      */

163     public void setPercent(Integer JavaDoc value) {
164         this.percent = value;
165     }
166
167     /**
168      * set the filters
169      * @ant.attribute ignore="true"
170      */

171     public void setFilters(String JavaDoc values) {
172         this.filters = values;
173     }
174
175     /**
176      * Adds a path to source files.
177      */

178     public Path createSourcepath() {
179         if (sourcePath == null) {
180             sourcePath = new Path(getProject());
181         }
182         return sourcePath.createPath();
183     }
184
185     /**
186      * The name of the snapshot file that is the source to the report.
187      */

188     public void setSnapshot(File JavaDoc value) {
189         this.snapshot = value;
190     }
191
192     /**
193      * The name of the generated output file.
194      */

195     public void setTofile(File JavaDoc value) {
196         this.tofile = value;
197     }
198
199     /**
200      * @todo needs to be removed
201      * @ant.element ignore="true"
202      */

203     public Path createCoveragepath() {
204         if (coveragePath == null) {
205             coveragePath = new Path(getProject());
206         }
207         return coveragePath.createPath();
208     }
209
210     /**
211      * Adds a set of classes whose coverage information will be
212      * checked against.
213      */

214     public Reference createReference() {
215         if (reference == null) {
216             reference = new Reference();
217         }
218         return reference;
219     }
220
221
222     public CovReport() {
223     }
224
225     /** check for mandatory options */
226     protected void checkOptions() throws BuildException {
227         if (tofile == null) {
228             throw new BuildException("'tofile' attribute must be set.");
229         }
230         if (snapshot == null) {
231             throw new BuildException("'snapshot' attribute must be set.");
232         }
233         if (getHome() == null) {
234             throw new BuildException("'home' attribute must be set to JProbe home directory");
235         }
236         File JavaDoc jar = findCoverageJar();
237         if (!jar.exists()) {
238             throw new BuildException("Cannot find Coverage directory: " + getHome());
239         }
240         if (reference != null && !"xml".equals(format)) {
241             log("Ignored reference. It cannot be used in non XML report.");
242             reference = null; // nullify it so that there is no ambiguity
243
}
244
245     }
246
247     public void execute() throws BuildException {
248         checkOptions();
249         try {
250             Commandline cmdl = new Commandline();
251             // we need to run Coverage from his directory due to dll/jar issues
252
cmdl.setExecutable(findExecutable("jpcovreport"));
253             String JavaDoc[] params = getParameters();
254             for (int i = 0; i < params.length; i++) {
255                 cmdl.createArgument().setValue(params[i]);
256             }
257
258             // use the custom handler for stdin issues
259
LogStreamHandler handler
260                 = new LogStreamHandler(this, Project.MSG_INFO, Project.MSG_WARN);
261             Execute exec = new Execute(handler);
262             log(cmdl.describeCommand(), Project.MSG_VERBOSE);
263             exec.setCommandline(cmdl.getCommandline());
264             int exitValue = exec.execute();
265             if (Execute.isFailure(exitValue)) {
266                 throw new BuildException("JProbe Coverage Report failed ("
267                     + exitValue + ")");
268             }
269             log("coveragePath: " + coveragePath, Project.MSG_VERBOSE);
270             log("format: " + format, Project.MSG_VERBOSE);
271             if (reference != null && "xml".equals(format)) {
272                 reference.createEnhancedXMLReport();
273             }
274
275         } catch (IOException JavaDoc e) {
276             throw new BuildException("Failed to execute JProbe Coverage Report.", e);
277         }
278     }
279
280
281     protected String JavaDoc[] getParameters() {
282         Vector JavaDoc v = new Vector JavaDoc();
283         if (format != null) {
284             v.addElement("-format=" + format);
285         }
286         if (type != null) {
287             v.addElement("-type=" + type);
288         }
289         if (percent != null) {
290             v.addElement("-percent=" + percent);
291         }
292         if (filters != null) {
293             v.addElement("-filters=" + filters);
294         }
295         v.addElement("-output=" + getProject().resolveFile(tofile.getPath()));
296         v.addElement("-snapshot=" + getProject().resolveFile(snapshot.getPath()));
297         // as a default -sourcepath use . in JProbe, so use project .
298
if (sourcePath == null) {
299             sourcePath = new Path(getProject());
300             sourcePath.createPath().setLocation(getProject().resolveFile("."));
301         }
302         v.addElement("-sourcepath=" + sourcePath);
303
304         if ("verydetailed".equalsIgnoreCase(format) && "xml".equalsIgnoreCase(type)) {
305             v.addElement("-inc_src_text=" + (includeSource ? "on" : "off"));
306         }
307
308         String JavaDoc[] params = new String JavaDoc[v.size()];
309         v.copyInto(params);
310         return params;
311     }
312
313
314     public class Reference {
315         protected Path classPath;
316         protected ReportFilters filters;
317
318         public Path createClasspath() {
319             if (classPath == null) {
320                 classPath = new Path(CovReport.this.getProject());
321             }
322             return classPath.createPath();
323         }
324
325         public ReportFilters createFilters() {
326             if (filters == null) {
327                 filters = new ReportFilters();
328             }
329             return filters;
330         }
331
332         protected void createEnhancedXMLReport() throws BuildException {
333             // we need a classpath element
334
if (classPath == null) {
335                 throw new BuildException("Need a 'classpath' element.");
336             }
337             // and a valid one...
338
String JavaDoc[] paths = classPath.list();
339             if (paths.length == 0) {
340                 throw new BuildException("Coverage path is invalid. It does not contain any existing path.");
341             }
342             // and we need at least one filter include/exclude.
343
if (filters == null || filters.size() == 0) {
344                 createFilters();
345                 log("Adding default include filter to *.*()", Project.MSG_VERBOSE);
346                 ReportFilters.Include include = new ReportFilters.Include();
347                 filters.addInclude(include);
348             }
349             try {
350                 log("Creating enhanced XML report", Project.MSG_VERBOSE);
351                 XMLReport report = new XMLReport(CovReport.this, tofile);
352                 report.setReportFilters(filters);
353                 report.setJProbehome(new File JavaDoc(getHome().getParent()));
354                 Document JavaDoc doc = report.createDocument(paths);
355                 TransformerFactory JavaDoc tfactory = TransformerFactory.newInstance();
356                 Transformer JavaDoc transformer = tfactory.newTransformer();
357                 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
358                 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
359                 Source JavaDoc src = new DOMSource JavaDoc(doc);
360                 Result JavaDoc res = new StreamResult JavaDoc("file:///" + tofile.toString());
361                 transformer.transform(src, res);
362             } catch (Exception JavaDoc e) {
363                 throw new BuildException("Error while performing enhanced XML "
364                     + "report from file " + tofile, e);
365             }
366         }
367     }
368 }
369
Popular Tags