# HG changeset patch # User casties # Date 1478200331 -3600 # Node ID 5b2a97d417d5873a50d8661873e5299af42641b4 # Parent d2833ab25c54d17199fa0c3a3469808fd0cf7068 new CsvEntityListWriter. diff -r d2833ab25c54 -r 5b2a97d417d5 src/main/java/org/mpi/openmind/repository/utils/CsvEntityListWriter.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/org/mpi/openmind/repository/utils/CsvEntityListWriter.java Thu Nov 03 20:12:11 2016 +0100 @@ -0,0 +1,75 @@ +/** + * + */ +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 entities, Appendable output) throws IOException { + Set attNameSet = new HashSet(); + /* + * 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(); + } +}