org.hibernate.validator.HibernateValidatorConfiguration Java Examples

The following examples show how to use org.hibernate.validator.HibernateValidatorConfiguration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ValidationTest.java    From rest.vertx with Apache License 2.0 6 votes vote down vote up
@BeforeAll
static void start() {

    before();

    HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class)
            .configure();

    Validator validator = configuration.buildValidatorFactory()
            .getValidator();


    Router router = new RestBuilder(vertx)
            .register(TestValidRest.class)
            .validateWith(validator)
            .build();

    vertx.createHttpServer()
            .requestHandler(router)
            .listen(PORT, vertxTestContext.completing());
}
 
Example #2
Source File: BeanValidationImpl.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected HibernateValidatorConfiguration getValidatorFactoryConfiguration(Locale locale) {
    HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class)
            .configure()
            .clockProvider(new CubaValidationTimeProvider(timeSource))
            .traversableResolver(new CubaValidationTraversableResolver(metadata, entityStates))
            .messageInterpolator(new CubaValidationMessagesInterpolator(messages, locale));

    ConstraintMapping constraintMapping = configuration.createConstraintMapping();

    //Hibernate validators doesn't support java.sql.Date.
    //Replace standard validators for java.util.Date with support java.sql.Date
    registerPastValidators(constraintMapping.constraintDefinition(Past.class));
    registerPastOrPresentValidators(constraintMapping.constraintDefinition(PastOrPresent.class));
    registerFutureValidators(constraintMapping.constraintDefinition(Future.class));
    registerFutureOrPresentValidators(constraintMapping.constraintDefinition(FutureOrPresent.class));

    configuration.addMapping(constraintMapping);

    return configuration;
}
 
Example #3
Source File: ValidationUtil.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
@PostConstruct
private void init() {
	ValidatorProperties properties = ContextUtil.bean(ValidatorProperties.class);
	HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class).configure();
	//配置hibernate-validator消息插值源
	MessageInterpolator interpolator = new ResourceBundleMessageInterpolator(new PlatformResourceBundleLocator(properties
		.getMessageConfigPath()));
	configuration.messageInterpolator(interpolator);
	//配置快速失败
	configuration.failFast(properties.getFailFast());
	failFast = properties.getFailFast();
	engine = configuration.buildValidatorFactory().getValidator();
}
 
Example #4
Source File: InputValidation.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public InputValidation() {

    HibernateValidatorConfiguration config = Validation.byProvider(HibernateValidator.class).configure();
    this.validator = config
        .addMapping(configureTransforms(config.createConstraintMapping()))
        .buildValidatorFactory()
        .getValidator();
  }
 
Example #5
Source File: HibernateValidation.java    From validator-web with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ValidationContext context) {
    context.setValidatorDelegate(this);
    
    HibernateValidatorConfiguration configure = javax.validation.Validation.byProvider(HibernateValidator.class).configure();
    if (context instanceof ValidationContext.Accessor) {
        configure.failFast(((ValidationContext.Accessor) context).isFailFast());
    }
    ValidatorFactory factory = configure.buildValidatorFactory();
    validator = factory.getValidator();
}
 
Example #6
Source File: BeanValidation.java    From open-Autoscaler with Apache License 2.0 5 votes vote down vote up
public static HibernateValidatorConfiguration getPolicyTriggerRange(HibernateValidatorConfiguration config) {

		 Map<String, Map<String, Map<String, Map<String, String>>>> mulit_range = Constants.getTriggerRangeByTriggerType();
		 logger.debug("mulit trigger range: " + mulit_range.toString());
		 for (String class_type : mulit_range.keySet()){
			 Map<String, Map<String, Map<String, String>>> range = mulit_range.get(class_type);
			 Class<?> class_obj=null;
			 if (class_type.equals("trigger_Memory")) //only one metricType supported now
				 class_obj = PolicyTrigger.class;
			 for (String key : range.keySet()) {
				 Map<String, Map<String, String>> value = range.get(key);
				 for(String value_key : value.keySet()){
					 Map<String, String> value_item = value.get(value_key);
					 ConstraintMapping mapping = config.createConstraintMapping();
					 if (value_key.endsWith("Min")){
						 mapping.type(class_obj).property(key, ElementType.FIELD).constraint( new MinDef().value(Integer.parseInt(value_item.get("value"))).message(value_item.get("message")));
					 }
					 else if(value_key.endsWith("Max")){
						 mapping.type(class_obj).property(key, ElementType.FIELD).constraint( new MaxDef().value(Integer.parseInt(value_item.get("value"))).message(value_item.get("message")));
					 }
					 else if(value_key.endsWith("NotNull")){
						 mapping.type(class_obj).property(key, ElementType.FIELD).constraint( new NotNullDef().message(value_item.get("message")));
					 }
					 config.addMapping( mapping );
				 }
			 }
		 }
		 return config;
	}
 
