javax.validation.ConstraintViolationException#getConstraintViolations ( )源码实例Demo

下面列出了javax.validation.ConstraintViolationException#getConstraintViolations ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: crnk-framework   文件: ValidationEndToEndTest.java
@Test
public void testListElementAttributeNotNull() {
	ProjectData data = new ProjectData();
	data.setValue(null); // violation

	Project project = new Project();
	project.setId(1L);
	project.setName("test");
	project.getDataList().add(data);

	try {
		projectRepo.create(project);
	} catch (ConstraintViolationException e) {
		Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
		Assert.assertEquals(1, violations.size());
		ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next();
		Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate());
		Assert.assertEquals("dataList[0].value", violation.getPropertyPath().toString());
		Assert.assertNotNull(violation.getMessage());
		Assert.assertEquals("/data/attributes/data-list/0/value", violation.getErrorData().getSourcePointer());
	}
}
 
@Override
public ValidationErrorMessage createBody(ConstraintViolationException ex, HttpServletRequest req) {

    ErrorMessage tmpl = super.createBody(ex, req);
    ValidationErrorMessage msg = new ValidationErrorMessage(tmpl);

    for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
        Node pathNode = findLastNonEmptyPathNode(violation.getPropertyPath());

        // path is probably useful only for properties (fields)
        if (pathNode != null && pathNode.getKind() == ElementKind.PROPERTY) {
            msg.addError(pathNode.getName(), convertToString(violation.getInvalidValue()), violation.getMessage());

        // type level constraints etc.
        } else {
            msg.addError(violation.getMessage());
        }
    }
    return msg;
}
 
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public ResponseEntity<ErrorMessage> handleConstraintViolatedException(ConstraintViolationException ex
) {
	Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();


	List<String> errors = new ArrayList<>(constraintViolations.size());
	String error;
	for (ConstraintViolation constraintViolation : constraintViolations) {

		error = constraintViolation.getMessage();
		errors.add(error);
	}

	ErrorMessage errorMessage = new ErrorMessage(errors);
	return new ResponseEntity(errorMessage, HttpStatus.BAD_REQUEST);
}
 
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public ResponseEntity<ErrorMessage> handleConstraintViolatedException(ConstraintViolationException ex
) {
	Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();


	List<String> errors = new ArrayList<>(constraintViolations.size());
	String error;
	for (ConstraintViolation constraintViolation : constraintViolations) {

		error = constraintViolation.getMessage();
		errors.add(error);
	}

	ErrorMessage errorMessage = new ErrorMessage(errors);
	return new ResponseEntity(errorMessage, HttpStatus.BAD_REQUEST);
}
 
源代码5 项目: crnk-framework   文件: ValidationEndToEndTest.java
@Test
public void testPropertyOnRelationId() {

	ResourceRepository<Schedule, Serializable> scheduleRepo = client.getRepositoryForType(Schedule.class);

	Project project = new Project();
	project.setId(2L);
	project.setName("test");

	Schedule schedule = new Schedule();
	schedule.setId(1L);
	schedule.setName("test");
	schedule.setProjectId(null);
	try {
		scheduleRepo.create(schedule);
	} catch (ConstraintViolationException e) {
		Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
		Assert.assertEquals(1, violations.size());
		ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next();
		Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate());
		Assert.assertEquals("project", violation.getPropertyPath().toString());
		Assert.assertEquals("/data/relationships/project", violation.getErrorData().getSourcePointer());
	}
}
 
@Override
public Response toResponse(ConstraintViolationException exception) {
	ConstraintViolationException ex = (ConstraintViolationException) exception;
	List<FieldError> errors = new ArrayList<FieldError>();
	for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
		errors.add(new FieldError(Inflector.underscore(violation.getPropertyPath().toString()), violation.getMessage(), violation.getInvalidValue()));
	}
	Map<String, List<FieldError>> message = new HashMap<String, List<FieldError>>();
	message.put("fieldErrors", errors);
	return Response.status(UnprocessableEntityStatusType.INSTANCE).entity(message).build();
}
 
