org.springframework.web.bind.annotation.RequestBody Java Examples

The following examples show how to use org.springframework.web.bind.annotation.RequestBody. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TradletController.java    From java-trader with Apache License 2.0 6 votes vote down vote up
@RequestMapping(path=URL_PREFIX+"/group/{groupId}/queryData",
        method=RequestMethod.POST,
        consumes = MediaType.TEXT_PLAIN_VALUE,
        produces = MediaType.TEXT_PLAIN_VALUE)
public String tradletGroupQueryData(@PathVariable(value="groupId") String groupId, @RequestBody String queryExpr){
    TradletGroup g = null;
    for(TradletGroup group:tradletService.getGroups()) {
        if ( StringUtil.equalsIgnoreCase(groupId, group.getId()) ) {
            g = group;
            break;
        }
    }
    if ( g==null ) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }

    return g.queryData(queryExpr);
}
 
Example #2
Source File: ViewApi.java    From swaggy-jenkins with MIT License 6 votes vote down vote up
@ApiOperation(value = "", nickname = "postViewConfig", notes = "Update view configuration", authorizations = {
    @Authorization(value = "jenkins_auth")
}, tags={ "remoteAccess", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "Successfully updated view configuration"),
    @ApiResponse(code = 400, message = "An error has occurred - error message is embedded inside the HTML response", response = String.class),
    @ApiResponse(code = 401, message = "Authentication failed - incorrect username and/or password"),
    @ApiResponse(code = 403, message = "Jenkins requires authentication - please set username and password"),
    @ApiResponse(code = 404, message = "View cannot be found on Jenkins instance") })
@RequestMapping(value = "/view/{name}/config.xml",
    produces = { "*/*" }, 
    consumes = { "application/json" },
    method = RequestMethod.POST)
default ResponseEntity<Void> postViewConfig(@ApiParam(value = "Name of the view",required=true) @PathVariable("name") String name,@ApiParam(value = "View configuration in config.xml format" ,required=true )  @Valid @RequestBody String body,@ApiParam(value = "CSRF protection token" ) @RequestHeader(value="Jenkins-Crumb", required=false) String jenkinsCrumb) {
    return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);

}
 
Example #3
Source File: JobResource.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "Move a single timer job", tags = { "Jobs" })
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Indicates the timer job was moved. Response-body is intentionally empty."),
        @ApiResponse(code = 404, message = "Indicates the requested job was not found."),
        @ApiResponse(code = 500, message = "Indicates the an exception occurred while executing the job. The status-description contains additional detail about the error. The full error-stacktrace can be fetched later on if needed.")
})
@PostMapping("/management/timer-jobs/{jobId}")
public void executeTimerJobAction(@ApiParam(name = "jobId") @PathVariable String jobId, @RequestBody RestActionRequest actionRequest, HttpServletResponse response) {
    if (actionRequest == null || !MOVE_ACTION.equals(actionRequest.getAction())) {
        throw new FlowableIllegalArgumentException("Invalid action, only 'move' is supported.");
    }
    
    Job job = getTimerJobById(jobId);

    try {
        managementService.moveTimerToExecutableJob(job.getId());
    } catch (FlowableObjectNotFoundException aonfe) {
        // Re-throw to have consistent error-messaging across REST-api
        throw new FlowableObjectNotFoundException("Could not find a timer job with id '" + jobId + "'.", Job.class);
    }

    response.setStatus(HttpStatus.NO_CONTENT.value());
}
 
Example #4
Source File: QueryController.java    From Kylin with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/query/prestate", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
@Timed(name = "query")
public SQLResponse prepareQuery(@RequestBody PrepareSqlRequest sqlRequest) {
    long startTimestamp = System.currentTimeMillis();

    SQLResponse response = doQuery(sqlRequest);
    response.setDuration(System.currentTimeMillis() - startTimestamp);

    queryService.logQuery(sqlRequest, response, new Date(startTimestamp), new Date(System.currentTimeMillis()));

    if (response.getIsException()) {
        String errorMsg = response.getExceptionMessage();
        throw new InternalErrorException(QueryUtil.makeErrorMsgUserFriendly(errorMsg));
    }

    return response;
}
 
Example #5
Source File: ChatController.java    From Mastering-Distributed-Tracing with MIT License 6 votes vote down vote up
@RequestMapping(value = "/message", consumes = { "application/json" }, produces = {
        MediaType.APPLICATION_JSON_VALUE }, method = RequestMethod.POST)
