Menu

#167 Support validation against unknown columns

open
None
5
2024-12-15
2024-09-05
Gordon
No

I am using header name annotations.

Would it be possible to only allow known headers? i.e. headers annotated in bean class as either required or optional
From prod observations, unknown headers are user input errors, and ideally opencsv can validate against that input.
If thats not supported, can you provide guidance on where to inject custom validation?

Discussion

  • Gordon

    Gordon - 2024-12-09

    FWIW, I ended up adding a custom mapping strategy

    public class StrictColumnNameMappingStrategy<T> extends HeaderColumnNameMappingStrategy<T> {
    
        @Override
        public void captureHeader(CSVReader reader) throws IOException, CsvRequiredFieldEmptyException {
            super.captureHeader(reader);
    
            String[] header = headerIndex.getHeaderIndex();
            List<String> unknownHeaders = IntStream.rangeClosed(0, headerIndex.findMaxIndex())
                    .filter(column -> findField(column) == null)
                    .mapToObj(this::getColumnName)
                    .collect(Collectors.toList());
            if (!unknownHeaders.isEmpty()) {
                CsvUnknownFieldException csve = new CsvUnknownFieldException(
                        type,
                        String.format(
                                "Header contains unknown fields [%s]. The list of headers encountered is [%s].",
                                String.join(", ", unknownHeaders),
                                String.join(", ", header)));
                csve.setLine(header);
                throw csve;
            }
        }
    }
    
     
  • Scott Conway

    Scott Conway - 2024-12-13
    • assigned_to: Scott Conway
     
  • Scott Conway

    Scott Conway - 2024-12-15

    Gordon I am sorry it took so long to respond but life has been busy.

    The functionality you want is in the HeaderColumnNameTranslateMappingStrategy.

    If you look at the test code (either by downloading it or going to https://opencsv.sourceforge.net/xref-test/index.html) look at HeaderColumnNameTranslateMappingStrategyTest at the onlyConvertWhatIsInTheMap test.

    Hope that helps!

    Scott :)

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.