javax.validation.Validator Java Examples

The following examples show how to use javax.validation.Validator. 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: SimpleResourceConfigFactoryBeanTest.java    From cloud-config with MIT License 5 votes vote down vote up
private BoneCPDataSourceConfig createBean() throws Exception {
    SimpleResourceConfigFactoryBean<BoneCPDataSourceConfig> factoryBean = new SimpleResourceConfigFactoryBean<>();
    factoryBean.setClient(zkRootClient);
    factoryBean.setPath("/database/bcp");
    factoryBean.setResourceType(BoneCPDataSourceConfig.class);
    factoryBean.setAutoReload(true);

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

    factoryBean.afterPropertiesSet();
    return factoryBean.getObject();
}
 
Example #2
Source File: PersonModelTest.java    From blog with MIT License 5 votes vote down vote up
@Test
public void test_WHEN_valid_GIVEN_valid_model_THEN_ok_no_errors() {

	// GIVEN

	PersonModel person = new PersonModel( //
			"Kim", //
			"Kardashian", //
			new GregorianCalendar(1980, Calendar.OCTOBER, 21));
	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();

	// WHEN

	Set<ConstraintViolation<PersonModel>> constraintViolations = validator
			.validate(person);

	// THEN

	assertThat(constraintViolations).isEmpty();
}
 
Example #3
Source File: ValidatorConfig.java    From spring-boot-vue-admin with Apache License 2.0 5 votes vote down vote up
@Bean
public Validator validatorFailFast() {
  final ValidatorFactory validatorFactory =
      Validation.byProvider(HibernateValidator.class)
          .configure()
          .addProperty("hibernate.validator.fail_fast", "true")
          .buildValidatorFactory();
  return validatorFactory.getValidator();
}
 
Example #4
Source File: AbstractValidationFilter.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Result> invoke(final Invoker invoker, final RequestMessage<Invocation> request) {
    Invocation invocation = request.getPayLoad();
    //判断方法是否开启了验证
    Validator validator = request.getOption().getValidator();
    if (validator != null) {
        //JSR303验证
        Set<ConstraintViolation<Object>> violations = validator.forExecutables().validateParameters(
                invocation.getObject(), invocation.getMethod(), invocation.getArgs());
        if (!violations.isEmpty()) {
            //有异常
            StringBuilder builder = new StringBuilder(100);
            int i = 0;
            for (ConstraintViolation<Object> violation : violations) {
                if (i++ > 0) {
                    builder.append('\n');
                }
                builder.append("ConstraintViolation");
                builder.append("{message=").append(violation.getMessage());
                builder.append(", propertyPath=").append(violation.getPropertyPath());
                builder.append(", class=").append(className);
                builder.append('}');
            }
            // 无法直接序列化异常,只能转为字符串然后包装为RpcException
            RpcException re = new RpcException("validate is not passed, cause by: \n" + builder.toString(),
                    this instanceof ProviderFilter ? ExceptionCode.FILTER_VALID_PROVIDER : ExceptionCode.FILTER_VALID_CONSUMER);
            return CompletableFuture.completedFuture(new Result(request.getContext(), re));
        }
    }
    return invoker.invoke(request);
}
 
Example #5
Source File: ValidationEndToEndTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@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/data-map/someKey/value", violation.getErrorData().getSourcePointer());
	}
}
 
Example #6
Source File: ServiceMain.java    From helios with Apache License 2.0 5 votes vote down vote up
protected static Environment createEnvironment(final String name) {
  final Validator validator = Validation
      .byProvider(HibernateValidator.class)
      .configure()
      .addValidatedValueHandler(new OptionalValidatedValueUnwrapper())
      .buildValidatorFactory()
      .getValidator();
  return new Environment(name,
      Jackson.newObjectMapper(),
      validator,
      new MetricRegistry(),
      Thread.currentThread().getContextClassLoader());
}
 
Example #7
Source File: ValidatorFactoryExample.java    From Examples with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    /* Prepare user object */
    User user = new User();
    user.setFirstName("Vicky");
    user.setNickNames(Arrays.asList("vicks", "v"));
    user.setEmail("not-an-email");
    user.setPassword("1234567");
    
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    /* validate object and get constraints failed */
    Set<ConstraintViolation<User>> violations = validator.validate(user);
    
    for (ConstraintViolation<User> violation : violations) {
        System.err.println(violation.getMessage());
    }
}
 
