@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
  @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;
  }
  /**
   * Validates the Bean Validation constraints specified at the parameters and/or return value of
   * the intercepted constructor.
   *
   * @param ctx The context of the intercepted constructor invocation.
   * @throws Exception Any exception caused by the intercepted constructor invocation. A {@link
   *     ConstraintViolationException} in case at least one constraint violation occurred either
   *     during parameter or return value validation.
   */
  @AroundConstruct
  public void validateConstructorInvocation(InvocationContext ctx) throws Exception {
    ExecutableValidator executableValidator = validator.forExecutables();
    Set<? extends ConstraintViolation<?>> violations =
        executableValidator.validateConstructorParameters(
            ctx.getConstructor(), ctx.getParameters());

    if (!violations.isEmpty()) {
      throw new ConstraintViolationException(
          getMessage(ctx.getConstructor(), ctx.getParameters(), violations), violations);
    }

    ctx.proceed();
    Object createdObject = ctx.getTarget();

    violations =
        validator
            .forExecutables()
            .validateConstructorReturnValue(ctx.getConstructor(), createdObject);

    if (!violations.isEmpty()) {
      throw new ConstraintViolationException(
          getMessage(ctx.getConstructor(), ctx.getParameters(), violations), violations);
    }
  }
예제 #4
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;
  }
  @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);
    }
  }
  @Test
  public void shouldUnwrapParameterValueBasedOnProgrammaticConfiguration() throws Exception {
    HibernateValidatorConfiguration configuration = ValidatorUtil.getConfiguration();
    ConstraintMapping mapping = configuration.createConstraintMapping();
    mapping
        .type(OrderLine.class)
        .method("setId", Property.class)
        .parameter(0)
        .unwrapValidatedValue(true);

    Validator validator =
        configuration
            .addMapping(mapping)
            .addValidatedValueHandler(new PropertyValueUnwrapper())
            .buildValidatorFactory()
            .getValidator();

    OrderLine orderLine = new OrderLine();
    Method method = OrderLine.class.getMethod("setId", Property.class);
    Object[] parameterValues = new Object[] {new Property<Long>(0L)};

    Set<ConstraintViolation<OrderLine>> violations =
        validator.forExecutables().validateParameters(orderLine, method, parameterValues);

    assertEquals(violations.size(), 1);
  }
예제 #7
0
 public static void main(String[] args) {
   Configuration configuration = Validation.byProvider(HibernateValidator.class).configure();
   ValidatorFactory factory = configuration.buildValidatorFactory();
   Validator validator = factory.getValidator();
   validator.validate(Object.class);
   // programmation constraint mappings
   ConstraintMapping mapping = new ConstraintMapping();
 }
 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;
 }
예제 #9
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>");
  }
예제 #10
0
 /**
  * Triggers a bean validation call for the given bean and reports the found validations as {@link
  * PmValidationMessage}s for the given pmCtxt.
  *
  * @param pmCtxt The PM to report found validation errors for.
  * @param bean The bean to validate.
  */
 public static void validateBean(PmObject pmCtxt, Object bean) {
   Validator validator = BeanValidationPmUtil.getBeanValidator();
   if (validator != null) {
     @SuppressWarnings("unchecked")
     Set<ConstraintViolation<?>> violations =
         (Set<ConstraintViolation<?>>) (Object) validator.validate(bean);
     beanConstraintViolationsToPmMessages(pmCtxt, violations);
   }
 }
 public static void main(String[] args) {
   Movimentacao m = new Movimentacao();
   m.setValor(BigDecimal.ZERO);
   Validator validator = new ValidatorUtil().getValidator();
   Set<ConstraintViolation<Movimentacao>> list = validator.validate(m);
   for (ConstraintViolation<Movimentacao> erro : list) {
     System.out.println(erro.getMessage());
     System.out.println(erro.getPropertyPath());
   }
 }
  @Test
  public void isValid() throws Exception {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    MeterReading meterReading = newMeterReading();

    Set<ConstraintViolation<MeterReading>> violations = validator.validate(meterReading);

    assertThat(violations, is(empty()));
  }
  @Test
  public void isInvalid() throws Exception {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    Authorization authorization = new Authorization();

    Set<ConstraintViolation<Authorization>> violations = validator.validate(authorization);

    assertThat(violations, is(not(empty())));
  }
  @Test
  public void isInvalid() throws Exception {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    ServiceCategory serviceCategory = new ServiceCategory();

    Set<ConstraintViolation<ServiceCategory>> violations = validator.validate(serviceCategory);

    assertThat(violations, is(not(empty())));
  }
 @Test
 @SpecAssertions({@SpecAssertion(section = "7.1.1.3", id = "f")})
 public void testWrongPropertyNameThrowsException() {
   try {
     Validator validator = TestUtil.getValidatorUnderTest();
     validator.getConstraintsForClass(User.class);
   } catch (ValidationException e) {
     // success
   }
 }
  @Test
  public void isInvalid() throws Exception {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    Subscription subscription = new Subscription();

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

    assertFalse(violations.isEmpty());
  }
