Java Code Examples for javax.validation.Validator#validate()

The following examples show how to use javax.validation.Validator#validate() . 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: WorkflowDefValidatorTest.java    From conductor with Apache License 2.0 7 votes vote down vote up
@Test
public void testWorkflowTasklistInputParamWithEmptyString() {
	WorkflowDef workflowDef = new WorkflowDef();//name is null
	workflowDef.setSchemaVersion(2);
	workflowDef.setName("test_env");
	workflowDef.setOwnerEmail("[email protected]");

	WorkflowTask workflowTask = new WorkflowTask();//name is null

	workflowTask.setName("t1");
	workflowTask.setWorkflowTaskType(TaskType.SIMPLE);
	workflowTask.setTaskReferenceName("t1");

	Map<String, Object> map = new HashMap<>();
	map.put("blabla", "");
	map.put("foo", new String[]{""});
	workflowTask.setInputParameters(map);

	workflowDef.getTasks().add(workflowTask);

	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();
	Set<ConstraintViolation<Object>> result = validator.validate(workflowDef);
	assertEquals(0, result.size());
}
 
Example 2
Source File: Main.java    From Java-Coding-Problems with MIT License 6 votes vote down vote up
public static void main(String[] args) {

        User user;
        
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();        
        
        User.UserBuilder userBuilder = new User.UserBuilder("monika", "klooi0988")
                .email("[email protected]")
                .firstName("Monika")
                .lastName("Gunther");

        final Set<ConstraintViolation<User.UserBuilder>> violations
                = validator.validate(userBuilder);

        if (violations.isEmpty()) {
            user = userBuilder.build();

            System.out.println("User successfully created on: " + user.getCreated());
        } else {
            printConstraintViolations("UserBuilder Violations: ", violations);
        }
    }
 
Example 3
Source File: User.java    From picocli with Apache License 2.0 6 votes vote down vote up
private void validate() {
    System.out.println(spec.commandLine().getParseResult().originalArgs());
    System.out.println(this);

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<User>> violations = validator.validate(this);

    if (!violations.isEmpty()) {
        String errorMsg = "";
        for (ConstraintViolation<User> violation : violations) {
            errorMsg += "ERROR: " + violation.getMessage() + "\n";
        }
        throw new ParameterException(spec.commandLine(), errorMsg);
    }
}
 
Example 4
Source File: IntervalBlockValidationTests.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();

	IntervalBlock intervalBlock = newIntervalBlock();

	Set<ConstraintViolation<IntervalBlock>> violations = validator
			.validate(intervalBlock);

	assertThat(violations, is(empty()));
}
 
Example 5
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 6
Source File: ParsecValidationExceptionMapperTest.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
private Set<ConstraintViolation<Entity>> getViolations() {
    Entity entity = new Entity();
    Validator validator = Validation.buildDefaultValidatorFactory()
            .getValidator();

    return validator.validate(entity);
}
 
Example 7
Source File: CValidatorTest.java    From hj-t212-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void test(){
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    TestBean bean = new TestBean();
    bean.c1 = "1";
    bean.c2 = "12-";

    Set<ConstraintViolation<TestBean>> e1 = validator.validate(bean,
            Default.class);
    assertEquals(e1.size(),1);
}
 
Example 8
Source File: DataManagerBean.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected void validateEntity(Entity entity, List<Class> validationGroups) {
    Validator validator = beanValidation.getValidator();
    Set<ConstraintViolation<Entity>> violations;
    if (validationGroups == null || validationGroups.isEmpty()) {
        violations = validator.validate(entity);
    } else {
        violations = validator.validate(entity, validationGroups.toArray(new Class[0]));
    }
    if (!violations.isEmpty())
        throw new EntityValidationException(String.format("Entity %s validation failed.", entity.toString()), violations);
}
 
Example 9
Source File: CustomerValidatorTest.java    From POC with Apache License 2.0 5 votes vote down vote up
@Test
void shouldNotValidateWhenFirstNameEmpty() {

	LocaleContextHolder.setLocale(Locale.ENGLISH);
	Customer customer = new Customer();
	customer.setLastName("kolli");

	Validator validator = createValidator();
	Set<ConstraintViolation<Customer>> constraintViolations = validator.validate(customer);

	assertThat(constraintViolations.size()).isEqualTo(1);
	ConstraintViolation<Customer> violation = constraintViolations.iterator().next();
	assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName");
	assertThat(violation.getMessage()).isEqualTo("Customer firstName is mandatory");
}
 
Example 10
Source File: OpenAPIUtils.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
public static <T> void validate(T obj) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
    if (constraintViolations.size() > 0) {
        StringBuilder errors = new StringBuilder();
        for (ConstraintViolation<T> contraintes : constraintViolations) {
            errors.append(String.format("%s.%s %s\n",
            contraintes.getRootBeanClass().getSimpleName(),
            contraintes.getPropertyPath(),
            contraintes.getMessage()));
        }
        throw new RuntimeException("Bean validation : " + errors);
    }
}
 
