本文整理汇总了Java中javax.validation.Validator类的典型用法代码示例。如果您正苦于以下问题:Java Validator类的具体用法?Java Validator怎么用?Java Validator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Validator类属于javax.validation包,在下文中一共展示了Validator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: create
import javax.validation.Validator; //导入依赖的package包/类
public void create(T entity) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity);
if(constraintViolations.size() > 0){
Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
while(iterator.hasNext()){
ConstraintViolation<T> cv = iterator.next();
System.err.println(cv.getRootBeanClass().getName()+"."+cv.getPropertyPath() + " " +cv.getMessage());
System.err.println(cv.getRootBeanClass().getSimpleName()+"."+cv.getPropertyPath() + " " +cv.getMessage());
}
}else{
getEntityManager().persist(entity);
}
}
示例2: onInitialize
import javax.validation.Validator; //导入依赖的package包/类
@Override
protected void onInitialize() {
super.onInitialize();
add(new INullAcceptingValidator<T>() {
@Override
public void validate(IValidatable<T> validatable) {
Validator validator = AppLoader.getInstance(Validator.class);
Set<?> violations = validator.validateValue(
propertyDescriptor.getBeanClass(),
propertyDescriptor.getPropertyName(),
validatable.getValue());
for (Object each: violations) {
ConstraintViolation<?> violation = (ConstraintViolation<?>) each;
addError(violation.getMessage());
}
}
});
add(new AttributeAppender("class", " property editor editable"));
}
示例3: validate
import javax.validation.Validator; //导入依赖的package包/类
@Override
public void validate(Object entity) throws HttpException {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Object>> violations = validator.validate(entity);
if (!violations.isEmpty()) {
List<ConstraintViolationDescription> errors = new ArrayList<>();
ConstraintViolationResponseError error = new ConstraintViolationResponseError();
error.setMessage(UNPROCESSABLE_ENTITY_MESSAGE);
for (ConstraintViolation<Object> violation : violations) {
String attribute = violation.getPropertyPath().toString();
String message = violation.getMessage();
errors.add(new ConstraintViolationDescription(message, attribute));
}
error.setErrors(errors);
throw new UnprocessableEntityException(error);
}
}
示例4: KvMapperFactory
import javax.validation.Validator; //导入依赖的package包/类
@Autowired
@SuppressWarnings("unchecked")
public KvMapperFactory(ObjectMapper objectMapper, KeyValueStorage storage, TextEncryptor encryptor, Validator validator) {
this.objectMapper = objectMapper;
this.storage = storage;
this.validator = validator;
ImmutableMap.Builder<Class<?>, FieldSetter> builder = ImmutableMap.builder();
builder.put(Map.class, (field, value) -> {
Map fieldMap = (Map) field;
fieldMap.clear();
if (value != null) {
fieldMap.putAll((Map)value);
}
});
builder.put(Collection.class, (field, value) -> {
Collection fieldColl = (Collection) field;
fieldColl.clear();
fieldColl.addAll((Collection)value);
});
setters = builder.build();
interceptors = ImmutableMap.<Class<?>, PropertyInterceptor>builder()
.put(PropertyCipher.class, new PropertyCipher(encryptor))
.build();
}
示例5: main
import javax.validation.Validator; //导入依赖的package包/类
public static void main(String[] args) {
String src = "src.org/hack/controller";
src = src.replaceAll("/", File.separator + File.separator);
System.out.println(src);
System.out.println("src\\org\\hack\\controller");
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
System.out.println(factory.getMessageInterpolator().getClass());
Validator validator = factory.getValidator();
Blog blog = new Blog("1", "2121", "212", new Date(), 2);
Set<ConstraintViolation<Blog>> constraintViolations = validator.validate(blog);
System.out.println(validator.getClass());
for (ConstraintViolation<Blog> c : constraintViolations) {
System.out.println(c.getInvalidValue() + ":" + c.getMessage());
}
}
示例6: testMapElementAttributeNotNull
import javax.validation.Validator; //导入依赖的package包/类
@Test
public void testMapElementAttributeNotNull() {
ProjectData data = new ProjectData();
data.setValue(null); // violation
Project project = new Project();
project.setId(1L);
project.setName("test");
project.setDataMap(new LinkedHashMap());
project.getDataMap().put("someKey", data);
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
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("dataMap[someKey].value", violation.getPropertyPath().toString());
Assert.assertNotNull(violation.getMessage());
Assert.assertEquals("/data/attributes/dataMap/someKey/value", violation.getErrorData().getSourcePointer());
}
}
示例7: invokeWithinValidation
import javax.validation.Validator; //导入依赖的package包/类
@SuppressWarnings("deprecation")
public static Object invokeWithinValidation(MethodInvocation invocation, Validator validator, Class<?>[] groups)
throws Throwable {
org.hibernate.validator.method.MethodValidator methodValidator = validator.unwrap(org.hibernate.validator.method.MethodValidator.class);
Set<org.hibernate.validator.method.MethodConstraintViolation<Object>> result = methodValidator.validateAllParameters(
invocation.getThis(), invocation.getMethod(), invocation.getArguments(), groups);
if (!result.isEmpty()) {
throw new org.hibernate.validator.method.MethodConstraintViolationException(result);
}
Object returnValue = invocation.proceed();
result = methodValidator.validateReturnValue(
invocation.getThis(), invocation.getMethod(), returnValue, groups);
if (!result.isEmpty()) {
throw new org.hibernate.validator.method.MethodConstraintViolationException(result);
}
return returnValue;
}
示例8: onInitialize
import javax.validation.Validator; //导入依赖的package包/类
@Override
protected void onInitialize() {
super.onInitialize();
add(new IValidator<T>() {
@Override
public void validate(IValidatable<T> validatable) {
Validator validator = AppLoader.getInstance(Validator.class);
for (ConstraintViolation<T> violation: validator.validate(validatable.getValue())) {
ValuePath valuePath = new ValuePath(violation.getPropertyPath());
if (!valuePath.getElements().isEmpty()) {
PathSegment.Property property = (Property) valuePath.getElements().iterator().next();
if (!propertyNames.contains(property.getName()))
continue;
}
ErrorContext errorContext = getErrorContext(valuePath);
errorContext.addError(violation.getMessage());
}
}
});
add(AttributeAppender.append("class", " bean editor editable"));
}
示例9: getAccounts
import javax.validation.Validator; //导入依赖的package包/类
public List<Account> getAccounts() {
final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
final ObjectMapper mapper = new ObjectMapper()
.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
List<Account> accounts = null;
try {
accounts = mapper.readValue(rulesFile,
new TypeReference<List<Account>>() {});
if (accounts != null) {
accounts.forEach((account) -> {
final Set<ConstraintViolation<Account>> accountViolations = validator.validate(account);
if (accountViolations.size() > 0) {
throw new AccountValidationException(accountViolations);
}
account.getRules().sort((o1, o2) -> o1.getType().compareTo(o2.getType()));
});
}
} catch (IOException ex) {
Logger.getLogger(AccountService.class.getName()).log(Level.SEVERE, null, ex);
}
return accounts;
}
示例10: configure
import javax.validation.Validator; //导入依赖的package包/类
@Override
protected void configure() {
bind(ObjectMapper.class).toInstance(JavaUtils.newObjectMapper());
bind(MetricRegistry.class).toInstance(new MetricRegistry());
SingularityRunnerBaseLogging.quietEagerLogging();
bind(Validator.class).toInstance(Validation.buildDefaultValidatorFactory().getValidator());
bind(SingularityRunnerExceptionNotifier.class).in(Scopes.SINGLETON);
final Optional<String> consolidatedConfigFilename = Optional.fromNullable(Strings.emptyToNull(System.getProperty(CONFIG_PROPERTY)));
final ConfigurationBinder configurationBinder = ConfigurationBinder.newBinder(binder());
configurationBinder.bindPrimaryConfiguration(primaryConfigurationClass, consolidatedConfigFilename);
for (Class<? extends BaseRunnerConfiguration> additionalConfigurationClass : additionalConfigurationClasses) {
configurationBinder.bindConfiguration(additionalConfigurationClass, consolidatedConfigFilename);
}
if (!additionalConfigurationClasses.contains(SingularityRunnerBaseConfiguration.class)) {
configurationBinder.bindConfiguration(SingularityRunnerBaseConfiguration.class, consolidatedConfigFilename);
}
bind(SingularityRunnerBaseLogging.class).asEagerSingleton();
bind(new TypeLiteral<Optional<String>>(){}).annotatedWith(Names.named(CONSOLIDATED_CONFIG_FILENAME)).toInstance(consolidatedConfigFilename);
}
示例11: validateRequired
import javax.validation.Validator; //导入依赖的package包/类
public List<ConstraintViolation> validateRequired() {
List<ConstraintViolation> returnListreturnList = new ArrayList();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
for (DatasetField dsf : this.getFlatDatasetFields()) {
dsf.setValidationMessage(null); // clear out any existing validation message
Set<ConstraintViolation<DatasetField>> constraintViolations = validator.validate(dsf);
for (ConstraintViolation<DatasetField> constraintViolation : constraintViolations) {
dsf.setValidationMessage(constraintViolation.getMessage());
returnListreturnList.add(constraintViolation);
break; // currently only support one message, so we can break out of the loop after the first constraint violation
}
}
return returnListreturnList;
}
开发者ID:pengchengluo,项目名称:Peking-University-Open-Research-Data-Platform,代码行数:17,代码来源:DatasetVersion.java
示例12: invokeWithinValidation
import javax.validation.Validator; //导入依赖的package包/类
@SuppressWarnings("deprecation")
public static Object invokeWithinValidation(MethodInvocation invocation, Validator validator, Class<?>[] groups)
throws Throwable {
org.hibernate.validator.method.MethodValidator methodValidator =
validator.unwrap(org.hibernate.validator.method.MethodValidator.class);
Set<org.hibernate.validator.method.MethodConstraintViolation<Object>> result =
methodValidator.validateAllParameters(
invocation.getThis(), invocation.getMethod(), invocation.getArguments(), groups);
if (!result.isEmpty()) {
throw new org.hibernate.validator.method.MethodConstraintViolationException(result);
}
Object returnValue = invocation.proceed();
result = methodValidator.validateReturnValue(
invocation.getThis(), invocation.getMethod(), returnValue, groups);
if (!result.isEmpty()) {
throw new org.hibernate.validator.method.MethodConstraintViolationException(result);
}
return returnValue;
}
示例13: main
import javax.validation.Validator; //导入依赖的package包/类
public static void main(String[] args) {
Email email = new Email();
email.setFrom("[email protected]");
email.setTo("someone");
email.setSubject("");
email.setBody(null);
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
Set<ConstraintViolation<Email>> violations = validator.validate(email);
for (ConstraintViolation<Email> constraintViolation : violations) {
String propertyPath = constraintViolation.getPropertyPath().toString();
String message = constraintViolation.getMessage();
System.out.println("invalid value for: '" + propertyPath + "': " + message);
}
}
示例14: testValidation
import javax.validation.Validator; //导入依赖的package包/类
@Test
public void testValidation() throws Exception {
// 検証対象の値を格納したBean
InputBean bean = new InputBean();
bean.setCode("123456");
// Validatorの生成
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator v = factory.getValidator();
// 検証結果を取得、検証メッセージを表示
Set<ConstraintViolation<InputBean>> result = v.validate(bean);
for (ConstraintViolation<InputBean> cv : result) {
System.out.println(cv.getMessage());
System.out.println(cv.getConstraintDescriptor().getAnnotation());
System.out.println(cv.getPropertyPath());
}
}
示例15: validateAdditionalRules
import javax.validation.Validator; //导入依赖的package包/类
public void validateAdditionalRules(ValidationErrors errors) {
// all previous validations return no errors
if (crossFieldValidate && errors.isEmpty()) {
BeanValidation beanValidation = AppBeans.get(BeanValidation.NAME);
Validator validator = beanValidation.getValidator();
Set<ConstraintViolation<Entity>> violations = validator.validate(getItem(), UiCrossFieldChecks.class);
violations.stream()
.filter(violation -> {
Path propertyPath = violation.getPropertyPath();
Path.Node lastNode = Iterables.getLast(propertyPath);
return lastNode.getKind() == ElementKind.BEAN;
})
.forEach(violation -> errors.add(violation.getMessage()));
}
}