From 276ee681dd0f4f363f0d901b326610af59c23045 Mon Sep 17 00:00:00 2001 From: Sylvain Royer Date: Tue, 21 Apr 2015 17:59:17 -0700 Subject: [PATCH] Add abstractcsvexporter and gitignore to ooo-utils --- .gitignore | 1 + .../threerings/util/AbstractCsvExporter.java | 72 +++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 .gitignore create mode 100644 src/main/java/com/threerings/util/AbstractCsvExporter.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/src/main/java/com/threerings/util/AbstractCsvExporter.java b/src/main/java/com/threerings/util/AbstractCsvExporter.java new file mode 100644 index 0000000..793d6e5 --- /dev/null +++ b/src/main/java/com/threerings/util/AbstractCsvExporter.java @@ -0,0 +1,72 @@ +// +// $Id: AbstractCsvExporter.java 36591 2014-03-18 17:54:12Z ray $ + +package com.threerings.util; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import java.util.List; + +import com.google.common.base.CharMatcher; +import com.google.common.base.Function; +import com.google.common.base.Joiner; +import com.google.common.collect.Iterables; +import com.google.common.collect.Ordering; + +import static com.threerings.util.Log.log; + +/** + * Abstract class for exporting information to csv. + */ +public abstract class AbstractCsvExporter +{ + /** + * The details of an individual row. + */ + public interface Details> + extends Comparable + { + public List toRow (); + } + + /** + * Export the rows to a file. + */ + protected static void export ( + File file, List headers, Iterable> rows) + { + try { + PrintStream ps = new PrintStream(new FileOutputStream(file), true, "UTF-8"); + ps.println(toCsv(headers)); + for (Details row : Ordering.natural().immutableSortedCopy(rows)) { + ps.println(toCsv(row.toRow())); + } + ps.close(); + } catch (IOException ioe) { + log.warning("Error creating file.", "file", file, ioe); + } + } + + /** + * Convert the row to csv. + */ + protected static String toCsv (List row) + { + return Joiner.on(',').join( + Iterables.transform( + row, + new Function() { + public Object apply (Object o) { + if ((o == null) || (o instanceof Number) || (o instanceof Boolean)) { + return o; + } + // quotes need to be escaped by doubling them + return "\"" + CharMatcher.is('"').replaceFrom(String.valueOf(o), "\"\"") + + "\""; + } + })); + } +}