KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > umd > cs > findbugs > ProjectStats


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

20
21 package edu.umd.cs.findbugs;
22
23 import java.io.ByteArrayInputStream JavaDoc;
24 import java.io.ByteArrayOutputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.io.OutputStream JavaDoc;
28 import java.io.Reader JavaDoc;
29 import java.io.Writer JavaDoc;
30 import java.text.ParseException JavaDoc;
31 import java.text.SimpleDateFormat JavaDoc;
32 import java.text.NumberFormat JavaDoc;
33 import java.util.Collection JavaDoc;
34 import java.util.Date JavaDoc;
35 import java.util.Locale JavaDoc;
36 import java.util.SortedMap JavaDoc;
37 import java.util.TreeMap JavaDoc;
38
39 import javax.xml.transform.Transformer JavaDoc;
40 import javax.xml.transform.TransformerException JavaDoc;
41 import javax.xml.transform.TransformerFactory JavaDoc;
42 import javax.xml.transform.stream.StreamResult JavaDoc;
43 import javax.xml.transform.stream.StreamSource JavaDoc;
44
45 import edu.umd.cs.findbugs.PackageStats.ClassStats;
46 import edu.umd.cs.findbugs.xml.OutputStreamXMLOutput;
47 import edu.umd.cs.findbugs.xml.XMLOutput;
48 import edu.umd.cs.findbugs.xml.XMLWriteable;
49
50 /**
51  * Statistics resulting from analyzing a project.
52  */

