org.springframework.http.HttpStatus#UNPROCESSABLE_ENTITY源码实例Demo

下面列出了org.springframework.http.HttpStatus#UNPROCESSABLE_ENTITY 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: POC   文件: CustomerController.java
/**
 * Create a new customer and return in response with HTTP 201.
 * @param customer a {@link com.poc.restfulpoc.entities.Customer} object.
 * @return created customer
 * @param ucBuilder a {@link org.springframework.web.util.UriComponentsBuilder}
 * object.
 * @param errors a {@link org.springframework.validation.Errors} object.
 */
@PostMapping
public ResponseEntity<Object> createCustomer(@Valid @RequestBody Customer customer, UriComponentsBuilder ucBuilder,
		Errors errors) {
	this.customerValidator.validate(customer, errors);
	if (errors.hasErrors()) {
		final String errorMessage = errors.getAllErrors().stream().map(ObjectError::getDefaultMessage)
				.collect(Collectors.joining(","));
		final ApiError apiError = new ApiError(HttpStatus.UNPROCESSABLE_ENTITY, new Throwable(errorMessage));
		log.error("Detailed Error while processing request :{}", apiError.toString());
		return new ResponseEntity<>(apiError, apiError.getStatus());
	}
	log.info("Creating Customer :{} ", customer.getFirstName());
	if (this.customerService.isCustomerExist(customer.getFirstName())) {
		log.error("A Customer with name {} already exist ", customer.getFirstName());
		return new ResponseEntity<>(HttpStatus.CONFLICT);
	}

	this.customerService.createCustomer(customer);

	final HttpHeaders headers = new HttpHeaders();
	headers.setLocation(ucBuilder.path("/rest/customers/{customerId}").buildAndExpand(customer.getId()).toUri());
	return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
 
源代码2 项目: steady   文件: BugController.java
/**
	 * Adds a set of {@link AffectedLibrary}s for the given {@link Bug} and {@link AffectedVersionSource}.
	 * This method is only allows for source CHECK_VERSION, AST_EQUALITY, MINOR_EQUALITY MAJOR_EQUALITY GREATER_RELEASE TO_REVIEW
	 *
	 * @return 409 {@link HttpStatus#CONFLICT} if bug with given bug ID already exists, 201 {@link HttpStatus#CREATED} if the bug was successfully created
	 * @param bugid a {@link java.lang.String} object.
	 * @param source a {@link com.sap.psr.vulas.shared.enums.AffectedVersionSource} object.
	 * @param affectedLibraries an array of {@link com.sap.psr.vulas.backend.model.AffectedLibrary} objects.
	 */
	@RequestMapping(value = "/{bugid}/affectedLibIds", method = RequestMethod.PUT, consumes = {"application/json;charset=UTF-8"}, produces = {"application/json;charset=UTF-8"})
	@JsonView(Views.BugAffLibs.class)
	public ResponseEntity<List<AffectedLibrary>> addAffectedLibrary(@PathVariable String bugid, @RequestParam(value="source", required=true) AffectedVersionSource source, @RequestBody AffectedLibrary[] affectedLibraries) {
		//Ensure that PUT is only used by CHECK_VERSION or PATCH EVAL results
		final StopWatch sw = new StopWatch("PUT affected libraries for source: " + source).start();
//		if(!source.equals(AffectedVersionSource.CHECK_VERSION)&&!source.equals(AffectedVersionSource.AST_EQUALITY)&&!source.equals(AffectedVersionSource.GREATER_RELEASE)&&!source.equals(AffectedVersionSource.INTERSECTION)&&!source.equals(AffectedVersionSource.MINOR_EQUALITY)&&!source.equals(AffectedVersionSource.MAJOR_EQUALITY)&&!source.equals(AffectedVersionSource.TO_REVIEW) &&!source.equals(AffectedVersionSource.PROPAGATE_MANUAL)){
//			sw.lap("not allowed",true);
//			return new ResponseEntity<List<AffectedLibrary>>(HttpStatus.UNPROCESSABLE_ENTITY);
//		}
		
		// Ensure that bug exists
		Bug bug = null;
		try { bug = BugRepository.FILTER.findOne(this.bugRepository.findByBugId(bugid)); }
		catch (EntityNotFoundException e) { return new ResponseEntity<List<AffectedLibrary>>(HttpStatus.NOT_FOUND); }

		// Ensure consistency of path variable and JSON content
		for(AffectedLibrary afflib: affectedLibraries)
			if(!source.equals(afflib.getSource())){
				sw.lap("path/json inconsistency",true);
				return new ResponseEntity<List<AffectedLibrary>>(HttpStatus.UNPROCESSABLE_ENTITY);
			}
		sw.stop();
		// Save and return
		return new ResponseEntity<List<AffectedLibrary>>(this.afflibRepository.customSave(bug, affectedLibraries), HttpStatus.OK);
	}
 
源代码3 项目: spring-boot-shiro   文件: GlobalExceptionHand.java
/**
 * 422 - UNPROCESSABLE_ENTITY
 */
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(MaxUploadSizeExceededException.class)
public Response handleMaxUploadSizeExceededException(Exception e) {
    String msg = "所上传文件大小超过最大限制,上传失败!";
    log.error(msg, e);
    return new Response().failure(msg);
}
 
/**
 * Add booking with the specified information.
 *
 * @param bookingVO
 * @return A non-null booking.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Booking> add(@RequestBody BookingVO bookingVO) {
    logger.info(String.format("booking-service add() invoked: %s for %s", bookingService.getClass().getName(), bookingVO.getName()));
    System.out.println(bookingVO);
    Booking booking = new Booking(null, null, null, null, null, null, null);
    BeanUtils.copyProperties(bookingVO, booking);
    try {
        bookingService.add(booking);
    } catch (Exception ex) {
        logger.log(Level.WARNING, "Exception raised add Booking REST Call {0}", ex);
        return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
    }
    return new ResponseEntity<>(HttpStatus.CREATED);
}
 
/**
 * Add restaurant with the specified information.
 *
 * @param restaurantVO
 * @return A non-null restaurant.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Restaurant> add(@RequestBody RestaurantVO restaurantVO) {
    logger.info(String.format("restaurant-service add() invoked: %s for %s", restaurantService.getClass().getName(), restaurantVO.getName()));
    System.out.println(restaurantVO);
    Restaurant restaurant = new Restaurant(null, null, null, null);
    BeanUtils.copyProperties(restaurantVO, restaurant);
    try {
        restaurantService.add(restaurant);
    } catch (Exception ex) {
        logger.log(Level.WARNING, "Exception raised add Restaurant REST Call {0}", ex);
        return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
    }
    return new ResponseEntity<>(HttpStatus.CREATED);
}
 
/**
 * Add restaurant with the specified information.
 *
 * @param restaurantVO
 * @return A non-null restaurant.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Restaurant> add(@RequestBody RestaurantVO restaurantVO) {
    logger.info(String.format("restaurant-service add() invoked: %s for %s", restaurantService.getClass().getName(), restaurantVO.getName()));
    System.out.println(restaurantVO);
    Restaurant restaurant = new Restaurant(null, null, null, null);
    BeanUtils.copyProperties(restaurantVO, restaurant);
    try {
        restaurantService.add(restaurant);
    } catch (Exception ex) {
        logger.log(Level.WARNING, "Exception raised add Restaurant REST Call {0}", ex);
        return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
    }
    return new ResponseEntity<>(HttpStatus.CREATED);
}
 
源代码7 项目: hygieia-core   文件: TestRestTemplate.java
@Override
public <T> ResponseEntity<T> exchange(String var1, HttpMethod var2, HttpEntity<?> var3, Class<T> var4, Object... var5) throws RestClientException {

    if (response.containsKey(var1)) {
        return new ResponseEntity(response.get(var1).getBody(),response.get(var1).getStatus());
    } else {
        return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
    }
}
 
/**
 * Add booking with the specified information.
 *
 * @param bookingVO
 * @return A non-null booking.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Booking> add(@RequestBody BookingVO bookingVO) {
    logger.info(String.format("booking-service add() invoked: %s for %s", bookingService.getClass().getName(), bookingVO.getName()));
    System.out.println(bookingVO);
    Booking booking = new Booking(null, null, null, null, null, null, null);
    BeanUtils.copyProperties(bookingVO, booking);
    try {
        bookingService.add(booking);
    } catch (Exception ex) {
        logger.log(Level.WARNING, "Exception raised add Booking REST Call {0}", ex);
        return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
    }
    return new ResponseEntity<>(HttpStatus.CREATED);
}
 
源代码9 项目: football-events   文件: DemoApplication.java
private void rest(String[] line) {
    String httpMethod = line[1];
    String url = line[2];
    String body = line[3];
    body = applyParams(line, 4, body, isoFormat);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpStatus statusCode = null;

    for (int i = 0; i < 3; i++) {
        try {
            statusCode = fbApp.command(url, HttpMethod.valueOf(httpMethod), body);

            if (statusCode.is2xxSuccessful()) {
                logger.debug("{} {} {} {}", statusCode, httpMethod, url, body);
                return;
            }
            if (statusCode == HttpStatus.NOT_FOUND || statusCode == HttpStatus.UNPROCESSABLE_ENTITY) {
                logger.warn("retry {} {} {} {}", statusCode, httpMethod, url, body);
                sleep(2000);
                continue;
            }
            throw new RuntimeException(statusCode + " " + httpMethod + " " + url + " " + body);
        } catch (RestClientException e) {
            throw new RuntimeException(httpMethod + " " + url + " " + body, e);
        }
    }
    throw new RuntimeException("Response status is still " + statusCode + " " + httpMethod + " " + url
            + " " + body);
}
 
/**
 * Add restaurant with the specified information.
 *
 * @param restaurantVO
 * @return A non-null restaurant.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Restaurant> add(@RequestBody RestaurantVO restaurantVO) {
    logger.info(String.format("restaurant-service add() invoked: %s for %s", restaurantService.getClass().getName(), restaurantVO.getName()));
    System.out.println(restaurantVO);
    Restaurant restaurant = new Restaurant(null, null, null, null);
    BeanUtils.copyProperties(restaurantVO, restaurant);
    try {
        restaurantService.add(restaurant);
    } catch (Exception ex) {
        logger.log(Level.WARNING, "Exception raised add Restaurant REST Call {0}", ex);
        return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
    }
    return new ResponseEntity<>(HttpStatus.CREATED);
}
 
/**
 * Add user with the specified information.
 *
 * @param userVO
 * @return A non-null user.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<User> add(@RequestBody UserVO userVO) {
    logger.info(String.format("user-service add() invoked: %s for %s", userService.getClass().getName(), userVO.getName()));
    System.out.println(userVO);
    User user = new User(null, null, null, null, null);
    BeanUtils.copyProperties(userVO, user);
    try {
        userService.add(user);
    } catch (Exception ex) {
        logger.log(Level.WARNING, "Exception raised add Booking REST Call {0}", ex);
        return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
    }
    return new ResponseEntity<>(HttpStatus.CREATED);
}
 
源代码12 项目: spring-boot-jwt   文件: UserService.java
public String signup(User user) {
  if (!userRepository.existsByUsername(user.getUsername())) {
    user.setPassword(passwordEncoder.encode(user.getPassword()));
    userRepository.save(user);
    return jwtTokenProvider.createToken(user.getUsername(), user.getRoles());
  } else {
    throw new CustomException("Username is already in use", HttpStatus.UNPROCESSABLE_ENTITY);
  }
}
 
/**
 * Add user with the specified information.
 *
 * @param userVO
 * @return A non-null user.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<User> add(@RequestBody UserVO userVO) {
    logger.info(String.format("user-service add() invoked: %s for %s", userService.getClass().getName(), userVO.getName()));
    System.out.println(userVO);
    User user = new User(null, null, null, null, null);
    BeanUtils.copyProperties(userVO, user);
    try {
        userService.add(user);
    } catch (Exception ex) {
        logger.log(Level.WARNING, "Exception raised add Booking REST Call {0}", ex);
        return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
    }
    return new ResponseEntity<>(HttpStatus.CREATED);
}
 
源代码14 项目: microcks   文件: DynamicMockRestController.java
@RequestMapping(value = "/{service}/{version}/{resource}", method = RequestMethod.POST)
public ResponseEntity<String> createResource(
      @PathVariable("service") String serviceName,
      @PathVariable("version") String version,
      @PathVariable("resource") String resource,
      @RequestParam(value="delay", required=false) Long delay,
      @RequestBody(required=true) String body,
      HttpServletRequest request
) {
   log.debug("Creating a new resource '{}' for service '{}-{}'", resource, serviceName, version);
   long startTime = System.currentTimeMillis();

   serviceName = sanitizeServiceName(serviceName);

   MockContext mockContext = getMockContext(serviceName, version, "POST /" + resource);
   if (mockContext != null) {
      Document document = null;
      GenericResource genericResource = null;

      try {
         // Try parsing body payload that should be json.
         document = Document.parse(body);
         // Now create a generic resource.
         genericResource = new GenericResource();
         genericResource.setServiceId(mockContext.service.getId());
         genericResource.setPayload(document);

         genericResource = genericResourceRepository.save(genericResource);
      } catch (JsonParseException jpe) {
         // Return a 422 code : unprocessable entity.
         return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
      }

      // Append id and wait if specified before returning.
      document.append(ID_FIELD, genericResource.getId());
      waitForDelay(startTime, delay, mockContext);
      return new ResponseEntity<>(document.toJson(), HttpStatus.CREATED);
   }
   // Return a 400 code : bad request.
   return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
 
@ExceptionHandler(TestException.class)
public ModelAndView handleException() {
	return new ModelAndView("view", HttpStatus.UNPROCESSABLE_ENTITY);
}
 
@ExceptionHandler(TestException.class)
public ModelAndView handleException() {
	return new ModelAndView("view", HttpStatus.UNPROCESSABLE_ENTITY);
}
 
源代码17 项目: jlineup   文件: JLineupController.java
@ExceptionHandler(BrowserNotInstalledException.class)
public ResponseEntity<String> exceptionHandler(final BrowserNotInstalledException exception) {
    // https://httpstatuses.com/422
    return new ResponseEntity<>(String.format("Browser %s is not installed or not configured on server side.", exception.getDesiredBrowser().name()), HttpStatus.UNPROCESSABLE_ENTITY);
}
 
源代码18 项目: coderadar   文件: ExceptionHandlerController.java
@ExceptionHandler(ProjectIsBeingProcessedException.class)
public ResponseEntity<ErrorMessageResponse> projectProcessingException(
    ProjectIsBeingProcessedException e) {
  return new ResponseEntity<>(
      new ErrorMessageResponse(e.getMessage()), HttpStatus.UNPROCESSABLE_ENTITY);
}
 
源代码19 项目: jlineup   文件: JLineupController.java
@ExceptionHandler(ValidationError.class)
public ResponseEntity<String> exceptionHandler(final ValidationError exception) {
    return new ResponseEntity<>(exception.getMessage(), HttpStatus.UNPROCESSABLE_ENTITY);
}
 
/**
 * Handle a {@link ServiceInstanceBindingDoesNotExistException}
 *
 * @param ex the exception
 * @return an error message
 */
@ExceptionHandler(ServiceInstanceBindingDoesNotExistException.class)
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
public ErrorMessage handleException(ServiceInstanceBindingDoesNotExistException ex) {
	return getErrorResponse(ex);
}