private Work getWork() throws Exception {
Map<String,JSONObject> rowsByUploadId = null;
// Deal with document database
{
CouchQuery query = new CouchQuery();
query.setViewName("server_work");
CouchQueryResults results;
results = documentDbDesign.performQuery(query);
rowsByUploadId = findUploadIds(results);
for(JSONObject row : results.getRows()) {
String id = row.optString("id");
String state = null;
String attachmentName = null;
JSONArray key = row.optJSONArray("key");
if( null != key ){
if( key.length() > 0 ){
state = key.getString(0);
}
if( key.length() > 1 ){
attachmentName = key.getString(1);
}
};
// Discount documents in error state
synchronized(this) {
if( docIdsToSkip.contains(id) ) {
continue;
}
}
if( UploadConstants.UPLOAD_STATUS_WAITING_FOR_UPLOAD.equals(state) ) {
// In the case of "waiting_for_upload", the attachment name
// refers to the uploadId
JSONObject uploadIdRow = rowsByUploadId.get(attachmentName);
if( null == uploadIdRow ) {
// Missing information to continue
continue;
} else {
String uploadRequestDocId = uploadIdRow.getString("id");
WorkDocumentDb work = new WorkDocumentDb(documentDbDesign, state, id);
work.setUploadId(attachmentName);
work.setUploadRequestDocId(uploadRequestDocId);
return work;
}
} else if( UploadConstants.UPLOAD_WORK_UPLOADED_FILE.equals(state) ) {
// Ignore
continue;
} else {
// Everything else
WorkDocumentDb work = new WorkDocumentDb(documentDbDesign, state, id);
work.setAttachmentName(attachmentName);
return work;
}
}
}
// At this point, no work found in the document database. Look in the
// submission database, if present
if( null != submissionDbDesign ){
CouchQuery query = new CouchQuery();
query.setViewName("upload-work");
CouchQueryResults results = submissionDbDesign.performQuery(query);
for(JSONObject row : results.getRows()) {
String id = row.optString("id");