53 public class ProjectStats implements XMLWriteable, Cloneable JavaDoc {
54     private static final String JavaDoc TIMESTAMP_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z";
55     private SortedMap JavaDoc<String JavaDoc, PackageStats> packageStatsMap;
56     private int[] totalErrors = new int[] { 0, 0, 0, 0, 0 };
57     private int totalClasses;
58     private int totalSize;
59     private Date JavaDoc timestamp;
60     private Footprint baseFootprint;
61
62     /**
63      * Constructor. Creates an empty object.
64      */

65     public ProjectStats() {
66         this.packageStatsMap = new TreeMap JavaDoc<String JavaDoc, PackageStats>();
67         this.totalClasses = 0;
68         this.timestamp = new Date JavaDoc();
69         this.baseFootprint = new Footprint();
70     }
71     
72     @Override JavaDoc
73     public Object JavaDoc clone() {
74         try {
75             return super.clone();
76         } catch (CloneNotSupportedException JavaDoc e) {
77             // can't happen
78
throw new AssertionError JavaDoc(e);
79         }
80     }
81
82     public int getCodeSize() {
83         return totalSize;
84     }
85     public int getTotalBugs() {
86         return totalErrors[0];
87     }
88     public int getBugsOfPriority(int priority) {
89         return totalErrors[priority];
90     }
91     /**
92      * Set the timestamp for this analysis run.
93      *
94      * @param timestamp the time of the analysis run this
95      * ProjectStats represents, as previously
96      * reported by writeXML.
97      */

98     public void setTimestamp(String JavaDoc timestamp) throws ParseException JavaDoc {
99         this.timestamp = new SimpleDateFormat JavaDoc(TIMESTAMP_FORMAT, Locale.ENGLISH).parse(timestamp);
100     }
101     
102     public void setTimestamp(long timestamp) {
103         this.timestamp = new Date JavaDoc(timestamp);
104     }
105     
106     /**
107      * Get the number of classes analyzed.
108      */

109     public int getNumClasses() {
110         return totalClasses;
111     }
112
113     /**
114      * Report that a class has been analyzed.
115      *
116      * @param className the full name of the class
117      * @param isInterface true if the class is an interface
118      * @param size a normalized class size value;
119      * see detect/FindBugsSummaryStats.
120      */

121     public void addClass(String JavaDoc className, boolean isInterface, int size) {
122         String JavaDoc packageName;
123         int lastDot = className.lastIndexOf('.');
124         if (lastDot < 0)
125             packageName = "";
126         else
127             packageName = className.substring(0, lastDot);
128         PackageStats stat = getPackageStats(packageName);
129         stat.addClass(className, isInterface, size);
130         totalClasses++;
131         totalSize += size;
132     }
133     
134     /**
135      * Report that a class has been analyzed.
136      *
137      * @param className the full name of the class
138      */

139     public ClassStats getClassStats(String JavaDoc className) {
140         String JavaDoc packageName;
141         int lastDot = className.lastIndexOf('.');
142         if (lastDot < 0)
143             packageName = "";
144         else
145             packageName = className.substring(0, lastDot);
146         PackageStats stat = getPackageStats(packageName);
147         return stat.getClassStatsOrNull(className);
148     }
149
150     /**
151      * Called when a bug is reported.
152      */

153     public void addBug(BugInstance bug) {
154         PackageStats stat = getPackageStats(bug.getPrimaryClass().getPackageName());
155         stat.addError(bug);
156         ++totalErrors[0];
157         int priority = bug.getPriority();
158         if (priority >= 1) {
159             ++totalErrors[Math.min(priority, totalErrors.length - 1)];
160         }
161     }
162
163     /**
164      * Clear bug counts
165      */

166     public void clearBugCounts() {
167         for(int i = 0; i < totalErrors.length; i++)
168             totalErrors[i] = 0;
169         for (PackageStats stats : packageStatsMap.values()) {
170             stats.clearBugCounts();
171         }
172     }
173     /**
174      * Output as XML.
175      */

176     public void writeXML(XMLOutput xmlOutput) throws IOException JavaDoc {
177         xmlOutput.startTag("FindBugsSummary");
178         
179         xmlOutput.addAttribute("timestamp",
180                 new SimpleDateFormat JavaDoc(TIMESTAMP_FORMAT, Locale.ENGLISH).format(timestamp));
181         xmlOutput.addAttribute("total_classes", String.valueOf(totalClasses));
182         xmlOutput.addAttribute("total_bugs", String.valueOf(totalErrors[0]));
183         xmlOutput.addAttribute("total_size", String.valueOf(totalSize));
184         xmlOutput.addAttribute("num_packages", String.valueOf(packageStatsMap.size()));
185         
186         Footprint delta = new Footprint(baseFootprint);
187         NumberFormat JavaDoc twoPlaces = NumberFormat.getInstance(Locale.ENGLISH);
188         twoPlaces.setMinimumFractionDigits(2);
189         twoPlaces.setMaximumFractionDigits(2);
190         twoPlaces.setGroupingUsed(false);
191         long cpuTime = delta.getCpuTime(); // nanoseconds
192
if (cpuTime >= 0) {
193             xmlOutput.addAttribute("cpu_seconds", twoPlaces.format(cpuTime / 1000000000.0));
194         }
195         long clockTime = delta.getClockTime(); // milliseconds
196
if (clockTime >= 0) {
197             xmlOutput.addAttribute("clock_seconds", twoPlaces.format(clockTime / 1000.0));
198         }
199         long peakMemory = delta.getPeakMemory(); // bytes
200
if (peakMemory >= 0) {
201             xmlOutput.addAttribute("peak_mbytes", twoPlaces.format(peakMemory / (1024.0*1024)));
202         }
203         long gcTime = delta.getCollectionTime(); // milliseconds
204
if (gcTime >= 0) {
205             xmlOutput.addAttribute("gc_seconds", twoPlaces.format(gcTime / 1000.0));
206         }
207         
208         PackageStats.writeBugPriorities(xmlOutput, totalErrors);
209         
210         xmlOutput.stopTag(false);
211
212         for (PackageStats stats : packageStatsMap.values()) {
213             stats.writeXML(xmlOutput);
214         }
215         
216         xmlOutput.closeTag("FindBugsSummary");
217     }
218     
219     /**
220      * Report statistics as an XML document to given output stream.
221      */

222     public void reportSummary(OutputStream JavaDoc out) throws IOException JavaDoc {
223         XMLOutput xmlOutput = new OutputStreamXMLOutput(out);
224         writeXML(xmlOutput);
225         xmlOutput.finish();
226     }
227
228     /**
229      * Transform summary information to HTML.
230      *
231      * @param htmlWriter the Writer to write the HTML output to
232      */

233     public void transformSummaryToHTML(Writer JavaDoc htmlWriter)
234             throws IOException JavaDoc, TransformerException JavaDoc {
235
236         ByteArrayOutputStream JavaDoc summaryOut = new ByteArrayOutputStream JavaDoc(8096);
237         reportSummary(summaryOut);
238
239         StreamSource JavaDoc in = new StreamSource JavaDoc(new ByteArrayInputStream JavaDoc(summaryOut.toByteArray()));
240         StreamResult JavaDoc out = new StreamResult JavaDoc(htmlWriter);
241         InputStream JavaDoc xslInputStream = this.getClass().getClassLoader().getResourceAsStream("summary.xsl");
242         if (xslInputStream == null)
243             throw new IOException JavaDoc("Could not load summary stylesheet");
244         StreamSource JavaDoc xsl = new StreamSource JavaDoc(xslInputStream);
245
246         TransformerFactory JavaDoc tf = TransformerFactory.newInstance();
247         Transformer JavaDoc transformer = tf.newTransformer(xsl);
248         transformer.transform(in, out);
249
250         Reader JavaDoc rdr = in.getReader();
251         if (rdr != null)
252             rdr.close();
253         htmlWriter.close();
254         InputStream JavaDoc is = xsl.getInputStream();
255         if (is != null)
256             is.close();
257     }
258
259     public Collection JavaDoc<PackageStats> getPackageStats() {
260         return packageStatsMap.values();
261     }
262     private PackageStats getPackageStats(String JavaDoc packageName) {
263         PackageStats stat = packageStatsMap.get(packageName);
264         if (stat == null) {
265             stat = new PackageStats(packageName);
266             packageStatsMap.put(packageName, stat);
267         }
268         return stat;
269     }
270
271     /**
272      * @param stats2
273      */

274     public void addStats(ProjectStats stats2) {
275         totalSize += stats2.totalSize;
276         totalClasses += stats2.totalClasses;
277         for(int i = 0; i < totalErrors.length; i++)
278             totalErrors[i] += stats2.totalErrors[i];
279         packageStatsMap.putAll(stats2.packageStatsMap);
280     }
281 }
282
Popular Tags