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 | 0 | public class HeaderColumnNameMappingStrategy<T> implements MappingStrategy<T> { |
29 | |
protected String[] header; |
30 | 0 | protected Map<String, PropertyDescriptor> descriptorMap = null; |
31 | |
protected Class<T> type; |
32 | |
|
33 | |
public void captureHeader(CSVReader reader) throws IOException { |
34 | 0 | header = reader.readNext(); |
35 | 0 | } |
36 | |
|
37 | |
public PropertyDescriptor findDescriptor(int col) throws IntrospectionException { |
38 | 0 | String columnName = getColumnName(col); |
39 | 0 | return (null != columnName && columnName.trim().length()>0) ? findDescriptor(columnName) : null; |
40 | |
} |
41 | |
|
42 | |
protected String getColumnName(int col) { |
43 | 0 | return (null != header && col < header.length) ? header[col] : null; |
44 | |
} |
45 | |
protected PropertyDescriptor findDescriptor(String name) throws IntrospectionException { |
46 | 0 | if (null == descriptorMap) descriptorMap = loadDescriptorMap(getType()); |
47 | 0 | return descriptorMap.get(name.toUpperCase().trim()); |
48 | |
} |
49 | |
protected boolean matches(String name, PropertyDescriptor desc) { |
50 | 0 | return desc.getName().equals(name.trim()); |
51 | |
} |
52 | |
|
53 | |
protected Map<String, PropertyDescriptor> loadDescriptorMap(Class<T> cls) throws IntrospectionException |
54 | |
{ |
55 | 0 | Map<String, PropertyDescriptor> map = new HashMap<String, PropertyDescriptor>(); |
56 | |
|
57 | |
PropertyDescriptor[] descriptors; |
58 | 0 | descriptors = loadDescriptors(getType()); |
59 | 0 | for (PropertyDescriptor descriptor : descriptors) |
60 | |
{ |
61 | 0 | map.put(descriptor.getName().toUpperCase().trim(), descriptor); |
62 | |
} |
63 | |
|
64 | 0 | return map; |
65 | |
} |
66 | |
|
67 | |
private PropertyDescriptor[] loadDescriptors(Class<T> cls) throws IntrospectionException { |
68 | 0 | BeanInfo beanInfo = Introspector.getBeanInfo(cls); |
69 | 0 | return beanInfo.getPropertyDescriptors(); |
70 | |
} |
71 | |
public T createBean() throws InstantiationException, IllegalAccessException { |
72 | 0 | return type.newInstance(); |
73 | |
} |
74 | |
public Class<T> getType() { |
75 | 0 | return type; |
76 | |
} |
77 | |
|
78 | |
public void setType(Class<T> type) { |
79 | 0 | this.type = type; |
80 | 0 | } |
81 | |
} |