javax.validation.ConstraintViolation源码实例Demo

org.springframework.web.bind.annotation.ExceptionHandler#javax.validation.ConstraintViolation源码实例Demo

下面列出了org.springframework.web.bind.annotation.ExceptionHandler#javax.validation.ConstraintViolation 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: carbon-apimgt   文件: RestApiUtil.java
public static <T> ErrorDTO getConstraintViolationErrorDTO(Set<ConstraintViolation<T>> violations) {
    ErrorDTO errorDTO = new ErrorDTO();
    errorDTO.setDescription("Validation Error");
    errorDTO.setMessage("Bad Request");
    errorDTO.setCode(400l);
    errorDTO.setMoreInfo("");
    List<ErrorListItemDTO> errorListItemDTOs = new ArrayList<>();
    for (ConstraintViolation violation : violations) {
        ErrorListItemDTO errorListItemDTO = new ErrorListItemDTO();
        errorListItemDTO.setCode(400 + "_" + violation.getPropertyPath());
        errorListItemDTO.setMessage(violation.getPropertyPath() + ": " + violation.getMessage());
        errorListItemDTOs.add(errorListItemDTO);
    }
    errorDTO.setError(errorListItemDTOs);
    return errorDTO;
}
 
源代码2 项目: sinavi-jfw   文件: MinLengthTest.java
@Theory
public void override_message_test(String invalid) {

    Assume.assumeThat(Arrays.asList(INVALIDS), hasItem(invalid));
    class MinLengthTargetBean {

        @MinLength(value = 5, message = "{value}文字を超える値のみ入力可能です。${validatedValue}")
        public String value;
    }
    MinLengthTargetBean target = new MinLengthTargetBean();
    target.value = invalid;
    Set<ConstraintViolation<MinLengthTargetBean>> errors = VALIDATOR.validate(target);
    assertThat(errors, notNullValue());
    assertThat(errors.size(), is(1));
    assertEqualsErrorMessages(errors, "5文字を超える値のみ入力可能です。" + invalid);
}
 
源代码3 项目: sinavi-jfw   文件: DecimalTest.java
@Theory
public void validWithSigned(String sign, String precision, String scale) {

    Assume.assumeThat(Arrays.asList(SIGN), hasItem(sign));
    Assume.assumeThat(Arrays.asList(PRECISION), hasItem(precision));
    Assume.assumeThat(Arrays.asList(SCALE), hasItem(scale));
    class DecimalTargetBean {

        @Decimal(precision = 7, scale = 3, signed = true)
        public String value;
    }
    DecimalTargetBean target = new DecimalTargetBean();
    target.value = sign + precision + scale;
    Set<ConstraintViolation<DecimalTargetBean>> errors = VALIDATOR.validate(target);
    assertThat(errors, notNullValue());
    assertThat(errors.size(), is(0));
}
 
源代码4 项目: Java-EE-8-Sampler   文件: ClientChoiceTest.java
@Test
public void givenMapWithConstraints_shouldValidate() {

    ClientChoice clientChoice = new ClientChoice();

    clientChoice.addClientChoices("John", new ArrayList<Choice>() {{
        add(new Choice(1, "Roast Lamb"));
        add(new Choice(1, "Ice Cream"));
        add(new Choice(1, "Apple"));
    }});

    clientChoice.addClientChoices("May", new ArrayList<Choice>() {{
        add(new Choice(1, "Grapes"));
        add(new Choice(1, "Beef Stake"));
        add(new Choice(1, "Pizza"));
    }});

    Set<ConstraintViolation<ClientChoice>> constraintViolations = validator.validate(clientChoice);
    assertThat(constraintViolations.size()).isEqualTo(0);
}
 
