Java Code Examples for javax.validation.Validation#buildDefaultValidatorFactory()

The following examples show how to use javax.validation.Validation#buildDefaultValidatorFactory() . 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: ViewController.java    From hibernate-demos with Apache License 2.0 6 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()));

    validateButton.setOnAction(e -> {
        final Set<ConstraintViolation<Model>> violations = validator.validate(model);



        validateMessageLabel.setText(violations.stream().map(v -> v.getMessage()).reduce("", (a, b) -> a + b));
    });
}
 
Example 3
Source File: BeanValidation.java    From open-Autoscaler with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source File: T212MapValidDateValidatorTest.java    From hj-t212-parser with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("Duplicates")
@Test
public void test(){
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    T212Map t212Map = T212Map.createDataLevel(map);

    Set<ConstraintViolation<T212Map>> e0 = validator.validate(t212Map,
            Default.class);
    assertEquals(e0.size(),0);

    t212Map.clear();
    map.put("QN","20180101123010123-");
    Set<ConstraintViolation<T212Map>> e1 = validator.validate(t212Map,
            Default.class);
    assertEquals(e1.size(),1);

}
 
Example 5
Source File: CardExpiryValidatorTest.java    From pay-publicapi with MIT License 6 votes vote down vote up
@BeforeClass
public static void setUpValidator() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    validator = factory.getValidator();

    builder
            .withAmount(1200)
            .withDescription("Some description")
            .withReference("Some reference")
            .withProcessorId("1PROC")
            .withProviderId("1PROV")
            .withLastFourDigits("1234")
            .withFirstSixDigits("123456")
            .withCardType("visa")
            .withPaymentOutcome(new PaymentOutcome("success"));
}
 
Example 6
Source File: CardFirstSixDigitsValidatorTest.java    From pay-publicapi with MIT License 6 votes vote down vote up
@BeforeClass
public static void setUpValidator() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    validator = factory.getValidator();

    builder
            .withAmount(1200)
            .withDescription("Some description")
            .withReference("Some reference")
            .withProcessorId("1PROC")
            .withProviderId("1PROV")
            .withCardExpiry("01/99")
            .withCardType("visa")
            .withLastFourDigits("1234")
            .withPaymentOutcome(new PaymentOutcome("success"));
}
 
Example 7
Source File: CustomValidatorFactoryTest.java    From guice-validator with MIT License 5 votes vote down vote up
@Test
public void testConstraintCleanup() throws Exception {
    final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Guice.createInjector(new ValidationModule(factory).validateAnnotatedOnly())
            .getInstance(CustomService.class)
            .doAction(new ComplexBean("perfect", 12));
    factory.close();
}
 
Example 8
Source File: JValidator.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 9
Source File: BeanValidation.java    From open-Autoscaler with Apache License 2.0 5 votes vote down vote up
public static JsonNode parseMetrics(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, HistoryData.class);
	 //new_mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
	 logger.info("Received metrics: " + jsonString);
	 Metrics metrics = new_mapper.readValue(jsonString, Metrics.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<Metrics>> set = validator.validate(metrics);
	 if (set.size() > 0 ){
		 for (ConstraintViolation<Metrics> constraintViolation : set) {
			 violation_message.add(constraintViolation.getMessage());
		 }
		 result.set("violation_message", new_mapper.valueToTree(violation_message));
		 return result;
	 }
         

	 //additional data manipulation
   	 String new_json = metrics.transformOutput();
	 result.put("valid", true);
	 result.put("new_json", new_json);
	 return result;
}
 
Example 10
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 11
Source File: NotStandardTest.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 5 votes vote down vote up
@BeforeEach
public void init() {
    emFactory = Persistence.createEntityManagerFactory("DB");
    em = emFactory.createEntityManager();

    valFactory = Validation.buildDefaultValidatorFactory();
    validator = valFactory.getValidator();
}
 
