Mercurial > hg > openmind
view src/main/java/org/mpi/openmind/repository/utils/CsvEntityListWriter.java @ 52:5b2a97d417d5
new CsvEntityListWriter.
author | casties |
---|---|
date | Thu, 03 Nov 2016 20:12:11 +0100 |
parents | |
children | 94d354107165 |
line wrap: on
line source
/** * */ package org.mpi.openmind.repository.utils; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.QuoteMode; import org.apache.commons.lang.ArrayUtils; import org.mpi.openmind.repository.bo.Attribute; import org.mpi.openmind.repository.bo.Entity; /** * Class that creates a CSV file from a List of Entities. * * Creates columns for all Attributes. * * @author casties * */ public class CsvEntityListWriter { public static void writeEntities(List<Entity> entities, Appendable output) throws IOException { Set<String> attNameSet = new HashSet<String>(); /* * create a list of all attribute names */ for (Entity entity : entities) { for (Attribute att : entity.getAttributes()) { attNameSet.add(att.getName()); } } String[] attNames = attNameSet.toArray(new String[attNameSet.size()]); String[] entProps = new String[] {"id", "object_class", "own_value"}; String[] headers = (String[]) ArrayUtils.addAll(entProps, attNames); // create CSV format with header CSVFormat format = CSVFormat.DEFAULT.withHeader(headers).withQuoteMode(QuoteMode.NON_NUMERIC); // create CSVPrinter CSVPrinter printer = new CSVPrinter(output, format); /* * print all Entities */ for (Entity entity : entities) { for (String field : headers) { if (field.equals("id")) { printer.print(entity.getId()); } else if (field.equals("object_class")) { printer.print(entity.getObjectClass()); } else if (field.equals("own_value")) { printer.print(entity.getOwnValue()); } else { // print attribute Attribute att = entity.getAttributeByName(field); if (att != null) { printer.print(att.getOwnValue()); } else { printer.print(null); } } } printer.println(); } printer.flush(); printer.close(); } }