源代码5 项目: jeecg   文件: JformOrderMain2Controller.java
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
@ApiOperation(value="创建订单主信息")
public ResponseMessage<?> create(@ApiParam(name="订单主信息对象")@RequestBody JformOrderMain2Page jformOrderMain2Page, UriComponentsBuilder uriBuilder) {
	//调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息.
	Set<ConstraintViolation<JformOrderMain2Page>> failures = validator.validate(jformOrderMain2Page);
	if (!failures.isEmpty()) {
		return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
	}

	//保存
	List<JformOrderTicket2Entity> jformOrderTicket2List =  jformOrderMain2Page.getJformOrderTicket2List();
	List<JformOrderCustomer2Entity> jformOrderCustomer2List =  jformOrderMain2Page.getJformOrderCustomer2List();
	
	JformOrderMain2Entity jformOrderMain2 = new JformOrderMain2Entity();
	try{
		MyBeanUtils.copyBeanNotNull2Bean(jformOrderMain2Page,jformOrderMain2);
	}catch(Exception e){
           logger.info(e.getMessage());
           return Result.error("保存订单主信息失败");
       }
	jformOrderMain2Service.addMain(jformOrderMain2, jformOrderTicket2List,jformOrderCustomer2List);

	return Result.success(jformOrderMain2);
}
 
源代码6 项目: credhub   文件: CertificateSetRequestTest.java
@Test
public void whenTheValueIsValid_doesNotRequireTheCertificate() {
  final String setJson = JSONObject.toJSONString(
    ImmutableMap.<String, String>builder()
      .put("ca", TEST_CA)
      .put("private_key", TEST_PRIVATE_KEY)
      .build());

  final String json = "{"
    + "\"name\": \"/example/certificate\","
    + "\"type\": \"certificate\","
    + "\"value\": " + setJson
    + "}";

  final Set<ConstraintViolation<CertificateSetRequest>> violations = deserializeAndValidate(json,
    CertificateSetRequest.class);
  assertThat(violations.size(), equalTo(0));

  final CertificateSetRequest certificateSetRequest = deserialize(json, CertificateSetRequest.class);
  assertNull(certificateSetRequest.getCertificateValue().getCertificate());
}
 
源代码7 项目: krazo   文件: ConstraintViolations.java
private static Annotation[] getPropertyAnnotations(ConstraintViolation<?> violation, Path.PropertyNode node) {

        Class<?> leafBeanClass = violation.getLeafBean().getClass();
        Set<Annotation> allAnnotations = new HashSet<>();
        try {

            Field field = leafBeanClass.getDeclaredField(node.getName());
            allAnnotations.addAll(Arrays.asList(field.getAnnotations()));

        } catch (NoSuchFieldException e) {
            // ignore for now
        }

        allAnnotations.addAll(readAndWriteMethodAnnotationsForField(leafBeanClass, node.getName()));

        return allAnnotations.toArray(new Annotation[0]);
    }
 
源代码8 项目: crnk-framework   文件: ValidationEndToEndTest.java
@Test
public void testResourceObjectValidation() {
	Project project = new Project();
	project.setId(1L);
	project.setName(ComplexValidator.INVALID_NAME);
	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("{complex.message}", violation.getMessageTemplate());
		Assert.assertEquals("", violation.getPropertyPath().toString());
		Assert.assertEquals("", violation.getErrorData().getSourcePointer());
	}
}
 
@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);
}
 
源代码10 项目: springdoc-openapi   文件: GlobalControllerAdvice.java
@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);
}
 
源代码11 项目: syndesis   文件: AbstractResourceUpdateHandler.java
protected <V> List<LeveledMessage> computeValidatorMessages(Supplier<LeveledMessage.Builder> supplier, V target) {
    final List<LeveledMessage> messages = new ArrayList<>();
    final Set<ConstraintViolation<V>> constraintViolations = validator.validate(target, AllValidations.class);

    for (ConstraintViolation<V> violation : constraintViolations) {
        messages.add(
            supplier.get()
                .code(LeveledMessage.Code.SYNDESIS008)
                .level(LeveledMessage.Level.ERROR)
                .message(violation.getMessage())
                .build()
        );
    }

    return messages;
}
 
