@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");
  }
  @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);
    }
  }
 @SuppressWarnings("rawtypes")
 @Override
 public Response toResponse(javax.validation.ValidationException exception) {
   Response.Status errorStatus = Response.Status.INTERNAL_SERVER_ERROR;
   List<String> errorsList = new ArrayList<String>();
   if (exception instanceof ConstraintViolationException) {
     ConstraintViolationException constraint = (ConstraintViolationException) exception;
     Iterator i$ = constraint.getConstraintViolations().iterator();
     while (i$.hasNext()) {
       ConstraintViolation violation = (ConstraintViolation) i$.next();
       String errorMessage = this.getPropertyName(violation) + ": " + violation.getMessage();
       errorsList.add(errorMessage);
       LOG.error(
           violation.getRootBeanClass().getSimpleName()
               + "."
               + violation.getPropertyPath()
               + ": "
               + violation.getMessage());
     }
     if (!(constraint instanceof ResponseConstraintViolationException)) {
       errorStatus = Response.Status.BAD_REQUEST;
     }
   }
   String errorsAsString = StringUtils.join(errorsList, ", ");
   Response response = Response.status(errorStatus).entity(errorsAsString).build();
   return response;
 }
  @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);
  }
  public void testBeanValidation() throws Exception {
    Artist a = new Artist();
    a.setName("TOO OLD ARTIST");
    a.setAge(120);

    XPersistence.getManager().persist(a);
    try {
      XPersistence.commit();
    } catch (RollbackException ex) {

      if (ex.getCause() instanceof javax.validation.ConstraintViolationException) {
        javax.validation.ConstraintViolationException vex =
            (javax.validation.ConstraintViolationException) ex.getCause();
        assertEquals("1 invalid value is expected", 1, vex.getConstraintViolations().size());
        ConstraintViolation violation = vex.getConstraintViolations().iterator().next();
        assertEquals("Bean", "Artist", violation.getRootBeanClass().getSimpleName());
        String expectedMessage =
            "es".equals(Locale.getDefault().getLanguage())
                ? "tiene que ser menor o igual que 90"
                : "must be less than or equal to 90";
        assertEquals("Message text", expectedMessage, violation.getMessage());
        return;
      }
    }
    fail("A constraint violation exception should be thrown");
  }
  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;
  }
  @Override
  public void saveEntities(DataImportContext context) {
    bindEntities(context);

    Object[] entities = context.getEntities();
    SystemDAO systemDAO = DAOFactory.getInstance().getSystemDAO();

    for (int i = 0; i < entities.length; i++) {
      Object entity = entities[i];

      Set<ConstraintViolation<Object>> constraintViolations = systemDAO.validateEntity(entity);

      if (constraintViolations.size() == 0) {
        systemDAO.persistEntity(entity);
      } else {
        String message = "";
        for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
          message += constraintViolation.getMessage() + '\n';
        }

        throw new SmvcRuntimeException(
            PyramusStatusCode.VALIDATION_FAILURE, "Validation failure: " + message);
      }
    }
  }
Beispiel #8
0
  private static void doSomething(ApplicationContext context) {
    OrderService orderService = context.getBean(OrderService.class);
    String customerId = "CUS0001";
    Item item = context.getBean(Item.class);
    item.setName("ITEM0001");
    item.setZipCode("110000");

    Order order = null;
    try {
      order = orderService.placeOrder(customerId, item, 3);
    } catch (ConstraintViolationException e) {
      // TODO Auto-generated catch block
      Set<ConstraintViolation<?>> results = e.getConstraintViolations();
      for (ConstraintViolation<?> result : results) {
        //			    System.out.println("校验错误信息模板: " + result.getMessageTemplate());
        System.out.println(
            ""
                + result.getLeafBean().getClass().getName()
                + "."
                + result.getPropertyPath()
                + ": "
                + result.getMessage());
        //				System.out.println(result.getConstraintDescriptor());
      }

      //			System.out.println(results);
    }
    System.out.println("返回的订单信息: " + order);
  }
  @Override
  public void intercept(InterceptorStack stack, ControllerMethod method, Object instance)
      throws InterceptionException {
    try {
      stack.next(method, instance);
    } catch (Exception e) {

      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);

      Throwable cause = e.getCause();
      if (cause != null) {
        if (cause instanceof ConstraintViolationException) {
          Set<ConstraintViolation<?>> constraintViolations =
              ((ConstraintViolationException) cause).getConstraintViolations();
          pw.printf("\nConstraint Violations: \n");
          for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            pw.printf("\t" + constraintViolation.getConstraintDescriptor().getAnnotation() + "\n");
          }
          pw.printf("\n");
          log.error(sw.toString());
        }
        cause.printStackTrace(pw);
      } else {
        e.printStackTrace(pw);
      }

      pw.close();
      result.include("stacktrace", sw.toString());
      throw e;
    }
  }
  public Type getConstraintType(Object o) {
    if (!(o instanceof ConstraintViolation)) {
      throw new RuntimeException(Messages.MESSAGES.unknownObjectPassedAsConstraintViolation(o));
    }
    ConstraintViolation<?> v = ConstraintViolation.class.cast(o);
    if (v instanceof MethodConstraintViolation) {
      MethodConstraintViolation<?> mv = MethodConstraintViolation.class.cast(v);
      return mv.getKind() == MethodConstraintViolation.Kind.PARAMETER
          ? Type.PARAMETER
          : Type.RETURN_VALUE;
    }

    Object b = v.getRootBean();
    String fieldName = null;
    Iterator<Node> it = v.getPropertyPath().iterator();
    while (it.hasNext()) {
      Node node = it.next();
      fieldName = node.getName();
      if (fieldName == null) {
        return Type.CLASS;
      }
    }
    String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    try {
      //         getMethod(v.getLeafBean().getClass(), getterName);
      getMethod(v.getRootBeanClass(), getterName);
      return Type.PROPERTY;
    } catch (NoSuchMethodException e) {
      return Type.FIELD;
    }
  }