Example #8
Source File: SubscriptionValidationTests.java    From OpenESPI-Common-java with Apache License 2.0 5 votes vote down vote up
@Test
public void isValid() throws Exception {
	Validator validator = Validation.buildDefaultValidatorFactory()
			.getValidator();

	Subscription subscription = newSubscription();

	Set<ConstraintViolation<Subscription>> violations = validator
			.validate(subscription);

	assertThat(violations, is(empty()));
}
 
Example #9
Source File: MethodValidationInterceptor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public static Object invokeWithinValidation(MethodInvocation invocation, Validator validator, Class<?>[] groups)
		throws Throwable {

	org.hibernate.validator.method.MethodValidator methodValidator =
			validator.unwrap(org.hibernate.validator.method.MethodValidator.class);
	Set<org.hibernate.validator.method.MethodConstraintViolation<Object>> result =
			methodValidator.validateAllParameters(
					invocation.getThis(), invocation.getMethod(), invocation.getArguments(), groups);
	if (!result.isEmpty()) {
		throw new org.hibernate.validator.method.MethodConstraintViolationException(result);
	}
	Object returnValue = invocation.proceed();
	result = methodValidator.validateReturnValue(
			invocation.getThis(), invocation.getMethod(), returnValue, groups);
	if (!result.isEmpty()) {
		throw new org.hibernate.validator.method.MethodConstraintViolationException(result);
	}
	return returnValue;
}
 
Example #10
Source File: ElectricPowerUsageSummaryValidationTests.java    From OpenESPI-Common-java with Apache License 2.0 5 votes vote down vote up
@Test
public void isValid() throws Exception {
	Validator validator = Validation.buildDefaultValidatorFactory()
			.getValidator();

	ElectricPowerUsageSummary electricPowerUsageSummary = newElectricPowerUsageSummary();

	Set<ConstraintViolation<ElectricPowerUsageSummary>> violations = validator
			.validate(electricPowerUsageSummary);

	assertThat(violations, is(empty()));
}
 
Example #11
Source File: ViewController.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
public void initialize(final URL location, final ResourceBundle resources) {
    final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    final Model model = new Model();
    final Validator validator = factory.getValidator();

    nameField.textProperty().bindBidirectional(model.nameProperty());

    model.countProperty().bind(Bindings.createObjectBinding(() ->
                    countSlider.valueProperty().intValue()
            , countSlider.valueProperty()));


    validateMessageLabel.textProperty().bind(Bindings.createStringBinding(() -> {
        final Set<ConstraintViolation<Model>> violations = validator.validate(model);
        return violations.stream().map(v -> v.getMessage()).reduce("", (a, b) -> a + System.lineSeparator() + b);
    }, model.nameProperty(), model.countProperty()));
}
 
Example #12
Source File: BeanValidationItemProcessor.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Override
public Object processItem(final Object item) throws Exception {
    final Validator validator = getValidator();
    final Set<ConstraintViolation<Object>> result = validate(validator, item);
    if (result != null && !result.isEmpty()) {
        if (Boolean.parseBoolean(skipNotValidated)) {
            return null;
        }
        throw new ConstraintViolationException(Set.class.cast(result));
    }
    return item;
}
 
Example #13
Source File: ValidationBundle.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public static javax.validation.Validator getValidator ()
{
    synchronized ( ValidationBundle.class )
    {
        if ( lastTrackingCount != tracker.getTrackingCount () )
        {
            lastTrackingCount = tracker.getTrackingCount ();
            validator = null;
        }

        if ( validator == null )
        {
            validator = buildValidator ();
        }

        return validator;
    }
}
 
Example #14
Source File: TarocoCommonAutoConfig.java    From Taroco with Apache License 2.0 5 votes vote down vote up
/**
 * 定义 Validator bean
 * 一个校验失败就立即返回
 */
@Bean
public Validator validator() {
    return Validation.byProvider(HibernateValidator.class)
            .configure()
            .failFast(true)
            .buildValidatorFactory()
            .getValidator();
}
 
Example #15
Source File: EntityValidator.java    From dropwizard-spring-di-security-onejar-example with Apache License 2.0 5 votes vote down vote up
/**
 * Validates an entity against its Hibernate validators
 * @param entity Entity
 * @param idFieldName  The name of its primary Id field (used for sorting error messages)
 */
public <E> void validate(E entity, String idFieldName) {
    Validator v = validatorFactory.getValidator();

    Set<ConstraintViolation<E>> violations = v.validate(entity);
    if (violations.size() > 0) {
        ConstraintViolation   cv = getFirstContraintViolation(violations, idFieldName);
        //return first error
        throw new EntityConstraintViolationException(cv.getRootBeanClass().getSimpleName(),
                cv.getPropertyPath().toString(),cv.getInvalidValue(),cv.getMessage());
    }
}
 
