javax.validation.groups.Default Java Examples

The following examples show how to use javax.validation.groups.Default. 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: CpDataLevelMapDeserializer.java    From hj-t212-parser with Apache License 2.0 6 votes vote down vote up
@Deprecated
private void verifyByVersion(Map<String, Object> result) throws T212FormatException {
    List<Class> groups = new ArrayList<>();
    groups.add(Default.class);
    groups.add(T212MapLevelGroup.DataLevel.class);

    int flag = 0;
    T212Map t212Map;
    if(result.containsKey(DataElement.Flag.name())){
        String f = (String) result.get(DataElement.Flag.name());
        flag = Integer.valueOf(f);
    }
    if(DataFlag.V0.isMarked(flag)){
        t212Map = T212Map.create2017(result);
    }else{
        t212Map = T212Map.create2005(result);
    }
    if(DataFlag.D.isMarked(flag)){
        groups.add(ModeGroup.UseSubPacket.class);
    }

    Set<ConstraintViolation<T212Map>> constraintViolationSet = validator.validate(t212Map,groups.toArray(new Class[]{}));
    if(!constraintViolationSet.isEmpty()) {
        create_format_exception(constraintViolationSet,result);
    }
}
 
Example #2
Source File: ClientDataValidationErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddExtraLoggingDetailsForClientDataValidationError() {
    ConstraintViolation<Object> violation1 = setupConstraintViolation(SomeValidatableObject.class, "path.to.violation1", NotNull.class, "MISSING_EXPECTED_CONTENT");
    ConstraintViolation<Object> violation2 = setupConstraintViolation(Object.class, "path.to.violation2", NotEmpty.class, "TYPE_CONVERSION_ERROR");
    ClientDataValidationError ex = new ClientDataValidationError(
            Arrays.asList(new SomeValidatableObject("someArg1", "someArg2"), new Object()),
            Arrays.asList(violation1, violation2),
            new Class<?>[] {Default.class, SomeValidationGroup.class}
    );

    List<Pair<String, String>> extraLoggingDetails = new ArrayList<>();
    listener.processClientDataValidationError(ex, extraLoggingDetails);
    assertThat(extraLoggingDetails, containsInAnyOrder(
            Pair.of("client_data_validation_failed_objects", SomeValidatableObject.class.getName() + "," + Object.class.getName()),
            Pair.of("validation_groups_considered", Default.class.getName() + "," + SomeValidationGroup.class.getName()),
            Pair.of("constraint_violation_details",
                    "SomeValidatableObject.path.to.violation1|javax.validation.constraints.NotNull|MISSING_EXPECTED_CONTENT,Object.path.to.violation2|org.hibernate.validator.constraints" +
                            ".NotEmpty|TYPE_CONVERSION_ERROR"))
    );
}
 
Example #3
Source File: ParameterValidator.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public <T> void beforeMethodInvoke(SwaggerInvocation invocation, SwaggerProducerOperation producerOperation,
    Object[] args)
    throws ConstraintViolationException {
  if (paramValidationEnabled.get()) {
    if (null == executableValidator) {
      ValidatorFactory factory =
          Validation.byDefaultProvider()
              .configure()
              .parameterNameProvider(new DefaultParameterNameProvider())
              .messageInterpolator(messageInterpolator())
              .buildValidatorFactory();
      executableValidator = factory.getValidator().forExecutables();
    }
    Set<ConstraintViolation<Object>> violations =
        executableValidator.validateParameters(producerOperation.getProducerInstance(),
            producerOperation.getProducerMethod(),
            args,
            Default.class);
    if (violations.size() > 0) {
      LOGGER.warn("Parameter validation failed : " + violations.toString());
      throw new ConstraintViolationException(violations);
    }
  }
}
 
Example #4
Source File: NoDefaultGroupTest.java    From guice-validator with MIT License 6 votes vote down vote up
@Test
public void testDefaultGroupDisable() throws Exception {
    final Injector injector = Guice.createInjector(new ValidationModule()
            .strictGroupsDeclaration());
    final Service service = injector.getInstance(Service.class);

    // default group not applied - no validation errors
    service.call(new Model("sample", null, null));

    // verify default group would fail
    injector.getInstance(ValidationContext.class).doWithGroups(new GroupAction<Object>() {
        @Override
        public Object call() throws Throwable {
            try {
                service.call(new Model("sample", null, null));
            } catch (ConstraintViolationException ex) {
                Set<String> props = PropFunction.convert(ex.getConstraintViolations());
                Assert.assertEquals(1, props.size());
                Assert.assertEquals(Sets.newHashSet("def"), props);
            }
            return null;
        }
    }, Default.class);
}
 
