1 package com.opencsv.validators;
2
3 import com.opencsv.exceptions.CsvValidationException;
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 public class RowMustHaveSameNumberOfColumnsAsFirstRowValidator implements RowValidator {
21 private static final int NO_ROWS = 0;
22 private int numRows = NO_ROWS;
23
24
25
26
27 public RowMustHaveSameNumberOfColumnsAsFirstRowValidator() {
28 }
29
30 @Override
31 public boolean isValid(String[] row) {
32 if (row == null || row.length == 0) {
33 return false;
34 }
35
36 if (firstRowNotSetYet()) {
37 numRows = row.length;
38 }
39 return row.length == numRows;
40 }
41
42 @Override
43 public void validate(String[] row) throws CsvValidationException {
44 if (!isValid(row)) {
45 if (firstRowNotSetYet()) {
46 throw new CsvValidationException("First row should not be empty or null");
47 } else if (row == null || row.length == 0) {
48 throw new CsvValidationException("Row should not be empty or null");
49 } else {
50 throw new CsvValidationException(String.format("Row was expected to have %d elements but had %d instead", numRows, row.length));
51 }
52
53 }
54 }
55
56 private boolean firstRowNotSetYet() {
57 return numRows == NO_ROWS;
58 }
59 }