Java Code Examples for org.springframework.http.HttpStatus#NO_CONTENT

The following examples show how to use org.springframework.http.HttpStatus#NO_CONTENT . 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: AuthorBlogRestController.java    From JiwhizBlogWeb with Apache License 2.0 6 votes vote down vote up
@RequestMapping(method = RequestMethod.PUT, value = ApiUrls.URL_AUTHOR_BLOGS_BLOG)
public HttpEntity<Void> updateBlogPost(
		@PathVariable("blogId") String blogId, 
        @RequestBody BlogPostForm blogPostForm) throws ResourceNotFoundException {
    BlogPost blogPost = getBlogByIdAndCheckAuthor(blogId);
    blogPost.setContent(blogPostForm.getContent());
    blogPost.setTitle(blogPostForm.getTitle());
    blogPost.parseAndSetTags(blogPostForm.getTagString());
    blogPost = blogPostRepository.save(blogPost);
    
    AuthorBlogResource resource = authorBlogResourceAssembler.toResource(blogPost);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(URI.create(resource.getLink("self").getHref()));
    
    return new ResponseEntity<Void>(httpHeaders, HttpStatus.NO_CONTENT);
}
 
Example 2
Source File: MultiUploadController.java    From jeecg with Apache License 2.0 6 votes vote down vote up
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<?> create(@RequestBody MultiUploadEntity multiUpload, UriComponentsBuilder uriBuilder) {
	//调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息.
	Set<ConstraintViolation<MultiUploadEntity>> failures = validator.validate(multiUpload);
	if (!failures.isEmpty()) {
		return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
	}

	//保存
	try{
		multiUploadService.save(multiUpload);
	} catch (Exception e) {
		e.printStackTrace();
		return new ResponseEntity(HttpStatus.NO_CONTENT);
	}
	//按照Restful风格约定,创建指向新任务的url, 也可以直接返回id或对象.
	String id = multiUpload.getId();
	URI uri = uriBuilder.path("/rest/multiUploadController/" + id).build().toUri();
	HttpHeaders headers = new HttpHeaders();
	headers.setLocation(uri);

	return new ResponseEntity(headers, HttpStatus.CREATED);
}
 
Example 3
Source File: DeployController.java    From eladmin with Apache License 2.0 5 votes vote down vote up
@Log("修改部署")
   @ApiOperation(value = "修改部署")
   @PutMapping
@PreAuthorize("@el.check('deploy:edit')")
   public ResponseEntity<Object> update(@Validated @RequestBody Deploy resources){
       deployService.update(resources);
       return new ResponseEntity<>(HttpStatus.NO_CONTENT);
   }
 
Example 4
Source File: RestaurantController.java    From Microservices-Building-Scalable-Software with MIT License 5 votes vote down vote up
/**
 * Fetch restaurants with the specified name. A partial case-insensitive
 * match is supported. So <code>http://.../restaurants/rest</code> will find
 * any restaurants with upper or lower case 'rest' in their name.
 *
 * @param name
 * @return A non-null, non-empty collection of restaurants.
 */
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Collection<Restaurant>> findByName(@RequestParam("name") String name) {
    logger.info(String.format("restaurant-service findByName() invoked:{} for {} ", restaurantService.getClass().getName(), name));
    name = name.trim().toLowerCase();
    Collection<Restaurant> restaurants;
    try {
        restaurants = restaurantService.findByName(name);
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception raised findByName REST Call", ex);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return restaurants.size() > 0 ? new ResponseEntity<>(restaurants, HttpStatus.OK)
            : new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
 
Example 5
Source File: UserController.java    From production-ready-microservices-starter with MIT License 5 votes vote down vote up
/**
 * Update user by id.
 *
 * @param id                the id
 * @param userCreateRequest the user create update request
 * @param bindingResult     the binding result
 * @return the response entity
 */
@PutMapping("/{id}")
public ResponseEntity<Void> updateUser(@PathVariable String id,
                                       @RequestBody @Valid UserCreateRequest userCreateRequest,
                                       BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
        throw new ValidationException(bindingResult);
    }

    userService.update(id, userCreateRequest);
    return new ResponseEntity(HttpStatus.NO_CONTENT);
}
 
Example 6
Source File: ReportWs.java    From poli with MIT License 5 votes vote down vote up
@RequestMapping(
        value = "/pdf",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_PDF_VALUE)
@Transactional(readOnly = true)
public ResponseEntity<?> exportToPdf(@RequestBody ExportRequest exportRequest,
                                     HttpServletRequest request) {

    User user = (User) request.getAttribute(Constants.HTTP_REQUEST_ATTR_USER);
    exportRequest.setSessionKey(user.getSessionKey());

    try {
        byte[] pdfData = httpClient.postJson(appProperties.getExportServerUrl(), mapper.writeValueAsString(exportRequest));
        ByteArrayResource resource = new ByteArrayResource(pdfData);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + exportRequest.getReportName() + ".pdf");
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(pdfData.length)
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    } catch (IOException e) {
        return new ResponseEntity<String>(HttpStatus.NO_CONTENT);
    }
}
 
