blob: 38273912a74e9e63f43de56b7e3c93d763dd64aa [file] [log] [blame]
Stuart McCulloch26e7a5a2011-10-17 10:31:43 +00001package aQute.bnd.make.coverage;
2
3import static aQute.bnd.make.coverage.Coverage.*;
4
5import java.io.*;
6import java.lang.reflect.*;
7import java.util.*;
8
9import aQute.lib.osgi.*;
10import aQute.lib.osgi.Clazz.*;
11import aQute.lib.tag.*;
12
13/**
14 * Creates an XML Coverage report. This class can be used as a resource so the
15 * report is created only when the JAR is written.
16 *
17 */
18public class CoverageResource extends WriteResource {
19 Collection<Clazz> testsuite;
20 Collection<Clazz> service;
21
22 public CoverageResource(Collection<Clazz> testsuite,
23 Collection<Clazz> service) {
24 this.testsuite = testsuite;
25 this.service = service;
26 }
27
28 @Override
29 public long lastModified() {
30 return 0;
31 }
32
33 @Override
34 public void write(OutputStream out) throws IOException {
35 try {
36 Map<MethodDef, List<MethodDef>> table = getCrossRef(testsuite,
37 service);
38 Tag coverage = toTag(table);
39 PrintWriter pw = new PrintWriter(new OutputStreamWriter(out,
40 Constants.DEFAULT_CHARSET));
41 try {
42 coverage.print(0, pw);
43 } finally {
44 pw.flush();
45 }
46 } catch (Exception e) {
47 e.printStackTrace();
48 }
49 }
50
51 public static Tag toTag(Map<MethodDef, List<MethodDef>> catalog) {
52 Tag coverage = new Tag("coverage");
53 String currentClass = null;
54 Tag classTag = null;
55
56 for (Map.Entry<MethodDef, List<MethodDef>> m : catalog.entrySet()) {
57 String className = m.getKey().clazz;
58 if (!className.equals(currentClass)) {
59 classTag = new Tag("class");
60 classTag.addAttribute("name", className);
61 classTag.addAttribute("package", Clazz.getPackage(className));
62 classTag.addAttribute("short", Clazz.getShortName(className));
63 coverage.addContent(classTag);
64 currentClass = className;
65 }
66 Tag method = doMethod(new Tag("method"), m.getKey());
67 classTag.addContent(method);
68 for (MethodDef r : m.getValue()) {
69 Tag ref = doMethod(new Tag("ref"), r);
70 method.addContent(ref);
71 }
72 }
73 return coverage;
74 }
75
76 private static Tag doMethod(Tag tag, MethodDef method) {
77 tag.addAttribute("pretty", method.getPretty());
78 if (Modifier.isPublic(method.access))
79 tag.addAttribute("public", true);
80 if (Modifier.isStatic(method.access))
81 tag.addAttribute("static", true);
82 if (Modifier.isProtected(method.access))
83 tag.addAttribute("protected", true);
84 if (Modifier.isInterface(method.access))
85 tag.addAttribute("interface", true);
86 tag.addAttribute("constructor", method.isConstructor());
87 if (!method.isConstructor())
88 tag.addAttribute("name", method.name);
89 tag.addAttribute("descriptor", method.descriptor);
90 return tag;
91 }
92}