Example #5
Source File: JValidator.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
    String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName);
    Class<?> methodClass = null;
    try {
        methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
    } catch (ClassNotFoundException e) {
    }
    Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
    Method method = clazz.getMethod(methodName, parameterTypes);
    Object parameterBean = getMethodParameterBean(clazz, method, arguments);
    if (parameterBean != null) {
        if (methodClass != null) {
            violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass));
        } else {
            violations.addAll(validator.validate(parameterBean, Default.class, clazz));
        }
    }
    for (Object arg : arguments) {
        validate(violations, arg, clazz, methodClass);
    }
    if (violations.size() > 0) {
        throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
    }
}
 
Example #6
Source File: AbstractBeanValidator.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(Object value) {
    Validator validator = beanValidation.getValidator();

    Class[] groups = this.validationGroups;
    if (groups == null || groups.length == 0) {
        groups = new Class[]{Default.class, UiComponentChecks.class};
    }

    @SuppressWarnings("unchecked")
    Set<ConstraintViolation> violations = validator.validateValue(beanClass, beanProperty, value, groups);

    if (!violations.isEmpty()) {
        List<CompositeValidationException.ViolationCause> causes = new ArrayList<>(violations.size());
        for (ConstraintViolation violation : violations) {
            causes.add(new BeanPropertyValidator.BeanValidationViolationCause(violation));
        }

        String validationMessage = this.validationErrorMessage;
        if (validationMessage == null) {
            validationMessage = getDefaultErrorMessage();
        }

        throw new CompositeValidationException(validationMessage, causes);
    }
}
 
Example #7
Source File: JValidator.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
    String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName);
    Class<?> methodClass = null;
    try {
        methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
    } catch (ClassNotFoundException e) {
    }
    Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
    Method method = clazz.getMethod(methodName, parameterTypes);
    Object parameterBean = getMethodParameterBean(clazz, method, arguments);
    if (parameterBean != null) {
        if (methodClass != null) {
            violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass));
        } else {
            violations.addAll(validator.validate(parameterBean, Default.class, clazz));
        }
    }
    for (Object arg : arguments) {
        validate(violations, arg, clazz, methodClass);
    }
    if (violations.size() > 0) {
        throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
    }
}
 
Example #8
Source File: ExtensionHandler.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private Set<Violation> doValidate(Extension extension) {
    ListResult<Extension> result = getDataManager().fetchAll(Extension.class);
    ExtensionWithDomain target = new ExtensionWithDomain(extension, result.getItems());

    final Set<ConstraintViolation<ExtensionWithDomain>> constraintViolations =
        getValidator().validate(target, Default.class, AllValidations.class);

    if (!constraintViolations.isEmpty()) {
        throw new ConstraintViolationException(constraintViolations);
    }

    Set<ConstraintViolation<ExtensionWithDomain>> warnings =
        getValidator().validate(target, NonBlockingValidations.class);
    return warnings.stream()
        .map(Violation.Builder::fromConstraintViolation)
        .collect(Collectors.toSet());
}
 
Example #9
Source File: JValidator.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
    String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName);
    Class<?> methodClass = null;
    try {
        methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
    } catch (ClassNotFoundException e) {
    }
    Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
    Method method = clazz.getMethod(methodName, parameterTypes);
    Object parameterBean = getMethodParameterBean(clazz, method, arguments);
    if (parameterBean != null) {
        if (methodClass != null) {
            violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass));
        } else {
            violations.addAll(validator.validate(parameterBean, Default.class, clazz));
        }
    }
    for (Object arg : arguments) {
        validate(violations, arg, clazz, methodClass);
    }
    if (violations.size() > 0) {
        throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
    }
}
 
