CSVRenderer.java
01 /**
02  * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03  */
04 package net.sourceforge.pmd.renderers;
05 
06 import java.io.IOException;
07 import java.io.Writer;
08 import java.util.Iterator;
09 import java.util.Properties;
10 
11 import net.sourceforge.pmd.PMD;
12 import net.sourceforge.pmd.RuleViolation;
13 import net.sourceforge.pmd.util.StringUtil;
14 
15 /**
16  * Renderer to comma separated format.
17  */
18 public class CSVRenderer extends AbstractIncrementingRenderer {
19 
20     public static final String NAME = "csv";
21 
22     private int violationCount = 1;
23 
24     public CSVRenderer(Properties properties) {
25   super(NAME, "Comma-separated values tabular format.", properties);
26     }
27 
28     /**
29      * {@inheritDoc}
30      */
31     @Override
32     public void start() throws IOException {
33   StringBuffer buf = new StringBuffer(300);
34   quoteAndCommify(buf, "Problem");
35   quoteAndCommify(buf, "Package");
36   quoteAndCommify(buf, "File");
37   quoteAndCommify(buf, "Priority");
38   quoteAndCommify(buf, "Line");
39   quoteAndCommify(buf, "Description");
40   quoteAndCommify(buf, "Rule set");
41   quote(buf, "Rule");
42   buf.append(PMD.EOL);
43   getWriter().write(buf.toString());
44     }
45 
46     /**
47      * {@inheritDoc}
48      */
49     @Override
50     public void renderFileViolations(Iterator<RuleViolation> violationsthrows IOException {
51   StringBuffer buf = new StringBuffer(300);
52   Writer writer = getWriter();
53 
54   RuleViolation rv;
55   while (violations.hasNext()) {
56       buf.setLength(0);
57       rv = violations.next();
58       quoteAndCommify(buf, Integer.toString(violationCount));
59       quoteAndCommify(buf, rv.getPackageName());
60       quoteAndCommify(buf, rv.getFilename());
61       quoteAndCommify(buf, Integer.toString(rv.getRule().getPriority().getPriority()));
62       quoteAndCommify(buf, Integer.toString(rv.getBeginLine()));
63       quoteAndCommify(buf, StringUtil.replaceString(rv.getDescription()'\"'"'"));
64       quoteAndCommify(buf, rv.getRule().getRuleSetName());
65       quote(buf, rv.getRule().getName());
66       buf.append(PMD.EOL);
67       writer.write(buf.toString());
68       violationCount++;
69   }
70     }
71 
72     private void quote(StringBuffer buffer, String s) {
73   buffer.append('"').append(s).append('"');
74     }
75 
76     private void quoteAndCommify(StringBuffer buffer, String s) {
77   quote(buffer, s);
78   buffer.append(',');
79     }
80 }