import org.apache.wicket.ajax.json.JSONObject; //导入依赖的package包/类
/**
* Upload a source document into project where user has "ADMIN" role
*
* Test when running in Eclipse, use the Linux "curl" command.
*
* curl -v -F '[email protected]' -F 'filetype=text'
* 'http://USERNAME:[email protected]:8080/webanno-webapp/api/projects/{aProjectId}/sourcedocs/
* '
*
* @param aFile
* File for {@link SourceDocument}.
* @param aProjectId
* {@link Project} id.
* @param aFileType
* Extension of the file.
* @return returns JSON string with id to the created source document.
* @throws Exception
* if there was an error.
*/
@RequestMapping(
value = "/" + PROJECTS + "/{" + PARAM_PROJECT_ID + "}/" + DOCUMENTS,
method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity sourceDocumentCreate(
@RequestParam(PARAM_FILE) MultipartFile aFile,
@RequestParam(PARAM_FILETYPE) String aFileType,
@PathVariable(PARAM_PROJECT_ID) long aProjectId)
throws Exception
{
// Get current user
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User user = userRepository.get(username);
if (user == null) {
return ResponseEntity
.badRequest()
.body("User [" + username + "] not found.");
}
// Get project
Project project;
try {
project = projectRepository.getProject(aProjectId);
}
catch (NoResultException e) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body("Project [" + aProjectId + "] not found.");
}
// Check for the access
boolean hasAccess =
SecurityUtil.isProjectAdmin(project, projectRepository, user) ||
SecurityUtil.isSuperAdmin(projectRepository, user);
if (!hasAccess) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("User [" + username
+ "] is not allowed to access project [" + aProjectId + "]");
}
// Existing project
if (documentRepository.existsSourceDocument(project, aFile.getOriginalFilename())) {
return ResponseEntity
.status(HttpStatus.CONFLICT)
.body("A document with name [" + aFile.getOriginalFilename() + "] already exists");
}
// Check if file already present or not
try (InputStream is = aFile.getInputStream()) {
uploadSourceDocumentFile(is,aFile.getOriginalFilename(), project, aFileType);
}
// add id of added source document in return json string
JSONObject returnJSON = new JSONObject();
returnJSON.put("id",
documentRepository.getSourceDocument(project, aFile.getOriginalFilename()).getId());
return ResponseEntity.ok(returnJSON.toString());
}