Example #10
Source File: DataLevelMapDeserializer.java    From hj-t212-parser with Apache License 2.0 6 votes vote down vote up
@Deprecated
private void verifyByVersion(Map<String, String> result) throws T212FormatException {
    List<Class> groups = new ArrayList<>();
    groups.add(Default.class);
    groups.add(T212MapLevelGroup.DataLevel.class);

    int flag = 0;
    T212Map t212Map;
    if(result.containsKey(DataElement.Flag.name())){
        String f = result.get(DataElement.Flag.name());
        flag = Integer.valueOf(f);
    }
    if(DataFlag.V0.isMarked(flag)){
        t212Map = T212Map.create2017(result);
    }else{
        t212Map = T212Map.create2005(result);
    }
    if(DataFlag.D.isMarked(flag)){
        groups.add(ModeGroup.UseSubPacket.class);
    }

    Set<ConstraintViolation<T212Map>> constraintViolationSet = validator.validate(t212Map,groups.toArray(new Class[]{}));
    if(!constraintViolationSet.isEmpty()) {
        create_format_exception(constraintViolationSet,result);
    }
}
 
Example #11
Source File: DataDeserializer.java    From hj-t212-parser with Apache License 2.0 6 votes vote down vote up
private void verify(Data result) throws T212FormatException {
    List<Class> groups = new ArrayList<>();
    groups.add(Default.class);
    if(DataFlag.V0.isMarked(result.getDataFlag())){
        groups.add(VersionGroup.V2017.class);
    }else{
        groups.add(VersionGroup.V2005.class);
    }
    if(DataFlag.D.isMarked(result.getDataFlag())){
        groups.add(ModeGroup.UseSubPacket.class);
    }

    Set<ConstraintViolation<Data>> constraintViolationSet =
            validator.validate(result,groups.toArray(new Class[]{}));
    if(!constraintViolationSet.isEmpty()) {
        if(THROW_ERROR_VERIFICATION_FAILED.enabledIn(verifyFeature)){
            create_format_exception(constraintViolationSet,result);
        }else{
            //TODO set context
        }
    }
}
 
Example #12
Source File: T212MapVerifyTest.java    From hj-t212-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testDataLevelFalse(){
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Map m = dataLevel.entrySet()
            .stream()
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    kv -> kv.getValue() + "---------------"
            ));
    T212Map t212Map = T212Map.createDataLevel(m);

    Set<ConstraintViolation<T212Map>> e2005 = validator.validate(t212Map,Default.class,
            VersionGroup.V2005.class);
    assertTrue(e2005.size() > 0);
    Set<ConstraintViolation<T212Map>> e2017 = validator.validate(t212Map,Default.class,
            VersionGroup.V2017.class);
    assertTrue(e2017.size() > 0);
}
 
Example #13
Source File: LocalBeanServiceInvoker.java    From jsongood with Apache License 2.0 6 votes vote down vote up
public void validate(Class clazz, String methodName, Class<?>[] parameterTypes, Object[] arguments)
        throws Exception {
    String methodClassName = clazz.getName() + "_" + toUpperMethoName(methodName);
    Class<?> methodClass = null;
    try {
        methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
    } catch (ClassNotFoundException e) {
    }
    Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
    Method method = clazz.getMethod(methodName, parameterTypes);
    Object parameterBean = getMethodParameterBean(clazz, method, arguments);
    if (parameterBean != null) {
        if (methodClass != null) {
            violations.addAll(validator.validate(parameterBean, Default.class, clazz, methodClass));
        } else {
            violations.addAll(validator.validate(parameterBean, Default.class, clazz));
        }
    }
    for (Object arg : arguments) {
        validate(violations, arg, clazz, methodClass);
    }
    if (violations.size() > 0) {
        throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: "
                + methodName + ", cause: " + violations, violations);
    }
}
 
Example #14
Source File: CredentialsManagementValidationTest.java    From airsonic-advanced with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void credCreation_correct() {
    CredentialsCommand cc = new CredentialsCommand("username", "bcrypt", App.AIRSONIC, null, null, null, null, null);
    cc.setCredential("c");
    cc.setConfirmCredential("c");
    assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isEmpty();

    cc.setEncoder("legacyhex");
    assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isEmpty();

    cc.setEncoder("noop");
    assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isEmpty();

    cc.setApp(App.LASTFM);
    assertThat(v.validate(cc, Default.class, CredentialCreateChecks.class)).isEmpty();
}
 