public ResponseEntity<Message> postMessage(@RequestBody Message msg) throws Exception {
    msg.init();
    System.out.println("Received message: " + msg);
    if ("async1".equals(sendMode)) {
        kafka.sendMessageAsync(msg, executor1);
        System.out.println("Message sent async (executor1) to Kafka");
    } else if ("async2".equals(sendMode)) {
        kafka.sendMessageAsync(msg, executor2);
        System.out.println("Message sent async (executor2) to Kafka");
    } else {
        kafka.sendMessage(msg);
        System.out.println("Message sent sync to Kafka");
    }
    return new ResponseEntity<Message>(msg, HttpStatus.OK);
}
 
Example #6
Source File: JobUserService.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * getJobUserList(获取调度系统用户 不带分页数据-服务)
 *
 * @param jobUser
 * @return
 * @author rufei.cn
 */
public List<JobUser> getJobUserList(@RequestBody JobUser jobUser) {
    String parms = JSON.toJSONString(jobUser);
    List<JobUser> list = null;
    logger.info("getJobUserList(获取调度系统用户 不带分页数据-服务) 开始 parms={}", parms);
    if (jobUser == null) {
        return list;
    }
    try {
        list = jobUserDao.getJobUserList(jobUser);
    } catch (Exception e) {
        String msg = "getJobUserList 异常 " + StringUtil.getExceptionMsg(e);
        logger.error(msg);
        sysCommonService.sendDingTalkMessage("base-service[getJobUserList]", parms, null, msg, this.getClass());

    }
    logger.info("getJobUserList(获取调度系统用户 不带分页数据-服务) 结束");
    return list;
}
 
Example #7
Source File: StatsController.java    From spring-cloud-contract-samples with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/stats",
		method= RequestMethod.POST,
		consumes="application/json",
		produces="application/json")
public StatsResponse check(@RequestBody StatsRequest request) {
	int bottles = this.statsService.findBottlesByName(request.getName());
	String text = String.format("Dear %s thanks for your interested in drinking beer", request.getName());
	return new StatsResponse(bottles, text);
}
 
Example #8
Source File: CoursesController.java    From training with MIT License 5 votes vote down vote up
@RequestMapping(value = "", method = RequestMethod.POST) // SOLUTION
public void createCourse(@RequestBody CourseDto dto) throws ParseException { // SOLUTION
	if (courseRepo.getByName(dto.name) != null) {
		throw new IllegalArgumentException("Another course with that name already exists");
	}
	courseRepo.save(mapToEntity(dto));
}
 
Example #9
Source File: IngredientController.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@PostMapping
public ResponseEntity<Ingredient> postIngredient(@RequestBody Ingredient ingredient) {
  Ingredient saved = repo.save(ingredient);
  HttpHeaders headers = new HttpHeaders();
  headers.setLocation(URI.create("http://localhost:8080/ingredients/" + ingredient.getId()));
  return new ResponseEntity<>(saved, headers, HttpStatus.CREATED);
}
 
Example #10
Source File: SysMenuController.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 保存
 */
@SysLog("保存菜单")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys:menu:save')")
public ResponseEntity<Void> save(@Valid @RequestBody SysMenu menu){
	//数据校验
	verifyForm(menu);
	sysMenuService.save(menu);
	return ResponseEntity.ok().build();
}
 
Example #11
Source File: UserApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * POST /user/createWithList : Creates list of users with given input array
 *
 * @param body List of user object (required)
 * @return successful operation (status code 200)
 */
@ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithListInput", notes = "", tags={ "user", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "successful operation") })
@RequestMapping(value = "/user/createWithList",
    method = RequestMethod.POST)
default CompletableFuture<ResponseEntity<Void>> createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true )  @Valid @RequestBody List<User> body) {
    return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED));

}
 
Example #12
Source File: CommentController.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
@PreAuthorize("@permissionService.hasPermission('blog:comment:add')")
@Log(title = "评论管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody @Validated Comment comment) {
    comment.setCreateBy(SecurityUtils.getUsername());
    return toAjax(commentService.insertComment(comment));
}
 
Example #13
Source File: RemoteAccessApi.java    From swaggy-jenkins with MIT License 5 votes vote down vote up
@ApiOperation(value = "", notes = "Update view configuration", response = Void.class, authorizations = {
    @Authorization(value = "jenkins_auth")
}, tags={ "remoteAccess", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "Successfully updated view configuration"),
    @ApiResponse(code = 400, message = "An error has occurred - error message is embedded inside the HTML response", response = String.class),
    @ApiResponse(code = 401, message = "Authentication failed - incorrect username and/or password"),
    @ApiResponse(code = 403, message = "Jenkins requires authentication - please set username and password"),
    @ApiResponse(code = 404, message = "View cannot be found on Jenkins instance") })
