@Test
  public void testCustomConstraintValidatorFactory() {

    Configuration<?> configuration = Validation.byDefaultProvider().configure();
    assertDefaultBuilderAndFactory(configuration);

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

    Customer customer = new Customer();
    customer.setFirstName("John");

    Set<ConstraintViolation<Customer>> constraintViolations = validator.validate(customer);
    assertEquals(constraintViolations.size(), 1, "Wrong number of constraints");
    ConstraintViolation<Customer> constraintViolation = constraintViolations.iterator().next();
    assertEquals("may not be empty", constraintViolation.getMessage(), "Wrong message");

    // get a new factory using a custom configuration
    configuration = Validation.byDefaultProvider().configure();
    configuration.constraintValidatorFactory(
        new ConstraintValidatorFactory() {

          public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
            if (key == NotNullValidator.class) {
              return (T) new BadlyBehavedNotNullConstraintValidator();
            }
            return new ConstraintValidatorFactoryImpl().getInstance(key);
          }
        });
    factory = configuration.buildValidatorFactory();
    validator = factory.getValidator();
    constraintViolations = validator.validate(customer);
    assertEquals(constraintViolations.size(), 0, "Wrong number of constraints");
  }
Пример #2
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    PrintWriter out = resp.getWriter();
    resp.setContentType("text/html");
    out.print("<html><head><title>SimpleBVServlet</title></head><body>");

    javax.validation.Validator beanValidator = configureValidation(req, resp);

    out.print("<h1>");
    out.print("Validating person class using validateValue with valid property");
    out.print("</h1>");

    List<String> listOfString = new ArrayList<String>();
    listOfString.add("one");
    listOfString.add("two");
    listOfString.add("three");

    Set<ConstraintViolation<Person>> violations =
        beanValidator.validateValue(Person.class, "listOfString", listOfString);

    printConstraintViolations(out, violations, "case1");

    out.print("<h1>");
    out.print("Validating person class using validateValue with invalid property");
    out.print("</h1>");

    try {
      violations = beanValidator.validateValue(Person.class, "nonExistentProperty", listOfString);
    } catch (IllegalArgumentException iae) {
      out.print("<p>");
      out.print("case2: caught IllegalArgumentException.  Message: " + iae.getMessage());
      out.print("</p>");
    }
    Person person = new Person();

    out.print("<h1>");
    out.print("Validating invalid person instance using validate.");
    out.print("</h1>");

    violations = beanValidator.validate(person);

    printConstraintViolations(out, violations, "case3");

    out.print("<h1>");
    out.print("Validating valid person.");
    out.print("</h1>");

    person.setFirstName("John");
    person.setLastName("Yaya");
    person.setListOfString(listOfString);

    violations = beanValidator.validate(person);
    printConstraintViolations(out, violations, "case4");

    out.print("</body></html>");
  }
Пример #3
0
  @Test
  public void userIdLength() throws Exception {
    User user = new User("us", "password", "name", "");
    Set<ConstraintViolation<User>> constraintViolations = validator.validate(user);
    assertEquals(1, constraintViolations.size());
    System.out.println(constraintViolations.iterator().next().getMessage());

    user = new User("userIduserId2", "password", "name", "");
    constraintViolations = validator.validate(user);
    assertEquals(1, constraintViolations.size());
    System.out.println(constraintViolations.iterator().next().getMessage());
  }
 @Test
 public void testTypeValidation() {
   // invalid
   SalesOrder salesOrder = new SalesOrder();
   salesOrder.setOrderNum("");
   salesOrder.setCustomer("customer");
   assertEquals(1, validator.validate(salesOrder).size());
   // valid
   salesOrder.setOrderNum("o_1");
   salesOrder.setTotalPrice(100);
   assertEquals(0, validator.validate(salesOrder).size());
 }
Пример #5
0
  @Test
  public void testValidationOfBeanDirectly() {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    MyBean b = new MyBean("hi", 1, 2);

    Set<ConstraintViolation<MyBean>> violations = validator.validate(b);
    Assert.assertEquals(0, violations.size());

    b = new MyBean("hi", 2, 1);
    violations = validator.validate(b);
    Assert.assertEquals(1, violations.size());
    Assert.assertEquals(
        "script expression \"_this.i < _this.j\" didn't evaluate to true",
        violations.iterator().next().getMessage());
  }
  @Test
  public void testSymbolsPermitttedButNotRequired() throws Exception {
    ChangePasswordForm form = new ChangePasswordForm();
    form.setOldPassword("Ben Kingsley  is my no. 1 actor");
    form.setPassword("passw0rd");
    form.setRetypedPassword("passw0rd");
    Set<ConstraintViolation<ChangePasswordForm>> errors = validator.validate(form);
    assertEquals("Should be no errors", 0, errors.size());

    // check that the test doesn't break when symbols introduced
    form.setPassword("p$ssw0rd");
    form.setRetypedPassword("p$ssw0rd");
    errors = validator.validate(form);
    assertEquals("Should be no errors", 0, errors.size());
  }