源代码7 项目: common-project   文件: ControllerAdviceHandler.java
@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public Object handle(Exception exception) {
    logger.error("错误信息  ====  "+exception.getMessage());
    if (exception instanceof BindException) {
        BindException bindException = (BindException) exception;
        List<FieldError> fieldErrors = bindException.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            return ResponseMessage.error(10010,fieldError.getField() + fieldError.getDefaultMessage());
        }
    }

    if (exception instanceof ConstraintViolationException) {
        ConstraintViolationException exs = (ConstraintViolationException) exception;

        Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            return ResponseMessage.error(10010,violation.getPropertyPath() + violation.getMessage());
        }
    }
    if (exception instanceof HandlerException) {
        HandlerException handlerException = (HandlerException) exception;
        return new ResponseMessage(handlerException.getCode(), handlerException.getErrorInfo());
    }
    if (exception instanceof MissingServletRequestParameterException) {
        MissingServletRequestParameterException missingServletRequestParameterException = (MissingServletRequestParameterException) exception;
        return ResponseMessage.error(10010, "请求参数" + missingServletRequestParameterException.getParameterName() + "不能为空");
    }
    if (exception instanceof FileUploadException) {
        FileUploadException fileUploadException = (FileUploadException) exception;
        return ResponseMessage.error(10010, fileUploadException.getMessage());
    }

    return ResponseMessage.error(0, "服务异常");
}
 
源代码8 项目: crnk-framework   文件: ValidationEndToEndTest.java
@Test
public void testSetElementAttributeNotNull() {
	Project project = new Project();
	project.setId(1L);
	project.setName("test");
	// ProjectData corrupedElement = null;
	for (int i = 0; i < 11; i++) {
		ProjectData data = new ProjectData();
		if (i != 3) {
			data.setValue(Integer.toString(i));
			// corrupedElement = data;
		}
		project.getDataSet().add(data);
	}

	try {
		projectRepo.create(project);
	} catch (ConstraintViolationException e) {
		Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
		Assert.assertEquals(1, violations.size());
		ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next();
		Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate());
		Assert.assertTrue(violation.getPropertyPath().toString().startsWith("dataSet["));
		Assert.assertTrue(violation.getPropertyPath().toString().endsWith("].value"));

		Assert.assertTrue(violation.getErrorData().getSourcePointer().startsWith("/data/attributes/dataSet/"));

		//	TODO attempt to preserver order in Crnk by comparing incoming request, sourcePointer and server Set
		//  or use of order preserving sets
		//			List<ProjectData> list = new ArrayList<>(project.getDataSet());
		//			int index = list.indexOf(corrupedElement);
		//			Assert.assertEquals(violation.getErrorData().getSourcePointer(), "/data/attributes/dataSet/" + index +
		// "/value");
	}
}
 
@Test
public void shouldValidateDeviceId() {
  // given
  final Installation installation = new Installation();
  installation.setDeviceToken("invalid");

  final iOSVariant variant = new iOSVariant();
  variant.setName("iOS Variant Name");
  variant.setPassphrase("12");
  variant.setProduction(false);
  variant.setCertificate("12".getBytes());
  entityManager.persist(variant);
  installation.setVariant(variant);

  // when
  installationDao.create(installation);
  try {
    entityManager.flush();
    fail("ConstraintViolationException should have been thrown");
  } catch (ConstraintViolationException violationException) {
    // then
    final Set<ConstraintViolation<?>> constraintViolations = violationException
        .getConstraintViolations();
    assertThat(constraintViolations).isNotEmpty();
    assertThat(constraintViolations.size()).isEqualTo(1);

    assertThat(constraintViolations.iterator().next().getMessage()).isEqualTo(
        "Device token is not valid for this device type");
  }
}
 
源代码10 项目: nexus-public   文件: ValidationResponse.java
public ValidationResponse(final ConstraintViolationException cause) {
  super(false, new ArrayList<>());
  //noinspection ThrowableResultOfMethodCallIgnored
  checkNotNull(cause);
  Set<ConstraintViolation<?>> violations = cause.getConstraintViolations();
  if (violations != null && !violations.isEmpty()) {
    for (ConstraintViolation<?> violation : violations) {
      List<String> entries = new ArrayList<>();
      // iterate path to get the full path
      Iterator<Node> it = violation.getPropertyPath().iterator();
      while (it.hasNext()) {
        Node node = it.next();
        if (ElementKind.PROPERTY == node.getKind() || (ElementKind.PARAMETER == node.getKind() && !it.hasNext())) {
          if (node.getKey() != null) {
            entries.add(node.getKey().toString());
          }
          entries.add(node.getName());
        }
      }
      if (entries.isEmpty()) {
        if (messages == null) {
          messages = new ArrayList<>();
        }
        messages.add(violation.getMessage());
      }
      else {
        if (errors == null) {
          errors = new HashMap<>();
        }
        errors.put(Joiner.on('.').join(entries), violation.getMessage());
      }
    }
  }
  else if (cause.getMessage() != null) {
    messages = new ArrayList<>();
    messages.add(cause.getMessage());
  }
}
 