Example 12
Source File: WorkflowDefValidatorTest.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Test
public void testWorkflowDefConstraintsWithMapAsInputParam() {
	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} ${NETFLIX_STACK}");
	Map<String, Object> envInputParam = new HashMap<>();
	envInputParam.put("packageId", "${workflow.input.packageId}");
	envInputParam.put("taskId", "${CPEWF_TASK_ID}");
	envInputParam.put("NETFLIX_STACK", "${NETFLIX_STACK}");
	envInputParam.put("NETFLIX_ENVIRONMENT", "${NETFLIX_ENVIRONMENT}");

	inputParam.put("env", envInputParam);

	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 13
Source File: BeanValidationInterceptorTest.java    From hibersap with Apache License 2.0 5 votes vote down vote up
@Test
public void throwsConstraintViolationExceptionWhoseMessageContainsNameOfNonValidatingClass() {
    final ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    final BeanValidationInterceptor interceptor = new BeanValidationInterceptor(validatorFactory);

    assertThatThrownBy(() -> interceptor.beforeExecution(new TestObject()))
            .isInstanceOf(ConstraintViolationException.class)
            .hasMessageContaining("org.hibersap.interceptor.impl.BeanValidationInterceptorTest$InnerObject");
}
 
Example 14
Source File: TodoIT.java    From java-microservice with MIT License 5 votes vote down vote up
@Test
public void validateTodoValid() {
    ToDo toDo = new ToDo("[email protected]","caption", "description 1", 6);
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<ToDo>> constraintViolations = validator.validate(toDo);
    assertTrue(constraintViolations.isEmpty());       
}
 
Example 15
Source File: UserValidationUnitTest.java    From tutorials with MIT License 4 votes vote down vote up
@BeforeClass
public static void before() {
    ValidatorFactory config = Validation.buildDefaultValidatorFactory();
    validator = config.getValidator();
    sessionFactory = HibernateUtil.getSessionFactory(Strategy.MAP_KEY_BASED);
}
 
Example 16
Source File: BookTest.java    From Java-EE-8-Sampler with MIT License 4 votes vote down vote up
@BeforeClass
public static void setUpValidator() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    validator = factory.getValidator();
}
 
Example 17
Source File: UserVMTest.java    From jhipster-microservices-example with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    validator = factory.getValidator();
}
 
Example 18
Source File: T212MapVerifyTest.java    From hj-t212-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testCPDataLevel(){
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<T212Map>> e2005 = validator.validate(cpDataLevel,Default.class,
            T212MapLevelGroup.CpDataLevel.class, VersionGroup.V2005.class);
    assertTrue(e2005.isEmpty());
    Set<ConstraintViolation<T212Map>> e2017 = validator.validate(cpDataLevel,Default.class,
            T212MapLevelGroup.CpDataLevel.class, VersionGroup.V2017.class);
    assertTrue(e2017.isEmpty());
}
 
Example 19
Source File: EntityDefinitionTest.java    From xlsmapper with Apache License 2.0 4 votes vote down vote up
@Before
public void setupBefore() {

    // BeanValidatorの式言語の実装を独自のものにする。
    ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    Validator validator = validatorFactory.usingContext()
            .messageInterpolator(new MessageInterpolatorAdapter(
                    // メッセージリソースの取得方法を切り替える
                    new ResourceBundleMessageResolver(),

                    // EL式の処理を切り替える
                    new MessageInterpolator(new ExpressionLanguageJEXLImpl())))
            .getValidator();

    // BeanValidationのValidatorを渡す
    this.sheetBeanValidator = new SheetBeanValidator(validator);

    this.errorFormatter = new SheetErrorFormatter();

}
 
Example 20
Source File: TableReplicationTest.java    From circus-train with Apache License 2.0 4 votes vote down vote up
@Before
public void before() {
  ValidatorFactory config = Validation.buildDefaultValidatorFactory();
  validator = config.getValidator();
}