源代码12 项目: sinavi-jfw   文件: IPv4Test.java
@Theory
public void default_message_test(String invalid) {

    Assume.assumeThat(Arrays.asList(INVALIDS), hasItem(invalid));
    class IPv4TargetBean {

        @IPv4
        public String value;
    }
    IPv4TargetBean target = new IPv4TargetBean();
    target.value = invalid;
    Set<ConstraintViolation<IPv4TargetBean>> errors = VALIDATOR.validate(target);
    assertThat(errors, notNullValue());
    assertThat(errors.size(), is(1));
    assertEqualsErrorMessages(errors, "IPv4の形式で入力してください。");
}
 
源代码13 项目: syndesis   文件: ExtensionHandler.java
private Set<Violation> doValidate(Extension extension) {
    ListResult<Extension> result = getDataManager().fetchAll(Extension.class);
    ExtensionWithDomain target = new ExtensionWithDomain(extension, result.getItems());

    final Set<ConstraintViolation<ExtensionWithDomain>> constraintViolations =
        getValidator().validate(target, Default.class, AllValidations.class);

    if (!constraintViolations.isEmpty()) {
        throw new ConstraintViolationException(constraintViolations);
    }

    Set<ConstraintViolation<ExtensionWithDomain>> warnings =
        getValidator().validate(target, NonBlockingValidations.class);
    return warnings.stream()
        .map(Violation.Builder::fromConstraintViolation)
        .collect(Collectors.toSet());
}
 
@Test  // SPR-13406
public void testApplyMessageSourceResolvableToStringArgumentValueWithUnresolvedLogicalFieldName() {
	TestBean testBean = new TestBean();
	testBean.setEmail("[email protected]");
	testBean.setConfirmEmail("[email protected]");

	BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean");
	validatorAdapter.validate(testBean, errors);

	assertThat(errors.getFieldErrorCount("email"), is(1));
	assertThat(errors.getFieldValue("email"), is("[email protected]"));
	assertThat(errors.getFieldErrorCount("confirmEmail"), is(1));
	FieldError error1 = errors.getFieldError("email");
	FieldError error2 = errors.getFieldError("confirmEmail");
	assertNotNull(error1);
	assertNotNull(error2);
	assertThat(messageSource.getMessage(error1, Locale.ENGLISH), is("email must be same value as confirmEmail"));
	assertThat(messageSource.getMessage(error2, Locale.ENGLISH), is("Email required"));
	assertTrue(error1.contains(ConstraintViolation.class));
	assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("email"));
	assertTrue(error2.contains(ConstraintViolation.class));
	assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("confirmEmail"));
}
 
private Set<ConstraintViolation<Object>> validate(final Validator validator, final Object item) throws ClassNotFoundException {
    final Set<ConstraintViolation<Object>> result;
    if (group == null) {
        result = validator.validate(item);
    } else {
        result = validator.validate(item, loadGroup());
    }
    return result;
}
 
@Test
public void noKeyVaultConfigsReturnsEmptySet() {
    KeyConfiguration keyConfiguration = new KeyConfiguration();

    Set<ConstraintViolation<?>> results = validator.validate(keyConfiguration, null);
    assertThat(results).isEmpty();
}
 
源代码17 项目: sinavi-jfw   文件: AfterTest.java
@Test
public void invalidListAllErrors() throws ParseException {

    AfterListTestBean target = new AfterListTestBean();
    target.setFromDate1(toDate("2013/07/20"));
    target.setToDate1(toDate("2013/07/21"));
    target.setFromDate2(toDate("2012/11/20"));
    target.setToDate2(toDate("2012/11/21"));
    Set<ConstraintViolation<AfterListTestBean>> errors = VALIDATOR.validate(target);
    assertThat(errors, notNullValue());
    assertThat(errors.size(), is(2));
}
 