Example #7
Source File: BeanValidation.java    From open-Autoscaler with Apache License 2.0 5 votes vote down vote up
public static JsonNode parsePolicy(String jsonString, Map<String, String> service_info, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{
	 List<String> violation_message = new ArrayList<String>();
	 ObjectNode result = new_mapper.createObjectNode();
	 result.put("valid", false);
	 logger.info("received policy : " + jsonString); //debug
	 new_mapper.readValue(jsonString, Policy.class); //for syntax error check
	 String transfered_json = TransferedPolicy.packServiceInfo(jsonString, service_info);
	 logger.info("transfered policy after update with service_information : " + transfered_json); //debug
	 TransferedPolicy policy = new_mapper.readValue(transfered_json, TransferedPolicy.class);
	 logger.info("we get policy as " + (Obj2Map(policy)).toString());//debug
	 //additional data manipulation and check again
	 policy = policy.setMaxInstCount();
	 HibernateValidatorConfiguration config = BeanValidation.getPolicyRange();
	 ValidatorFactory vf = config.buildValidatorFactory();
	 Locale locale = LocaleUtil.getLocale(httpServletRequest);
	 MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale);
	 Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator();
	 Set<ConstraintViolation<TransferedPolicy>> set = validator.validate(policy);
	 if (set.size() > 0 ){
		 for (ConstraintViolation<TransferedPolicy> constraintViolation : set) {
			 violation_message.add(constraintViolation.getMessage());
		 }
		 result.set("violation_message", new_mapper.valueToTree(violation_message));
		 return result;
	 }

	 String new_json = policy.transformInput();
	 logger.info("policy before trigger back : " + new_json); //debug
	 new_json = TransferedPolicy.unpackServiceInfo(new_json, service_info);
	 result.put("valid", true);
	 logger.info("send out policy: " + new_json); //debug
	 result.put("new_json", new_json);
	 return result;
}
 
Example #8
Source File: BeanValidationImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public Validator getValidator(@Nullable ConstraintMapping constraintMapping, ValidationOptions options) {
    checkNotNullArgument(options);

    if (constraintMapping == null
            && options.getFailFast() == null
            && options.getLocale() != null) {
        return getValidatorWithDefaultFactory(options.getLocale());
    }

    Locale locale;
    if (options.getLocale() != null) {
        locale = options.getLocale();
    } else {
        locale = getCurrentLocale();
    }

    HibernateValidatorConfiguration configuration = getValidatorFactoryConfiguration(locale);
    if (options.getFailFast() != null) {
        configuration.failFast(options.getFailFast());
    }
    if (constraintMapping != null) {
        configuration.addMapping(constraintMapping);
    }

    ValidatorFactory factory = configuration.buildValidatorFactory();
    return factory.getValidator();
}
 
Example #9
Source File: BeanValidation.java    From open-Autoscaler with Apache License 2.0 4 votes vote down vote up
public static HibernateValidatorConfiguration getPolicyRange() throws JsonParseException, JsonMappingException, IOException{
	HibernateValidatorConfiguration config = Validation.byProvider( HibernateValidator.class ).configure();

	config = getPolicyTriggerRange(config);
	return config;
}
 
Example #10
Source File: BeanValidationImpl.java    From cuba with Apache License 2.0 4 votes vote down vote up
protected Validator getValidatorWithDefaultFactory(Locale locale) {
    HibernateValidatorConfiguration configuration = getValidatorFactoryConfiguration(locale);
    ValidatorFactory factory = configuration.buildValidatorFactory();
    return factory.getValidator();
}
 
Example #11
Source File: AbstractValidationTest.java    From hibernate-demos with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
	final Configuration<HibernateValidatorConfiguration> configuration = Validation.byProvider( HibernateValidator.class ).configure();
	validator = configuration.buildValidatorFactory().getValidator();
}
 
Example #12
Source File: AbstractValidationTest.java    From hibernate-demos with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
	final Configuration<HibernateValidatorConfiguration> configuration = Validation.byProvider( HibernateValidator.class ).configure();
	validator = configuration.buildValidatorFactory().getValidator();
}
 
Example #13
Source File: HibernateValidatorService.java    From wisdom with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes the validator, and registers it as an OSGi service (if the bundle context is set).
 *
 * @return the validator.
 */
@Validate
public Validator initialize() {
    // configure and build an instance of ValidatorFactory
    ProviderSpecificBootstrap<HibernateValidatorConfiguration> validationBootStrap = javax.validation.Validation
            .byProvider(HibernateValidator.class);

    // bootstrap to properly resolve in an OSGi environment
    validationBootStrap.providerResolver(new HibernateValidationProviderResolver());

    HibernateValidatorConfiguration configure = validationBootStrap.configure().messageInterpolator(interpolator);
    interpolator.setDefaultInterpolator(configure.getDefaultMessageInterpolator());

    // now that we've done configuring the ValidatorFactory, let's build it
    ValidatorFactory validatorFactory = configure.buildValidatorFactory();

    // retrieve a unique validator.
    Validator validator = validatorFactory.getValidator();

    // Register the validator.
    if (context != null) {
        registration = context.registerService(Validator.class, new WrappedValidator(validator), null);
        factoryRegistration = context.registerService(ValidatorFactory.class, validatorFactory, null);
    }

    return validator;
}
 
Example #14
Source File: ValidationUnitTests.java    From shimmer with Apache License 2.0 3 votes vote down vote up
@BeforeClass
public static void prepareValidator() {

    HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class).configure();

    // enable fail-fast mode for unit tests to simplify debugging
    ValidatorFactory factory = configuration.failFast(true).buildValidatorFactory();

    validator = factory.getValidator();
}