View Javadoc
1   package com.opencsv.validators;
2   
3   import com.opencsv.exceptions.CsvValidationException;
4   
5   /**
6    * This validator is used when the number of columns is not neccessarily known but must be consistent.
7    * The first row validated will always be considered valid, unless null or empty, and after that the each
8    * subsequent row must have the same number of columns as the first.
9    * <p>
10   * Arrays that are empty or null are considered to have 0 elements.  An empty or null first row is considered
11   * invalid.
12   * <p>
13   * As with all row validators the assumption is you have control of the data and have skipped any initial
14   * empty lines.    If you have data that has empty lines or separators lines in your data then you should not
15   * use this class.   Either extend it or write your own validator.
16   *
17   * @author Scott Conway
18   * @since 5.0
19   */
20  public class RowMustHaveSameNumberOfColumnsAsFirstRowValidator implements RowValidator {
21      private static final int NO_ROWS = 0;
22      private int numRows = NO_ROWS;
23  
24      /**
25       * Default constructor.
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  }