下面列出了怎么用javax.validation.ConstraintViolation的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
@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);
}
@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));
}
@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);
}
@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);
}
@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());
}
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]);
}
@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);
}
@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);
}
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;
}
@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の形式で入力してください。");
}
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();
}
@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());
}
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;
}
@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");
}
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);
}
@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);
}
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));
}
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());
}
@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);
}
}
private void validateConfiguration(final Configuration configuration) {
Set<ConstraintViolation<?>> violations = new HashSet<>();
configurationValidators.forEach(
validator -> maybeAdd(violations, validator.validate(configuration))
);
maybePropagate(violations, log);
}