Example #15
Source File: CredentialsManagementController.java    From airsonic-advanced with GNU General Public License v3.0 6 votes vote down vote up
@PostMapping
protected String createNewCreds(Principal user,
        @ModelAttribute("newCreds") @Validated(value = { Default.class, CredentialCreateChecks.class }) CredentialsCommand cc,
        BindingResult br, RedirectAttributes redirectAttributes, ModelMap map) {
    if (br.hasErrors()) {
        map.addAttribute("open_CreateCredsDialog", true);
        return "credentialsSettings";
    }

    UserCredential uc = new UserCredential(user.getName(), cc.getUsername(), cc.getCredential(), cc.getEncoder(), cc.getApp(), "Created by user", cc.getExpirationInstant());

    if (!APPS_CREDS_SETTINGS.get(uc.getApp()).getUsernameRequired()) {
        uc.setAppUsername(user.getName());
    }

    boolean success = true;
    if (!securityService.createCredential(uc)) {
        LOG.warn("Could not create creds for user {}", user.getName());
        success = false;
    }

    redirectAttributes.addFlashAttribute("settings_toast", success);

    return "redirect:credentialsSettings.view";
}
 
Example #16
Source File: AbstractForm.java    From viritin with Apache License 2.0 5 votes vote down vote up
/**
 * @return the JSR 303 bean validation groups that should be used to
 * validate the bean
 */
public Class<?>[] getValidationGroups() {
    if (validationGroups == null) {
        return new Class<?>[]{Default.class};
    }
    return validationGroups;
}
 
Example #17
Source File: StorageFacetImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void doValidate(final Configuration configuration) throws Exception {
  facet(ConfigurationFacet.class).validateSection(configuration, STORAGE, Config.class,
      Default.class, getRepository().getType().getValidationGroup()
  );

  StorageFacetImpl.Config configToValidate = facet(ConfigurationFacet.class)
      .readSection(configuration, STORAGE, StorageFacetImpl.Config.class);
  Set<ConstraintViolation<?>> violations = new HashSet<>();
  maybeAdd(violations, validateBlobStoreNotInGroup(configToValidate.blobStoreName));
  maybePropagate(violations, log);
}
 
Example #18
Source File: ContentFacetSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void doValidate(final Configuration configuration) throws Exception {
  facet(ConfigurationFacet.class).validateSection(configuration, STORAGE, Config.class,
      Default.class, getRepository().getType().getValidationGroup()
  );

  Config configToValidate = facet(ConfigurationFacet.class).readSection(configuration, STORAGE, Config.class);

  Set<ConstraintViolation<?>> violations = new HashSet<>();
  maybeAdd(violations, validateBlobStoreNotInGroup(configToValidate.blobStoreName));
  maybePropagate(violations, log);
}
 
Example #19
Source File: CleanupPolicyComponent.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Update an existing {@link CleanupPolicy} from a {@link CleanupPolicyXO}.
 *
 * @param cleanupPolicyXO - {@link CleanupPolicyXO}
 * @return CleanupPolicyXO from updated {@link CleanupPolicy}
 */
@DirectMethod
@Timed
@ExceptionMetered
@RequiresAuthentication
@RequiresPermissions("nexus:*")
@Validate(groups = {Update.class, Default.class})
public CleanupPolicyXO update(@NotNull @Valid final CleanupPolicyXO cleanupPolicyXO) {
  CleanupPolicy cleanupPolicy = cleanupPolicyStorage.get(cleanupPolicyXO.getName());
  return fromCleanupPolicy(cleanupPolicyStorage.update(mergeIntoCleanupPolicy(cleanupPolicyXO, cleanupPolicy)));
}
 
Example #20
Source File: FluentHibernateValidatorTest.java    From fluent-validator with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompanyMultiGrouping() {
    Company company = CompanyBuilder.buildSimple();
    company.setName("$%^$%^$%");

    Result ret = FluentValidator.checkAll(Default.class, AddCompany.class)
            .on(company, new HibernateSupportedValidator<Company>().setHibernateValidator(validator))
            .on(company, new CompanyCustomValidator())
            .doValidate().result(toSimple());
    System.out.println(ret);
    assertThat(ret.isSuccess(), is(false));
    assertThat(ret.getErrorNumber(), is(2));
}
 
