View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.renderers;
5   
6   import java.io.IOException;
7   import java.io.Writer;
8   import java.util.Iterator;
9   import java.util.List;
10  
11  /**
12   * A generic writer that formats input items into rows and columns per the provided column descriptors.
13   *
14   * @author Brian Remedios
15   * @param <T>
16   */
17  public class CSVWriter<T extends Object>  {
18  
19  	private final String					separator;			// e.g., the comma
20  	private final String					lineSeparator;		// cr
21  	private final List<ColumnDescriptor<T>> columns;
22  
23      public CSVWriter(List<ColumnDescriptor<T>> theColumns, String theSeparator, String theLineSeparator) {
24      	columns = theColumns;
25      	separator = theSeparator;
26      	lineSeparator = theLineSeparator;
27      }
28  
29      public void writeTitles(Writer writer) throws IOException {
30      	StringBuilder buf = new StringBuilder(300);
31      	for (int i=0; i<columns.size()-1; i++) {
32      		quoteAndCommify(buf, columns.get(i).title);
33      	}
34  
35      	quote(buf, columns.get(columns.size()-1).title);
36  
37  		buf.append(lineSeparator);
38  		writer.write(buf.toString());
39      }
40  
41      public void writeData(Writer writer, Iterator<T> items) throws IOException {
42  
43          int count = 1;
44  
45      	StringBuilder buf = new StringBuilder(300);
46  
47  		T rv;
48  		final int lastColumnIdx = columns.size()-1;
49  
50  		while (items.hasNext()) {
51  		    buf.setLength(0);
52  		    rv = items.next();
53  
54  		    for (int i=0; i<lastColumnIdx; i++) {
55  		    	quoteAndCommify(buf, columns.get(i).accessor.get(count, rv, separator));
56  		    }
57  
58  		    quote(buf, columns.get(lastColumnIdx).accessor.get(count, rv, separator));
59  
60  		    buf.append(lineSeparator);
61  		    writer.write(buf.toString());
62  		    count++;
63  		}
64      }
65  
66      private void quote(StringBuilder buffer, String s) {
67      	if (s == null) {
68      	    return;
69      	}
70      	buffer.append('"').append(s).append('"');
71      }
72  
73      private void quoteAndCommify(StringBuilder buffer, String s) {
74  		quote(buffer, s);
75  		buffer.append(separator);
76      }
77  }