当前位置: 首页>>代码示例>>Java>>正文


Java Validation类代码示例

本文整理汇总了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);
    }
}
 
开发者ID:jerbaer,项目名称:GoHost,代码行数:17,代码来源:AbstractFacade.java

示例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);

}
 
开发者ID:zhoukekestar,项目名称:java-notes,代码行数:22,代码来源:App.java

示例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());
			  
}
 
开发者ID:gilmardeveloper,项目名称:java-validator-safeguard,代码行数:27,代码来源:TesteDeObjetosAnotados.java

示例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);
    }
    
}
 
开发者ID:tdsis,项目名称:lambda-forest,代码行数:24,代码来源:DefaultRequestValidator.java

示例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());
    }
  }
 
开发者ID:slashchenxiaojun,项目名称:wall.e,代码行数:19,代码来源:Blog.java

示例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;
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Programming-Blueprints,代码行数:24,代码来源:AccountService.java

示例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());
	}
}
 
开发者ID:crnk-project,项目名称:crnk-framework,代码行数:27,代码来源:ValidationEndToEndTest.java

示例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());
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:19,代码来源:CustomValidatorBean.java

示例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;
}
 
开发者ID:TheFinnishSocialInsuranceInstitution,项目名称:KantaCDA-API,代码行数:15,代码来源:BeanValidator.java

示例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());
        });
    }
 
开发者ID:nomemory,项目名称:java-bean-validation-extension,代码行数:11,代码来源:SimpleValidation.java

示例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();
}
 
开发者ID:dachengxi,项目名称:EatDubbo,代码行数:13,代码来源:JValidator.java

示例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
    );
}
 
开发者ID:alphagov,项目名称:verify-hub,代码行数:14,代码来源:FileBackedTransactionConfigDataSource.java

示例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
    );
}
 
开发者ID:alphagov,项目名称:verify-hub,代码行数:15,代码来源:FileBackedCountriesConfigDataSource.java

示例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
    );
}
 
开发者ID:alphagov,项目名称:verify-hub,代码行数:15,代码来源:FileBackedMatchingServiceConfigDataSource.java

示例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
    );
}
 
开发者ID:alphagov,项目名称:verify-hub,代码行数:15,代码来源:FileBackedIdentityProviderConfigDataSource.java


注:本文中的javax.validation.Validation类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。