In my web application, I have integrated a DMS using ModeShape. Usually, it works perfectly fine. However, from time to time, the application does not allow writing new files anymore due to an exception:
InvalidItemStateException: Node 'folder/filename' is versionable but was not yet persisted via Session.save(), and therefore no version history is available yet
My code for adding a new file to the DMS looks like this.
protected boolean addFile(Session session, String path, String filename, InputStream fileContent, boolean overwriteIfExist, boolean isAbsolutPath) {
try {
Node folder=null;
if(isAbsolutPath) {
try {
folder = session.getNode(path);
} catch (PathNotFoundException e) {
LOG.error("Path not found in DMS for path "+path,e);
}
}
else {
Node root = session.getRootNode();
folder = root.getNode(path);
}
if(folder!=null) {
Node fileNode;
VersionManager versionManager = null;
if(folder.hasNode(filename)){
fileNode=folder.getNode(filename);
if(!overwriteIfExist) {
//create new Version if file exists and should not be overwritten
versionManager = session.getWorkspace().getVersionManager();
versionManager.checkout(fileNode.getPath());
}
try {
JcrTools jcrTools = new JcrTools(false);
jcrTools.removeAllChildren(fileNode);
} catch (Exception e) {
LOG.error("Error while removing children nodes of node "+fileNode.toString(),e);
}
}
else {
// Create an 'nt:file' node at the supplied path ...
fileNode = folder.addNode(filename,NodeType.NT_FILE);
fileNode.addMixin(NodeType.MIX_VERSIONABLE);
versionManager = session.getWorkspace().getVersionManager();
versionManager.checkout(fileNode.getPath());
}
// Upload the file to that node ...
Node contentNode = fileNode.hasNode(Property.JCR_CONTENT)?fileNode.getNode(Property.JCR_CONTENT):fileNode.addNode(Property.JCR_CONTENT, NodeType.NT_RESOURCE);
if(!isNodeExist(session, contentNode))
contentNode=fileNode.addNode(Property.JCR_CONTENT,NodeType.NT_RESOURCE);
Binary binary = session.getValueFactory().createBinary(fileContent);
contentNode.setProperty(Property.JCR_DATA, binary);
session.save();
if(versionManager!=null) {
versionManager.checkin(fileNode.getPath());
}
// Save the session (and auto-created the properties) ...
return true;
}
else {
LOG.warn("Could not find folder with given path "+path+" in the repository!");
return false;
}
} catch (RepositoryException e) {
LOG.error("Error handling the repository while adding file "+filename,e);
return false;
}
}
Do you have an idea why this exception is occuring? As can be seen in the code, I am executing session.save() after writing a new file or writing a new version of a file. Thank you for the support in advance.