Example 11
Source File: WorkflowDefValidatorTest.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Test
public void testWorkflowOwnerInvalidEmail() {
	WorkflowDef workflowDef = new WorkflowDef();
	workflowDef.setName("test_env");
	workflowDef.setOwnerEmail("owner");

	WorkflowTask workflowTask = new WorkflowTask();

	workflowTask.setName("t1");
	workflowTask.setWorkflowTaskType(TaskType.SIMPLE);
	workflowTask.setTaskReferenceName("t1");

	Map<String, Object> map = new HashMap<>();
	map.put("blabla", "");
	workflowTask.setInputParameters(map);

	workflowDef.getTasks().add(workflowTask);

	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();
	Set<ConstraintViolation<Object>> result = validator.validate(workflowDef);
	assertEquals(1, result.size());

	List<String> validationErrors = new ArrayList<>();
	result.forEach(e -> validationErrors.add(e.getMessage()));

	assertTrue(validationErrors.contains("ownerEmail should be valid email address"));
}
 
Example 12
Source File: MessageConsumer.java    From code-examples with MIT License 5 votes vote down vote up
public void consumeStringMessage(String messageString) throws IOException {
  logger.info("Consuming message '{}'", messageString);
  UserCreatedMessage message = objectMapper.readValue(messageString, UserCreatedMessage.class);
  Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
  Set<ConstraintViolation<UserCreatedMessage>> violations = validator.validate(message);
  if(!violations.isEmpty()){
    throw new ConstraintViolationException(violations);
  }
  // pass message into business use case
}
 
Example 13
Source File: ValidationUtils.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Throws exception when specified object is invalid.
 * @param validator validator
 * @param obj validating object
 * @param id string which can identify object
 * @param msg message whic pass to exception, mai be null
 * @param <T> type of object
 * @throws ValidityException
 */
public static <T> void assertValid(Validator validator, T obj, String id, String msg) throws ValidityException {
    Set<ConstraintViolation<T>> res = validator.validate(obj);
    Validity validity = new JsrValidityImpl(id, res);
    if(!validity.isValid()) {
        if(msg == null) {
            msg = "Invalid: " + id;
        }
        throw new ValidityException(msg, validity);
    }
}
 
Example 14
Source File: IdentifiedObjectValidationTests.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();

	IdentifiedObject identifiedObject = new IdentifiedObject();
	identifiedObject.setUUID(UUID.randomUUID());

	Set<ConstraintViolation<IdentifiedObject>> violations = validator
			.validate(identifiedObject);

	assertTrue(violations.isEmpty());
}
 
Example 15
Source File: ProgrammaticallyValidatingService.java    From code-examples with MIT License 5 votes vote down vote up
public void validateInput(Input input) {
  ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
  Validator validator = factory.getValidator();
  Set<ConstraintViolation<Input>> violations = validator.validate(input);
  if (!violations.isEmpty()) {
    throw new ConstraintViolationException(violations);
  }
}
 
Example 16
Source File: UsagePointValidationTests.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();

	UsagePoint usagePoint = new UsagePoint();
	usagePoint.setMRID("urn:uuid:E8E75691-7F9D-49F3-8BE2-3A74EBF6BFC0");
	usagePoint.setServiceCategory(new ServiceCategory(
			ServiceCategory.ELECTRICITY_SERVICE));

	Set<ConstraintViolation<UsagePoint>> violations = validator
			.validate(usagePoint);

	assertTrue(violations.isEmpty());
}
 
Example 17
Source File: BackupRestoreCLI.java    From cassandra-backup with Apache License 2.0 4 votes vote down vote up
static void init(final Runnable command,
                 final CassandraJMXSpec jmxSpec,
                 final OperationRequest operationRequest,
                 final Logger logger,
                 final List<Module> appSpecificModules) {

    final List<Module> modules = new ArrayList<>();

    if (jmxSpec != null) {
        modules.add(new CassandraModule(new CassandraJMXConnectionInfo(jmxSpec.jmxPassword,
                                                                       jmxSpec.jmxUser,
                                                                       jmxSpec.jmxServiceURL,
                                                                       jmxSpec.trustStore,
                                                                       jmxSpec.trustStorePassword)));
    } else {
        modules.add(new AbstractModule() {
            @Override
            protected void configure() {
                bind(StorageServiceMBean.class).toProvider(() -> null);
                bind(Cassandra4StorageServiceMBean.class).toProvider(() -> null);
            }
        });
    }

    modules.add(new OperationsModule());
    modules.add(new StorageModules());
    modules.add(new ExecutorsModule());
    modules.addAll(appSpecificModules);

    final Injector injector = Guice.createInjector(
        Stage.PRODUCTION, // production binds singletons as eager by default
        modules
    );

    GuiceInjectorHolder.INSTANCE.setInjector(injector);

    injector.injectMembers(command);

    final Validator validator = Validation.byDefaultProvider()
        .configure()
        .constraintValidatorFactory(new GuiceInjectingConstraintValidatorFactory()).buildValidatorFactory()
        .getValidator();

    final Set<ConstraintViolation<OperationRequest>> violations = validator.validate(operationRequest);

    if (!violations.isEmpty()) {
        violations.forEach(violation -> logger.error(violation.getMessage()));
        throw new ValidationException();
    }
}
 
