Skip to content

Instantly share code, notes, and snippets.

@robertwatts
Created December 5, 2013 17:14
Show Gist options
  • Save robertwatts/7809403 to your computer and use it in GitHub Desktop.
Save robertwatts/7809403 to your computer and use it in GitHub Desktop.
Read a CSV file containing un-ordered relationships, create a Node tree and pretty print
/**
* Parses an un-ordered CSV file with the following structure:
* parent_node name, parent_node id, node name, node id
*
* .. and populates a Node tree which is then walked over to pretty print.
*/
@Grab(group='net.sf.opencsv', module='opencsv', version='2.3')
import au.com.bytecode.opencsv.CSVReader;
/**
* Simple Node object that keeps data separate from object relationship
*/
class Node {
def children = new ArrayList<Node>()
Node parent
def data = [:]
def printPretty(sb, String indent, boolean last) {
def newIndent
sb.append(indent)
if (last) {
sb.append('\\-')
newIndent = indent + ' '
} else {
sb.append('| ')
newIndent = indent + '| '
}
sb.append(data.node_name)
if (children.size() > 0) sb.append(" [children: ${children.size()}]")
sb.append('\n')
for (int i=0; i<children.size(); i++) {
children.get(i).printPretty(sb, newIndent, i == children.size() - 1)
}
}
}
def csvFile = "parentchild.csv"
if (args.length > 0 && args[0]) csvFile = args[0]
System.out.println("Loading csv: " + csvFile)
def tree = [:] // A map of id to Node objects
def roots = [] // A list of root Node object
List<String[]> rows = new CSVReader(
new InputStreamReader(getClass().classLoader.getResourceAsStream(csvFile)))
.readAll()
rows.each() { row ->
def node = new Node()
node.data = [
parent_name: row[0],
parent_id: row[1],
node_name: row[2],
node_id: row[3]
]
if (node.data.parent_id == null || node.data.parent_id.isEmpty()) {
roots += node
}
tree[node.data.node_id] = node
}
// Associate parent-child nodes
tree.values().each {
if (tree.containsKey(it.data.parent_id)) {
def parent = tree[it.data.parent_id]
it.parent = parent
parent.children += it
}
}
def sb = new StringBuilder()
// Get roots
roots.each {
it.printPretty(sb, "", true)
}
System.out.println(sb.toString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment