| 1 | |
package liquibase.util.csv.opencsv.bean; |
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | |
|
| 16 | |
import liquibase.util.csv.opencsv.CSVReader; |
| 17 | |
|
| 18 | |
import java.beans.IntrospectionException; |
| 19 | |
import java.beans.PropertyDescriptor; |
| 20 | |
import java.beans.PropertyEditor; |
| 21 | |
import java.beans.PropertyEditorManager; |
| 22 | |
import java.io.Reader; |
| 23 | |
import java.lang.reflect.InvocationTargetException; |
| 24 | |
import java.util.ArrayList; |
| 25 | |
import java.util.List; |
| 26 | |
|
| 27 | |
public class CsvToBean { |
| 28 | |
|
| 29 | 0 | public CsvToBean() { |
| 30 | 0 | } |
| 31 | |
|
| 32 | |
public List parse(MappingStrategy mapper, Reader reader) { |
| 33 | |
try { |
| 34 | 0 | CSVReader csv = new CSVReader(reader); |
| 35 | 0 | mapper.captureHeader(csv); |
| 36 | |
String[] line; |
| 37 | 0 | List list = new ArrayList(); |
| 38 | 0 | while (null != (line = csv.readNext())) { |
| 39 | 0 | Object obj = processLine(mapper, line); |
| 40 | 0 | list.add(obj); |
| 41 | 0 | } |
| 42 | 0 | return list; |
| 43 | 0 | } catch (Exception e) { |
| 44 | 0 | throw new RuntimeException("Error parsing CSV!", e); |
| 45 | |
} |
| 46 | |
} |
| 47 | |
|
| 48 | |
protected Object processLine(MappingStrategy mapper, String[] line) throws IllegalAccessException, |
| 49 | |
InvocationTargetException, InstantiationException, IntrospectionException { |
| 50 | 0 | Object bean = mapper.createBean(); |
| 51 | 0 | for (int col = 0; col < line.length; col++) { |
| 52 | 0 | String value = line[col]; |
| 53 | 0 | PropertyDescriptor prop = mapper.findDescriptor(col); |
| 54 | 0 | if (null != prop) { |
| 55 | 0 | Object obj = convertValue(value, prop); |
| 56 | 0 | prop.getWriteMethod().invoke(bean, new Object[] { obj }); |
| 57 | |
} |
| 58 | |
} |
| 59 | 0 | return bean; |
| 60 | |
} |
| 61 | |
|
| 62 | |
protected Object convertValue(String value, PropertyDescriptor prop) throws InstantiationException, |
| 63 | |
IllegalAccessException { |
| 64 | 0 | PropertyEditor editor = getPropertyEditor(prop); |
| 65 | 0 | Object obj = value; |
| 66 | 0 | if (null != editor) { |
| 67 | 0 | editor.setAsText(value); |
| 68 | 0 | obj = editor.getValue(); |
| 69 | |
} |
| 70 | 0 | return obj; |
| 71 | |
} |
| 72 | |
|
| 73 | |
|
| 74 | |
|
| 75 | |
|
| 76 | |
protected PropertyEditor getPropertyEditor(PropertyDescriptor desc) throws InstantiationException, |
| 77 | |
IllegalAccessException { |
| 78 | 0 | Class cls = desc.getPropertyEditorClass(); |
| 79 | 0 | if (null != cls) |
| 80 | 0 | return (PropertyEditor) cls.newInstance(); |
| 81 | 0 | return PropertyEditorManager.findEditor(desc.getPropertyType()); |
| 82 | |
} |
| 83 | |
|
| 84 | |
} |