// 'replace' is actually a 'remove existing/add new' operation;
// this unfortunately changes the order of this node's
// child node entries (JCR-1055);
// => backup list of child node entries beforehand in order
// to restore it afterwards
NodeState state = data.getNodeState();
ChildNodeEntry cneExisting = state.getChildNodeEntry(id);
if (cneExisting == null) {
throw new ItemNotFoundException(
this + ": no child node entry with id " + id);
}
List<ChildNodeEntry> cneList = new ArrayList<ChildNodeEntry>(state.getChildNodeEntries());
// remove existing
existing.remove();
// create new child node
NodeImpl node = addNode(nodeName, nodeTypeName, id);
if (mixinNames != null) {
for (Name mixinName : mixinNames) {
node.addMixin(mixinName);
}
}
// fetch <code>state</code> again, as it changed while removing child
state = data.getNodeState();
// restore list of child node entries (JCR-1055)
if (cneExisting.getName().equals(nodeName)) {
// restore original child node list
state.setChildNodeEntries(cneList);
} else {
// replace child node entry with different name
// but preserving original position
state.removeAllChildNodeEntries();
for (ChildNodeEntry cne : cneList) {
if (cne.getId().equals(id)) {
// replace entry with different name
state.addChildNodeEntry(nodeName, id);
} else {
state.addChildNodeEntry(cne.getName(), cne.getId());
}
}
}
return node;