public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
context.pushDocumentContext();
try {
ExtendedXMLStreamReader reader;
NodeValue nv = (NodeValue) args[0].itemAt(0);
if (nv.getImplementationType() == NodeValue.IN_MEMORY_NODE) {
NodeImpl node = (NodeImpl) nv;
reader = new InMemoryXMLStreamReader(node.getDocument(), node.getDocument());
} else {
NodeProxy proxy = (NodeProxy) nv;
reader = context.getBroker().newXMLStreamReader(new NodeProxy(proxy.getDocument(), NodeId.DOCUMENT_NODE, proxy.getDocument().getFirstChildAddress()), false);
}
nv = (NodeValue) args[1].itemAt(0);
if (nv.getImplementationType() == NodeValue.IN_MEMORY_NODE)
throw new XPathException("patch cannot be applied to in-memory documents");
NodeProxy diffProxy = (NodeProxy) nv;
DocumentImpl diff = diffProxy.getDocument();
MemTreeBuilder builder = context.getDocumentBuilder();
DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
Patch patch = new Patch(context.getBroker(), diff);
if (isCalledAs("annotate"))
patch.annotate(reader, receiver);
else
patch.patch(reader, receiver);
NodeValue result = (NodeValue) builder.getDocument().getDocumentElement();
return result == null ? Sequence.EMPTY_SEQUENCE : result;
} catch (IOException e) {
throw new XPathException(this, e.getMessage(), e);
} catch (XMLStreamException e) {
throw new XPathException(this, e.getMessage(), e);