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.text.Format;
21 import java.util.ArrayList;
22 import java.util.List;
23
24 import com.orangesignal.csv.CsvReader;
25 import com.orangesignal.csv.CsvWriter;
26 import com.orangesignal.csv.bean.CsvBeanOperation;
27 import com.orangesignal.csv.bean.CsvBeanTemplate;
28 import com.orangesignal.csv.filters.CsvNamedValueFilter;
29 import com.orangesignal.csv.io.CsvBeanReader;
30 import com.orangesignal.csv.io.CsvBeanWriter;
31
32
33
34
35
36
37
38 public class BeanListHandler<T> extends AbstractBeanListHandler<T, CsvBeanTemplate<T>, BeanListHandler<T>> implements CsvBeanOperation<BeanListHandler<T>> {
39
40
41
42
43
44
45 private boolean header = true;
46
47
48
49
50
51
52
53
54
55 public BeanListHandler(final Class<T> type) {
56 super(CsvBeanTemplate.newInstance(type));
57 }
58
59
60
61 @Override
62 public BeanListHandler<T> includes(final String... names) {
63 template.includes(names);
64 return this;
65 }
66
67 @Override
68 public BeanListHandler<T> excludes(final String... names) {
69 template.excludes(names);
70 return this;
71 }
72
73
74
75
76
77
78
79
80
81 public BeanListHandler<T> format(final String name, final Format format) {
82 template.format(name, format);
83 return this;
84 }
85
86 @Override
87 public BeanListHandler<T> filter(final CsvNamedValueFilter filter) {
88 template.filter(filter);
89 return this;
90 }
91
92
93
94
95
96
97
98
99 public BeanListHandler<T> header(final boolean header) {
100 this.header = header;
101 return this;
102 }
103
104
105
106 @Override
107 public List<T> load(final CsvReader reader, final boolean ignoreScalar) throws IOException {
108 @SuppressWarnings("resource")
109 final CsvBeanReader<T> r = new CsvBeanReader<T>(reader, template);
110
111
112 final List<T> results = new ArrayList<T>();
113 final boolean order = ignoreScalar || orders != null && !orders.isEmpty();
114 int offset = 0;
115
116 List<String> values;
117 while ((values = r.readValues()) != null && (order || limit <= 0 || results.size() < limit)) {
118 if (beanFilter == null && !order && offset < this.offset) {
119 offset++;
120 continue;
121 }
122 final T bean = r.toBean(values);
123 if (beanFilter != null) {
124 if (!beanFilter.accept(bean)) {
125 continue;
126 }
127 if (!order && offset < this.offset) {
128 offset++;
129 continue;
130 }
131 }
132 results.add(bean);
133 }
134
135 if (ignoreScalar || !order) {
136 return results;
137 }
138 return processScalar(results);
139 }
140
141 @Override
142 public void save(final List<T> list, final CsvWriter writer) throws IOException {
143 @SuppressWarnings("resource")
144 final CsvBeanWriter<T> w = new CsvBeanWriter<T>(writer, template, header);
145
146
147 for (final T bean : list) {
148
149 if (bean == null) {
150 w.write(null);
151 continue;
152 } else if (beanFilter != null && !beanFilter.accept(bean)) {
153 continue;
154 }
155 w.write(bean);
156 }
157 }
158
159 }