*/
try {
// Get CouchDb instance on behalf of the user
CouchDb userCouchDb = getUserCouchDbFromCookies(cookies);
CouchAuthenticationContext userContext = getUserFromClient(userCouchDb.getClient());
// Create an upload request
JSONObject doc = new JSONObject();
JSONObject uploadRequest = new JSONObject();
doc.put("nunaliit_upload_request", uploadRequest);
uploadRequest.put("docId", docId);
uploadRequest.put("revision", revision);
uploadRequest.put("uploadId", uploadId);
JSONArray files = new JSONArray();
uploadRequest.put("files", files);
Set<String> fileNames = new HashSet<String>();
for(LoadedFile uploadedFile : uploadedFiles) {
File actualFile = uploadedFile.getFile();
String originalName = uploadedFile.getOriginalFileName();
// Compute name for attachment
String attachmentName = null;
{
File tempFile = new File(originalName);
attachmentName = tempFile.getName();
if( fileNames.contains(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( fileNames.contains(attachmentName) ) {
attachmentName = prefix + counter + suffix;
++counter;
}
}
}
fileNames.add(attachmentName);
JSONObject file = new JSONObject();
files.put(file);
file.put("attachmentName", attachmentName);
file.put("originalName", originalName);
file.put("submitter", userContext.getName());
JSONObject original = new JSONObject();
file.put("original", original);
original.put("mediaFile", actualFile.getName());