@Test
public void testFields() {
    AlphanumericBeanField alphanumericBeanField = new AlphanumericBeanField();

    Set<ConstraintViolation<AlphanumericBeanField>> violations =
            validator.validate(alphanumericBeanField);

    Assert.assertEquals(3, violations.size());
}
 
源代码19 项目: scoold   文件: ScooldUtils.java
public <P extends ParaObject> Map<String, String> validate(P pobj) {
	HashMap<String, String> error = new HashMap<String, String>();
	if (pobj != null) {
		Set<ConstraintViolation<P>> errors = ValidationUtils.getValidator().validate(pobj);
		for (ConstraintViolation<P> err : errors) {
			error.put(err.getPropertyPath().toString(), err.getMessage());
		}
	}
	return error;
}
 
源代码20 项目: act-platform   文件: SearchMetaFactsRequestTest.java
@Test
public void testRequestValidationFailsOnMax() {
  Set<ConstraintViolation<SearchMetaFactsRequest>> violations = getValidator().validate(new SearchMetaFactsRequest()
          .setFact(UUID.randomUUID())
          .setMinimum(1.1f)
          .setMaximum(1.2f)
  );

  assertEquals(2, violations.size());
  assertPropertyInvalid(violations, "minimum");
  assertPropertyInvalid(violations, "maximum");
}
 
源代码21 项目: Java-EE-8-and-Angular   文件: App.java
public void saveWithManualValidation() {
    Task theTask = new Task();
    theTask.setName("A longer name than allowed");

    Set<ConstraintViolation<Task>> violationsFound = validator.validate(theTask);
    violationsFound.stream().map(ConstraintViolation::getMessage).forEach(System.out::println);
}
 
源代码22 项目: parsec-libraries   文件: DateTimeValidatorTest.java
@Test
public void ValidDateTimeTest() {
    List<Set<ConstraintViolation<Entity>>> violations = getViolations(
            "2015-01-17T18:23:02+06:45",
            "2015-01-17T18:23:02Z",
            "2015-01-17T18:23:02-00:00",
            "2015-03-29T18:23:02+00:00"
    );

    for (Set<ConstraintViolation<Entity>> violation : violations) {
        Assert.assertEquals(violation.size(), 0);
    }
}
 
/**
 * Handle an invalid property. Can be:
 * <p>
 * 1. Invalid request parameter (annotated bean param field or annotated resource class field)
 * 2. Invalid request entity property (annotated bean param field)
 *
 * @param constraintViolation
 */
private ValidationError handleInvalidProperty(ConstraintViolation constraintViolation) {

    Path.Node leafNode = getLeafNode(constraintViolation.getPropertyPath()).get();
    Class<?> beanClass = constraintViolation.getLeafBean().getClass();

    // Can be an invalid request parameter (annotated bean param field or annotated resource class field)
    Optional<Field> optionalField = getField(leafNode.getName(), beanClass);
    if (optionalField.isPresent()) {
        Optional<ParameterDetails> optionalParameterDetails = getParameterDetails(optionalField.get().getAnnotations());
        if (optionalParameterDetails.isPresent()) {
            return createErrorForParameter(optionalParameterDetails.get(), constraintViolation);
        }
    }

    // Get Jackson ObjectMapper
    ContextResolver<ObjectMapper> resolver = providers.getContextResolver(ObjectMapper.class, MediaType.WILDCARD_TYPE);
    ObjectMapper mapper = resolver.getContext(ObjectMapper.class);

    // Can be an invalid request entity property (annotated bean param field)
    Optional<String> optionalJsonProperty = getJsonPropertyName(mapper, beanClass, leafNode.getName());
    if (optionalJsonProperty.isPresent()) {
        ValidationError error = new ValidationError();
        error.setType(REQUEST_ENTITY_PROPERTY);
        error.setName(optionalJsonProperty.get());
        error.setMessage(constraintViolation.getMessage());
        return error;
    }

    return handleUnknownSource(constraintViolation);
}
 
