}
}
// Get CouchDb instance on behalf of the user
CouchDb userCouchDb = getUserCouchDbFromCookies(cookies);
CouchUserContext userContext = getUserFromClient(userCouchDb.getClient());
if( null != docId
&& null != revision
&& uploadedFiles.size() > 0 ) {
// This is uploading to an existing document
JSONObject doc = null;
try {
doc = userCouchDb.getDocument(docId);
logger.info("onLoad fetched: "+doc.optString("_id")+" -> "+doc.optString("_rev")
+ " for: " + userContext.getName() );
} catch(Exception e) {
logger.error("Unable to load document for id: "+docId,e);
}
if( null != doc ) {
for(LoadedFile uploadedFile : uploadedFiles) {
File actualFile = uploadedFile.getFile();
String originalName = uploadedFile.getOriginalFileName();
JSONObject nunaliitAttachments = doc.optJSONObject(UploadConstants.ATTACHMENTS_KEY);
if( null == nunaliitAttachments ) {
nunaliitAttachments = new JSONObject();
nunaliitAttachments.put("nunaliit_type", "attachment_descriptions");
nunaliitAttachments.put("files", new JSONObject());
doc.put(UploadConstants.ATTACHMENTS_KEY, nunaliitAttachments);
}
JSONObject fileDic = nunaliitAttachments.optJSONObject("files");
if( null == fileDic ) {
fileDic = new JSONObject();
nunaliitAttachments.put("files",fileDic);
}
// Compute name for attachment
String attachmentName = null;
{
File tempFile = new File(originalName);
attachmentName = tempFile.getName();
if( JSONSupport.containsKey(fileDic, attachmentName) ) {
// Select a different file name
String prefix = "";
String suffix = "";
int pos = attachmentName.indexOf('.', 1);
if( pos < 0 ) {
prefix = attachmentName;
} else {
prefix = attachmentName.substring(0, pos-1);
suffix = attachmentName.substring(pos);
}
int counter = 0;
while( JSONSupport.containsKey(fileDic, attachmentName) ) {
attachmentName = prefix + counter + suffix;
++counter;
}
}
}
FileConversionContext conversionContext = new FileConversionContext(doc, dd, attachmentName, mediaDir);
AttachmentDescriptor fileDescription = conversionContext.getAttachmentDescription();
fileDescription.setAttachmentName(attachmentName);
fileDescription.setStatus(UploadConstants.UPLOAD_STATUS_SUBMITTED);
fileDescription.setOriginalName(originalName);
fileDescription.setSubmitterName(userContext.getName());
OriginalFileDescriptor originalJson = fileDescription.getOriginalFileDescription();
originalJson.setMediaFileName(actualFile.getName());
// Add user data