Beispiel #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;
  }
 /*
  * (non-Javadoc)
  *
  * @see com.vaadin.data.Validator#validate(java.lang.Object)
  */
 @Override
 public void validate(final Object value) throws InvalidValueException {
   Set<?> violations = getJavaxBeanValidator().validateValue(beanClass, propertyName, value);
   if (violations.size() > 0) {
     List<String> exceptions = new ArrayList<String>();
     for (Object v : violations) {
       final ConstraintViolation<?> violation = (ConstraintViolation<?>) v;
       String msg =
           getJavaxBeanValidatorFactory()
               .getMessageInterpolator()
               .interpolate(
                   violation.getMessageTemplate(),
                   new SimpleContext(value, violation.getConstraintDescriptor()),
                   locale);
       exceptions.add(msg);
     }
     StringBuilder b = new StringBuilder();
     for (int i = 0; i < exceptions.size(); i++) {
       if (i != 0) {
         b.append("<br/>");
       }
       b.append(exceptions.get(i));
     }
     throw new InvalidValueException(b.toString());
   }
 }
 public CommandConstraintException(Set<ConstraintViolation<ICommand>> constraintViolations) {
   if (UtilValidator.isNotEmpty(constraintViolations)) {
     for (ConstraintViolation constraintViolation : constraintViolations) {
       constraintMessages.add(constraintViolation.getMessage());
     }
     this.constraintViolations = constraintViolations;
   }
 }
Beispiel #14
0
 /**
  * @param e
  * @param errorCode
  * @param propertyPath
  */
 public static void assertViolationContainsTemplateAndPath(
     final ConstraintViolationException e, final String errorCode, final String propertyPath) {
   Assert.assertNotNull(e.getConstraintViolations());
   Assert.assertEquals(1, CollectionUtils.size(e.getConstraintViolations()));
   final ConstraintViolation<?> violation = e.getConstraintViolations().iterator().next();
   Assert.assertEquals(errorCode, violation.getMessageTemplate());
   Assert.assertEquals(propertyPath, violation.getPropertyPath().toString());
 }
 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;
 }
