8
8
import java .util .ArrayList ;
9
9
import java .util .List ;
10
10
11
+ import static java .util .Arrays .asList ;
11
12
import static java .util .Collections .emptyList ;
12
13
13
14
public class ListOfObjectWriter extends DataTableWriter {
14
15
private static final List <Comment > NO_COMMENTS = emptyList ();
15
16
private final List <DataTableRow > rows = new ArrayList <DataTableRow >();
16
17
private final TableConverter tableConverter ;
18
+ private final List <String > fieldNames ;
19
+
17
20
private int nodeDepth = 0 ;
18
- private List < String > header = new ArrayList < String >() ;
19
- private List < String > cells ;
21
+ private String [] fieldValues ;
22
+ private int fieldIndex = - 1 ;
20
23
21
- public ListOfObjectWriter (TableConverter tableConverter ) {
24
+ public ListOfObjectWriter (TableConverter tableConverter , String ... columnNames ) {
22
25
this .tableConverter = tableConverter ;
26
+ fieldNames = asList (columnNames );
27
+
28
+ DataTableRow headerRow = new DataTableRow (NO_COMMENTS , fieldNames , 0 );
29
+ rows .add (headerRow );
23
30
}
24
31
25
32
@ Override
@@ -31,10 +38,10 @@ public DataTable getDataTable() {
31
38
public void startNode (String name ) {
32
39
nodeDepth ++;
33
40
if (nodeDepth == 2 ) {
34
- cells = new ArrayList < String >() ;
41
+ fieldValues = new String [ fieldNames . size ()] ;
35
42
}
36
- if (nodeDepth == 3 && header != null ) {
37
- header . add (name );
43
+ if (nodeDepth == 3 ) {
44
+ fieldIndex = fieldNames . indexOf (name );
38
45
}
39
46
}
40
47
@@ -44,23 +51,33 @@ public void addAttribute(String name, String value) {
44
51
45
52
@ Override
46
53
public void setValue (String text ) {
47
- cells .add (text );
54
+ if (fieldIndex != -1 ) {
55
+ fieldValues [fieldIndex ] = text ;
56
+ }
48
57
}
49
58
50
59
@ Override
51
60
public void endNode () {
52
61
if (nodeDepth == 2 ) {
53
- if (header != null ) {
54
- DataTableRow headerRow = new DataTableRow (NO_COMMENTS , header , 0 );
55
- rows .add (headerRow );
56
- header = null ;
57
- }
62
+ List <String > cells = toArrayReplacingNullWithEmptyString ();
58
63
DataTableRow row = new DataTableRow (NO_COMMENTS , cells , 0 );
59
64
rows .add (row );
60
65
}
61
66
nodeDepth --;
62
67
}
63
68
69
+ private List <String > toArrayReplacingNullWithEmptyString () {
70
+ List <String > cells = new ArrayList <String >(fieldValues .length );
71
+ for (int i = 0 ; i < fieldValues .length ; i ++) {
72
+ String fieldValue = fieldValues [i ];
73
+ if (fieldValue == null ) {
74
+ fieldValue = "" ;
75
+ }
76
+ cells .add (fieldValue );
77
+ }
78
+ return cells ;
79
+ }
80
+
64
81
@ Override
65
82
public void flush () {
66
83
throw new UnsupportedOperationException ();
0 commit comments