1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.orangesignal.csv.handlers;
18
19 import java.io.IOException;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.List;
23 import java.util.Map;
24
25 import com.orangesignal.csv.CsvReader;
26 import com.orangesignal.csv.CsvWriter;
27 import com.orangesignal.csv.filters.CsvNamedValueFilter;
28 import com.orangesignal.csv.io.CsvColumnNameMapReader;
29 import com.orangesignal.csv.io.CsvColumnNameMapWriter;
30
31
32
33
34
35
36
37 public class ColumnNameMapListHandler extends AbstractCsvListHandler<Map<String, String>, ColumnNameMapListHandler> {
38
39
40
41
42 private List<String> columnNames;
43
44
45
46
47
48
49 private boolean header = true;
50
51
52
53
54 private CsvNamedValueFilter valueFilter;
55
56
57
58
59 public ColumnNameMapListHandler() {}
60
61
62
63
64
65
66
67 public ColumnNameMapListHandler addColumn(final String columnName) {
68 if (columnNames == null) {
69 columnNames = new ArrayList<String>();
70 }
71 columnNames.add(columnName);
72 return this;
73 }
74
75
76
77
78
79
80
81 public ColumnNameMapListHandler columnNames(final Collection<String> columnNames) {
82 this.columnNames = new ArrayList<String>(columnNames);
83 return this;
84 }
85
86
87
88
89
90
91
92
93 public ColumnNameMapListHandler filter(final CsvNamedValueFilter filter) {
94 this.valueFilter = filter;
95 return this;
96 }
97
98
99
100
101
102
103
104
105 public ColumnNameMapListHandler header(final boolean header) {
106 this.header = header;
107 return this;
108 }
109
110 @Override
111 public List<Map<String, String>> load(final CsvReader reader, final boolean ignoreScalar) throws IOException {
112 @SuppressWarnings("resource")
113 final CsvColumnNameMapReader r = new CsvColumnNameMapReader(reader, columnNames);
114 r.setFilter(valueFilter);
115
116
117 final List<Map<String, String>> results = new ArrayList<Map<String, String>>();
118 int offset = 0;
119
120 List<String> values;
121 while ((values = r.readValues()) != null && (ignoreScalar || limit <= 0 || results.size() < limit)) {
122 if (!ignoreScalar && offset < this.offset) {
123 offset++;
124 continue;
125 }
126 results.add(r.toMap(values));
127 }
128 return results;
129 }
130
131 @Override
132 public void save(final List<Map<String, String>> list, final CsvWriter writer) throws IOException {
133 @SuppressWarnings("resource")
134 final CsvColumnNameMapWriter w = new CsvColumnNameMapWriter(writer, columnNames, header);
135 w.setFilter(valueFilter);
136
137
138 for (final Map<String, String> map : list) {
139 w.write(map);
140 }
141 }
142
143 }