Example 18
Source File: ModelValidationTest.java    From pnc with Apache License 2.0 4 votes vote down vote up
/**
 * Test validation of the version string regex
 * 
 * @throws Exception
 */
@Test
public void testVersionStringValidation() throws Exception {

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

    Product product = Product.Builder.newBuilder().name("Test Product").build();
    ProductVersion productVersion = ProductVersion.Builder.newBuilder().product(product).version("1.0").build();

    // Test validation of product version
    Set<ConstraintViolation<ProductVersion>> productVersionViolations = validator.validate(productVersion);
    Assert.assertTrue(productVersionViolations.size() == 0);

    productVersion.setVersion("1.0.x");
    productVersionViolations = validator.validate(productVersion);
    Assert.assertTrue(productVersionViolations.size() == 1);

    productVersion.setVersion("foo");
    productVersionViolations = validator.validate(productVersion);
    Assert.assertTrue(productVersionViolations.size() == 1);

    // Test product milestone versions
    ProductMilestone milestone = ProductMilestone.Builder.newBuilder()
            .productVersion(productVersion)
            .version("1.0.0.ER1")
            .build();
    Set<ConstraintViolation<ProductMilestone>> milestoneVersionViolations = validator.validate(milestone);
    Assert.assertTrue(milestoneVersionViolations.size() == 0);

    milestone.setVersion("1.0");
    milestoneVersionViolations = validator.validate(milestone);
    Assert.assertTrue(milestoneVersionViolations.size() == 1);

    milestone.setVersion("1.0-DR1");
    milestoneVersionViolations = validator.validate(milestone);
    Assert.assertTrue(milestoneVersionViolations.size() == 1);

    milestone.setVersion("1.0-x");
    milestoneVersionViolations = validator.validate(milestone);
    Assert.assertTrue(milestoneVersionViolations.size() == 1);

    // Test product release versions
    ProductRelease release = ProductRelease.Builder.newBuilder()
            .productMilestone(milestone)
            .version("1.0.0.GA")
            .build();
    Set<ConstraintViolation<ProductRelease>> releaseVersionViolations = validator.validate(release);
    Assert.assertTrue(releaseVersionViolations.size() == 0);

    release.setVersion("1.0");
    releaseVersionViolations = validator.validate(release);
    Assert.assertTrue(releaseVersionViolations.size() == 1);

    release.setVersion("1.0-DR1");
    releaseVersionViolations = validator.validate(release);
    Assert.assertTrue(releaseVersionViolations.size() == 1);

    release.setVersion("1.0-x");
    releaseVersionViolations = validator.validate(release);
    Assert.assertTrue(releaseVersionViolations.size() == 1);

}
 
Example 19
Source File: WorkflowDefValidatorTest.java    From conductor with Apache License 2.0 4 votes vote down vote up
@Test
public void testWorkflowDefConstraintsSingleEnvVariable() {
	WorkflowDef workflowDef = new WorkflowDef();//name is null
	workflowDef.setSchemaVersion(2);
	workflowDef.setName("test_env");
	workflowDef.setOwnerEmail("[email protected]");

	WorkflowTask workflowTask_1 = new WorkflowTask();
	workflowTask_1.setName("task_1");
	workflowTask_1.setTaskReferenceName("task_1");
	workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE);

	Map<String, Object> inputParam = new HashMap<>();
	inputParam.put("taskId", "${CPEWF_TASK_ID}");

	workflowTask_1.setInputParameters(inputParam);

	List<WorkflowTask> tasks = new ArrayList<>();
	tasks.add(workflowTask_1);

	workflowDef.setTasks(tasks);

	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();
	Set<ConstraintViolation<Object>> result = validator.validate(workflowDef);
	assertEquals(0, result.size());
}
 
Example 20
Source File: ValidatorTests.java    From docker-workflow-plugin with MIT License 4 votes vote down vote up
@Test
   public void shouldNotValidateWhenFirstNameEmpty() {

LocaleContextHolder.setLocale(Locale.ENGLISH);
       Person person = new Person();
       person.setFirstName("");
       person.setLastName("smith");

       Validator validator = createValidator();
       Set<ConstraintViolation<Person>> constraintViolations = validator.validate(person);

       Assert.assertEquals(1, constraintViolations.size());
       ConstraintViolation<Person> violation =  constraintViolations.iterator().next();
       assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName");
       assertThat(violation.getMessage()).isEqualTo("may not be empty");
   }