Search code examples
javaopencsv

OpenCsv - set custom validation on field


I am using OpenCsv to convert a csv file into Java Bean.

My file looks like this:

USER_NAME, USER_ID, FREQUENCY
aaa,111,DAILY
bbb,222,WEEKLY,
ccc,333,MONTHLY
ddd,444,SOME_RANDOM_VALUE
eee,555,YEARLY

I need to enforce the below validation on the columns:

USER_NAME -> not null, alphabets only
USER_ID -> not null, digits only
FREQUENCY -> not null, allowed values - DAILY, WEEKLY, MONTHLY, YEARLY

For any other value of FREQUENCY, log the USER_NAME, column as given below: dddd, FREQUENCY

I only need the line to be logged and the flow to continue as usual, i.e. 'eeee' should be mapped to the java bean.

Based on Opencsv custom logic in parcing, I created the following logic in the java bean.

The trouble is that the flow stops with 'dddd' and 'eeee' is not mapped.

class UserBean {

    private String userName;
    private String userID;
    private String frequency;

    //Getters and Setters for userName, userID
    public void setFrequency(String frequency) {
        if(frequency.isEmpty() && !(frequency.equalsIgnoreCase("DAILY") && frequency.equalsIgnoreCase("WEEKLY") && frequency.equalsIgnoreCase("MONTHLY") && frequency.equalsIgnoreCase("YEARLY"))) {
            throw new IllegalArgumentException("Invalid value for FREQUENCY"); 
        }
    }
}

public static void main() {

            CsvToBean<UserBean> csvToBean = new CsvToBean<UserBean>();
            Reader reader = new FileReader((File) INPUT_DIR);
            csvToBean = new CsvToBeanBuilder(reader).withSeparator(',')
                    .withType(User.class)
                    .withOrderedResults(true)
                    .withIgnoreLeadingWhiteSpace(true)
                    .build();
            Iterator<PrimeAOBean> csvUserIterator = csvToBean.iterator();

            List<Exception> exceptionList = new ArrayList<Exception>();

            while (csvUserIterator.hasNext()) {
                try {
                UserBean userBean = csvUserIterator.next();
                userDataMap.put(userBean.getUserID(), userBean);
                }
                catch(Exception e) {
                    exceptionList.add(e);
                    continue;
                }
                finally {
                    FileWriter fileWriter = new FileWriter(ERROR_DIR);
                    PrintWriter printWriter = new PrintWriter(fileWriter);
                    for (Exception excep: exceptionList) {
                        printWriter.print(excep.getLocalizedMessage());
                        printWriter.close();
                    }
                    continue;
                }
            }               
                }

Solution

  • You can add .withThrowExceptions(false) to ignore runtime exception as described here