源代码24 项目: sinavi-jfw   文件: RequiredsTest.java
private static void assertEqualsErrorMessages(Set<? extends ConstraintViolation<?>> errors,
    String... expectedMessages) {

    List<String> expectedMessagesAsList = Arrays.asList(expectedMessages);
    List<String> actualMessages = new ArrayList<String>();
    for (ConstraintViolation<?> error : errors) {
        actualMessages.add(error.getMessage());
    }
    Collections.sort(expectedMessagesAsList);
    Collections.sort(actualMessages);
    assertThat(actualMessages, is(expectedMessagesAsList));
}
 
源代码25 项目: jim-framework   文件: BaseController.java
private String getConstraintViolationsMsg(Set<ConstraintViolation<?>> constraintViolations){
    if(null==constraintViolations){
        return "";
    }
    StringBuffer stringBuffer=new StringBuffer();
    Iterator<ConstraintViolation<?>> iterable= constraintViolations.iterator();
    while (iterable.hasNext()){
        ConstraintViolation<?> constraintViolation= iterable.next();
        stringBuffer.append(constraintViolation.getMessage()+",");
    }
    return stringBuffer.toString();
}
 
/**
 * Determine a field for the given constraint violation.
 * <p>The default implementation returns the stringified property path.
 * @param violation the current JSR-303 ConstraintViolation
 * @return the Spring-reported field (for use with {@link Errors})
 * @since 4.2
 * @see javax.validation.ConstraintViolation#getPropertyPath()
 * @see org.springframework.validation.FieldError#getField()
 */
protected String determineField(ConstraintViolation<Object> violation) {
	Path path = violation.getPropertyPath();
	StringBuilder sb = new StringBuilder();
	boolean first = true;
	for (Path.Node node : path) {
		if (node.isInIterable()) {
			sb.append('[');
			Object index = node.getIndex();
			if (index == null) {
				index = node.getKey();
			}
			if (index != null) {
				sb.append(index);
			}
			sb.append(']');
		}
		String name = node.getName();
		if (name != null && node.getKind() == ElementKind.PROPERTY && !name.startsWith("<")) {
			if (!first) {
				sb.append('.');
			}
			first = false;
			sb.append(name);
		}
	}
	return sb.toString();
}
 
@Test
public void testType() {
    MinDigitsDoubleBeanType minDigitsDoubleBean = new MinDigitsDoubleBeanType();

    Set<ConstraintViolation<MinDigitsDoubleBeanType>> violations =
            validator.validate(minDigitsDoubleBean);

    Assert.assertEquals(1, violations.size());
}
 
源代码28 项目: sinavi-jfw   文件: NumberTest.java
@Theory
public void validWithSign(Integer valid) {

    Assume.assumeThat(Arrays.asList(VALIDS_WITH_SIGN), hasItem(valid));
    class NumberTargetBean {

        @Number(precision = 4, signed = true)
        public Integer value;
    }
    NumberTargetBean target = new NumberTargetBean();
    target.value = valid;
    Set<ConstraintViolation<NumberTargetBean>> errors = VALIDATOR.validate(target);
    assertThat(errors, notNullValue());
    assertThat(errors.size(), is(0));
}
 
private void buildProblemError(ObjectError objectError, Error.Builder builder) {
  if (objectError.contains(ConstraintViolation.class)) {
    buildProblemErrorConstraintViolation(objectError, builder);
  } else if (objectError.contains(Throwable.class)) {
    buildProblemErrorThrowable(objectError, builder);
  } else {
    buildProblemErrorConstraintViolation(objectError, builder);
  }
}
 
源代码30 项目: nexus-public   文件: RepositoryManagerImpl.java
private void validateConfiguration(final Configuration configuration) {
  Set<ConstraintViolation<?>> violations = new HashSet<>();
  configurationValidators.forEach(
      validator -> maybeAdd(violations, validator.validate(configuration))
  );
  maybePropagate(violations, log);
}