Java 类javax.validation.ValidatorFactory 实例源码

项目: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());
    }
  }
项目: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());
    }
}
项目:lams    文件:TypeSafeActivator.java   
@SuppressWarnings("UnusedDeclaration")
public static void activate(ActivationContext activationContext) {
    final Properties properties = activationContext.getConfiguration().getProperties();
    final ValidatorFactory factory;
    try {
        factory = getValidatorFactory( properties );
    }
    catch (IntegrationException e) {
        if ( activationContext.getValidationModes().contains( ValidationMode.CALLBACK ) ) {
            throw new IntegrationException( "Bean Validation provider was not available, but 'callback' validation was requested", e );
        }
        if ( activationContext.getValidationModes().contains( ValidationMode.DDL ) ) {
            throw new IntegrationException( "Bean Validation provider was not available, but 'ddl' validation was requested", e );
        }

        LOG.debug( "Unable to acquire Bean Validation ValidatorFactory, skipping activation" );
        return;
    }

    applyRelationalConstraints( factory, activationContext );

    applyCallbackListeners( factory, activationContext );
}
项目:lams    文件:TypeSafeActivator.java   
@SuppressWarnings({"unchecked", "UnusedParameters"})
private static void applyRelationalConstraints(ValidatorFactory factory, ActivationContext activationContext) {
    final Properties properties = activationContext.getConfiguration().getProperties();
    if ( ! ConfigurationHelper.getBoolean( BeanValidationIntegrator.APPLY_CONSTRAINTS, properties, true ) ){
        LOG.debug( "Skipping application of relational constraints from legacy Hibernate Validator" );
        return;
    }

    final Set<ValidationMode> modes = activationContext.getValidationModes();
    if ( ! ( modes.contains( ValidationMode.DDL ) || modes.contains( ValidationMode.AUTO ) ) ) {
        return;
    }

    applyRelationalConstraints(
            factory,
            activationContext.getConfiguration().createMappings().getClasses().values(),
            properties,
            activationContext.getServiceRegistry().getService( JdbcServices.class ).getDialect()
    );
}
项目: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);
    }

}
项目:flink-operator-library    文件:StreamingAppRuntime.java   
/**
 * Validates the provided {@link StreamingAppConfiguration} against constraints provided to fields holding the
 * configuration
 * @param configuration
 * @param outputStream
 * @return
 * @throws IOException
 */
protected boolean validateConfiguration(final StreamingAppConfiguration configuration, final OutputStream outputStream) throws IOException {
    if(outputStream == null)
        throw new IOException("Missing required output stream\n");

    if(configuration == null) {
        outputStream.write(MSG_MISSING_CFG_INSTANCE);
        return false;
    }

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<StreamingAppConfiguration>> violations = validator.validate(configuration);
    if(violations.isEmpty())
        return true;    

    for(ConstraintViolation<StreamingAppConfiguration> v : violations) {
        StringBuffer error = new StringBuffer("Invalid configuration at: ");
        error.append(v.getPropertyPath()).append(", error: ").append(v.getMessage()).append("\n");
        outputStream.write(error.toString().getBytes());
        outputStream.flush();
    }       
    return false;
}
项目:Peking-University-Open-Research-Data-Platform    文件:DatasetVersion.java   
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;
}
项目:restler    文件:TestRestlerModule.java   
@Override
public RestlerConfig getConfiguration()  {
    ObjectMapper objectMapper = Jackson.newObjectMapper();

    ValidatorFactory validatorFactory = Validation
            .byProvider(HibernateValidator.class)
            .configure()
            .addValidatedValueHandler(new OptionalValidatedValueUnwrapper())
            .buildValidatorFactory();


    final ConfigurationFactory<RestlerConfig> configurationFactory =
            new DefaultConfigurationFactoryFactory<RestlerConfig>().create(RestlerConfig.class, validatorFactory.getValidator(), objectMapper, "dw");

    try {
        return configurationFactory.build(new FileConfigurationSourceProvider(), TEST_CONFIG_FILE);
    } catch (Exception e) {
        throw new RuntimeException("Cannot get test configuration", e);
    }
}
项目:MapChat    文件:AbstractFacade.java   
/**
 * Creates an entity in the facade
 * @param entity the entity needed to be created
 */
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());

        JsfUtil.addErrorMessage(cv.getRootBeanClass().getSimpleName()+"."+cv.getPropertyPath() + " " +cv.getMessage());
    }
}else{
    getEntityManager().persist(entity);
}
}
项目:baratine    文件:ValidatorProviderJsr303.java   
public ValidatorProviderJsr303()
{
  ValidatorFactory validatorFactory = null;

  try {
    validatorFactory = Validation.buildDefaultValidatorFactory();

    if (validatorFactory.getValidator() == null) {
      validatorFactory = null;
    }
  } catch (Throwable t) {
    log.log(Level.WARNING, t.toString(), t);
  }

  _validatorFactory = validatorFactory;
}
项目:ozark    文件:BeanValidationProducer.java   
/**
 * We should be able to get a ValidatorFactory from the container in an Java EE environment.
 * However, if we don't get the factory, we will will use a default one. This is especially
 * useful for non Java EE environments and in the CDI tests
 */
