View Javadoc
1   package com.opencsv.bean;
2   
3   /*
4    Copyright 2007 Kyle Miller.
5   
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9   
10   http://www.apache.org/licenses/LICENSE-2.0
11  
12   Unless required by applicable law or agreed to in writing, software
13   distributed under the License is distributed on an "AS IS" BASIS,
14   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   See the License for the specific language governing permissions and
16   limitations under the License.
17   */
18  
19  import com.opencsv.CSVWriter;
20  
21  import java.beans.IntrospectionException;
22  import java.beans.PropertyDescriptor;
23  import java.io.Writer;
24  import java.lang.reflect.InvocationTargetException;
25  import java.lang.reflect.Method;
26  import java.util.ArrayList;
27  import java.util.List;
28  
29  /**
30   * Allows exporting content from Java beans to a new CSV spreadsheet file.
31   *
32   * @author Kali <kali.tystrit@gmail.com>
33   * @author Andrew Rucker Jones
34   * @param <T> Type of object that is being processed.
35   * @deprecated Please use the much easier and more powerful {@link StatefulBeanToCsv}.
36   */
37  @Deprecated
38  public class BeanToCsv<T> {
39  
40      /**
41       * Default constructor.
42       * It is, however, unnecessary to instantiate this class. This constructor
43       * is preserved for backward compatibility.
44       * @deprecated All methods in this class are static. Simply use them that way.
45       */
46      public BeanToCsv() {}
47  
48      /**
49       * Writes all the objects, one at a time, to a created
50       * {@link java.io.Writer Writer} using the passed in strategy.
51       *
52       * @param mapper  Mapping strategy for the bean.
53       * @param writer  Writer object used to construct the CSVWriter.
54       * @param objects List of objects to write.
55       * @param <T> Type of object that is being processed.
56       * @return False if there are no objects to process, true otherwise.
57       */
58      public static <T> boolean write(MappingStrategy<T> mapper, Writer writer,
59                           List<? extends T> objects) {
60          return write(mapper, new CSVWriter(writer), objects);
61      }
62  
63      /**
64       * Writes an single object allowing users to write large number of objects without worrying about
65       * a large collection filling up memory.  However it is up to the user to determine if the header needs
66       * to be written or not.
67       *
68       * @param mapper      Mapping Strategy for the bean
69       * @param csv         CSVWriter
70       * @param bean        Object to be written.
71       * @param writeHeader If the header needs to be written or not.
72       * @param <T> Type of object that is being processed.
73       * @return False if no object is written (null object) true otherwise.
74       */
75      public static <T> boolean write(MappingStrategy<T> mapper, CSVWriter csv, T bean, boolean writeHeader) {
76          if (bean == null) {
77              return false;
78          }
79  
80          try {
81              if (writeHeader) {
82                  csv.writeNext(processHeader(mapper));
83              }
84              String[] line = processObject(findGetters(mapper), bean);
85              csv.writeNext(line);
86              return true;
87          } catch (Exception e) {
88              throw new RuntimeException("Error writing bean!", e);
89          }
90      }
91  
92      /**
93       * Writes all the objects, one at a time, to the CSVWriter using the passed
94       * in Strategy.
95       * @param mapper Mapping strategy for the bean.
96       * @param csv CSVWriter
97       * @param objects List of objects to write.
98       * @param <T> Type of object that is being processed.
99       * @return False if there are no objects to process, true otherwise.
100      */
101     public static <T> boolean write(MappingStrategy<T> mapper, CSVWriter csv, List<? extends T> objects) {
102         if (objects == null || objects.isEmpty()) {
103             return false;
104         }
105 
106         try {
107             csv.writeNext(processHeader(mapper));
108             List<Method> getters = findGetters(mapper);
109             processAndWriteObjects(csv, objects, getters);
110             return true;
111         } catch (Exception e) {
112             throw new RuntimeException("Error writing CSV!", e);
113         }
114     }
115 
116     /**
117      * Processes a list of objects.
118      * @param csv CSVWriter
119      * @param objects List of objects to process
120      * @param getters List of getter methods to retrieve the data from the objects.
121      * @throws IntrospectionException Thrown if there is a failure in introspection.
122      * @throws IllegalAccessException Thrown if there is a failure in introspection.
123      * @throws InvocationTargetException Thrown if there is a failure in introspection.
124      */
125     private static <T> void processAndWriteObjects(CSVWriter csv, List<? extends T> objects, List<Method> getters) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
126         for (Object obj : objects) {
127             String[] line = processObject(getters, obj);
128             csv.writeNext(line);
129         }
130     }
131 
132     /**
133      * Processes the header for the bean.
134      * @param mapper MappingStrategy for the bean
135      * @param <T> Type of object that is being processed.
136      * @return String array with header values.
137      * @throws IntrospectionException Thrown if there is a failure in introspection.
138      */
139     protected static <T> String[] processHeader(MappingStrategy<T> mapper) throws IntrospectionException {
140         List<String> values = new ArrayList<String>();
141         int i = 0;
142         PropertyDescriptor prop = mapper.findDescriptor(i);
143         while (prop != null) {
144             values.add(prop.getName());
145             prop = mapper.findDescriptor(++i);
146         }
147         return values.toArray(new String[values.size()]);
148     }
149 
150     /**
151      * Retrieve all the information out of an object.
152      * @param getters List of methods to retrieve information.
153      * @param bean Object to get the information from.
154      * @param <T> Type of the bean to be written
155      * @return String array containing the information from the object
156      * @throws IntrospectionException Thrown by error in introspection.
157      * @throws IllegalAccessException Thrown by error in introspection.
158      * @throws InvocationTargetException Thrown by error in introspection.
159      */
160     protected static <T> String[] processObject(List<Method> getters, T bean) throws IntrospectionException,
161             IllegalAccessException, InvocationTargetException {
162         List<String> values = new ArrayList<String>(getters.size());
163         // retrieve bean values
164         for (Method getter : getters) {
165             Object value = getter.invoke(bean, (Object[]) null);
166             if (value == null) {
167                 values.add("null");
168             } else {
169                 values.add(value.toString());
170             }
171         }
172         return values.toArray(new String[values.size()]);
173     }
174 
175     /**
176      * Build getters list from provided mapper.
177      * @param mapper MappingStrategy for the bean
178      * @param <T> Type of object that is being processed.
179      * @return List of methods for getting the data in the bean.
180      * @throws IntrospectionException Thrown if there is a failure in introspection.
181      */
182     private static <T> List<Method> findGetters(MappingStrategy<T> mapper)
183             throws IntrospectionException {
184         int i = 0;
185         PropertyDescriptor prop = mapper.findDescriptor(i);
186         // build getters methods list
187         List<Method> readers = new ArrayList<Method>();
188         while (prop != null) {
189             readers.add(prop.getReadMethod());
190             prop = mapper.findDescriptor(++i);
191         }
192         return readers;
193     }
194 
195 }