View Javadoc

1   package au.com.bytecode.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 au.com.bytecode.opencsv.CSVReader;
20  
21  import java.beans.IntrospectionException;
22  import java.beans.PropertyDescriptor;
23  import java.beans.PropertyEditor;
24  import java.beans.PropertyEditorManager;
25  import java.io.Reader;
26  import java.lang.reflect.InvocationTargetException;
27  import java.util.ArrayList;
28  import java.util.HashMap;
29  import java.util.List;
30  import java.util.Map;
31  
32  public class CsvToBean<T> {
33  	private Map <Class<?>, PropertyEditor> editorMap = null;
34      public CsvToBean() {
35      }
36  
37      public List<T> parse(MappingStrategy<T> mapper, Reader reader) {
38  
39      	return parse(mapper, new CSVReader(reader));
40      }
41      
42      public List<T> parse(MappingStrategy<T> mapper, CSVReader csv) {
43          try {
44              mapper.captureHeader(csv);
45              String[] line;
46              List<T> list = new ArrayList<T>();
47              while(null != (line = csv.readNext())) {
48                  T obj = processLine(mapper, line);
49                  list.add(obj); // TODO: (Kyle) null check object
50              }
51              return list;
52          } catch (Exception e) {
53              throw new RuntimeException("Error parsing CSV!", e);
54          }
55      }
56  
57      protected T processLine(MappingStrategy<T> mapper, String[] line) throws IllegalAccessException, InvocationTargetException, InstantiationException, IntrospectionException {
58      	T bean = mapper.createBean();
59          for(int col = 0; col < line.length; col++) {
60              String value = line[col];
61              PropertyDescriptor prop = mapper.findDescriptor(col);
62              if (null != prop) {
63                  Object obj = convertValue(value, prop);
64                  prop.getWriteMethod().invoke(bean, obj);
65              }
66          }
67          return bean;
68      }
69  
70      protected Object convertValue(String value, PropertyDescriptor prop) throws InstantiationException, IllegalAccessException {
71          PropertyEditor editor = getPropertyEditor(prop);
72          Object obj = value;
73          if (null != editor) {
74              editor.setAsText(value.trim());
75              obj = editor.getValue();
76          }
77          return obj;
78      }
79      
80      private PropertyEditor getPropertyEditorValue(Class<?> cls)
81      {
82         if (editorMap == null)
83         {
84            editorMap = new HashMap<Class<?>, PropertyEditor>();
85         }
86         
87         PropertyEditor editor = editorMap.get(cls);
88         
89         if (editor == null)
90         {
91            editor = PropertyEditorManager.findEditor(cls);
92            addEditorToMap(cls, editor);
93         }
94         
95         return editor;
96      }
97  
98     private void addEditorToMap(Class<?> cls, PropertyEditor editor)
99     {
100       if (editor != null)
101        {   
102           editorMap.put(cls, editor);
103        }
104    }
105 
106 
107     /*
108      * Attempt to find custom property editor on descriptor first, else try the propery editor manager.
109      */
110     protected PropertyEditor getPropertyEditor(PropertyDescriptor desc) throws InstantiationException, IllegalAccessException {
111         Class<?> cls = desc.getPropertyEditorClass();
112         if (null != cls) return (PropertyEditor) cls.newInstance();
113         return getPropertyEditorValue(desc.getPropertyType());
114     }
115 
116 }