if( null == currentDoc ) {
// New document. Create.
JSONObject originalDoc = SubmissionUtils.getApprovedDocumentFromSubmission(submissionDoc);
CouchDb targetDb = documentDbDesignDocument.getDatabase();
targetDb.createDocument(originalDoc);
CouchDb submissionDb = submissionDbDesignDocument.getDatabase();
submissionDoc.getJSONObject("nunaliit_submission")
.put("state", "complete");
submissionDb.updateDocument(submissionDoc);
} else if( isDeletion ) {
CouchDb targetDb = documentDbDesignDocument.getDatabase();
JSONObject toDeleteDoc = targetDb.getDocument(docId);
targetDb.deleteDocument(toDeleteDoc);
CouchDb submissionDb = submissionDbDesignDocument.getDatabase();
submissionDoc.getJSONObject("nunaliit_submission")
.put("state", "complete");
submissionDb.updateDocument(submissionDoc);
} else {
String currentVersion = currentDoc.getString("_rev");
JSONObject approvedDoc = SubmissionUtils.getApprovedDocumentFromSubmission(submissionDoc);
String approvedVersion = approvedDoc.optString("_rev",null);
if( currentVersion.equals(approvedVersion) ) {
// No changes since approval. Simply update the document
// database.
CouchDb targetDb = documentDbDesignDocument.getDatabase();
targetDb.updateDocument(approvedDoc);
CouchDb submissionDb = submissionDbDesignDocument.getDatabase();
submissionDoc.getJSONObject("nunaliit_submission")
.put("state", "complete");
submissionDb.updateDocument(submissionDoc);
} else {
// Get document that the changes were made against
CouchDb couchDb = documentDbDesignDocument.getDatabase();
CouchDocumentOptions options = new CouchDocumentOptions();
options.setRevision(approvedVersion);
JSONObject rootDoc = couchDb.getDocument(docId, options);
// Compute patch from submission
JSONObject submissionPatch = JSONPatcher.computePatch(rootDoc, approvedDoc);
JSONObject databasePatch = JSONPatcher.computePatch(rootDoc, currentDoc);
// Detect collision. Apply patches in different order, if result
// is same, then no collision
JSONObject doc1 = JSONSupport.copyObject(rootDoc);
JSONPatcher.applyPatch(doc1, submissionPatch);
JSONPatcher.applyPatch(doc1, databasePatch);
JSONObject doc2 = JSONSupport.copyObject(rootDoc);
JSONPatcher.applyPatch(doc2, databasePatch);
JSONPatcher.applyPatch(doc2, submissionPatch);
if( 0 == JSONSupport.compare(doc1, doc2) ) {
// No collision
logger.error("rootDoc: "+rootDoc);
logger.error("submissionPatch: "+submissionPatch);
logger.error("databasePatch: "+databasePatch);
logger.error("no collision: "+doc1);
CouchDb targetDb = documentDbDesignDocument.getDatabase();
targetDb.updateDocument(doc1);
CouchDb submissionDb = submissionDbDesignDocument.getDatabase();
submissionDoc.getJSONObject("nunaliit_submission")
.put("state", "complete");
submissionDb.updateDocument(submissionDoc);
} else {
// Collision case
CouchDb submissionDb = submissionDbDesignDocument.getDatabase();
submissionDoc.getJSONObject("nunaliit_submission")
.put("state", "collision");
submissionDb.updateDocument(submissionDoc);
}
}
}
}