Пример #7
0
 @Test
 public void userIdIsNull() {
   User user = new User(null, "password", "name", "");
   Set<ConstraintViolation<User>> constraintViolations = validator.validate(user);
   assertEquals(1, constraintViolations.size());
   System.out.println(constraintViolations.iterator().next().getMessage());
 }
Пример #8
0
  @Test
  public void nullValuesLocation() throws Exception {
    Location location = new Location();

    Set<ConstraintViolation<Location>> violations = validator.validate(location);
    assertEquals(2, violations.size());
  }
  @Test
  public void checkRulePassengerTime() {
    List<PassengerGenerationRule> workDayRulesOfGagarina = new ArrayList<>();
    workDayRulesOfGagarina.add(
        PassengerGenerationRule.of(8, LocalTime.of(6, 0), LocalTime.of(6, 0), LocalTime.of(0, 15)));
    //        workDayRulesOfGagarina.add(PassengerGenerationRule.of(
    //                4, LocalTime.of(9, 0), LocalTime.of(13, 0), LocalTime.of(0, 17))
    //        );
    //        workDayRulesOfGagarina.add(PassengerGenerationRule.of(
    //                2, LocalTime.of(13, 0), LocalTime.of(16, 0), LocalTime.of(0, 17))
    //        );
    //        workDayRulesOfGagarina.add(PassengerGenerationRule.of(
    //                8, LocalTime.of(16, 0), LocalTime.of(19, 0), LocalTime.of(0, 15))
    //        );
    //        workDayRulesOfGagarina.add(PassengerGenerationRule.of(
    //                4, LocalTime.of(19, 0), LocalTime.of(23, 0), LocalTime.of(0, 15))
    //        );

    PassengerGenerationRuleList item =
        PassengerGenerationRuleList.of(HOLIDAY, workDayRulesOfGagarina);

    Set<ConstraintViolation<PassengerGenerationRuleList>> constraintViolations =
        validator.validate(item, ImitationSourceSequence.class);
    constraintViolations.forEach(System.out::println);

    assertEquals(1, constraintViolations.size());
    assertEquals(
        "{incorrect rule passenger generation time}",
        constraintViolations.iterator().next().getMessage());
  }
Пример #10
0
 @Test
 public void testIsInValid() throws Exception {
   EmailTest t = new EmailTest("12893 NC");
   Set<ConstraintViolation<EmailTest>> constraintViolations = validator.validate(t);
   assertViolations(
       constraintViolations, 1, "{org.hibernate.validator.constraints.Email.message}");
 }
Пример #11
0
  public static <T> List<ValidationMessages> validateEntity(
      Validator validator, T entity, Class<?>... groups) {

    Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity, groups);
    Map<String, List<String>> fieldMessages = new HashMap<>();
    if (!constraintViolations.isEmpty()) {
      for (ConstraintViolation<T> constraintViolation : constraintViolations) {
        String property = constraintViolation.getPropertyPath().toString();
        List<String> messages = fieldMessages.get(property);
        if (messages == null) {
          messages = new ArrayList<>();
          fieldMessages.put(property, messages);
        }
        messages.add(constraintViolation.getMessage());
      }
    }
    List<ValidationMessages> validationErrors = new ArrayList<>();
    fieldMessages.forEach(
        (k, v) -> {
          ValidationMessages errors = new ValidationMessages();
          errors.setField(k);
          errors.setMessages(v.toArray(new String[v.size()]));
          validationErrors.add(errors);
        });

    return validationErrors;
  }
Пример #12
0
 @Test
 public void validateCreditorHasNoIbanOrPropiataryId() {
   FinancialAccount account = new CreditorFinancialAccount();
   Set<ConstraintViolation<FinancialAccount>> validationResult = validator.validate(account);
   assertThat(validationResult.isEmpty()).isFalse();
   assertThat(validationResult.size()).isEqualTo(1);
 }
