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

The following examples show how to use org.springframework.http.HttpStatus#UNPROCESSABLE_ENTITY . 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: CustomerController.java    From POC with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 2
Source File: BugController.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
	 * 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);
	}
 
Example 3
Source File: GlobalExceptionHand.java    From spring-boot-shiro with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 4
Source File: BookingController.java    From Mastering-Microservices-with-Java-9-Second-Edition with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 5
Source File: UserController.java    From Microservices-Building-Scalable-Software with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 6
Source File: RestaurantController.java    From Microservices-Building-Scalable-Software with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 7
Source File: UserService.java    From spring-boot-jwt with MIT License 5 votes vote down vote up
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);
  }
}
 
Example 8
Source File: UserController.java    From Microservices-Building-Scalable-Software with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 9
Source File: RestaurantController.java    From Mastering-Microservices-with-Java with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 10
Source File: TestRestTemplate.java    From hygieia-core with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 11
Source File: BookingController.java    From Mastering-Microservices-with-Java with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 12
Source File: DemoApplication.java    From football-events with MIT License 5 votes vote down vote up
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);
}
 
Example 13
Source File: RestaurantController.java    From Mastering-Microservices-with-Java-9-Second-Edition with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 14
Source File: JLineupController.java    From jlineup with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(ValidationError.class)
public ResponseEntity<String> exceptionHandler(final ValidationError exception) {
    return new ResponseEntity<>(exception.getMessage(), HttpStatus.UNPROCESSABLE_ENTITY);
}
 
Example 15
Source File: ExceptionHandlerController.java    From coderadar with MIT License 4 votes vote down vote up
@ExceptionHandler(ProjectIsBeingProcessedException.class)
public ResponseEntity<ErrorMessageResponse> projectProcessingException(
    ProjectIsBeingProcessedException e) {
  return new ResponseEntity<>(
      new ErrorMessageResponse(e.getMessage()), HttpStatus.UNPROCESSABLE_ENTITY);
}
 
Example 16
Source File: JLineupController.java    From jlineup with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 17
Source File: ServletAnnotationControllerHandlerMethodTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@ExceptionHandler(TestException.class)
public ModelAndView handleException() {
	return new ModelAndView("view", HttpStatus.UNPROCESSABLE_ENTITY);
}
 
Example 18
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@ExceptionHandler(TestException.class)
public ModelAndView handleException() {
	return new ModelAndView("view", HttpStatus.UNPROCESSABLE_ENTITY);
}
 
Example 19
Source File: DynamicMockRestController.java    From microcks with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 20
Source File: ServiceBrokerExceptionHandler.java    From spring-cloud-open-service-broker with Apache License 2.0 2 votes vote down vote up
/**
 * 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);
}