本文整理汇总了Java中javax.validation.Validation类的典型用法代码示例。如果您正苦于以下问题:Java Validation类的具体用法?Java Validation怎么用?Java Validation使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Validation类属于javax.validation包,在下文中一共展示了Validation类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: create
import javax.validation.Validation; //导入依赖的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: main
import javax.validation.Validation; //导入依赖的package包/类
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
AutoRunHelper.run(App.class);
// 测试参数校验
App app = new App();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
ExecutableValidator executableValidator = factory.getValidator().forExecutables();
Method method = App.class.getMethod("showEmail", String.class);
Object[] parameterValues = {"email"};
Set<ConstraintViolation<App>> violations = executableValidator.validateParameters(app, method, parameterValues);
String message = violations.iterator().hasNext() ? violations.iterator().next().getMessage() : "";
System.out.println("values:" + parameterValues[0].toString() + " size: " + violations.size() + " msg:" + message);
Object[] parameterValues2 = {"abc"};
violations = executableValidator.validateParameters(app, method, parameterValues2);
message = violations.iterator().hasNext() ? violations.iterator().next().getMessage() : "";
System.out.println("values:" + parameterValues2[0].toString() + " size: " + violations.size() + " msg:" + message);
}
示例3: loads
import javax.validation.Validation; //导入依赖的package包/类
@Test
public void loads() {
Pessoa pessoa = new Pessoa();
pessoa.setNome("João da Silva");
pessoa.setCpf("12345678901");
pessoa.setTelefone("(11)3266-4455");
pessoa.setEndereco("Rua A, 123, Bananal, Guarulhos - SP");
Check check = new SafeguardCheck();
/*Validação manual usando a interface Check*/
Check resultados = check.elementOf(pessoa).validate();
int quantidadeDeElementosInvalidos = resultados.getInvalidElements().size();
boolean temErro = resultados.hasError();
/*Validação pelo provedor de validação, usando javax.validation*/
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
javax.validation.Validator validator = factory.getValidator();
Set<ConstraintViolation<Pessoa>> violacoes = validator.validate(pessoa, Default.class);
Assert.assertEquals(1, quantidadeDeElementosInvalidos);
Assert.assertEquals(true, temErro);
Assert.assertEquals(1, violacoes.size());
}
示例4: validate
import javax.validation.Validation; //导入依赖的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);
}
}
示例5: main
import javax.validation.Validation; //导入依赖的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: getAccounts
import javax.validation.Validation; //导入依赖的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;
}
示例7: testMapElementAttributeNotNull
import javax.validation.Validation; //导入依赖的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());
}
}
示例8: afterPropertiesSet
import javax.validation.Validation; //导入依赖的package包/类
@Override
public void afterPropertiesSet() {
if (this.validatorFactory == null) {
this.validatorFactory = Validation.buildDefaultValidatorFactory();
}
ValidatorContext validatorContext = this.validatorFactory.usingContext();
MessageInterpolator targetInterpolator = this.messageInterpolator;
if (targetInterpolator == null) {
targetInterpolator = this.validatorFactory.getMessageInterpolator();
}
validatorContext.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator));
if (this.traversableResolver != null) {
validatorContext.traversableResolver(this.traversableResolver);
}
setTargetValidator(validatorContext.getValidator());
}
示例9: doValidation
import javax.validation.Validation; //导入依赖的package包/类
/**
* Validoi annettu bean:in siinä annettuja BeanValidation annotaatio-ehtoja vasten.
*
* @param bean
* Validoitava bean.
* @return Listaus löytyneistä validointivirheistä.
*/
public Set<ConstraintViolation<T>> doValidation(T bean) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<T>> errors = validator.validate(bean);
return errors;
}
示例10: validate
import javax.validation.Validation; //导入依赖的package包/类
public static <T> void validate(T object) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<T>> validatorSet = validator.validate(object);
validatorSet.forEach(cv -> {
throw new BeanValidationException(cv.getPropertyPath() + " - " + cv.getMessage());
});
}
示例11: JValidator
import javax.validation.Validation; //导入依赖的package包/类
@SuppressWarnings({ "unchecked", "rawtypes" })
public JValidator(URL url) {
this.clazz = ReflectUtils.forName(url.getServiceInterface());
String jvalidation = url.getParameter("jvalidation");
ValidatorFactory factory;
if (jvalidation != null && jvalidation.length() > 0) {
factory = Validation.byProvider((Class)ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory();
} else {
factory = Validation.buildDefaultValidatorFactory();
}
this.validator = factory.getValidator();
}
示例12: FileBackedTransactionConfigDataSource
import javax.validation.Validation; //导入依赖的package包/类
@Inject
public FileBackedTransactionConfigDataSource(ConfigConfiguration configuration,
ConfigurationFactoryFactory<TransactionConfigEntityData> configurationFactoryFactory,
ObjectMapper objectMapper) {
super(
configuration,
configurationFactoryFactory.create(TransactionConfigEntityData.class,
Validation.buildDefaultValidatorFactory().getValidator(),
objectMapper,
"hub"),
TRANSACTIONS_DATA_DIRECTORY
);
}
示例13: FileBackedCountriesConfigDataSource
import javax.validation.Validation; //导入依赖的package包/类
@Inject
public FileBackedCountriesConfigDataSource(
ConfigConfiguration configuration,
ConfigurationFactoryFactory<CountriesConfigEntityData> configurationFactoryFactory,
ObjectMapper objectMapper) {
super(
configuration,
configurationFactoryFactory.create(CountriesConfigEntityData.class,
Validation.buildDefaultValidatorFactory().getValidator(),
objectMapper,
"hub"),
COUNTRIES_DATA_DIRECTORY
);
}
示例14: FileBackedMatchingServiceConfigDataSource
import javax.validation.Validation; //导入依赖的package包/类
@Inject
public FileBackedMatchingServiceConfigDataSource(
ConfigConfiguration configuration,
ConfigurationFactoryFactory<MatchingServiceConfigEntityData> configurationFactoryFactory,
ObjectMapper objectMapper) {
super(
configuration,
configurationFactoryFactory.create(MatchingServiceConfigEntityData.class,
Validation.buildDefaultValidatorFactory().getValidator(),
objectMapper,
"hub"),
MATCHING_SERVICE_DATA_DIRECTORY
);
}
示例15: FileBackedIdentityProviderConfigDataSource
import javax.validation.Validation; //导入依赖的package包/类
@Inject
public FileBackedIdentityProviderConfigDataSource(
ConfigConfiguration configuration,
ConfigurationFactoryFactory<IdentityProviderConfigEntityData> configurationFactoryFactory,
ObjectMapper objectMapper) {
super(
configuration,
configurationFactoryFactory.create(IdentityProviderConfigEntityData.class,
Validation.buildDefaultValidatorFactory().getValidator(),
objectMapper,
"hub"),
IDENTITY_PROVIDER_DATA_DIRECTORY
);
}