Example 7
Source File: RestCaseController.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
@ResponseBody
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteUser(@PathVariable("id") int id) throws InterruptedException {
    User currentUser = users.get(id);
    if (currentUser == null) {
        return;
    }
    users.remove(id);
}
 
Example 8
Source File: TagController.java    From spring-mvc-react with MIT License 5 votes vote down vote up
@JsonView(Views.Public.class)
@RequestMapping(value = "/tags", method = RequestMethod.GET)
public ResponseEntity<List<Tag>> listAllQuestions() {
    List<Tag> tags = tagService.getAll();
    if (tags.isEmpty()) {
        return new ResponseEntity(HttpStatus.NO_CONTENT);
        // You many decide to return HttpStatus.NOT_FOUND
    }
    return new ResponseEntity<List<Tag>>(tags, HttpStatus.OK);
}
 
Example 9
Source File: HttpProxiedController.java    From smockin with Apache License 2.0 5 votes vote down vote up
@RequestMapping(path="/proxy/{extId}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<?> create(@PathVariable("extId") final String extId,
                                              @RequestBody final HttpProxiedDTO dto,
                                              @RequestHeader(value = GeneralUtils.OAUTH_HEADER_NAME, required = false) final String bearerToken)
                                                    throws RecordNotFoundException, ValidationException {

    httpProxyService.addResponse(extId, dto, GeneralUtils.extractOAuthToken(bearerToken));

    return new ResponseEntity<String>(HttpStatus.NO_CONTENT);
}
 
Example 10
Source File: StoreCouponIssueController.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
@Log("修改状态")
@ApiOperation(value = "修改状态")
@PutMapping(value = "/yxStoreCouponIssue")
@PreAuthorize("@el.check('admin','YXSTORECOUPONISSUE_ALL','YXSTORECOUPONISSUE_EDIT')")
public ResponseEntity update(@Validated @RequestBody YxStoreCouponIssue resources){
    yxStoreCouponIssueService.saveOrUpdate(resources);
    return new ResponseEntity(HttpStatus.NO_CONTENT);
}
 
