1
2
3
4
5
6
7
8
9
10
11 package org.csveed.bean;
12
13 import java.io.Writer;
14 import java.util.Collection;
15
16 import org.csveed.bean.conversion.BeanWrapper;
17 import org.csveed.bean.conversion.ConversionException;
18 import org.csveed.bean.conversion.DefaultConverters;
19 import org.csveed.row.HeaderImpl;
20 import org.csveed.row.LineWithInfo;
21 import org.csveed.row.RowImpl;
22 import org.csveed.row.RowWriter;
23 import org.csveed.row.RowWriterImpl;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27
28
29
30
31
32
33 public class BeanWriterImpl<T> implements BeanWriter<T> {
34
35
36 private static final Logger logger = LoggerFactory.getLogger(BeanWriterImpl.class);
37
38
39 private final RowWriter rowWriter;
40
41
42 private final BeanInstructions beanInstructions;
43
44
45 private boolean headerWritten;
46
47
48 private DefaultConverters defaultConverters = new DefaultConverters();
49
50
51 private HeaderImpl header;
52
53
54
55
56
57
58
59
60
61 public BeanWriterImpl(Writer writer, Class<T> beanClass) {
62 this(writer, new BeanParser().getBeanInstructions(beanClass));
63 }
64
65
66
67
68
69
70
71
72
73 public BeanWriterImpl(Writer writer, BeanInstructions beanInstructions) {
74 this.beanInstructions = beanInstructions;
75 this.rowWriter = new RowWriterImpl(writer, this.beanInstructions.getRowInstructions());
76 }
77
78 @Override
79 public void writeBeans(Collection<T> beans) {
80 for (T bean : beans) {
81 writeBean(bean);
82 }
83 }
84
85 @Override
86 public void writeBean(T bean) {
87 writeHeader();
88
89 LineWithInfo line = new LineWithInfo();
90
91 BeanWrapper beanWrapper = new BeanWrapper(defaultConverters, bean);
92 for (BeanProperty property : beanInstructions.getProperties()) {
93 try {
94 line.addCell(beanWrapper.getProperty(property));
95 } catch (ConversionException e) {
96 logger.error("{}", e.getMessage());
97 logger.trace("", e);
98 }
99 }
100 rowWriter.writeRow(new RowImpl(line, header));
101 }
102
103 @Override
104 public void writeHeader() {
105 if (!beanInstructions.useHeader() || headerWritten) {
106 return;
107 }
108 LineWithInfo line = new LineWithInfo();
109 for (BeanProperty property : beanInstructions.getProperties()) {
110 line.addCell(property.getColumnName());
111 }
112 header = new HeaderImpl(line);
113 rowWriter.writeHeader(header);
114 headerWritten = true;
115 }
116
117 @Override
118 public RowWriter getRowWriter() {
119 return rowWriter;
120 }
121
122 }