JCR with Scala: Adding Nodes
In a previous post I showed how to access a JCR compliant repository with Scala. This time I show how to add child nodes to a given node. Again I leverage Scala's implicit parameters mechanism to retroactively extend the Node class. A working example of the following code is available from my personal blog.
My goal was to define an operator for adding nodes in such a way that the tree structure of the nodes becomes apparent just from looking at the code. Optimally the code would look similar to an ASCII art drawing of a file system hierarchy.
????mobile
????monads
????parsing
? ????lambda
? ????test
????pilib
????tcpoly
? ????collection
? ????monads
????xml
????phonebook
To achieve this I had to come up with a chainable mechanism to recursively add child nodes to a parent node. Two operators are involved in this mechanism: one for adding nodes and another for opening a new branch. The operator for adding a child node to a parent node is just an alias for JCR's addNode method:
def ¦-(relPath: String) = node.addNode(relPath)
def ¦-(relPath: String, tyqe: String) =
node.addNode(relPath, tyqe)
The operator for opening a new branch is a bit trickier:
def -+[T](f: Node => T) = f(node)
It takes a lambda expression and applies it to the node it was called on. That way a block of code following the -+ operator receives a binding for its parent node. It can then use this binding to recursively add further nodes and branches. With these operators in place adding new nodes to a parent node can be expressed in a very concise way:
def addSubtree(n: Node) {
n ¦- "1" -+ { n: Node =>
n ¦- "i"
n ¦- "ii"
n ¦- "iii"
n ¦- "iv"
n ¦- "v"
}
n ¦- "2"
n ¦- "3" -+ { n: Node =>
n ¦- "i"
n ¦- "ii" -+ { n: Node =>
n ¦- "a"
n ¦- "b"
n ¦- "c"
}
n ¦- "iii"
n ¦- "iv"
n ¦- "v"
}
n ¦- "4"
n ¦- "5"
n ¦- ("6", "nt:file")
}
Extending this mechanism to single valued properties is straightforward. Handling multi valued properties in a consistent way (i.e. allowing the property's value to be passed as sequence) turns out to be much more difficult. I will write more about this in a later post.
