Java 类javax.validation.Validation 实例源码

项目:GoHost    文件:AbstractFacade.java   
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);
    }
}
项目:java-notes    文件:App.java   
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);

}
项目:java-validator-safeguard    文件:TesteDeObjetosAnotados.java   
@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());

}
项目:wall.e    文件:Blog.java   
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());
    }
  }
项目:Java-9-Programming-Blueprints    文件:AccountService.java   
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;
}
项目:crnk-framework    文件:ValidationEndToEndTest.java   
@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());
    }
}
项目:lambda-forest    文件:DefaultRequestValidator.java   
@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);
    }

}
项目:lams    文件:CustomValidatorBean.java   
@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());
}
项目:KantaCDA-API    文件:BeanValidator.java   
/**
 * 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;
}
项目:java-bean-validation-extension    文件:SimpleValidation.java   
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());
        });
    }
项目:EatDubbo    文件:JValidator.java   
@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();
}
项目:verify-hub    文件:FileBackedTransactionConfigDataSource.java   
@Inject
public FileBackedTransactionConfigDataSource(ConfigConfiguration configuration,
                                             ConfigurationFactoryFactory<TransactionConfigEntityData> configurationFactoryFactory,
                                             ObjectMapper objectMapper) {
    super(
            configuration,
            configurationFactoryFactory.create(TransactionConfigEntityData.class,
                    Validation.buildDefaultValidatorFactory().getValidator(),
                    objectMapper,
                    "hub"),
            TRANSACTIONS_DATA_DIRECTORY
    );
}
项目:verify-hub    文件:FileBackedCountriesConfigDataSource.java   
@Inject
public FileBackedCountriesConfigDataSource(
        ConfigConfiguration configuration,
        ConfigurationFactoryFactory<CountriesConfigEntityData> configurationFactoryFactory,
        ObjectMapper objectMapper) {
    super(
            configuration,
            configurationFactoryFactory.create(CountriesConfigEntityData.class,
                    Validation.buildDefaultValidatorFactory().getValidator(),
                    objectMapper,
                    "hub"),
            COUNTRIES_DATA_DIRECTORY
    );
}
项目:verify-hub    文件:FileBackedMatchingServiceConfigDataSource.java   
@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
    );
}
项目:verify-hub    文件:FileBackedIdentityProviderConfigDataSource.java   
@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
    );
}
项目:safecharge-java    文件:BasePaymentCCTest.java   
@BeforeClass
public static void setup() {
    gson = new GsonBuilder().serializeNulls()
            .create();
    validator = Validation.buildDefaultValidatorFactory()
            .getValidator();
}
项目:jmzTab-m    文件:MzTabValidator.java   
@Override
public List<ValidationMessage> validate(MzTab mzTab) {
    List<ValidationMessage> list = new LinkedList<>();
    ValidatorFactory validatorFactory = Validation.byDefaultProvider()
            .configure()
            .buildValidatorFactory();
    javax.validation.Validator validator = validatorFactory.getValidator();
    Set<ConstraintViolation<MzTab>> violations = validator.validate(mzTab);
    for(ConstraintViolation<MzTab> violation:violations) {
        list.add(new ValidationMessage().message(getPathLocatorString(
            violation)+": "+violation.getMessage()).messageType(ValidationMessage.MessageTypeEnum.ERROR));
    }
    return list;
}
项目:jmzTab-m    文件:MzTabValidatorTest.java   
@Test
public void testDefaultMetadataBeanValidation() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<MzTab>> violations = validator.validate(
        createTestFile());
    for (ConstraintViolation<MzTab> violation : violations) {
        System.err.println("Validation error at " + violation.
            getPropertyPath().
            toString() + ": " + violation.getMessage());
    }
}
项目:dubbo2    文件:JValidator.java   
@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();
}
项目:syndesis    文件:ValidatorContextResolver.java   
@Override
public GeneralValidator getContext(final Class<?> type) {
    final ResourceBundleLocator resourceBundleLocator = new PlatformResourceBundleLocator("messages");
    final MessageInterpolator messageInterpolator = new ResourceBundleMessageInterpolator(resourceBundleLocator);
    final Configuration<?> config = Validation.byDefaultProvider().configure()
        .messageInterpolator(messageInterpolator);
    final BootstrapConfiguration bootstrapConfiguration = config.getBootstrapConfiguration();
    final boolean isExecutableValidationEnabled = bootstrapConfiguration.isExecutableValidationEnabled();
    final Set<ExecutableType> defaultValidatedExecutableTypes = bootstrapConfiguration
        .getDefaultValidatedExecutableTypes();

    return new GeneralValidatorImpl(validatorFactory, isExecutableValidationEnabled,
        defaultValidatedExecutableTypes);
}
项目:syndesis    文件:IntegrationTest.java   
public IntegrationTest() {
    final DefaultConstraintMapping mapping = new DefaultConstraintMapping();
    mapping.constraintDefinition(UniqueProperty.class).validatedBy(UniqnenessValidator.class);
    final ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure()
        .addMapping(mapping).buildValidatorFactory();

    validator = validatorFactory.getValidator();
}
项目:easybinder    文件:BeanValidationBinderStringTest.java   
@Test
public void testValid() {
    TextField text = new TextField();

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Binder<MyEntity> binder = new BeanValidationBinder<>(MyEntity.class);
    binder.forField(text).withNullRepresentation("").bind("text");

    MyEntity t = new MyEntity();

    // valid
    t.setText("bla");
    binder.setBean(t);

    assertTrue(validator.validate(t).isEmpty());
    assertTrue(binder.validate().isOk());

    text.setValue("");
    assertNull(t.getText());

    /*
     * // invalid t.setText(""); binder.setBean(t);
     * assertFalse(validator.validate(t).isEmpty());
     * assertFalse(binder.validate().isOk());
     * 
     * t.setText(null); binder.setBean(t);
     * assertTrue(validator.validate(t).isEmpty());
     * assertTrue(binder.validate().isOk());
     */
}
项目:nifi-registry    文件:TestRegistryService.java   
@Before
public void setup() {
    metadataService = mock(MetadataService.class);
    flowPersistenceProvider = mock(FlowPersistenceProvider.class);
    snapshotSerializer = mock(VersionedProcessGroupSerializer.class);

    final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    validator = validatorFactory.getValidator();

    registryService = new RegistryService(metadataService, flowPersistenceProvider, snapshotSerializer, validator);
}
项目:esup-ecandidat    文件:MethodUtils.java   
/**
 * Valide un bean
 * 
 * @param bean
 * @throws CustomException
 */
