uniVocity / univocity-parsers

uniVocity-parsers is a suite of extremely fast and reliable parsers for Java. It provides a consistent interface for handling different file formats, and a solid framework for the development of new parsers.
905 stars 249 forks source link

How to provide date formats dynamically for validation #448

Closed srknkbs closed 3 years ago

srknkbs commented 3 years ago

I am trying to validate Date fields in my project with univocity parser.

I know there are custom validation and format annotation in univocity. But there we need to provide static date formats while implementing bean classes.

@Format(formats = "yyyy-MM-dd")
private Date createdAt

I have a specific requirement that I need to provide date formats dynamically. This means I need to parse date fields as a string and then validate them against DateTimeFormatter after parsing csv file (kind of post verifier).

Is there a way to provide either passing validation arguments at runtime or does univocity support a verifier that is to process all beans after creation?

Thanks!

twonky4 commented 3 years ago

There is a possibility by setting converter to the processor:

import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.List;

import com.univocity.parsers.annotations.Parsed;
import com.univocity.parsers.common.processor.BeanListProcessor;
import com.univocity.parsers.conversions.Conversions;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;

public class DynamicDateFormatParser {
    public static void main(String[] args) {
        BeanListProcessor<CsvRecord> rowProcessor = new BeanListProcessor<CsvRecord>(CsvRecord.class);
        rowProcessor.convertIndexes(Conversions.toDate("dd.MM.yyyy")).set(1);

        CsvParserSettings settings = new CsvParserSettings();
        settings.setProcessor(rowProcessor);

        CsvParser parser = new CsvParser(settings);

        parser.parse(new ByteArrayInputStream("foo,31.12.2021,bar".getBytes()));

        List<CsvRecord> allRows = rowProcessor.getBeans();

        // 1 rows
        System.out.println(allRows.size() + " rows");

        // Fri Dec 31 00:00:00 CET 2021
        System.out.println(allRows.get(0).field2);
    }

    static class CsvRecord {
        @Parsed(index = 0)
        String field1;

        @Parsed(index = 1)
        Date field2;

        @Parsed(index = 3)
        String field3;
    }
}