예제 #17
0
  @Test
  public void testeISBNVazio() {
    Titulo titulo = new Titulo();
    titulo.setNome("Nome");
    titulo.setIsbn("");
    titulo.setTipo("TIPO");
    Validator validator = createValidator();
    Set<ConstraintViolation<Titulo>> constraintViolations = validator.validate(titulo);

    Assert.assertEquals(1, constraintViolations.size());
  }
예제 #18
0
  @Test
  public void testeTipoComEspacoEmBranco() {
    Titulo titulo = new Titulo();
    titulo.setNome("Nome");
    titulo.setIsbn("1234567890");
    titulo.setTipo(" ");
    Validator validator = createValidator();
    Set<ConstraintViolation<Titulo>> constraintViolations = validator.validate(titulo);

    Assert.assertEquals(1, constraintViolations.size());
  }
  @Test
  @SpecAssertion(section = "8.2", id = "a")
  public void testValidBeanValidation11Mapping() {
    Validator validator =
        TestUtil.getConfigurationUnderTest()
            .addMapping(Version11InMappingXmlTest.class.getResourceAsStream(MAPPING_FILE))
            .buildValidatorFactory()
            .getValidator();

    assertFalse(validator.getConstraintsForClass(TestEntity.class).isBeanConstrained());
  }
  @Test
  @TestForIssue(jiraKey = "HV-639")
  public void testComposedConstraintWithoutReportAsSingleViolationEvaluatesAllConstraints() {
    Validator validator = ValidatorUtil.getValidator();

    Foo foo = new Foo();
    validator.validate(foo);
    assertEquals(
        InvocationCounter.getInvocationCount(foo),
        3,
        "Each constraint should be evaluated since w/o @ReportAsSingleViolation there might be several violations");
  }
 /**
  * Validate populated values based on JSR 303.
  *
  * @param bean the bean to validate
  * @throws PropertyException validation error
  */
 private void validateBean(Object bean) throws PropertyException {
   if (getValidatorFactory() != null) {
     Validator validator = getValidatorFactory().getValidator();
     Set<ConstraintViolation<Object>> constraintViolations = validator.validate(bean);
     if (!constraintViolations.isEmpty()) {
       throw new PropertyException(
           "Failed to validate bean: ["
               + constraintViolations.iterator().next().getMessage()
               + "]");
     }
   }
 }
예제 #22
0
  @Test
  public void ifNameIsNull_nameValidationFails() {
    User user = new User();
    user.setWorking(true);
    user.setAboutMe("Its all about me!!");
    user.setAge(50);

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<User>> violations = validator.validate(user);
    assertEquals(violations.isEmpty(), false);
  }
 @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());
 }
예제 #24
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());
  }
예제 #25
0
  @Test
  public void ifAgeNotRange_ageValidationFails() {
    User user = new User();
    user.setName("MyName");
    user.setAboutMe("Its all about me!!");
    user.setAge(8);

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<User>> violations = validator.validate(user);
    assertEquals(violations.isEmpty(), false);
  }
예제 #26
0
  @Test
  public void validateFromJson() throws IOException {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    XenonConfiguration actual =
        fromJson(jsonFixture("fixtures/xenon.json"), XenonConfiguration.class);

    Set<ConstraintViolation<XenonConfiguration>> constraintViolations =
        validator.validateProperty(actual, "scheduler");

    assertThat(constraintViolations.size()).isEqualTo(0);
  }
예제 #27
0
  @Test
  public void ifFnameNullAgeNotRangeAndWorkingIsFalse_validationFailsWithThreeErrors() {
    User user = new User();
    user.setAboutMe("Its all about me!!");
    user.setAge(300);

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<User>> violations = validator.validate(user);
    logViolations(violations);
    assertEquals(violations.isEmpty(), false);
    assertEquals(violations.size(), 3);
  }
예제 #28
0
 public static boolean hasErrors(Object obj, String message) {
   if (message != null) {
     ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
     Validator validator = factory.getValidator();
     Set<ConstraintViolation<Object>> errors = validator.validate(obj);
     for (ConstraintViolation<Object> constraintViolation : errors) {
       if (message.equals(constraintViolation.getMessage())) {
         return true;
       }
     }
   }
   return false;
 }
예제 #29
0
  @Test
  public void testeNomeNulo() {
    Titulo titulo = new Titulo();
    titulo.setNome(null);
    titulo.setIsbn("1234567890");
    titulo.setTipo("TIPO");
    Validator validator = createValidator();
    Set<ConstraintViolation<Titulo>> constraintViolations = validator.validate(titulo);

    Assert.assertEquals(1, constraintViolations.size());
    ConstraintViolation<Titulo> violacao = constraintViolations.iterator().next();

    Assert.assertEquals(violacao.getPropertyPath().toString(), "nome");
  }
예제 #30
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());
  }