Example #16
Source File: PersonModelTest.java    From blog with MIT License 5 votes vote down vote up
@Test
public void test_WHEN_valid_GIVEN_invalid_model_THEN_error() {

	// GIVEN

	PersonModel person = new PersonModel( //
			null, //
			"", //
			null);

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

	// WHEN

	Set<ConstraintViolation<PersonModel>> constraintViolations = validator
			.validate(person);

	// THEN

	assertThat(constraintViolations) //
			.hasSize(3) //
			.haveExactly(2, notNullCondition) //
			.haveExactly(1, notEmptyCondition);
}
 
Example #17
Source File: BuiltInEnvironmentEntries.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void add(final JndiConsumer jndi, final DeploymentModule module, final DeploymentModule app, final boolean defaults) {

        // Standard names
        add(jndi.getEnvEntryMap(), new EnvEntry().name("java:module/ModuleName").value(module.getModuleId()).type(String.class));
        add(jndi.getEnvEntryMap(), new EnvEntry().name("java:app/AppName").value(app.getModuleId()).type(String.class));

        // Standard References to built-in objects
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/BeanManager").type(BeanManager.class));
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/Validator").type(Validator.class));
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/ValidatorFactory").type(ValidatorFactory.class));
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/TransactionManager").type(TransactionManager.class));
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/TransactionSynchronizationRegistry").type(TransactionSynchronizationRegistry.class));

        if (defaults) {
            add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/DefaultManagedExecutorService").type(ManagedExecutorService.class));
            add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/DefaultManagedScheduledExecutorService").type(ManagedScheduledExecutorService.class));
            add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/DefaultManagedThreadFactory").type(ManagedThreadFactory.class));
            add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/DefaultContextService").type(ContextService.class));
            try {
                final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                contextClassLoader.loadClass("org.apache.activemq.ActiveMQSslConnectionFactory");
                final ResourceEnvRef ref = new ResourceEnvRef().name("java:comp/DefaultJMSConnectionFactory")
                    .type(contextClassLoader.loadClass("javax.jms.ConnectionFactory"));
                add(jndi.getResourceEnvRefMap(), ref);
            } catch (final ClassNotFoundException | NoClassDefFoundError notThere) {
                // no-op
            }
        }


        // OpenEJB specific feature
        add(jndi.getEnvEntryMap(), new EnvEntry().name("java:comp/ComponentName").value(jndi.getJndiConsumerName()).type(String.class));

    }
 
Example #18
Source File: BeanValidators.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
 * 调用JSR303的validate方法, 验证失败时抛出ConstraintViolationException.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void validateWithException(Validator validator, Object object, Class<?>... groups)
		throws ConstraintViolationException {
	Set constraintViolations = validator.validate(object, groups);
	if (!constraintViolations.isEmpty()) {
		throw new ConstraintViolationException(constraintViolations);
	}
}
 
Example #19
Source File: SpELClassValidatorTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpELCondition() {
    Validator validator = TestValidator.testStrictValidator();

    Root root = new Root(
            "root1",
            new Child("child1", 0, 2),
            new NullableChild("child2")
    );
    Set<ConstraintViolation<Root>> violations = validator.validate(root);

    System.out.println(violations);
    assertThat(violations).hasSize(1);
}
 
Example #20
Source File: IntervalReadingValidationTests.java    From OpenESPI-Common-java with Apache License 2.0 5 votes vote down vote up
@Test
public void isValid() throws Exception {
	Validator validator = Validation.buildDefaultValidatorFactory()
			.getValidator();

	IntervalReading intervalReading = new IntervalReading();

	Set<ConstraintViolation<IntervalReading>> violations = validator
			.validate(intervalReading);

	assertTrue(violations.isEmpty());
}
 
