-
Notifications
You must be signed in to change notification settings - Fork 100
/
RowParser.java
471 lines (425 loc) · 16.9 KB
/
RowParser.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/*
* Copyright 2020 Google LLC, MobilityData IO
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mobilitydata.gtfsvalidator.parsing;
import java.math.BigDecimal;
import java.time.ZoneId;
import java.util.Currency;
import java.util.Locale;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.mobilitydata.gtfsvalidator.annotation.FieldLevelEnum;
import org.mobilitydata.gtfsvalidator.notice.EmptyRowNotice;
import org.mobilitydata.gtfsvalidator.notice.InvalidColorNotice;
import org.mobilitydata.gtfsvalidator.notice.InvalidCurrencyNotice;
import org.mobilitydata.gtfsvalidator.notice.InvalidDateNotice;
import org.mobilitydata.gtfsvalidator.notice.InvalidFloatNotice;
import org.mobilitydata.gtfsvalidator.notice.InvalidIntegerNotice;
import org.mobilitydata.gtfsvalidator.notice.InvalidLanguageCodeNotice;
import org.mobilitydata.gtfsvalidator.notice.InvalidRowLengthNotice;
import org.mobilitydata.gtfsvalidator.notice.InvalidTimeNotice;
import org.mobilitydata.gtfsvalidator.notice.InvalidTimezoneNotice;
import org.mobilitydata.gtfsvalidator.notice.MissingRecommendedFieldNotice;
import org.mobilitydata.gtfsvalidator.notice.MissingRequiredFieldNotice;
import org.mobilitydata.gtfsvalidator.notice.NoticeContainer;
import org.mobilitydata.gtfsvalidator.notice.NumberOutOfRangeNotice;
import org.mobilitydata.gtfsvalidator.notice.TooManyRowsNotice;
import org.mobilitydata.gtfsvalidator.notice.UnexpectedEnumValueNotice;
import org.mobilitydata.gtfsvalidator.notice.ValidationNotice;
import org.mobilitydata.gtfsvalidator.table.GtfsColumnDescriptor;
import org.mobilitydata.gtfsvalidator.table.GtfsEnum;
import org.mobilitydata.gtfsvalidator.type.GtfsColor;
import org.mobilitydata.gtfsvalidator.type.GtfsDate;
import org.mobilitydata.gtfsvalidator.type.GtfsTime;
import org.mobilitydata.gtfsvalidator.validator.GtfsCellContext;
import org.mobilitydata.gtfsvalidator.validator.GtfsFieldValidator;
/**
* Parses cells of a CSV row as values of requested data types.
*
* <p>Interface functions of this class receive an instance of {@code NoticeContainer}. If a cell
* value cannot be parsed, these functions add a notice to the container, return null and don't
* throw an exception.
*/
public class RowParser {
private final String fileName;
private final CsvHeader header;
private final GtfsFieldValidator fieldValidator;
private CsvRow row;
// The largest CSV files contain about 100 M rows (as of 2022). Set the limit to 1 billion.
private static final long MAX_ROW_NUMBER = 1000000000;
private NoticeContainer noticeContainer;
public RowParser(String fileName, CsvHeader header, GtfsFieldValidator fieldValidator) {
this.fileName = fileName;
this.header = header;
this.fieldValidator = fieldValidator;
}
public void setRow(CsvRow row, NoticeContainer noticeContainer) {
this.row = row;
this.noticeContainer = noticeContainer;
}
public NoticeContainer getNoticeContainer() {
return noticeContainer;
}
public int getRowNumber() {
return (int) row.getRowNumber();
}
public boolean checkRowNumber() {
if (row.getRowNumber() > MAX_ROW_NUMBER) {
noticeContainer.addValidationNotice(new TooManyRowsNotice(fileName, row.getRowNumber()));
return false;
}
return true;
}
/**
* Checks whether the row lengths (cell count) is the same as the amount of file headers.
*
* <p>This function may add notices to {@code noticeContainer}.
*
* @return true if the row length is equal to column count
*/
public boolean checkRowLength() {
final int rowColumnCount = row.getColumnCount();
if (rowColumnCount == 0) {
// Empty row.
return false;
}
if (rowColumnCount == 1 && row.asString(0) == null) {
// If the last row has only spaces and does not end with a newline, then Univocity parser
// interprets it as a non-empty row that has a single column which is empty (sic!). We are
// unsure if this is a bug or feature in Univocity, so we show a warning.
noticeContainer.addValidationNotice(new EmptyRowNotice(fileName, getRowNumber()));
return false;
}
if (rowColumnCount != header.getColumnCount()) {
noticeContainer.addValidationNotice(
new InvalidRowLengthNotice(
fileName, getRowNumber(), rowColumnCount, header.getColumnCount()));
return false;
}
return true;
}
@Nullable
public String asString(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
String s = row.asString(columnIndex);
if (columnDescriptor.fieldLevel() == FieldLevelEnum.REQUIRED && s == null) {
noticeContainer.addValidationNotice(
new MissingRequiredFieldNotice(fileName, getRowNumber(), columnDescriptor.columnName()));
} else if (columnDescriptor.fieldLevel() == FieldLevelEnum.RECOMMENDED && s == null) {
noticeContainer.addValidationNotice(
new MissingRecommendedFieldNotice(
fileName, getRowNumber(), columnDescriptor.columnName()));
}
if (s != null) {
s =
fieldValidator.validateField(
s,
GtfsCellContext.create(fileName, getRowNumber(), header.getColumnName(columnIndex)),
noticeContainer);
}
return s;
}
@Nullable
public String asText(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return asString(columnIndex, columnDescriptor);
}
@Nullable
public String asId(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return asValidatedString(columnIndex, columnDescriptor, fieldValidator::validateId);
}
@Nullable
public String asUrl(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return asValidatedString(columnIndex, columnDescriptor, fieldValidator::validateUrl);
}
@Nullable
public String asEmail(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return asValidatedString(columnIndex, columnDescriptor, fieldValidator::validateEmail);
}
/**
* Returns the string value of the phone number to be validated if a valid number according to the
* {@code CountryCode}, returns {@code null} otherwise. Note that if {@code CountryCode} is
* unknown, only phone number starting by "+" are validated.
*
* @param columnIndex the column index
* @param columnDescriptor Gtfs Column Descriptor
* @return the string value of the phone number to be validated if a valid number according to the
* {@code CountryCode}, returns {@code null} otherwise. Note that if {@code CountryCode} is
* unknown, only phone number starting by "+" are validated.
*/
@Nullable
public String asPhoneNumber(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return asValidatedString(columnIndex, columnDescriptor, fieldValidator::validatePhoneNumber);
}
@Nullable
/**
* Reads the value at the specified {@code columnIndex} and parses it as {@code Locale}.
*
* @param columnIndex the column index
* @param level whether the value is required, recommended or optional according to GTFS
* @return If parsing was successful returns {@code Locale}, otherwise, {@code null} is returned.
*/
public Locale asLanguageCode(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return parseAsType(
columnIndex, columnDescriptor, RowParser::parseLocale, InvalidLanguageCodeNotice::new);
}
/**
* Returns a well-formed IETF BCP 47 language tag representing this locale.
*
* @return a BCP47 locale representing the {@code languageTag}.
* @throws java.util.IllformedLocaleException if the {@code languageTag} doesn't match with IETF
* BCP 47 standard.
* @see java.util.Locale.Builder#setLanguageTag(String) and check how <a
* href="https://docs.oracle.com/javase/tutorial/i18n/locale/extensions.html">BCP 47
* Extensions</a> implemented in java.
*/
private static Locale parseLocale(String languageTag) {
return new Locale.Builder().setLanguageTag(languageTag).build();
}
@Nullable
public ZoneId asTimezone(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return parseAsType(columnIndex, columnDescriptor, ZoneId::of, InvalidTimezoneNotice::new);
}
@Nullable
public Currency asCurrencyCode(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return parseAsType(
columnIndex, columnDescriptor, Currency::getInstance, InvalidCurrencyNotice::new);
}
@Nullable
public Double asFloat(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return parseAsType(columnIndex, columnDescriptor, Double::parseDouble, InvalidFloatNotice::new);
}
@Nullable
public Double asFloat(
int columnIndex, GtfsColumnDescriptor columnDescriptor, NumberBounds bounds) {
return checkBounds(asFloat(columnIndex, columnDescriptor), 0.0, columnIndex, "float", bounds);
}
@Nullable
public Double asLatitude(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
Double value = asFloat(columnIndex, columnDescriptor);
if (value != null && !(-90 <= value && value <= 90)) {
noticeContainer.addValidationNotice(
new NumberOutOfRangeNotice(
fileName,
getRowNumber(),
header.getColumnName(columnIndex),
"latitude within [-90, 90]",
value));
return value;
}
return value;
}
@Nullable
public Double asLongitude(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
Double value = asFloat(columnIndex, columnDescriptor);
if (value != null && !(-180 <= value && value <= 180)) {
noticeContainer.addValidationNotice(
new NumberOutOfRangeNotice(
fileName,
getRowNumber(),
header.getColumnName(columnIndex),
"longitude within [-180, 180]",
value));
return value;
}
return value;
}
@Nullable
public Integer asInteger(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return parseAsType(columnIndex, columnDescriptor, Integer::parseInt, InvalidIntegerNotice::new);
}
@Nullable
public Integer asInteger(
int columnIndex, GtfsColumnDescriptor columnDescriptor, NumberBounds bounds) {
return checkBounds(asInteger(columnIndex, columnDescriptor), 0, columnIndex, "integer", bounds);
}
@Nullable
public BigDecimal asDecimal(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return parseAsType(columnIndex, columnDescriptor, BigDecimal::new, InvalidFloatNotice::new);
}
@Nullable
public BigDecimal asDecimal(
int columnIndex, GtfsColumnDescriptor columnDescriptor, NumberBounds bounds) {
return checkBounds(
asDecimal(columnIndex, columnDescriptor),
new BigDecimal(0),
columnIndex,
"decimal",
bounds);
}
/**
* Checks that the value meets boundary requirements.
*
* @param value the value to check
* @param zero a zero instance for the given type
* @param columnIndex index of CSV column where the value is located
* @param typeName short descriptive type name, such as "integer"
* @param bounds boundary requirements
* @param <T> the actual type of the value
* @return the same value as passed to the function
*/
private <T extends Comparable<T>> T checkBounds(
@Nullable T value, T zero, int columnIndex, String typeName, NumberBounds bounds) {
if (value == null) {
return null;
}
final int compareToZero = value.compareTo(zero);
switch (bounds) {
case POSITIVE:
if (compareToZero <= 0) {
noticeContainer.addValidationNotice(
new NumberOutOfRangeNotice(
fileName,
getRowNumber(),
header.getColumnName(columnIndex),
"positive " + typeName,
value));
}
break;
case NON_NEGATIVE:
if (compareToZero < 0) {
noticeContainer.addValidationNotice(
new NumberOutOfRangeNotice(
fileName,
getRowNumber(),
header.getColumnName(columnIndex),
"non-negative " + typeName,
value));
}
break;
case NON_ZERO:
if (compareToZero == 0) {
noticeContainer.addValidationNotice(
new NumberOutOfRangeNotice(
fileName,
getRowNumber(),
header.getColumnName(columnIndex),
"non-zero " + typeName,
value));
}
break;
}
return value;
}
@Nullable
public GtfsColor asColor(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return parseAsType(
columnIndex, columnDescriptor, GtfsColor::fromString, InvalidColorNotice::new);
}
@Nullable
public <E extends GtfsEnum> Integer asEnum(
int columnIndex,
GtfsColumnDescriptor columnDescriptor,
EnumCreator<E> enumCreator,
E unrecognized) {
Integer i = asInteger(columnIndex, columnDescriptor);
if (i == null) {
return null;
}
if (enumCreator.convert(i) == null) {
noticeContainer.addValidationNotice(
new UnexpectedEnumValueNotice(
fileName, getRowNumber(), header.getColumnName(columnIndex), i));
return unrecognized.getNumber();
}
return i;
}
@Nullable
public GtfsTime asTime(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return parseAsType(columnIndex, columnDescriptor, GtfsTime::fromString, InvalidTimeNotice::new);
}
@Nullable
public GtfsDate asDate(int columnIndex, GtfsColumnDescriptor columnDescriptor) {
return parseAsType(columnIndex, columnDescriptor, GtfsDate::fromString, InvalidDateNotice::new);
}
public enum NumberBounds {
POSITIVE,
NON_NEGATIVE,
NON_ZERO,
}
@FunctionalInterface
public interface EnumCreator<E> {
E convert(int t);
}
/**
* Parses a string to a given type: {@link GtfsTime}, {@link GtfsColor} etc. and adds notices if
* parsing failed.
*
* @param columnIndex index of the column to parse
* @param columnDescriptor Gtfs Column Descriptor
* @param parsingFunction function that converts string to an object to return
* @param noticingFunction function to create a notice about parse errors
* @param <T> the type to return
* @return a parsed object or null if the value is missing or invalid
*/
@Nullable
private <T> T parseAsType(
int columnIndex,
GtfsColumnDescriptor columnDescriptor,
Function<String, T> parsingFunction,
NoticingFunction noticingFunction) {
String s = asString(columnIndex, columnDescriptor);
if (s == null) {
return null;
}
try {
return parsingFunction.apply(s);
} catch (RuntimeException e) {
// Most parsing functions throw an IllegalArgumentException but ZoneId.of() throws
// a ZoneRulesException or DateTimeException. Be sure to catch all of them.
noticeContainer.addValidationNotice(
noticingFunction.apply(fileName, getRowNumber(), header.getColumnName(columnIndex), s));
return null;
}
}
/**
* Validates a string as URL, phone number etc. and adds notices for invalid values.
*
* <p>{@code validatingFunction} can emit errors or warnings to {@code noticeContainer}. If an
* error is emitted, the value is considered invalid.
*
* @param columnIndex index of the column to parse
* @param columnDescriptor GTFS column descriptor
* @param validatingFunction the predicate to validate a given string
* @return the cell value at the given column or null if the value is missing
*/
@Nullable
private String asValidatedString(
int columnIndex,
GtfsColumnDescriptor columnDescriptor,
FieldValidatingFunction validatingFunction) {
String s = asString(columnIndex, columnDescriptor);
if (s == null) {
return null;
}
validatingFunction.apply(
s,
GtfsCellContext.create(fileName, getRowNumber(), header.getColumnName(columnIndex)),
noticeContainer);
return s;
}
/**
* Generates a validation notice for the given value at the given position in a file.
*
* @param <T> the type of a returned notice
*/
@FunctionalInterface
private interface NoticingFunction<T extends ValidationNotice> {
T apply(String filename, int csvRowNumber, String fieldName, String fieldValue);
}
/** Validates the given field and adds appropriate notices to the container. */
@FunctionalInterface
private interface FieldValidatingFunction {
void apply(String fieldValue, GtfsCellContext cellContext, NoticeContainer noticeContainer);
}
}