jsonobject java 8_Java JSONObject类代码示例

该段代码展示了如何在Java中使用Spring MVC处理文件上传,并在上传前检查用户对项目的管理员权限。通过MultipartFile接收文件,验证项目存在,并确保用户具有“ADMIN”角色。如果文件已存在或用户无权访问,返回相应的HTTP状态码和错误信息。成功上传后,返回包含新源文档ID的JSONObject。
摘要由CSDN通过智能技术生成

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());

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值