-
Notifications
You must be signed in to change notification settings - Fork 866
/
OCSVExtractor.java
268 lines (224 loc) · 9.26 KB
/
OCSVExtractor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package com.orientechnologies.orient.etl.extractor;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.etl.OETLProcessor;
import com.orientechnologies.orient.etl.OExtractedItem;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import sun.misc.FloatConsts;
import java.io.IOException;
import java.io.Reader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by frank on 10/5/15.
*/
public class OCSVExtractor extends OAbstractSourceExtractor {
private static String NULL_STRING = "NULL";
protected OExtractedItem next;
private Map<String, OType> columnTypes = new HashMap<String, OType>();
private long skipFrom = -1;
private long skipTo = -1;
private Character stringCharacter = '"';
private boolean unicode = true;
private Iterator<CSVRecord> recordIterator;
private CSVFormat csvFormat;
private String nullValue = NULL_STRING;
private String dateFormat = "yyyy-MM-dd";
@Override
public ODocument getConfiguration() {
return new ODocument().fromJSON(
"{parameters:[" + getCommonConfigurationParameters() + ",{separator:{optional:true,description:'Column separator'}},"
+ "{columnsOnFirstLine:{optional:true,description:'Columns are described in the first line'}},"
+ "{columns:{optional:true,description:'Columns array containing names, and optionally type after : (e.g.: name:String, age:int'}},"
+ "{nullValue:{optional:true,description:'Value to consider as NULL_STRING. Default is NULL'}},"
+ "{dateFormat:{optional:true,description:'Date format used to parde dates. Default is yyyy-MM-dd'}},"
+ "{quote:{optional:true,description:'String character delimiter. Use \"\" to do not use any delimitator'}},"
+ "{ignoreEmptyLines:{optional:true,description:'Ignore empty lines',type:'boolean'}},"
+ "{skipFrom:{optional:true,description:'Line number where start to skip',type:'int'}},"
+ "{skipTo:{optional:true,description:'Line number where skip ends',type:'int'}}"
+ "{predefinedFormat:{optional:true,description:'Name of standard csv format (from Apache commons-csv): DEFAULT, EXCEL, MYSQL, RFC4180, TDF',type:'String'}}"
+ "],input:['String'],output:'ODocument'}");
}
@Override
public String getName() {
return "csv";
}
@Override
public String getUnit() {
return "rows";
}
@Override
public void configure(OETLProcessor iProcessor, ODocument iConfiguration, OCommandContext iContext) {
super.configure(iProcessor, iConfiguration, iContext);
csvFormat = CSVFormat.newFormat(',').withNullString(NULL_STRING).withEscape('\\').withQuote('"');
if (iConfiguration.containsField("predefinedFormat")) {
csvFormat = CSVFormat.valueOf(iConfiguration.<String>field("predefinedFormat").toUpperCase());
}
if (iConfiguration.containsField("separator")) {
csvFormat = csvFormat.withDelimiter(iConfiguration.field("separator").toString().charAt(0));
}
if (iConfiguration.containsField("dateFormat")) {
dateFormat = iConfiguration.<String>field("dateFormat");
}
if (iConfiguration.containsField("ignoreEmptyLines")) {
boolean ignoreEmptyLines = iConfiguration.field("ignoreEmptyLines");
csvFormat = csvFormat.withIgnoreEmptyLines(ignoreEmptyLines);
}
if (iConfiguration.containsField("columnsOnFirstLine")) {
Boolean columnsOnFirstLine = (Boolean) iConfiguration.field("columnsOnFirstLine");
if (columnsOnFirstLine.equals(Boolean.TRUE)) {
csvFormat = csvFormat.withHeader();
}
} else {
csvFormat = csvFormat.withHeader();
}
if (iConfiguration.containsField("columns")) {
final List<String> columns = iConfiguration.field("columns");
ArrayList<String> columnNames = new ArrayList<String>(columns.size());
columnTypes = new HashMap<String, OType>(columns.size());
for (String c : columns) {
final String[] parts = c.split(":");
columnNames.add(parts[0]);
if (parts.length > 1) {
columnTypes.put(parts[0], OType.valueOf(parts[1].toUpperCase()));
} else {
columnTypes.put(parts[0], OType.ANY);
}
}
csvFormat = csvFormat.withHeader(columnNames.toArray(new String[] {}));
}
if (iConfiguration.containsField("skipFrom")) {
skipFrom = ((Number) iConfiguration.field("skipFrom")).longValue();
}
if (iConfiguration.containsField("skipTo")) {
skipTo = ((Number) iConfiguration.field("skipTo")).longValue();
}
if (iConfiguration.containsField("nullValue")) {
nullValue = iConfiguration.<String>field("nullValue");
csvFormat = csvFormat.withNullString(nullValue);
}
if (iConfiguration.containsField("quote")) {
final String value = iConfiguration.field("quote").toString();
if (!value.isEmpty()) {
csvFormat = csvFormat.withQuote(value.charAt(0));
}
}
}
@Override
public void extract(final Reader iReader) {
super.extract(iReader);
try {
CSVParser parser = new CSVParser(iReader, csvFormat);
recordIterator = parser.iterator();
} catch (IOException e) {
throw new OExtractorException(e);
}
}
@Override
public boolean hasNext() {
if (recordIterator.hasNext()) {
CSVRecord csvRecord = recordIterator.next();
while (shouldSkipRecord(csvRecord) && recordIterator.hasNext()) {
csvRecord = recordIterator.next();
}
next = fetchNext(csvRecord);
return true;
}
return false;
}
private boolean shouldSkipRecord(CSVRecord csvRecord) {
return csvRecord.getRecordNumber() <= skipTo && csvRecord.getRecordNumber() >= skipFrom;
}
private OExtractedItem fetchNext(CSVRecord csvRecord) {
ODocument doc = new ODocument();
final Map<String, String> recordAsMap = csvRecord.toMap();
if (columnTypes.isEmpty()) {
for (Map.Entry<String, String> en : recordAsMap.entrySet()) {
final String value = en.getValue();
if (value == null || nullValue.equals(value) || value.isEmpty())
doc.field(en.getKey(), null, OType.ANY);
else
doc.field(en.getKey(), determineTheType(value));
}
} else {
for (Map.Entry<String, OType> typeEntry : columnTypes.entrySet()) {
final String fieldName = typeEntry.getKey();
final OType fieldType = typeEntry.getValue();
String fieldValueAsString = recordAsMap.get(fieldName);
try {
Object fieldValue = OType.convert(fieldValueAsString, fieldType.getDefaultJavaType());
doc.field(fieldName, fieldValue);
} catch (Exception e) {
processor.getStats().incrementErrors();
log(OETLProcessor.LOG_LEVELS.ERROR, "Error on converting row %d field '%s' (%d), value '%s' (class:%s) to type: %s",
csvRecord.getRecordNumber(), fieldName, fieldValueAsString, fieldValueAsString.getClass().getName(), fieldType);
}
}
}
log(OETLProcessor.LOG_LEVELS.DEBUG, "document=%s", doc);
current++;
return new OExtractedItem(current, doc);
}
@Override
public OExtractedItem next() {
return next;
}
private Object determineTheType(String fieldStringValue) {
Object fieldValue;
if ((fieldValue = transformToDate(fieldStringValue)) == null)// try maybe Date type
if ((fieldValue = transformToNumeric(fieldStringValue)) == null)// try maybe Numeric type
fieldValue = fieldStringValue; // type String
return fieldValue;
}
private Object transformToDate(String fieldStringValue) {
// DATE
DateFormat df = new SimpleDateFormat(dateFormat);
df.setLenient(true);
Object fieldValue;
try {
fieldValue = df.parse(fieldStringValue);
} catch (ParseException pe) {
fieldValue = null;
}
return fieldValue;
}
private Object transformToNumeric(final String fieldStringValue) {
if (fieldStringValue.isEmpty())
return fieldStringValue;
final char c = fieldStringValue.charAt(0);
if (c != '-' && !Character.isDigit(c))
// NOT A NUMBER FOR SURE
return fieldStringValue;
Object fieldValue;
try {
if (fieldStringValue.contains(".") || fieldStringValue.contains(",")) {
String numberAsString = fieldStringValue.replaceAll(",", ".");
fieldValue = new Float(numberAsString);
if (!isFinite((Float) fieldValue)) {
fieldValue = new Double(numberAsString);
}
} else {
try {
fieldValue = new Integer(fieldStringValue);
} catch (Exception e) {
fieldValue = new Long(fieldStringValue);
}
}
} catch (NumberFormatException nf) {
fieldValue = fieldStringValue;
}
return fieldValue;
}
/**
* Backport copy of Float.isFinite() method that was introduced since Java 1.8 but we must support 1.6. TODO replace after
* choosing Java 1.8 as minimal supported
**/
protected boolean isFinite(Float f) {
return Math.abs(f) <= FloatConsts.MAX_VALUE;
}
}