1 package au.com.bytecode.opencsv.bean;
2 import java.beans.BeanInfo;
3 import java.beans.IntrospectionException;
4 import java.beans.Introspector;
5 import java.beans.PropertyDescriptor;
6 import java.io.IOException;
7 import java.util.HashMap;
8 import java.util.Map;
9
10 import au.com.bytecode.opencsv.CSVReader;
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 public class HeaderColumnNameMappingStrategy<T> implements MappingStrategy<T> {
29 protected String[] header;
30 protected Map<String, PropertyDescriptor> descriptorMap = null;
31 protected Class<T> type;
32
33 public void captureHeader(CSVReader reader) throws IOException {
34 header = reader.readNext();
35 }
36
37 public PropertyDescriptor findDescriptor(int col) throws IntrospectionException {
38 String columnName = getColumnName(col);
39 return (null != columnName && columnName.trim().length()>0) ? findDescriptor(columnName) : null;
40 }
41
42 protected String getColumnName(int col) {
43 return (null != header && col < header.length) ? header[col] : null;
44 }
45 protected PropertyDescriptor findDescriptor(String name) throws IntrospectionException {
46 if (null == descriptorMap) descriptorMap = loadDescriptorMap(getType());
47 return descriptorMap.get(name.toUpperCase().trim());
48 }
49 protected boolean matches(String name, PropertyDescriptor desc) {
50 return desc.getName().equals(name.trim());
51 }
52
53 protected Map<String, PropertyDescriptor> loadDescriptorMap(Class<T> cls) throws IntrospectionException
54 {
55 Map<String, PropertyDescriptor> map = new HashMap<String, PropertyDescriptor>();
56
57 PropertyDescriptor[] descriptors;
58 descriptors = loadDescriptors(getType());
59 for (PropertyDescriptor descriptor : descriptors)
60 {
61 map.put(descriptor.getName().toUpperCase().trim(), descriptor);
62 }
63
64 return map;
65 }
66
67 private PropertyDescriptor[] loadDescriptors(Class<T> cls) throws IntrospectionException {
68 BeanInfo beanInfo = Introspector.getBeanInfo(cls);
69 return beanInfo.getPropertyDescriptors();
70 }
71 public T createBean() throws InstantiationException, IllegalAccessException {
72 return type.newInstance();
73 }
74 public Class<T> getType() {
75 return type;
76 }
77
78 public void setType(Class<T> type) {
79 this.type = type;
80 }
81 }