0

I’d like to make Univocity use annotated bean instances to determine a part of the CSV contents, namely, the first few columns only. The rest of the columns are provided by some complicated programming logic, that is independent of the bean instances or types.

I understand that Univocity can transform annotated beans to records, but I can’t find how to process an annotated bean with Univocity to obtain a partial record while I programmatically determine the rest of the record without using annotated beans.

The bean would be annotated with @Headers and with @Parsed annotations. (The annotated bean would be provided by the user of my library.)

I would like to implement something functionally equivalent to the following.

public void toCsv(Map<UserBean, MyContent> entries) {
    CsvWriter writer = …
    List<String> beanHeaders = someUnivocityHelper.getAsHeaders(UserBean.class);
    List<String> allHeaders = ImmutableList.builder().addAll(beanHeaders).addAll(myHeaders).build();
    writer.writeHeaders(allHeaders);
    for (Entry<UserBean, MyContent> entry : entries.entrySet()) {
        UserBean userBean = entry.getKey();
        Map<String, Object> beanAsMap = someUnivocityHelper.getAsMap(userBean);
        beanAsMap.entrySet().stream().forEach(e -> writer.addValue(e.getKey(), e.getValue()));
        MyContent content = entry.getValue();
        // Here I use content and the writer to write the rest of the record
        …
        writer.writeValuesToRow();
    }
}

How can I retrieve the headers from a bean class and the parsed values from bean instances using univocity?

Olivier Cailloux
  • 977
  • 9
  • 24

1 Answers1

0

To read headers only defined in bean you can probably try @Headers(extract=true), so library will use annotations from a user bean. After If you want write more headers - just set all required headers to csv writer: CsvWriterSettings.setHeaders(allHeaders).

Also take a look on com.univocity.parsers.annotations.helpers.AnnotationHelper public class.

art
  • 174
  • 1
  • 9
  • Thanks. [AnnotationHelper](https://www.javadoc.io/doc/com.univocity/univocity-parsers/latest/com/univocity/parsers/annotations/helpers/AnnotationHelper.html) seems promising. But I am not sure I can effectively use it for my purpose. I need to transform bean _instances_ to a map of property names and values. This helper seems to only provide partial means to explore annotations to discover how this mapping should be done. Even assuming I’d get all required information, it seems that I would still be left with the work of effectively extracting information from the bean instances. – Olivier Cailloux Jun 13 '20 at 12:24