@RequestMapping(value = "/view/{name}/config.xml",
    produces = { "*/*" }, 
    consumes = { "application/json" },
    method = RequestMethod.POST)
ResponseEntity<Void> postViewConfig(@ApiParam(value = "Name of the view",required=true ) @PathVariable("name") String name,@ApiParam(value = "View configuration in config.xml format" ,required=true )   @RequestBody String body,@ApiParam(value = "CSRF protection token" ) @RequestHeader(value="Jenkins-Crumb", required=false) String jenkinsCrumb, @RequestHeader(value = "Accept", required = false) String accept) throws Exception;
 
Example #14
Source File: ElasticSettingsResource.java    From logsniffer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "/system/settings/elastic", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public EsStatusAndSettings saveElasticSettings(@RequestBody @Valid final EsSettings settings) throws IOException {
	settingsHolder.storeSettings(settings);
	return getStatus(settings);

}
 
Example #15
Source File: QuartzJobController.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 更新定时任务
 * 
 * @param quartzJob
 * @return
 */
//@RequiresRoles({"admin"})
@RequestMapping(value = "/edit", method = RequestMethod.PUT)
public Result<?> eidt(@RequestBody QuartzJob quartzJob) {
	try {
		quartzJobService.editAndScheduleJob(quartzJob);
	} catch (SchedulerException e) {
		log.error(e.getMessage(),e);
		return Result.error("更新定时任务失败!");
	}
    return Result.ok("更新定时任务成功!");
}
 
Example #16
Source File: BookmarkRestController.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
public Bookmark createBookmark(@PathVariable String userId,
		@RequestBody Bookmark bookmark) {
	Bookmark bookmarkInstance = new Bookmark(userId, bookmark.getHref(),
			bookmark.getDescription(), bookmark.getLabel());
	return this.bookmarkRepository.save(bookmarkInstance);
}
 
Example #17
Source File: MethodController.java    From WeBASE-Collect-Bee with Apache License 2.0 5 votes vote down vote up
@PostMapping("paras/get")
@ApiOperation(value = "get by method and paras", httpMethod = "POST")
public CommonResponse getByMethodParas(@RequestBody @Valid UnitParaQueryPageReq<String> req, BindingResult result) {
    if (result.hasErrors()) {
        return ResponseUtils.validateError(result);
    }
    return methodManager.getPageListByReq(req);
}
 
Example #18
Source File: TpcMqTopicController.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
/**
 * 查询MQ topic列表.
 *
 * @param tpcMqTopic the tpc mq topic
 *
 * @return the wrapper
 */
@PostMapping(value = "/queryTopicListWithPage")
@ApiOperation(httpMethod = "POST", value = "查询MQ topic列表")
public Wrapper<List<TpcMqTopicVo>> queryTopicListWithPage(@ApiParam(name = "topic", value = "MQ-Topic") @RequestBody TpcMqTopic tpcMqTopic) {

	logger.info("查询角色列表tpcMqTopicQuery={}", tpcMqTopic);
	List<TpcMqTopicVo> list = tpcMqTopicService.listWithPage(tpcMqTopic);
	return WrapMapper.ok(list);
}
 
Example #19
Source File: CommentVoteController.java    From abixen-platform with GNU Lesser General Public License v2.1 5 votes vote down vote up
@RequestMapping(value = "", method = RequestMethod.POST)
public FormValidationResultRepresentation<CommentVoteForm> createCommentVote(@RequestBody @Valid CommentVoteForm commentVoteForm, BindingResult bindingResult) {
    log.debug("createCommentVote() - commentVoteForm: {}", commentVoteForm);

    if (bindingResult.hasErrors()) {
        final List<FormErrorRepresentation> formErrors = ValidationUtil.extractFormErrors(bindingResult);

        return new FormValidationResultRepresentation<>(commentVoteForm, formErrors);
    }
    final CommentVoteForm createdForm = commentVoteManagementService.createCommentVote(commentVoteForm);

    return new FormValidationResultRepresentation<>(createdForm);
}
 
Example #20
Source File: MenuController.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/save")
@RequiresPermissions(value = {"iam:menu"})
public RespBase<?> save(@RequestBody Menu menu) {
	RespBase<Object> resp = RespBase.create();
	menuService.save(menu);
	return resp;
}
 
