0

I am creating a bean processor and setting setStrictHeaderValidationEnabled to true. Now my CsvParserSettings are consuming this bean processor which in turn is consumed by CSVRoutines. But on iterating through csvroutines the bean processor does not validate headers and subsequent rows get converted to beans for files with invalid headers as well

Sample Code-

        final BeanProcessor<TestBean> rowProcessor = new BeanProcessor<TestBean>(TestBean.class) {

        @Override
        public void beanProcessed(TestBean bean, ParsingContext context) {

        }
    };
    rowProcessor.setStrictHeaderValidationEnabled(true);
    final CsvParserSettings parserSettings = new CsvParserSettings();
    parserSettings.setProcessor(rowProcessor);
    parserSettings.setHeaderExtractionEnabled(true);
    parserSettings.getFormat().setDelimiter(',');
    CsvRoutines routines = new CsvRoutines(parserSettings);
    for(TestBean bean : routines.iterate(TestBean.class, inputFile, StandardCharsets.UTF_8)) {
        try {
            System.out.println(OBJECT_MAPPER.writeValueAsString(bean));
        } catch (JsonProcessingException e) {

            e.printStackTrace();
        }
    }

Note: TestBean uses @Parsed annotation of univocity to set column names.

Harsh
  • 75
  • 5

1 Answers1

0

The iterate method returns a IterableResult, which provides you the ParsingContext from which you can get the headers parsed from the input.

Try this code:

    IterableResult<TestBean, ParsingContext> iterableResult = routines.iterate(TestBean.class, inputFile, StandardCharsets.UTF_8);
    ResultIterator<TestBean, ParsingContext> iterator = iterableResult.iterator();
    ParsingContext context = iterator.getContext();

    String[] headers = context.headers();
    //HEADERS HERE:
    System.out.println(Arrays.toString(headers));

    while(iterator.hasNext()){
        try {
            System.out.println(OBJECT_MAPPER.writeValueAsString(iterator.next()));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

Hope it helps

Jeronimo Backes
  • 6,141
  • 2
  • 25
  • 29
  • Thanks for the reply. But the actual issue I am facing is, on just using BeanProcessor and parsing the file, the file parsing fails for invalid headers. But on using beanprocessor with csvroutines, file is getting parsed for invalid headers as well. I want csvroutines iterator to validate header as well. I have rephrased the question. Thanks – Harsh Jun 09 '18 at 13:57
  • 1
    @Harsh, that is currently not supported as the CsvRoutines is a shorthand that creates a new `BeanProcessor` internally and doesn't use the one you give in your settings. You can copy the code used in `CsvRoutines` to iterate over beans and adjust it to do what you need. – Jeronimo Backes Jun 09 '18 at 21:20