@PostConstruct
public void init() {

    // Prefer the ValidatorFactory provided by the container
    Iterator<ValidatorFactory> iterator = validatorFactoryInstance.iterator();
    if (iterator.hasNext()) {
        this.validatorFactory = iterator.next();
    }

    // create a default factory if we didn't get one
    else {
        log.warning("Creating a ValidatorFactory because the container didn't provide one!");
        this.validatorFactory = Validation.buildDefaultValidatorFactory();
    }

}
项目:linkbinder    文件:BeanValidatorTest.java   
@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());
    }
}
项目:open-Autoscaler    文件:BeanValidation.java   
public static JsonNode parsePolicyEnable(String jsonString, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{
     List<String> violation_message = new ArrayList<String>();
     ObjectNode result = new_mapper.createObjectNode();
     result.put("valid", false);
     PolicyEnbale policyEnable = new_mapper.readValue(jsonString, PolicyEnbale.class);
     ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
     Locale locale = LocaleUtil.getLocale(httpServletRequest);
     MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale);
     Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator();
     Set<ConstraintViolation<PolicyEnbale>> set = validator.validate(policyEnable);
     if (set.size() > 0 ){
         for (ConstraintViolation<PolicyEnbale> constraintViolation : set) {
             violation_message.add(constraintViolation.getMessage());
         }
         result.set("violation_message", new_mapper.valueToTree(violation_message));
         return result;
     }

     //additional data manipulation
     String new_json = policyEnable.transformInput();
     result.put("valid", true);
     result.put("new_json", new_json);
     return result;
}
项目:open-Autoscaler    文件:BeanValidation.java   
public static JsonNode parseScalingHistory(String jsonString, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{
     List<String> violation_message = new ArrayList<String>();
     ObjectNode result = new_mapper.createObjectNode();
     result.put("valid", false);
     JavaType javaType = getCollectionType(ArrayList.class, ArrayList.class, HistoryData.class);
     new_mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
     List<HistoryData> scalinghistory = (List<HistoryData>)new_mapper.readValue(jsonString, javaType);
     ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
     Locale locale = LocaleUtil.getLocale(httpServletRequest);
     MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale);
     Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator();
     Set<ConstraintViolation<List<HistoryData>>> set = validator.validate(scalinghistory);
     if (set.size() > 0 ){
         for (ConstraintViolation<List<HistoryData>> constraintViolation : set) {
             violation_message.add(constraintViolation.getMessage());
         }
         result.set("violation_message", new_mapper.valueToTree(violation_message));
         return result;
     }

     //additional data manipulation
         String new_json = transformHistory(scalinghistory);
     result.put("valid", true);
     result.put("new_json", new_json);
     return result;
}
项目:springJpaKata    文件:ValidationPersonTest.java   
@Test
public void shouldValidate() {
     Person person =  Person.builder()
             .km(34d)
             .email("przodownikR1gmail.com")
             .firstname(null)
             .birthDay(ZonedDateTime.now())
             .modify(LocalDate.now())
             .build();

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

    Set<ConstraintViolation<Person>> validators = validator.validate(person);
    Assertions.assertThat(validators).hasSize(2);
    ConstraintViolation<Person> validation = validators.iterator().next();
    for(ConstraintViolation<Person> constraint : validators){
        //log.info("{}",constraint);
        log.info("property name  : {}, message : {} , messageTemplate : {}",constraint.getPropertyPath(),constraint.getMessage(),constraint.getMessageTemplate());
    }

  Assertions.assertThat(validators.stream().filter(p->p.getMessage().contains("not be null")).findFirst().isPresent());
 }
项目: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();
}
项目:beanvalidation    文件:ValidationTestHelper.java   
private static <T> void assertViolation(@Nullable final Class<? extends Annotation> clazz, final T bean, @Nullable final String property,
        final boolean expectedMatching, final String messageFormat, Class... groups) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<T>> violations = null;
    if (groups == null || groups.length == 0) {
        violations = validator.validate(bean);
    } else {
        violations = validator.validate(bean, groups);
    }
    ConstraintViolation<T> matchingViolation = null;
    for (ConstraintViolation<T> violation : violations) {
        if ((clazz == null || violation.getConstraintDescriptor().getAnnotation().annotationType().equals(clazz))
                && (property == null || violation.getPropertyPath().toString().equals(property))) {
            matchingViolation = violation;
            break;
        }
    }
    if (expectedMatching && matchingViolation == null || !expectedMatching && matchingViolation != null) {

        Class<? extends Annotation> annotation = clazz;
        String prop = property;
        String details = "";
        if (matchingViolation != null) {
            annotation = matchingViolation.getConstraintDescriptor().getAnnotation().annotationType();
            prop = matchingViolation.getPropertyPath().toString();
            details = " - " + matchingViolation;
        }
        throw new AssertionError(MessageFormat.format(messageFormat, annotation, prop) + details);
    }
}
项目: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    文件: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());
     */
}
项目: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);
    }
}
项目:lams    文件:BeanValidationEventListener.java   
public void initialize(Configuration cfg) {
    if ( !initialized ) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Properties props = cfg.getProperties();
        init( factory, props );
    }
}
项目:lams    文件:TypeSafeActivator.java   
/**
 * Used to validate a supplied ValidatorFactory instance as being castable to ValidatorFactory.
 *
 * @param object The supplied ValidatorFactory instance.
 */
