View Javadoc
1   package org.csveed.bean;
2   
3   import java.io.Writer;
4   import java.util.Collection;
5   
6   import org.csveed.bean.conversion.BeanWrapper;
7   import org.csveed.bean.conversion.ConversionException;
8   import org.csveed.bean.conversion.DefaultConverters;
9   import org.csveed.row.HeaderImpl;
10  import org.csveed.row.LineWithInfo;
11  import org.csveed.row.RowImpl;
12  import org.csveed.row.RowWriter;
13  import org.csveed.row.RowWriterImpl;
14  import org.slf4j.Logger;
15  import org.slf4j.LoggerFactory;
16  
17  public class BeanWriterImpl<T> implements BeanWriter<T> {
18  
19      private static final Logger logger = LoggerFactory.getLogger(BeanWriterImpl.class);
20  
21      private final RowWriter rowWriter;
22  
23      private final BeanInstructions beanInstructions;
24  
25      private boolean headerWritten;
26  
27      private DefaultConvertersaultConverters">DefaultConverters defaultConverters = new DefaultConverters();
28  
29      private HeaderImpl header;
30  
31      public BeanWriterImpl(Writer writer, Class<T> beanClass) {
32          this(writer, new BeanParser().getBeanInstructions(beanClass));
33      }
34  
35      public BeanWriterImpl(Writer writer, BeanInstructions beanInstructions) {
36          this.beanInstructions = beanInstructions;
37          this.rowWriter = new RowWriterImpl(writer, this.beanInstructions.getRowInstructions());
38      }
39  
40      @Override
41      public void writeBeans(Collection<T> beans) {
42          for (T bean : beans) {
43              writeBean(bean);
44          }
45      }
46  
47      @Override
48      public void writeBean(T bean) {
49          writeHeader();
50  
51          LineWithInfoneWithInfo">LineWithInfo line = new LineWithInfo();
52  
53          BeanWrapperml#BeanWrapper">BeanWrapper beanWrapper = new BeanWrapper(defaultConverters, bean);
54          for (BeanProperty property : beanInstructions.getProperties()) {
55              try {
56                  line.addCell(beanWrapper.getProperty(property));
57              } catch (ConversionException e) {
58                  logger.error("{}", e.getMessage());
59                  logger.trace("", e);
60              }
61          }
62          rowWriter.writeRow(new RowImpl(line, header));
63      }
64  
65      @Override
66      public void writeHeader() {
67          if (!beanInstructions.useHeader() || headerWritten) {
68              return;
69          }
70          LineWithInfoneWithInfo">LineWithInfo line = new LineWithInfo();
71          for (BeanProperty property : beanInstructions.getProperties()) {
72              line.addCell(property.getColumnName());
73          }
74          header = new HeaderImpl(line);
75          rowWriter.writeHeader(header);
76          headerWritten = true;
77      }
78  
79      @Override
80      public RowWriter getRowWriter() {
81          return rowWriter;
82      }
83  
84  }