Example #21
Source File: ResourcesController.java    From multi-tenant-rest-api with MIT License 5 votes vote down vote up
@PreAuthorize("@roleChecker.hasValidRole(#principal)")
@RequestMapping(value="/company", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CompanyDTO> createCompany(
		Principal principal,
		@RequestBody CompanyDTO companyDTO) {
	
	// Check for SUPERADMIN role
	// RoleChecker.hasValidRole(principal);
	
	companyDTO = companyService.create(companyDTO);
	
	return new ResponseEntity<CompanyDTO>(companyDTO, HttpStatus.CREATED);
}
 
Example #22
Source File: GroupsController.java    From guardedbox with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Edits a Group, belonging to the current session account.
 *
 * @param groupId The group ID.
 * @param editGroupDto Object with the necessary data to edit the Group.
 * @return Object with the edited group data.
 */
@PostMapping("/{group-id}")
public GroupDto editGroup(
        @PathVariable(name = "group-id", required = true) @NotNull UUID groupId,
        @RequestBody(required = true) @Valid EditGroupDto editGroupDto) {

    editGroupDto.setGroupId(groupId);
    return groupsService.editGroup(sessionAccount.getAccountId(), editGroupDto);

}
 
Example #23
Source File: AttributeController.java    From logging-log4j-audit with Apache License 2.0 5 votes vote down vote up
@PostMapping(value = "/update")
public ResponseEntity<Map<String, Object>> updateAttribute(@RequestBody Attribute attribute) {
    Map<String, Object> response = new HashMap<>();
    try {
        AttributeModel model = attributeConverter.convert(attribute);
        model = attributeService.saveAttribute(model);
        Attribute result = attributeModelConverter.convert(model);
        response.put("Result", "OK");
        response.put("Records", result);
    } catch (Exception ex) {
        response.put("Result", "FAILURE");
    }
    return new ResponseEntity<>(response, HttpStatus.OK);
}
 
Example #24
Source File: ResourceSortRestApi.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
@AuthorityVerify
@OperationLogger(value = "置顶资源分类")
@ApiOperation(value = "置顶分类", notes = "置顶分类", response = String.class)
@PostMapping("/stick")
public String stick(@Validated({Delete.class}) @RequestBody ResourceSortVO resourceSortVO, BindingResult result) {

    // 参数校验
    ThrowableUtils.checkParamArgument(result);
    return resourceSortService.stickResourceSort(resourceSortVO);
}
 
Example #25
Source File: GreetingController.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.PUT, path = "/greeting/{id}")
public Greeting add(@PathVariable Integer id,
      @RequestBody Greeting greeting)
            throws NoSuchRequestHandlingMethodException {
   try {
      return data.updateGreeting(id, greeting);
   } catch (IndexOutOfBoundsException e) {
      throw new NoSuchRequestHandlingMethodException("greeting",
            GreetingController.class);
   }
}
 
Example #26
Source File: CompanyApiController.java    From onboard with Apache License 2.0 5 votes vote down vote up
/**
 * 更新公司信息
 * 
 * @param companyId
 * @return
 */
@RequestMapping(value = "/{companyId}", method = { RequestMethod.PUT })
@Interceptors({ CompanyAdminRequired.class, CompanyChecking.class })
@ResponseBody
public CompanyDTO updateCompany(@PathVariable int companyId, @RequestBody CompanyDTO form) {
    form.setId(companyId);
    companyService.updateSelective(CompanyTransform.companyDTOtoCompany(form));
    return form;
}
 
Example #27
Source File: BlogSortRestApi.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
@AuthorityVerify
@OperationLogger(value = "批量删除博客分类")
@ApiOperation(value = "批量删除博客分类", notes = "批量删除博客分类", response = String.class)
@PostMapping("/deleteBatch")
public String delete(@Validated({Delete.class}) @RequestBody List<BlogSortVO> blogSortVoList, BindingResult result) {

    // 参数校验
    ThrowableUtils.checkParamArgument(result);

    return blogSortService.deleteBatchBlogSort(blogSortVoList);
}
 
Example #28
Source File: MvcRestApplicationTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@PostMapping("/addFoos")
@ResponseStatus(HttpStatus.ACCEPTED)
public Flux<Foo> addFoos(@RequestBody List<Foo> list) {
	Flux<Foo> flux = Flux.fromIterable(list).cache();
	flux.subscribe(value -> this.list.add(value.getValue()));
	return flux;
}
 
Example #29
Source File: UserController.java    From tutorials with MIT License 4 votes vote down vote up
@PostMapping("/users")
ResponseEntity<String> addUser(@Valid @RequestBody User user) {
    return ResponseEntity.ok("User is valid");
}
 
Example #30
Source File: RequestResponseBodyMethodProcessorMockTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@SuppressWarnings("unused")
@ResponseBody
public String handle1(@RequestBody String s, int i) {
	return s;
}