下面列出了怎么用org.springframework.web.bind.annotation.ResponseStatus的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* PUT /rest/users/:login/change_password -> changes the user's password
*/
@RequestMapping(value = "/rest/users/{login}/change-password", method = RequestMethod.PUT)
@ResponseStatus(value = HttpStatus.OK)
public void changePassword(@PathVariable String login, @RequestBody ObjectNode actionBody) {
if (actionBody.get("oldPassword") == null || actionBody.get("oldPassword").isNull()) {
throw new BadRequestException("oldPassword should not be empty");
} else if (actionBody.get("newPassword") == null || actionBody.get("newPassword").isNull()) {
throw new BadRequestException("newPassword should not be empty");
} else {
try {
userService.changePassword(login, actionBody.get("oldPassword").asText(), actionBody.get("newPassword").asText());
} catch(ActivitiServiceException ase) {
throw new BadRequestException(ase.getMessage());
}
}
}
/**
* Retrieve all task job executions with the task name specified
*
* @param jobName name of the job. SQL server specific wildcards are enabled (eg.: myJob%,
* m_Job, ...)
* @param pageable page-able collection of {@code TaskJobExecution}s.
* @param assembler for the {@link TaskJobExecution}s
* @return list task/job executions with the specified jobName.
* @throws NoSuchJobException if the job with the given name does not exist.
*/
@RequestMapping(value = "", method = RequestMethod.GET, produces = "application/json")
@ResponseStatus(HttpStatus.OK)
public PagedModel<JobExecutionResource> retrieveJobsByParameters(
@RequestParam(value = "name", required = false) String jobName,
@RequestParam(value = "status", required = false) BatchStatus status,
Pageable pageable, PagedResourcesAssembler<TaskJobExecution> assembler) throws NoSuchJobException, NoSuchJobExecutionException {
List<TaskJobExecution> jobExecutions;
Page<TaskJobExecution> page;
if (jobName == null && status == null) {
jobExecutions = taskJobService.listJobExecutions(pageable);
page = new PageImpl<>(jobExecutions, pageable, taskJobService.countJobExecutions());
} else {
jobExecutions = taskJobService.listJobExecutionsForJob(pageable, jobName, status);
page = new PageImpl<>(jobExecutions, pageable,
taskJobService.countJobExecutionsForJob(jobName, status));
}
return assembler.toModel(page, jobAssembler);
}
@RequestMapping(value = "/add/{productId}", method = RequestMethod.PUT)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addItem(@PathVariable String productId, HttpServletRequest request) {
String sessionId = request.getSession(true).getId();
Cart cart = cartService.read(sessionId);
if(cart== null) {
cart = cartService.create(new Cart(sessionId));
}
Product product = productService.getProductById(productId);
if(product == null) {
throw new IllegalArgumentException(new ProductNotFoundException(productId));
}
cart.addCartItem(new CartItem(product));
cartService.update(sessionId, cart);
}
/**
* 自定义业务/数据异常处理
*
* @param exception
* @return
*/
@ExceptionHandler(value = {SpringBootPlusException.class})
@ResponseStatus(HttpStatus.OK)
public ApiResult<Boolean> springBootPlusExceptionHandler(SpringBootPlusException exception) {
printRequestDetail();
log.error("springBootPlusException:", exception);
int errorCode;
if (exception instanceof BusinessException) {
errorCode = ApiCode.BUSINESS_EXCEPTION.getCode();
} else if (exception instanceof DaoException) {
errorCode = ApiCode.DAO_EXCEPTION.getCode();
} else if (exception instanceof VerificationCodeException) {
errorCode = ApiCode.VERIFICATION_CODE_EXCEPTION.getCode();
} else {
errorCode = ApiCode.SPRING_BOOT_PLUS_EXCEPTION.getCode();
}
return new ApiResult<Boolean>()
.setCode(errorCode)
.setMessage(exception.getMessage());
}
/**
*Post a string key's source to l10n server.
*
*/
@ApiIgnore
@ApiOperation(value = APIOperation.KEY_SOURCE_POST_VALUE, notes = APIOperation.KEY_SOURCE_POST_NOTES)
@RequestMapping(value = L10nI18nAPI.TRANSLATION_PRODUCT_NOCOMOPONENT_KEY_APIV1, method = RequestMethod.POST, produces = { API.API_CHARSET })
@ResponseStatus(HttpStatus.OK)
public SourceAPIResponseDTO collectV1KeyTranslationNoComponent(
@ApiParam(name = APIParamName.PRODUCT_NAME, required = true, value = APIParamValue.PRODUCT_NAME) @PathVariable(APIParamName.PRODUCT_NAME) String productName,
@ApiParam(name = APIParamName.VERSION, required = true, value = APIParamValue.VERSION) @RequestParam(value = APIParamName.VERSION, required = true) String version,
@ApiParam(name = APIParamName.KEY, required = true, value = APIParamValue.KEY) @PathVariable(APIParamName.KEY) String key,
@ApiParam(name = APIParamName.SOURCE, required = false, value = APIParamValue.SOURCE) @RequestParam(value = APIParamName.SOURCE, required = false) String source,
@ApiParam(name = APIParamName.COMMENT_SOURCE, value = APIParamValue.COMMENT_SOURCE) @RequestParam(value = APIParamName.COMMENT_SOURCE, required = false) String commentForSource,
@ApiParam(name = APIParamName.LOCALE, value = APIParamValue.LOCALE) @RequestParam(value = APIParamName.LOCALE, required = false) String locale,
@ApiParam(name = APIParamName.SOURCE_FORMAT, value = APIParamValue.SOURCE_FORMAT) @RequestParam(value = APIParamName.SOURCE_FORMAT, required = false) String sourceFormat,
@ApiParam(name = APIParamName.COLLECT_SOURCE, value = APIParamValue.COLLECT_SOURCE) @RequestParam(value = APIParamName.COLLECT_SOURCE, required = true, defaultValue = "true") String collectSource,
// @ApiParam(name = APIParamName.PSEUDO, value = APIParamValue.PSEUDO) @RequestParam(value = APIParamName.PSEUDO, required = false, defaultValue = ConstantsKeys.FALSE) String pseudo,
HttpServletRequest request) throws L10nAPIException {
String newLocale = locale == null ? ConstantsUnicode.EN : locale;
String newKey = StringUtils.isEmpty(sourceFormat) ? key
: (key + ConstantsChar.DOT + ConstantsChar.POUND + sourceFormat.toUpperCase());
String newSource = source == null ? "" : source;
StringSourceDTO sourceObj = SourceUtils.createSourceDTO(productName, version, ConstantsFile.DEFAULT_COMPONENT, newLocale, newKey,
newSource, commentForSource, sourceFormat);
boolean isSourceCached = sourceService.cacheSource(sourceObj);
return SourceUtils.handleSourceResponse(isSourceCached);
}
@RequestMapping( value = "/{uid}/favorite", method = RequestMethod.DELETE )
@ResponseStatus( HttpStatus.OK )
public void removeAsFavorite( @PathVariable( "uid" ) String pvUid, HttpServletRequest request, HttpServletResponse response ) throws Exception
{
if ( !getSchema().isFavoritable() )
{
throw new WebMessageException( WebMessageUtils.conflict( "Objects of this class cannot be set as favorite" ) );
}
List<Visualization> entity = (List<Visualization>) getEntity( pvUid );
if ( entity.isEmpty() )
{
throw new WebMessageException( WebMessageUtils.notFound( Chart.class, pvUid ) );
}
Visualization object = entity.get( 0 );
User user = currentUserService.getCurrentUser();
object.removeAsFavorite( user );
manager.updateNoAcl( object );
String message = String.format( "Object '%s' removed as favorite for user '%s'", pvUid, user.getUsername() );
webMessageService.send( WebMessageUtils.ok( message ), response, request );
}
/**
* Return a page-able list of {@link AuditRecordResource}s.
*
* @param pageable Pagination information
* @param assembler assembler for {@link AuditRecord}
* @param actions Optional. For which {@link AuditActionType}s do you want to retrieve
* {@link AuditRecord}s
* @param fromDate Optional. The fromDate must be {@link DateTimeFormatter}.ISO_DATE_TIME
* formatted. eg.: 2019-02-03T00:00:30
* @param toDate Optional. The toDate must be {@link DateTimeFormatter}.ISO_DATE_TIME
* formatted. eg.: 2019-02-05T23:59:30
* @param operations Optional. For which {@link AuditOperationType}s do you want to
* retrieve {@link AuditRecord}s
* @return list of audit records
*/
@RequestMapping(value = "", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public PagedModel<AuditRecordResource> list(Pageable pageable,
@RequestParam(required = false) AuditActionType[] actions,
@RequestParam(required = false) AuditOperationType[] operations,
@RequestParam(required = false) String fromDate,
@RequestParam(required = false) String toDate,
PagedResourcesAssembler<AuditRecord> assembler) {
final Instant fromDateAsInstant = paresStringToInstant(fromDate);
final Instant toDateAsInstant = paresStringToInstant(toDate);
if (fromDate != null && toDate != null && fromDate.compareTo(toDate) > 0) {
throw new InvalidDateRangeException("The fromDate cannot be after the toDate.");
}
final Page<AuditRecord> auditRecords = this.auditRecordService
.findAuditRecordByAuditOperationTypeAndAuditActionTypeAndDate(pageable, actions, operations,
fromDateAsInstant,
toDateAsInstant);
return assembler.toModel(auditRecords, new Assembler(auditRecords));
}
/**
* Adds a new Project to the Projects repository
*
* @param project
* @return project
*/
@ApiOperation(
value = "Adding a Project",
notes = "Project data has to be passed as JSON in the Request Body.")
@RequestMapping(
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public Project create(@RequestBody @Valid Project project)
throws NotAllowedException, NotFoundException {
log.info("Adding Project: " + project.getName());
if (utils.isAdmin()) {
return projectManagement.add(project);
} else {
throw new NotAllowedException("Forbidden to create project " + project.getName());
}
}
@ExceptionHandler(InternalServerException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView handleInternalServerException(final InternalServerException e) {
ModelAndView mav = new ModelAndView(new JsonResponseView());
mav.addObject(new JsonEmptyDataResponse(new JsonMeta(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage())));
return mav;
}
@RequestMapping (value = "/private/login", produces = MediaType.TEXT_PLAIN_VALUE)
@ResponseStatus (code = HttpStatus.FOUND)
@ResponseBody
public String login (final HttpServletRequest request, final HttpServletResponse response, @RequestBody (required = false) final String body, final Authentication auth) {
response.setHeader ("Location", this.serverLocation (request) + "/private/logged");
this.logRequest (request, body);
return "";
}
@DeleteMapping("/{orderId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteOrder(@PathVariable("orderId") Long orderId) {
try {
repo.deleteById(orderId);
} catch (EmptyResultDataAccessException e) {}
}
@RequestMapping(value = "/attach", method = RequestMethod.DELETE)
@Interceptors({ ProjectNotArchivedRequired.class })
@ResponseStatus(HttpStatus.OK)
public void deleteAttachTodos(@RequestParam(value = "attachType", required = true) String attachType,
@RequestParam(value = "attachId", required = true) Integer attachId,
@RequestParam(value = "todoId", required = true) Integer todoId) {
todoService.removeAttachToTodo(attachType, attachId, todoId);
}
@ExceptionHandler(DataIntegrityViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public BaseResponse handleDataIntegrityViolationException(DataIntegrityViolationException e) {
BaseResponse<?> baseResponse = handleBaseException(e);
if (e.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {
baseResponse = handleBaseException(e.getCause());
}
baseResponse.setMessage("字段验证错误,请完善后重试!");
return baseResponse;
}
/**
* Return meta information about the Skipper server.
*
* @return Detailed information about the enabled features, versions of implementation
* libraries, and security configuration
*/
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public AboutResource getAboutResource() {
final AboutResource aboutResource = new AboutResource();
final VersionInfo versionInfo = getVersionInfo();
aboutResource.setVersionInfo(versionInfo);
return aboutResource;
}
@RequestMapping(value = "/{quiz_id}/questions", method = RequestMethod.GET)
@PreAuthorize("permitAll")
@ResponseStatus(HttpStatus.OK)
public List<Question> findQuestions(@PathVariable Long quiz_id,
@RequestParam(required = false, defaultValue = "false") Boolean onlyValid) {
Quiz quiz = quizService.find(quiz_id);
if (onlyValid) {
return questionService.findValidQuestionsByQuiz(quiz);
} else {
return questionService.findQuestionsByQuiz(quiz);
}
}
/**
* Add a new {@link Criterion} as the lowest priority criterion for the given command.
*
* @param id The id of the command to add the new criterion to
* @param criterion The {@link Criterion} to add
* @throws NotFoundException When no {@link Command} with the given {@literal id} exists
*/
@PostMapping(value = "/{id}/clusterCriteria", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public void addClusterCriterionForCommand(
@PathVariable("id") final String id,
@RequestBody @Valid final Criterion criterion
) throws NotFoundException {
log.info("Called to add {} as the lowest priority cluster criterion for command {}", criterion, id);
this.persistenceService.addClusterCriterionForCommand(id, criterion);
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public String handleHttpMessageNotReadableException(HttpMessageNotReadableException e, Model model) {
logger.error("参数解析失败", e);
String message = "【参数解析失败】" + e.getMessage();
model.addAttribute("message", message);
model.addAttribute("code", 400);
return viewName;
}
/**
* Add a VNF Component (VNFC) in standby to a specific VNF. A standby VNFC is a VNFC instantiated
* configured but not started.
*
* @param body VNF Component to add as JSON.
* @param id NSR Id
* @param idVnf VNF Id of the target VNF
* @param idVdu VDU Id
* @param projectId Project Id
* @throws NotFoundException
* @throws BadFormatException
* @throws WrongStatusException
*/
@ApiOperation(
value = "Add a VNFC in standby",
notes = "Instantiate and configure a new VNFC without start it, namely in standby")
@RequestMapping(
value = "{id}/vnfrecords/{idVnf}/vdunits/{idVdu}/vnfcinstances/standby",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
@SuppressWarnings("unchecked")
public void postStandByVNFCInstance(
@RequestBody @Valid JsonObject body,
@PathVariable("id") String id,
@PathVariable("idVnf") String idVnf,
@PathVariable("idVdu") String idVdu,
@RequestHeader(value = "project-id") String projectId)
throws NotFoundException, BadFormatException, WrongStatusException {
VNFComponent component =
gson.fromJson(body.getAsJsonObject("vnfComponent"), VNFComponent.class);
List<String> vimInstanceNames =
gson.fromJson(body.getAsJsonArray("vimInstanceNames"), List.class);
log.debug(
"PostStandByVNFCInstance received the component: "
+ component
+ "\nand\n"
+ vimInstanceNames);
networkServiceRecordManagement.addVNFCInstance(
id, idVnf, idVdu, component, "standby", projectId, vimInstanceNames);
}
/**
* This operation is used to resume a failed Network Service Record
*
* @param id : the id of Network Service Record
*/
@ApiOperation(
value = "Resume a failed Network Service Record",
notes =
"Resumes a NSR that failed while executing a script in a VNFR. The id in the URL specifies the Network Service Record that will be resumed.")
@RequestMapping(value = "{id}/resume", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void resume(
@PathVariable("id") String id, @RequestHeader(value = "project-id") String projectId)
throws InterruptedException, ExecutionException, NotFoundException, BadFormatException {
networkServiceRecordManagement.resume(id, projectId);
}
/**
* Gets repository matching the given name
*
* @param repositoryName To filer on the name. Can be {@code null}
* @return List of {@link Repository}s
*/
@JsonView(View.Repository.class)
@RequestMapping(value = "/api/repositories", params = "name", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public List<Repository> getRepositories(@RequestParam(value = "name", required = true) String repositoryName) {
return repositoryService.findRepositoriesIsNotDeletedOrderByName(repositoryName);
}
@RequestMapping( value = "/softDeletedProgramInstanceRemoval", method = { RequestMethod.PUT, RequestMethod.POST } )
@PreAuthorize( "hasRole('ALL') or hasRole('F_PERFORM_MAINTENANCE')" )
@ResponseStatus( HttpStatus.NO_CONTENT )
public void deleteSoftDeletedProgramInstances()
{
maintenanceService.deleteSoftDeletedProgramInstances();
}
/**
* Provide supported locales by product name and version.
*
*/
@ApiOperation(value = APIOperation.PRODUCT_LOCALE_LIST_VALUE, notes = APIOperation.PRODUCT_LOCALE_LIST_NOTES)
@RequestMapping(value = APIV2.PRODUCT_LOCALE_LIST_GET, method = RequestMethod.GET, produces = {API.API_CHARSET})
@ResponseStatus(HttpStatus.OK)
public APIResponseDTO getSupportedLocales(
@ApiParam(name = APIParamName.PRODUCT_NAME, required = true, value = APIParamValue.PRODUCT_NAME) @PathVariable(APIParamName.PRODUCT_NAME) String productName,
@ApiParam(name = APIParamName.VERSION, required = true, value = APIParamValue.VERSION) @PathVariable(APIParamName.VERSION) String version,
HttpServletRequest request) throws Exception{
return super.getSLocales(productName, version, request);
}
@PostMapping( value = "/dashboard/interpretations/read" )
@ResponseStatus( value = HttpStatus.NO_CONTENT )
@ApiVersion( include = { DhisApiVersion.ALL, DhisApiVersion.DEFAULT } )
public void updateInterpretationsLastRead()
{
interpretationService.updateCurrentUserLastChecked();
}
/**
* {@link HttpRequestMethodNotSupportedException}をハンドリングします。
* @param e {@link HttpRequestMethodNotSupportedException}
* @return {@link ErrorMessage}
* HTTPステータス 405 でレスポンスを返却します。
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseBody
@ResponseStatus(value = HttpStatus.METHOD_NOT_ALLOWED)
@Override
public ErrorMessage handle(HttpRequestMethodNotSupportedException e) {
if (L.isDebugEnabled()) {
L.debug(R.getString("D-SPRINGMVC-REST-HANDLER#0002"), e);
}
ErrorMessage error = createClientErrorMessage(HttpStatus.METHOD_NOT_ALLOWED);
warn(error, e);
return error;
}
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(value = HttpStatus.FORBIDDEN)
@ResponseBody
private ErrorMessageResponse handleAccessDeniedException(AccessDeniedException e) {
LOG.warn("Access denied", e);
return new ErrorMessageResponse(Collections.singletonList(new ErrorMessage(e.getMessage())));
}
private String resolveResponseStatus(Method method) {
ResponseStatus responseStatusAnnotation = method.getAnnotation(ResponseStatus.class);
if (responseStatusAnnotation == null) {
return DEFAULT_RESPONSE_STATUS;
}
return String.valueOf(defaultIfUnexpectedServerError(responseStatusAnnotation.code(), responseStatusAnnotation.value()).value());
}
@ExceptionHandler(PasswordDoesNotMatchException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ResponseBody handlePasswordDoesNotMatchException(HttpServletRequest request,
PasswordDoesNotMatchException e) {
ApiResponse response = new ApiResponse(ApiResponse.USER_PASSWORD_DOES_NOT_MATCH);
return handleExceptionInternal(request, e, response);
}
@ApiOperation(
value = "Add a VNFC instance to a VDU of a VNFR",
notes = "Specifies and adds a VNFC instance in the VDU inside a VNFR that is inside the NSR")
@RequestMapping(
value = "{id}/vnfrecords/{idVnf}/vdunits/{idVdu}/vnfcinstances",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
@SuppressWarnings("unchecked")
public void postVNFCInstance(
@RequestBody @Valid JsonObject body,
@PathVariable("id") String id,
@PathVariable("idVnf") String idVnf,
@PathVariable("idVdu") String idVdu,
@RequestHeader(value = "project-id") String projectId)
throws NotFoundException, BadFormatException, WrongStatusException, BadRequestException {
if (!body.has("vnfComponent"))
throw new BadRequestException(
"The passed request body is not correct. It should include a field named: vnfComponent");
VNFComponent component = retrieveVNFComponentFromRequest(body);
List<String> vimInstanceNames = retrieveVimInstanceNamesFromRequest(body);
log.trace("Received: " + component + "\nand\n" + vimInstanceNames);
networkServiceRecordManagement.addVNFCInstance(
id, idVnf, idVdu, component, "", projectId, vimInstanceNames);
}
@RequestMapping(value = "/forgotPassword")
@PreAuthorize("permitAll")
@ResponseStatus(HttpStatus.OK)
public User forgotPassword(String email) {
User user = userService.findByEmail(email);
userManagementService.resendPassword(user);
return user;
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseResult handleMethodArgumentNotValidException(final MethodArgumentNotValidException e) {
log.error("MethodArgumentNotValidException", e);
return ResponseResult.failure(SystemErrorCode.DATA_BIND_VALIDATION_FAILURE, e);
}
如果文章对你有帮助,欢迎点击上方按钮打赏作者