Пример #13
0
 @Test
 public void validateHasPropiataryId() {
   FinancialAccount account = new CreditorFinancialAccount();
   account.setProprietaryId("Prop ID");
   Set<ConstraintViolation<FinancialAccount>> validationResult = validator.validate(account);
   assertThat(validationResult.isEmpty()).isTrue();
 }
 @Test
 @TestForIssue(jiraKey = "HV-933")
 public void incorrect_cnpj_without_separator_creates_constraint_violation() {
   Set<ConstraintViolation<Company>> violations =
       validator.validate(new Company("91509901000160"));
   assertNumberOfViolations(violations, 1);
 }
  @Test
  public void checkRulePassengerIntersection() {
    List<PassengerGenerationRule> workDayRulesOfGagarina = new ArrayList<>();
    workDayRulesOfGagarina.add(
        PassengerGenerationRule.of(
            8, LocalTime.of(6, 0), LocalTime.of(9, 50), LocalTime.of(0, 15)));
    workDayRulesOfGagarina.add(
        PassengerGenerationRule.of(
            8, LocalTime.of(5, 0), LocalTime.of(8, 50), LocalTime.of(0, 20)));
    workDayRulesOfGagarina.add(
        PassengerGenerationRule.of(
            8, LocalTime.of(22, 0), LocalTime.of(4, 50), LocalTime.of(0, 20)));

    PassengerGenerationRuleList item =
        PassengerGenerationRuleList.of(HOLIDAY, workDayRulesOfGagarina);

    Set<ConstraintViolation<PassengerGenerationRuleList>> constraintViolations =
        validator.validate(item, ImitationSourceSequence.class);
    constraintViolations.forEach(System.out::println);

    assertEquals(1, constraintViolations.size());
    assertEquals(
        "{rule passenger generation is intersection}",
        constraintViolations.iterator().next().getMessage());
  }
Пример #16
0
  @POST
  @Path("pay")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public ResponseBean payment(ExamBean2 bean) {

    ResponseBean<ExamBean2> res = new ResponseBean();

    // We can't @Inject Validator on Glassfish 4.0, 4.0.1 may be fix it.
    final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<ExamBean2>> violations =
        validator.validate(bean, bean.validateGroups());
    System.out.println(violations.toString());
    if (!violations.isEmpty()) {
      // There are some validation errors
      res.setSuccess(false);
      res.setValidationError(violations);
      return res;
    }

    res.setSuccess(true);
    return res;
  }
Пример #17
0
 @Override
 public Validator validate(Object object, Class<?>... groups) {
   if (object != null) {
     addAll(bvalidator.validate(object, groups));
   }
   return this;
 }
 @Test
 @TestForIssue(jiraKey = "HV-491")
 public void correct_cnpj_with_separator_validates() {
   Set<ConstraintViolation<Company>> violations =
       validator.validate(new Company("91.509.901/0001-69"));
   assertNumberOfViolations(violations, 0);
 }
Пример #19
0
  @SuppressWarnings("unchecked")
  public void afterPropertiesSet() throws Exception {

    Assert.state(yaml != null, "Yaml document should not be null");

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

    try {
      logger.trace("Yaml document is\n" + yaml);
      configuration = (T) (new Yaml(constructor)).load(yaml);
      Set<ConstraintViolation<T>> errors = validator.validate(configuration);

      if (!errors.isEmpty()) {
        logger.error("YAML configuration failed validation");
        for (ConstraintViolation<?> error : errors) {
          logger.error(error.getPropertyPath() + ": " + error.getMessage());
        }
        if (exceptionIfInvalid) {
          @SuppressWarnings("rawtypes")
          ConstraintViolationException summary = new ConstraintViolationException((Set) errors);
          throw summary;
        }
      }
    } catch (YAMLException e) {
      if (exceptionIfInvalid) {
        throw e;
      }
      logger.error("Failed to load YAML validation bean. Your YAML file may be invalid.", e);
    }
  }
  @Override
  public Category add(
      Category
          category) { // throws FieldNotValidException, CategoryExistentException { Not needed as it
                      // is mentioned in the interface

    // Validating the Hibernate Annotations
    Set<ConstraintViolation<Category>> errors = validator.validate(category);
    Iterator<ConstraintViolation<Category>> itErrors = errors.iterator();

    if (itErrors.hasNext()) {
      ConstraintViolation<Category> violation = itErrors.next();
      throw new FieldNotValidException(
          violation.getPropertyPath().toString(), violation.getMessage());

      // violation.getPropertyPath().toString() =>
      //								return "Category [id=" + id + ", name=" + name + "]";
    }

    if (categoryRepo.alreadyExists(category)) {
      throw new CategoryExistentException();
    }

    return categoryRepo.add(category);
  }
Пример #21
0
 private void validateObject(Object object, String context) throws BeanValidationException {
   // validate object using the bean validation framework
   Set<ConstraintViolation<Object>> violations = VALIDATOR.validate(object);
   if (!violations.isEmpty()) {
     throw new BeanValidationException(violations, context);
   }
 }
Пример #22
0
  @Override
  public String getTaxNumber(String firmokpo, String docnum, String docdate) {
    TaxNumberParameter params = new TaxNumberParameter(firmokpo, docnum, docdate);

    StringBuilder outputBuffer = new StringBuilder();

    // here we should validate parameters, that have been passed with query
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<TaxNumberParameter>> constraintViolations = validator.validate(params);

    StringBuilder validationBuffer = new StringBuilder();

    validationBuffer.append(
        constraintViolations
            .stream()
            .map(ConstraintViolation::getMessage)
            .collect(Collectors.joining("\n")));

    String validationMessage = validationBuffer.toString();
    if (!validationMessage.isEmpty()) {

      // outputBuffer.append(validationMessage);
      // Throwing Exception with contents.
      throw new IllegalArgumentException("Invalid input parameters: " + validationMessage);
    }

    String taxNumber = taxNumberDAO.getTaxNumber(params);

    return taxNumber;
  }