Example #21
Source File: ClientDataValidationServiceTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void validateObjectsWithGroupsFailFastShouldValidatePassedInObjectsWithGroups() {
    given(validatorMock.validate(any(), any(Class[].class))).willReturn(Collections.<ConstraintViolation<Object>>emptySet());
    Object objToValidate1 = new Object();
    Object objToValidate2 = new Object();
    Class<?>[] groups = new Class<?>[]{Default.class, String.class};
    validationServiceSpy.validateObjectsWithGroupsFailFast(groups, objToValidate1, objToValidate2);
    verify(validatorMock).validate(objToValidate1, groups);
    verify(validatorMock).validate(objToValidate2, groups);
}
 
Example #22
Source File: CleanupPolicyComponent.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create {@link CleanupPolicy} from a {@link CleanupPolicyXO} and store it.
 *
 * @param cleanupPolicyXO - {@link CleanupPolicyXO}
 * @return CleanupPolicyXO from created {@link CleanupPolicy}
 */
@DirectMethod
@Timed
@ExceptionMetered
@RequiresAuthentication
@RequiresPermissions("nexus:*")
@Validate(groups = {Create.class, Default.class})
public CleanupPolicyXO create(@NotNull @Valid final CleanupPolicyXO cleanupPolicyXO) {
  return fromCleanupPolicy(cleanupPolicyStorage.add(toCleanupPolicy(cleanupPolicyXO)));
}
 
Example #23
Source File: UserValidator.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void validate(Object target, Errors err) {
	Map<String, String> fieldValidation = ValidatorUtil.validate((User)target, Default.class);
	
	fieldValidation.forEach(
			(k, v) -> err.rejectValue(k, v)
	);
}
 
Example #24
Source File: TodoTest.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
@Test()
public void testInvalidDueDate() {
    Todo todo = new Todo();
    todo.setName("test");
    todo.setDueDate(LocalDateTime.now());
    Set<ConstraintViolation<Todo>> violations = validator.validate(todo, Default.class);
    LOG.log(Level.INFO, "violations.size ::" + violations.size());
    assertTrue(violations.size() == 1);
}
 
Example #25
Source File: TodoTest.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
@Test()
public void testInvalidTodo2() {
    Todo todo = new Todo();
    Set<ConstraintViolation<Todo>> violations = validator.validate(todo, Default.class);
    LOG.log(Level.INFO, "violations.size ::" + violations.size());
    assertTrue(violations.size() > 0);
}
 
Example #26
Source File: ValidationUtils.java    From wish-pay with Apache License 2.0 5 votes vote down vote up
public static <T> ValidationResult validateProperty(T obj, String propertyName) {
    ValidationResult result = new ValidationResult();
    Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class);
    if (CollectionUtils.isNotEmpty(set)) {
        result.setHasErrors(true);
        Map<String, String> errorMsg = Maps.newHashMap();
        for (ConstraintViolation<T> cv : set) {
            errorMsg.put(propertyName, cv.getMessage());
        }
        result.setErrorMsg(errorMsg);
    }
    return result;
}
 
Example #27
Source File: UserValidatorDemoController.java    From spring-boot-start-current with Apache License 2.0 5 votes vote down vote up
@PostMapping
public ResponseEntity< UserForm > saveValidated ( @RequestBody
												  @Validated( { ValidatedGroups.Save.class , Default.class } ) UserForm user ,
												  BindingResult result ) {
	// 这里可以自己进行处理
	AssertUtils.bindingResult( result );
	LogUtils.getLogger().debug( "user : {},验证通过" , user );
	return ResponseEntityPro.ok( user );
}
 
Example #28
Source File: ValidDateValidatorTest.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.yyyy = "2018";
    bean.hh = "2530";

    Set<ConstraintViolation<TestBean>> e1 = validator.validate(bean,
            Default.class);
    assertEquals(e1.size(),1);
}
 
Example #29
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 #30
Source File: NValidatorTest.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.n1 = "1";
    bean.n2_2 = "120.345";

    Set<ConstraintViolation<TestBean>> e1 = validator.validate(bean,
            Default.class);
    assertEquals(e1.size(),1);
}