1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.orangesignal.csv.io;
18
19 import java.io.Closeable;
20 import java.io.IOException;
21 import java.util.List;
22 import java.util.SortedMap;
23 import java.util.TreeMap;
24
25 import com.orangesignal.csv.CsvReader;
26 import com.orangesignal.csv.filters.CsvValueFilter;
27
28
29
30
31
32
33
34 public class CsvColumnPositionMapReader implements Closeable {
35
36
37
38
39 private CsvReader reader;
40
41
42
43
44 private CsvValueFilter filter;
45
46
47
48
49
50
51
52
53
54
55 public CsvColumnPositionMapReader(final CsvReader reader) {
56 if (reader == null) {
57 throw new IllegalArgumentException("CsvReader must not be null");
58 }
59 this.reader = reader;
60 }
61
62
63
64
65
66
67
68 private void ensureOpen() throws IOException {
69 if (reader == null) {
70 throw new IOException("CsvReader closed");
71 }
72 }
73
74
75
76
77 @Override
78 public void close() throws IOException {
79 synchronized (this) {
80 ensureOpen();
81 reader.close();
82 reader = null;
83 }
84 }
85
86
87
88
89
90
91
92
93
94
95 public SortedMap<Integer, String> read() throws IOException {
96 synchronized (this) {
97 ensureOpen();
98
99 final List<String> values = nextValues();
100 if (values == null) {
101 return null;
102 }
103 return convert(values);
104 }
105 }
106
107
108
109
110
111
112
113 public List<String> readValues() throws IOException {
114 synchronized (this) {
115 ensureOpen();
116 return nextValues();
117 }
118 }
119
120
121
122
123
124
125
126
127 public SortedMap<Integer, String> toMap(final List<String> values) throws IOException {
128 synchronized (this) {
129 ensureOpen();
130 return convert(values);
131 }
132 }
133
134 private List<String> nextValues() throws IOException {
135 List<String> values;
136 while ((values = reader.readValues()) != null) {
137 if (filter != null && !filter.accept(values)) {
138 continue;
139 }
140 return values;
141 }
142 return null;
143 }
144
145 private SortedMap<Integer, String> convert(final List<String> values) {
146 final SortedMap<Integer, String> map = new TreeMap<Integer, String>();
147 final int len = values.size();
148 for (int pos = 0; pos < len; pos++) {
149 map.put(pos, values.get(pos));
150 }
151 return map;
152 }
153
154
155
156
157
158
159
160
161
162 public CsvValueFilter getFilter() {
163 return filter;
164 }
165
166
167
168
169
170
171 public void setFilter(final CsvValueFilter filter) {
172 synchronized (this) {
173 this.filter = filter;
174 }
175 }
176
177 }