Пример #23
0
  protected boolean jsr303ValidateBean(T bean) {
    try {
      if (javaxBeanValidator == null) {
        javaxBeanValidator = getJavaxBeanValidatorFactory().getValidator();
      }
    } catch (Throwable t) {
      // This may happen without JSR303 validation framework
      Logger.getLogger(getClass().getName()).fine("JSR303 validation failed");
      return true;
    }

    Set<ConstraintViolation<T>> constraintViolations =
        new HashSet(javaxBeanValidator.validate(bean, getValidationGroups()));
    if (constraintViolations.isEmpty()) {
      return true;
    }
    Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
    while (iterator.hasNext()) {
      ConstraintViolation<T> constraintViolation = iterator.next();
      Class<? extends Annotation> annotationType =
          constraintViolation.getConstraintDescriptor().getAnnotation().annotationType();
      AbstractComponent errortarget = validatorToErrorTarget.get(annotationType);
      if (errortarget != null) {
        // user has declared a target component for this constraint
        errortarget.setComponentError(new UserError(constraintViolation.getMessage()));
        iterator.remove();
      }
      // else leave as "bean level error"
    }
    this.jsr303beanLevelViolations = constraintViolations;
    return false;
  }
Пример #24
0
 /** @return true if all parameters class and its inner members passed validation */
 protected boolean validateInputs() {
   Set<ConstraintViolation<P>> violations = validator.validate(getParameters());
   if (!violations.isEmpty()) {
     returnValue.setExceptionString(violations.toString());
     return false;
   }
   return true;
 }
 private <T> Map<String, ConstraintViolation<T>> validate(T user) {
   Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
   Map<String, ConstraintViolation<T>> violations = new HashMap<String, ConstraintViolation<T>>();
   for (ConstraintViolation<T> violation : validator.validate(user)) {
     violations.put(violation.getPropertyPath().toString(), violation);
   }
   return violations;
 }
Пример #26
0
 @Test
 public void validLocation() throws Exception {
   Location location = new Location();
   location.setBuilding("Galleriet");
   location.setRoom("82");
   Set<ConstraintViolation<Location>> violations = validator.validate(location);
   assertTrue(violations.isEmpty());
 }
  @Test
  @SpecAssertion(section = "7", id = "b")
  public void testXmlConfiguredValidatorConfigurationHasPrecedence() {
    Configuration<?> config = TestUtil.getConfigurationUnderTest();
    InputStream in =
        getInputStreamForPath(
            "org/hibernate/beanvalidation/tck/tests/constraints/builtinconstraints/builtin-constraints-override.xml");
    config.addMapping(in);
    Validator validator = config.buildValidatorFactory().getValidator();
    DummyEntity dummy = new DummyEntity();
    Set<ConstraintViolation<DummyEntity>> violations = validator.validate(dummy);
    assertCorrectNumberOfViolations(violations, 0);

    dummy.dummyProperty = "foobar";
    violations = validator.validate(dummy);
    assertCorrectNumberOfViolations(violations, 1);
  }
Пример #28
0
  @Test
  public void carIsValid() {
    Car car = new Car("Morris", "DD-AB-123", 2);

    Set<ConstraintViolation<Car>> constraintViolations = validator.validate(car);

    assertEquals(0, constraintViolations.size());
  }
  @Test
  public void testPasswordLengthMin8() {
    ChangePasswordForm form = new ChangePasswordForm();
    form.setPassword("a$1");
    Set<ConstraintViolation<ChangePasswordForm>> violations = validator.validate(form);
    Map<String, String> allErrorValues = retrieveErrorKeyAndMessage(violations);
    String password = allErrorValues.get("password");
    assertEquals(
        "Passwords must be 8 or more characters and contain at least 1 number and at least 1 alpha character or symbol",
        password);

    form.setPassword("a$1a$1a$1");
    violations = validator.validate(form);
    allErrorValues = retrieveErrorKeyAndMessage(violations);
    password = allErrorValues.get("password");
    assertNull(password);
  }
Пример #30
0
 @Around("com.zaliczenie.aspects.ConfigureAspect.aaa()")
 public Object ddd(ProceedingJoinPoint pjp) throws Throwable {
   Set<ConstraintViolation<Object>> bledy = validator.validate(pjp.getArgs()[0]);
   if (bledy.isEmpty()) {
     pjp.proceed();
   }
   return bledy;
 }