Beispiel #16
0
 protected boolean existsViolationsForJSF(Serializable entidade) {
   Set<ConstraintViolation<Serializable>> toReturn = getViolations(entidade);
   if (toReturn.isEmpty()) return false;
   for (ConstraintViolation<Serializable> constraintViolation : toReturn) {
     createFacesErrorMessage(constraintViolation.getMessage(), null);
   }
   return true;
 }
 @BeforeClass
 public static void setupForAll() {
   ConstraintViolation cv = mock(ConstraintViolation.class);
   when(cv.getMessage()).thenReturn(ERROR_MESSAGE_1);
   ConstraintViolation cv2 = mock(ConstraintViolation.class);
   when(cv2.getMessage()).thenReturn(ERROR_MESSAGE_2);
   nonEmptyViolationCollection.addAll(asList(cv, cv2));
 }
 /** 辅助方法, 转换Set<ConstraintViolation>为Map<property, message>. */
 @SuppressWarnings("rawtypes")
 public static Map<String, String> extractPropertyAndMessage(
     Set<? extends ConstraintViolation> constraintViolations) {
   Map<String, String> errorMessages = Maps.newHashMap();
   for (ConstraintViolation violation : constraintViolations) {
     errorMessages.put(violation.getPropertyPath().toString(), violation.getMessage());
   }
   return errorMessages;
 }
 /** 辅助方法, 转换Set<ConstraintViolation>为List<message> */
 @SuppressWarnings("rawtypes")
 public static List<String> extractMessage(
     Set<? extends ConstraintViolation> constraintViolations) {
   List<String> errorMessages = Lists.newArrayList();
   for (ConstraintViolation violation : constraintViolations) {
     errorMessages.add(violation.getMessage());
   }
   return errorMessages;
 }
 private void checkConstraint(String expected, ConstraintViolationException e) {
   for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
     String actual = constraintViolation.getPropertyPath().toString();
     if (actual.equals(expected)) {
       return;
     }
   }
   fail();
 }
 /** 辅助方法, 转换Set<ConstraintViolation>为List<propertyPath +separator+ message>. */
 @SuppressWarnings("rawtypes")
 public static List<String> extractPropertyAndMessageAsList(
     Set<? extends ConstraintViolation> constraintViolations, String separator) {
   List<String> errorMessages = Lists.newArrayList();
   for (ConstraintViolation violation : constraintViolations) {
     errorMessages.add(violation.getPropertyPath() + separator + violation.getMessage());
   }
   return errorMessages;
 }
  public void handleValidationException(ValidationException exception, ResponseBuilder builder) {
    builder.status(BAD_REQUEST);
    ValidationErrorMessageWrapper error = new ValidationErrorMessageWrapper();

    for (ConstraintViolation<Object> violation : exception.getViolations()) {
      error.addMessage(violation.getMessage());
    }
    builder.entity(error);
  }
 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());
   }
 }
Beispiel #24
0
  /** Converts a ConstraintViolation to a FieldError */
  private static FieldError of(ConstraintViolation<?> constraintViolation) {

    // Get the field name by removing the first part of the propertyPath.
    // (The first part would be the service method name)
    String field =
        StringUtils.substringAfter(constraintViolation.getPropertyPath().toString(), ".");

    return new FieldError(
        field, constraintViolation.getMessageTemplate(), constraintViolation.getMessage());
  }
  public String formatInvalidationInfo(Set<ConstraintViolation<T>> infos, String model) {
    Iterator<ConstraintViolation<T>> it = infos.iterator();
    StringBuilder sb = new StringBuilder();
    while (it.hasNext()) {
      ConstraintViolation<T> t = it.next();
      sb.append(model + " ").append(t.getMessage()).append(" ");
    }

    return sb.toString();
  }
 public <T> Validator addAll(Set<ConstraintViolation<T>> errors) {
   for (ConstraintViolation<T> v : errors) {
     String msg =
         interpolator.interpolate(v.getMessageTemplate(), new BeanValidatorContext(v), locale);
     String category = v.getPropertyPath().toString();
     add(new SimpleMessage(category, msg));
     logger.debug("added message {}={} for contraint violation", category, msg);
   }
   return this;
 }
Beispiel #27
0
 @Test
 public void testValidator() {
   User user = new User();
   user.setEmail("s");
   user.setPassword("12345678");
   Set<ConstraintViolation<User>> errors = validator.validate(user);
   for (ConstraintViolation<User> error : errors) {
     System.out.println(error.getPropertyPath() + error.getMessage());
   }
 }
Beispiel #28
0
  private Response.ResponseBuilder createViolationResponse(Set<ConstraintViolation<?>> violations) {
    logger.fine("Validation completed. violations found: " + violations.size());

    Map<String, String> responseObj = new HashMap<String, String>();

    for (ConstraintViolation<?> violation : violations) {
      responseObj.put(violation.getPropertyPath().toString(), violation.getMessage());
    }

    return Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
  }
Beispiel #29
0
 @Test
 public void invalidUser() throws Exception {
   User user = new User("us", "password", "name", "email");
   Set<ConstraintViolation<User>> constraintViolations = validator.validate(user);
   assertEquals(2, constraintViolations.size());
   Iterator<ConstraintViolation<User>> violations = constraintViolations.iterator();
   while (violations.hasNext()) {
     ConstraintViolation<User> each = violations.next();
     System.out.println(each.getPropertyPath() + " : " + each.getMessage());
   }
 }
  @Test(expected = AppException.class)
  public void createWithValidationError() throws AppException {
    SampleEntity sample = createSampleEntity(ID, "IPI");
    Set<ConstraintViolation<SampleEntity>> violations = new HashSet<>();
    ConstraintViolation constraintViolation = Mockito.mock(ConstraintViolation.class);
    violations.add(constraintViolation);
    Mockito.when(constraintViolation.getMessage()).thenReturn("Error");
    Mockito.when(validator.validate(sample)).thenReturn(violations);

    service.create(sample);
  }