public static <T> Boolean validateBean(T bean, Logger logger) {
    logger.debug(" ***VALIDATION*** : " + bean);
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<T>> constraintViolations = validator.validate(bean);
    if (constraintViolations != null && constraintViolations.size() > 0) {
        for (ConstraintViolation<?> violation : constraintViolations) {
            logger.debug(" *** " + violation.getPropertyPath().toString() + " : " + violation.getMessage());
        }
        return false;
    }
    return true;
}
项目:esup-ecandidat    文件:IndividuController.java   
/** Valide un bean d'individu
 * @param ind
 * @throws CustomException
 */
public void validateIndividuBean(Individu ind) throws CustomException{
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<Individu>> constraintViolations = validator.validate(ind);
    if (constraintViolations!=null && constraintViolations.size() > 0) {
        String erreur = ""; 
        for (ConstraintViolation<?> violation : constraintViolations) {
            erreur += (" *** "+ violation.getPropertyPath().toString() + " : " + violation.getMessage());
          }
        throw new CustomException(applicationContext.getMessage("droitprofil.individu.error", null, UI.getCurrent().getLocale())+" : "+erreur);
    }
}
项目:automatic-mower    文件:MowerPosition.java   
public MowerPosition(int x, int y, Direction direction, Lawn lawn) {
    this.x = x;
    this.y = y;
    this.direction = direction;
    this.lawn = lawn;
    this.vf = Validation.buildDefaultValidatorFactory();
}
项目:aaden-pay    文件:PaymentValidate.java   
private void validMust(PayRequest request) throws Exception {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    validator.validate(request.getMust());
    Set<ConstraintViolation<PayMustData>> validators = validator.validate(request.getMust());
    for (ConstraintViolation<PayMustData> constraintViolation : validators) {
        throw new Exception(constraintViolation.getMessage());
    }
}
项目:aaden-pay    文件:PaymentValidate.java   
private void validCash(PayRequest request) throws Exception {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    validator.validate(request.getCash());
    Set<ConstraintViolation<PayCashData>> validators = validator.validate(request.getCash());
    for (ConstraintViolation<PayCashData> constraintViolation : validators) {
        throw new Exception(constraintViolation.getMessage());
    }
}
项目:aaden-pay    文件:PaymentValidate.java   
private void validRecharge(PayRequest request) throws Exception {
    if (request.getSys().getPayType() == PayType.GATEWAY)
        return;
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    validator.validate(request.getRecharge());
    Set<ConstraintViolation<PayRechargeData>> validators = validator.validate(request.getRecharge());
    for (ConstraintViolation<PayRechargeData> constraintViolation : validators) {
        throw new Exception(constraintViolation.getMessage());
    }
}
项目:testing_security_development_enterprise_systems    文件:NotStandardTest.java   
@Before
public void init() {
    emFactory = Persistence.createEntityManagerFactory("DB");
    em = emFactory.createEntityManager();

    valFactory = Validation.buildDefaultValidatorFactory();
    validator = valFactory.getValidator();
}
项目:testing_security_development_enterprise_systems    文件:UserTest.java   
@Before
public void init() {
    emFactory = Persistence.createEntityManagerFactory("DB");
    em = emFactory.createEntityManager();

    valFactory = Validation.buildDefaultValidatorFactory();
    validator = valFactory.getValidator();
}
项目:dubbocloud    文件:JValidator.java   
@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();
}
项目:lams    文件:BeanValidationEventListener.java   
public void initialize(Configuration cfg) {
    if ( !initialized ) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Properties props = cfg.getProperties();
        init( factory, props );
    }
}
项目:hibatis    文件:EntityManagerImpl.java   
public EntityManagerImpl(SqlSessionFactory sqlSessionFactory) {
    super(sqlSessionFactory);
    try {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        this.validator = factory.getValidator();
    } catch (Exception e) {
        logger.warn("Unable to create  validator");
    }
}
项目:WordnetLoom    文件:PartOfSpeechServicesUTest.java   
@Before
public void initTestCase() {
    validator = Validation.buildDefaultValidatorFactory().getValidator();

    partOfSpeechRepository = mock(PartOfSpeechRepository.class);

    partOfSpeechService = new PartOfSpeechServiceBean();
    partOfSpeechService.validator = validator;
    partOfSpeechService.partOfSpeechRepository = partOfSpeechRepository;
}
项目:WordnetLoom    文件:LocalisedServicesUTest.java   
@Before
public void initTestCase() {
    validator = Validation.buildDefaultValidatorFactory().getValidator();

    repository = mock(LocalisedStringRepository.class);

    service = new LocalisedStringServiceBean();
    service.validator = validator;
    service.repository = repository;
}
项目:WordnetLoom    文件:LexiconServicesUTest.java   
@Before
public void initTestCase() {
    validator = Validation.buildDefaultValidatorFactory().getValidator();

    lexiconRepository = mock(LexiconRepository.class);

    lexiconService = new LexiconServiceBean();
    lexiconService.validator = validator;
    lexiconService.lexiconRepository = lexiconRepository;
}
项目:mafia    文件:ValidatorUtil.java   
public static <E> void checkParam(E obj, Class mafExceptionClass, Integer respCode, Class... validateGroup) throws Exception
{
    ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
    Validator validator = vf.getValidator();
    Set<ConstraintViolation<Object>> set = validator.validate(obj, validateGroup);
    for(ConstraintViolation<Object> cv : set)
    {
        Constructor constructor = mafExceptionClass.getConstructor(int.class, String.class);
        MafiaException mafException = (MafiaException) constructor.newInstance(respCode, cv.getMessage());
        throw mafException;
    }
}
项目:WordnetLoom    文件:RelationTypeServicesUTest.java   
@Before
public void initTestCase() {
    validator = Validation.buildDefaultValidatorFactory().getValidator();

    repository = mock(RelationTypeRepository.class);

    service = new RelationTypeServiceBean();
    service.validator = validator;
    service.relationTypeRepository = repository;
}