@SuppressWarnings( {"UnusedDeclaration"})
public static void validateSuppliedFactory(Object object) {
    if ( ! ValidatorFactory.class.isInstance( object ) ) {
        throw new IntegrationException(
                "Given object was not an instance of " + ValidatorFactory.class.getName()
                        + "[" + object.getClass().getName() + "]"
        );
    }
}
项目:lams    文件:TypeSafeActivator.java   
@SuppressWarnings( {"UnusedDeclaration"})
public static void applyCallbackListeners(ValidatorFactory validatorFactory, ActivationContext activationContext) {
    final Set<ValidationMode> modes = activationContext.getValidationModes();
    if ( ! ( modes.contains( ValidationMode.CALLBACK ) || modes.contains( ValidationMode.AUTO ) ) ) {
        return;
    }

    // de-activate not-null tracking at the core level when Bean Validation is present unless the user explicitly
    // asks for it
    if ( activationContext.getConfiguration().getProperty( Environment.CHECK_NULLABILITY ) == null ) {
        activationContext.getSessionFactory().getSettings().setCheckNullability( false );
    }

    final BeanValidationEventListener listener = new BeanValidationEventListener(
            validatorFactory,
            activationContext.getConfiguration().getProperties()
    );

    final EventListenerRegistry listenerRegistry = activationContext.getServiceRegistry()
            .getService( EventListenerRegistry.class );

    listenerRegistry.addDuplicationStrategy( DuplicationStrategyImpl.INSTANCE );

    listenerRegistry.appendListeners( EventType.PRE_INSERT, listener );
    listenerRegistry.appendListeners( EventType.PRE_UPDATE, listener );
    listenerRegistry.appendListeners( EventType.PRE_DELETE, listener );

    listener.initialize( activationContext.getConfiguration() );
}
项目:lams    文件:TypeSafeActivator.java   
private static void applyDDL(
        String prefix,
        PersistentClass persistentClass,
        Class<?> clazz,
        ValidatorFactory factory,
        Set<Class<?>> groups,
        boolean activateNotNull,
        Dialect dialect) {
    final BeanDescriptor descriptor = factory.getValidator().getConstraintsForClass( clazz );
    //no bean level constraints can be applied, go to the properties

    for ( PropertyDescriptor propertyDesc : descriptor.getConstrainedProperties() ) {
        Property property = findPropertyByName( persistentClass, prefix + propertyDesc.getPropertyName() );
        boolean hasNotNull;
        if ( property != null ) {
            hasNotNull = applyConstraints(
                    propertyDesc.getConstraintDescriptors(), property, propertyDesc, groups, activateNotNull, dialect
            );
            if ( property.isComposite() && propertyDesc.isCascaded() ) {
                Class<?> componentClass = ( (Component) property.getValue() ).getComponentClass();

                /*
                 * we can apply not null if the upper component let's us activate not null
                 * and if the property is not null.
                 * Otherwise, all sub columns should be left nullable
                 */
                final boolean canSetNotNullOnColumns = activateNotNull && hasNotNull;
                applyDDL(
                        prefix + propertyDesc.getPropertyName() + ".",
                        persistentClass, componentClass, factory, groups,
                        canSetNotNullOnColumns,
                           dialect
                );
            }
            //FIXME add collection of components
        }
    }
}
项目: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");
    }
}
项目:gitplex-mit    文件:ValidationConfigurationContextResolver.java   
@Override
public ValidationConfig getContext(final Class<?> type) {
    ValidatorFactory factory = AppLoader.getInstance(ValidatorFactory.class);
    ValidationConfig config = new ValidationConfig();
    config.constraintValidatorFactory(factory.getConstraintValidatorFactory());
    config.messageInterpolator(factory.getMessageInterpolator());
    config.parameterNameProvider(factory.getParameterNameProvider());
    config.traversableResolver(factory.getTraversableResolver());
    return config;
}
项目:minijax    文件:ValidationTest.java   
@BeforeClass
public static void setUpValidator() {
    //tag::setUpValidator[]
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    validator = factory.getValidator();
    //end::setUpValidator[]
}
项目:minijax    文件:CarTest.java   
@BeforeClass
public static void setUpValidator() {
    ValidatorFactory factory = Validation.byProvider( MinijaxValidationProvider.class )
            .configure()
            .buildValidatorFactory();
    validator = factory.getValidator();
}