源代码11 项目: dubbox-hystrix   文件: RpcExceptionMapper.java
protected Response handleConstraintViolationException(ConstraintViolationException cve) {
    ViolationReport report = new ViolationReport();
    for (ConstraintViolation cv : cve.getConstraintViolations()) {
        report.addConstraintViolation(new RestConstraintViolation(
                cv.getPropertyPath().toString(),
                cv.getMessage(),
                cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString()));
    }
    // TODO for now just do xml output
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(report).type(ContentType.TEXT_XML_UTF_8).build();
}
 
源代码12 项目: BigDataPlatform   文件: GlobalExceptionHandler.java
@ExceptionHandler(ValidationException.class)
@ResponseBody
public Object badArgumentHandler(ValidationException e) {
    logger.error(e.getMessage(), e);
    if (e instanceof ConstraintViolationException) {
        ConstraintViolationException exs = (ConstraintViolationException) e;
        Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
        for (ConstraintViolation<?> item : violations) {
            String message = ((PathImpl) item.getPropertyPath()).getLeafNode().getName() + item.getMessage();
            return ResponseUtil.fail(402, message);
        }
    }
    return ResponseUtil.badArgumentValue();
}
 
源代码13 项目: dubbox   文件: RpcExceptionMapper.java
protected Response handleConstraintViolationException(ConstraintViolationException cve) {
    ViolationReport report = new ViolationReport();
    for (ConstraintViolation cv : cve.getConstraintViolations()) {
        report.addConstraintViolation(new RestConstraintViolation(
                cv.getPropertyPath().toString(),
                cv.getMessage(),
                cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString()));
    }
    // TODO for now just do xml output
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(report).type(ContentType.TEXT_XML_UTF_8).build();
}
 
源代码14 项目: tutorials   文件: ApiExceptionHandler.java
@SuppressWarnings("rawtypes")
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<ErrorResponse> handle(ConstraintViolationException e) {
    ErrorResponse errors = new ErrorResponse();
    for (ConstraintViolation violation : e.getConstraintViolations()) {
        ErrorItem error = new ErrorItem();
        error.setCode(violation.getMessageTemplate());
        error.setMessage(violation.getMessage());
        errors.addError(error);
    }

    return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
 
源代码15 项目: EasyChatServer   文件: RestExceptionAdvice.java
@ExceptionHandler(ConstraintViolationException.class)
public Result<?> handler(ConstraintViolationException e) {
	Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
	List<String> fieldList = new ArrayList<>();
	if (log.isDebugEnabled()) {
		constraintViolations.forEach(f -> {
			fieldList.add(f.getPropertyPath().toString());
			log.debug("field format error: " + toString());
		});
	}
	return Result.fail(ResultCode.PARAM_INVALID, fieldList);
}
 
源代码16 项目: plumemo   文件: RestExceptionHandler.java
/**
 * validation 异常处理
 *
 * @param request 请求体
 * @param e       ConstraintViolationException
 * @return HttpResult
 */
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public Result onConstraintViolationException(HttpServletRequest request,
                                             ConstraintViolationException e) {
    Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
    if (!CollectionUtils.isEmpty(constraintViolations)) {
        String errorMessage = constraintViolations
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(";"));
        return Result.createWithErrorMessage(errorMessage, ErrorEnum.PARAM_ERROR.getCode());
    }
    return Result.createWithErrorMessage(e.getMessage(), ErrorEnum.PARAM_ERROR.getCode());
}
 
@AroundInvoke
@Override
public Object validateMethodInvocation(InvocationContext ctx) throws Exception {
    try {
        return super.validateMethodInvocation(ctx);
    } catch (ConstraintViolationException e) {
        throw new ResteasyViolationExceptionImpl(e.getConstraintViolations(), getAccept(ctx.getMethod()));
    }
}
 
private String prepareMessage(ConstraintViolationException exception) {
    StringBuilder message = new StringBuilder();

    for (ConstraintViolation<?> cv : exception.getConstraintViolations()) {
        message.append(cv.getMessage());
    }
    return message.toString();
}
 
@Override
public Response toResponse(ConstraintViolationException exception) {
    Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
    StringBuilder errors = new StringBuilder();
    constraintViolations.forEach(exc -> errors.append(exc.getMessage()));
    return ResponseFactory.response(BAD_REQUEST,
            new ErrorResponse(BAD_REQUEST.getStatusCode(), errors.toString()));
}
 
源代码20 项目: quarkus-quickstarts   文件: BookResource.java
@Path("/service-method-validation")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Result tryMeServiceMethodValidation(Book book) {
    try {
        bookService.validateBook(book);
        return new Result("Book is valid! It was validated by service method validation.");
    } catch (ConstraintViolationException e) {
        return new Result(e.getConstraintViolations());
    }
}