Example #21
Source File: CloudWatchReporterFactoryTest.java    From dropwizard-metrics-cloudwatch with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyConfigurable() throws Exception {
    ObjectMapper mapper = Jackson.newObjectMapper();

    // dropwizard 0.9.1 changed the validation wiring a bit..
    Class<ValidatedValueUnwrapper> optValidatorClazz = (Class<ValidatedValueUnwrapper>) Class
            .forName("io.dropwizard.validation.valuehandling.OptionalValidatedValueUnwrapper");

    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    if (optValidatorClazz != null) {
        validator = Validation.byProvider(HibernateValidator.class).configure()
                .addValidatedValueHandler(optValidatorClazz.newInstance())
                .buildValidatorFactory().getValidator();
    }

    ConfigurationFactory<CloudWatchReporterFactory> configFactory =
            new ConfigurationFactory<>(CloudWatchReporterFactory.class,
                    validator, mapper, "dw");
    CloudWatchReporterFactory f = configFactory.build(new File(Resources.getResource("cw.yml").getFile()));

    assertEquals("[env=default]", f.getGlobalDimensions().toString());
    assertEquals("us-east-1", f.getAwsRegion());
    assertEquals("a.b", f.getNamespace());
    assertEquals("XXXXX", f.getAwsSecretKey());
    assertEquals("11111", f.getAwsAccessKeyId());
    assertEquals("p.neustar.biz", f.getAwsClientConfiguration().getProxyHost());
    assertNull(f.getAwsClientConfiguration().getProxyUsername());
}
 
Example #22
Source File: ClientDataValidationService.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Inject
public ClientDataValidationService(Validator validator) {
    if (validator == null) {
        throw new IllegalArgumentException("Validator cannot be null");
    }

    this.validator = validator;
}
 
Example #23
Source File: CountryCodeValidatorTest.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
private Set<ConstraintViolation<Entity>> getViolations(String ccode) {
    Entity entity = new Entity();
    entity.ccode = ccode;
    Validator validator = Validation.buildDefaultValidatorFactory()
            .getValidator();

    return validator.validate(entity);
}
 
Example #24
Source File: MethodValidationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Bean
public static MethodValidationPostProcessor methodValidationPostProcessor(@Lazy Validator validator) {
	MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
	postProcessor.setValidator(validator);
	postProcessor.setProxyTargetClass(true);
	return postProcessor;
}
 
Example #25
Source File: HistoryItemServiceImpl.java    From graylog-plugin-aggregates with GNU General Public License v3.0 5 votes vote down vote up
@Inject
public HistoryItemServiceImpl(MongoConnection mongoConnection, MongoJackObjectMapperProvider mapperProvider,
		Validator validator) {
	this.validator = validator;
	final String collectionName = HistoryItemImpl.class.getAnnotation(CollectionName.class).value();
	final DBCollection dbCollection = mongoConnection.getDatabase().getCollection(collectionName);
	this.coll = JacksonDBCollection.wrap(dbCollection, HistoryItemImpl.class, String.class, mapperProvider.get());
	// this.coll.createIndex(new BasicDBObject("name", 1), new
	// BasicDBObject("unique", true));
}
 
Example #26
Source File: OidcResource.java    From dependency-track with Apache License 2.0 4 votes vote down vote up
@POST
@Path("/group")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Updates group",
        response = OidcGroup.class
)
@ApiResponses(value = {
        @ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response updateGroup(final OidcGroup jsonGroup) {
    final Validator validator = super.getValidator();
    failOnValidationError(
            validator.validateProperty(jsonGroup, "uuid"),
            validator.validateProperty(jsonGroup, "name")
    );

    try (QueryManager qm = new QueryManager()) {
        OidcGroup oidcGroup = qm.getObjectByUuid(OidcGroup.class, jsonGroup.getUuid());
        if (oidcGroup != null) {
            oidcGroup.setName(jsonGroup.getName());
            oidcGroup = qm.updateOidcGroup(oidcGroup);
            super.logSecurityEvent(LOGGER, SecurityMarkers.SECURITY_AUDIT, "Group updated: " + oidcGroup.getName());
            return Response.ok(oidcGroup).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).entity("An OpenID Connect group with the specified UUID does not exists.").build();
        }
    }
}
 
Example #27
Source File: AbstractService.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
@Autowired(required = false)
public void setValidator(Validator validator) {
    this.validator = validator;
}
 
Example #28
Source File: HiveValidator.java    From devicehive-java-server with Apache License 2.0 4 votes vote down vote up
@Autowired
public HiveValidator(Validator validator) {
    this.validator = validator;
}
 
Example #29
Source File: JacksonXMLMessageBodyProvider.java    From dropwizard-xml with Apache License 2.0 4 votes vote down vote up
public JacksonXMLMessageBodyProvider(XmlMapper mapper, Validator validator) {
    this.validator = validator;
    this.mapper = mapper;
    setMapper(mapper);
}
 
Example #30
Source File: PathValidatorTest.java    From jwala with Apache License 2.0 4 votes vote down vote up
@Bean
public Validator getValidator() {
    return new LocalValidatorFactoryBean();
}