1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package io.wcm.qa.glnm.configuration;
21
22 import java.io.File;
23 import java.io.IOException;
24 import java.lang.reflect.InvocationTargetException;
25 import java.nio.charset.Charset;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Map;
29
30 import org.apache.commons.beanutils.BeanUtils;
31 import org.apache.commons.csv.CSVFormat;
32 import org.apache.commons.csv.CSVParser;
33 import org.apache.commons.csv.CSVRecord;
34 import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 import io.wcm.qa.glnm.exceptions.GaleniumException;
39
40
41
42
43
44
45 public final class CsvUtil {
46
47 private static final Charset CHARSET_UTF8 = Charset.forName("utf-8");
48 private static final CSVFormat FORMAT = CSVFormat.DEFAULT.withQuote(null).withHeader(new String[] {});
49
50 private static final Logger LOG = LoggerFactory.getLogger(CsvUtil.class);
51
52 private CsvUtil() {
53
54 }
55
56
57
58
59
60
61
62
63 public static CSVParser parse(File csvFile) {
64 return parse(csvFile, false);
65 }
66
67
68
69
70
71
72
73
74
75 public static CSVParser parse(File csvFile, boolean skipHeaderRecord) {
76 if (csvFile == null) {
77 throw new GaleniumException("error when checking CSV input: file is null");
78 }
79 if (!csvFile.isFile()) {
80 throw new GaleniumException("error when reading CSV file: '" + csvFile.getPath() + "'");
81 }
82 try {
83 CSVFormat format = FORMAT.withSkipHeaderRecord(skipHeaderRecord);
84 return CSVParser.parse(csvFile, CHARSET_UTF8, format);
85 }
86 catch (IOException ex) {
87 throw new GaleniumException("error when parsing CSV file: '" + csvFile.getPath() + "'", ex);
88 }
89 }
90
91
92
93
94
95
96
97
98 public static CSVParser parse(String csvFilePath) {
99 return parse(new File(csvFilePath));
100 }
101
102
103
104
105
106
107
108
109
110
111 public static <T> Collection<T> parseToBeans(File csvFile, Class<T> beanClass) {
112 Collection<T> result = new ArrayList<>();
113 CSVParser parse = parse(csvFile);
114 for (CSVRecord csvRecord : parse) {
115 Map<String, String> map = csvRecord.toMap();
116 LOG.debug("from csv: " + csvRecord);
117 LOG.debug("from csv: " + ReflectionToStringBuilder.toString(csvRecord));
118 LOG.debug("map from csv: " + ReflectionToStringBuilder.toString(map));
119 try {
120 T newInstance = beanClass.newInstance();
121 BeanUtils.populate(newInstance, map);
122 LOG.debug("populated: " + newInstance);
123 result.add(newInstance);
124 }
125 catch (IllegalAccessException | InvocationTargetException | InstantiationException ex) {
126 throw new GaleniumException("error when constructing bean from CSV: '" + csvFile.getPath() + "'", ex);
127 }
128 }
129 return result;
130 }
131
132 }