Example 11
Source File: UserController.java    From spring-mvc-react with MIT License 5 votes vote down vote up
@JsonView(Views.Public.class)
@RequestMapping(value = "/users", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
    List<User> users = userService.getAll();
    if (users.isEmpty()) {
        return new ResponseEntity(HttpStatus.NO_CONTENT);
        // You many decide to return HttpStatus.NOT_FOUND
    }
    return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
 
Example 12
Source File: HelloController.java    From springdoc-openapi with Apache License 2.0 4 votes vote down vote up
@Operation(description = "Some operation")
@GetMapping(value = "/hello4", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
HelloDTO1 getDTOWithExplicitResponseStatus() {
	return null;
}
 
Example 13
Source File: SystemGroupDataController.java    From yshopmall with Apache License 2.0 4 votes vote down vote up
@Log("修改数据配置")
@ApiOperation(value = "修改数据配置")
@PutMapping(value = "/yxSystemGroupData")
@CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY,allEntries = true)
@PreAuthorize("@el.check('admin','YXSYSTEMGROUPDATA_ALL','YXSYSTEMGROUPDATA_EDIT')")
public ResponseEntity update(@RequestBody String jsonStr){

    JSONObject jsonObject = JSON.parseObject(jsonStr);
    if(ObjectUtil.isNotNull(jsonObject.get("name"))){
        if(StrUtil.isEmpty(jsonObject.get("name").toString())){
            throw new BadRequestException("名称必须填写");
        }
    }

    if(ObjectUtil.isNotNull(jsonObject.get("title"))){
        if(StrUtil.isEmpty(jsonObject.get("title").toString())){
            throw new BadRequestException("标题必须填写");
        }
    }

    if(ObjectUtil.isNotNull(jsonObject.get("pic"))){
        if(StrUtil.isEmpty(jsonObject.get("pic").toString())){
            throw new BadRequestException("图片必须上传");
        }
    }

    YxSystemGroupData yxSystemGroupData = new YxSystemGroupData();

    yxSystemGroupData.setGroupName(jsonObject.get("groupName").toString());
    jsonObject.remove("groupName");
    yxSystemGroupData.setValue(jsonObject.toJSONString());
    if(jsonObject.getInteger("status") == null){
        yxSystemGroupData.setStatus(1);
    }else{
        yxSystemGroupData.setStatus(jsonObject.getInteger("status"));
    }

    if(jsonObject.getInteger("sort") == null){
        yxSystemGroupData.setSort(0);
    }else{
        yxSystemGroupData.setSort(jsonObject.getInteger("sort"));
    }


    yxSystemGroupData.setId(Integer.valueOf(jsonObject.get("id").toString()));
    yxSystemGroupDataService.saveOrUpdate(yxSystemGroupData);
    return new ResponseEntity(HttpStatus.NO_CONTENT);
}
 
Example 14
Source File: JobController.java    From griffin with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/jobs/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteJob(@PathVariable("id") Long id)
    throws SchedulerException {
    jobService.deleteJob(id);
}
 
Example 15
Source File: MandatoryRuleTest.java    From CheckPoint with Apache License 2.0 4 votes vote down vote up
@Override
public void exception(ValidationData param, Object inputValue, Object standardValue) {
    throw new ValidationLibException(param.getName() + " order exception", HttpStatus.NO_CONTENT);
}
 
Example 16
Source File: FormTableDeployResource.java    From plumdo-work with Apache License 2.0 4 votes vote down vote up
@PostMapping("/form-tables/{id}/deploy")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deployFormTable(@PathVariable Integer id) {
    FormTable formTable = formTableRepository.findOne(id);
    List<FormField> formFields = formFieldRepository.findByTableId(id);
    List<FormLayout> formLayouts = formLayoutRepository.findByTableId(id);

    String formKey = formTable.getKey();
    String relationTable = TableConstant.RELATION_TABLE_PRE + formKey;
    int version;
    FormDefinition formDefinition = formDefinitionRepository.findLatestFormDefinitionByKey(formKey);
    if (formDefinition == null) {
        createDataTable(relationTable, formFields);
        version = 1;
    } else {
        alterDataTable(relationTable, formFields);
        version = formDefinition.getVersion() + 1;
    }

    formDefinition = new FormDefinition();
    formDefinition.setName(formTable.getName());
    formDefinition.setVersion(version);
    formDefinition.setKey(formKey);
    formDefinition.setRelationTable(relationTable);
    formDefinition.setCategory(formTable.getCategory());
    formDefinition.setTenantId(formTable.getTenantId());

    try {
        ByteArray byteArray = new ByteArray();
        byteArray.setName(formTable.getName() + TableConstant.TABLE_FIELD_SUFFIX);
        byteArray.setContentByte(objectMapper.writeValueAsBytes(formFields));
        byteArrayRepository.save(byteArray);
        formDefinition.setFieldSourceId(byteArray.getId());

        //复制一遍布局的设计存储,防止表单设计修改之后,定义也跟随编号
        copyFormLayouts(formLayouts);

        byteArray = new ByteArray();
        byteArray.setName(formTable.getName() + TableConstant.TABLE_LAYOUT_SUFFIX);
        byteArray.setContentByte(objectMapper.writeValueAsBytes(formLayouts));
        byteArrayRepository.save(byteArray);
        formDefinition.setLayoutSourceId(byteArray.getId());

        formDefinitionRepository.save(formDefinition);
    } catch (Exception e) {
        logger.error("deploy form exception", e);
    }
}
 
Example 17
Source File: PostController.java    From angularjs-springmvc-sample-boot with Apache License 2.0 3 votes vote down vote up
@DeleteMapping(value = "/{id}")
@ApiOperation(nickname = "deletePostById", value = "Delete an existing post")
public ResponseEntity<ResponseMessage> deletePostById(@PathVariable("id") Long id) {

    log.debug("delete post by id @" + id);

    blogService.deletePostById(id);

    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
 
Example 18
Source File: TaskController.java    From spring4-sandbox with Apache License 2.0 3 votes vote down vote up
@RequestMapping(value = "/{id}", method = RequestMethod.PUT, headers = "action=MARK_DOING")
public ResponseEntity<Task> markTaskDoing(@PathVariable("id") Long id) {

	Task task = taskRepository.findOne(id);

	if (task == null) {
		throw new TaskNotFoundException(id);
	}

	task.setStatus(Status.DOING);

	taskRepository.save(task);

	return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
 
Example 19
Source File: RestaurantServiceAPI.java    From Microservices-Building-Scalable-Software with MIT License 2 votes vote down vote up
/**
 * Fallback method
 *
 * @return
 */
public ResponseEntity<Collection<Restaurant>> defaultGetAllRestaurants() {
    LOG.warn("Fallback method for restaurant-service is being used.");
    return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
}
 
Example 20
Source File: RestaurantController.java    From Mastering-Microservices-with-Java with MIT License 2 votes vote down vote up
/**
 * Fallback method
 *
 * @param input
 * @return
 */
public ResponseEntity<Entity> defaultRestaurant(String input) {
    logger.warning("Fallback method for restaurant-service is being used.");
    return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
}