}
Node fileNode = null;
Node contentNode = null;
Node parentNode = null;
if (session.itemExists(fileName)) {
final Item item = session.getItem(fileName);
if (item.isNode()) {
final Node node = item.isNode() ? (Node) item : item.getParent();
if ("jcr:content".equals(node.getName())) {
// replace the content properties of the jcr:content
// node
parentNode = node;
contentNode = node;
} else if (node.isNodeType("nt:file")) {
// try to set the content properties of jcr:content
// node
parentNode = node;
contentNode = node.getNode("jcr:content");
} else { // fileName is a node
// try to set the content properties of the node
parentNode = node;
contentNode = node;
}
} else {
// replace property with an nt:file node (if possible)
parentNode = item.getParent();
item.remove();
session.save();
fileNode = parentNode.addNode(name, "nt:file");
}
} else {
if (lastPos <= 0) {
parentNode = session.getRootNode();
} else {
Item parent = session.getItem(path);
if (!parent.isNode()) {
throw new IOException("Parent at " + path + " is not a node.");
}
parentNode = (Node) parent;
}
fileNode = parentNode.addNode(name, "nt:file");