private void validateFixture(IFixture fixture, Validator validator) {
    Set<ConstraintViolation<IFixture>> violations = validator.validate(fixture);

    for (ConstraintViolation<IFixture> violation : violations) {
      if (violation.getLeafBean() instanceof ICompetition
          && "detail.competition.name".equals(violation.getPropertyPath().toString())) {
        assertEquals(violation.getLeafBean(), fixture.getCompetition());
        Annotation annotation = violation.getConstraintDescriptor().getAnnotation();
        assertEquals(annotation.annotationType(), NotNull.class);
        return;
      }
    }
    fail("@NotNull constraint violation for 'detail.competition.name' not detected");
  }
Exemplo n.º 2
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);
  }
 /**
  * Process the given JSR-303 ConstraintViolations, adding corresponding errors to the provided
  * Spring {@link Errors} object.
  *
  * @param violations the JSR-303 ConstraintViolation results
  * @param errors the Spring errors object to register to
  */
 protected void processConstraintViolations(
     Set<ConstraintViolation<Object>> violations, Errors errors) {
   for (ConstraintViolation<Object> violation : violations) {
     String field = violation.getPropertyPath().toString();
     FieldError fieldError = errors.getFieldError(field);
     if (fieldError == null || !fieldError.isBindingFailure()) {
       try {
         ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
         String errorCode = cd.getAnnotation().annotationType().getSimpleName();
         Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd);
         if (errors instanceof BindingResult) {
           // Can do custom FieldError registration with invalid value from ConstraintViolation,
           // as necessary for Hibernate Validator compatibility (non-indexed set path in field)
           BindingResult bindingResult = (BindingResult) errors;
           String nestedField = bindingResult.getNestedPath() + field;
           if ("".equals(nestedField)) {
             String[] errorCodes = bindingResult.resolveMessageCodes(errorCode);
             bindingResult.addError(
                 new ObjectError(
                     errors.getObjectName(), errorCodes, errorArgs, violation.getMessage()));
           } else {
             Object invalidValue = violation.getInvalidValue();
             if (!"".equals(field)
                 && (invalidValue == violation.getLeafBean()
                     || (field.contains(".") && !field.contains("[]")))) {
               // Possibly a bean constraint with property path: retrieve the actual property
               // value.
               // However, explicitly avoid this for "address[]" style paths that we can't handle.
               invalidValue = bindingResult.getRawFieldValue(field);
             }
             String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field);
             bindingResult.addError(
                 new FieldError(
                     errors.getObjectName(),
                     nestedField,
                     invalidValue,
                     false,
                     errorCodes,
                     errorArgs,
                     violation.getMessage()));
           }
         } else {
           // got no BindingResult - can only do standard rejectValue call
           // with automatic extraction of the current field value
           errors.rejectValue(field, errorCode, errorArgs, violation.getMessage());
         }
       } catch (NotReadablePropertyException ex) {
         throw new IllegalStateException(
             "JSR-303 validated property '"
                 + field
                 + "' does not have a corresponding accessor for Spring data binding - "
                 + "check your DataBinder's configuration (bean property versus direct field access)",
             ex);
       }
     }
   }
 }
Exemplo n.º 4
0
  /**
   * @param exception
   * @return
   */
  public static Response processException(Throwable exception) {

    if (exception instanceof RollbackException
        || exception instanceof TransactionRolledbackException
        || exception instanceof ObserverException
        || exception instanceof PersistenceException
        //                || exception instanceof javax.persistence.PersistenceException
        || exception instanceof org.omg.CORBA.TRANSACTION_ROLLEDBACK) {
      return processException(exception.getCause());

    } else if (exception instanceof EJBException) {
      return processException(((EJBException) exception).getCausedByException());

    } else if (exception instanceof DatabaseException) {
      DatabaseException dbe = (DatabaseException) exception;
      return processException(dbe.getInternalException());

    } else if (exception instanceof javax.script.ScriptException) {
      javax.script.ScriptException scriptException = (javax.script.ScriptException) exception;
      logger.error(exception.getLocalizedMessage());

      if (scriptException.getCause() instanceof ConstraintViolationException) {
        return processException(scriptException.getCause());
      } else {
        return Response.status(Response.Status.BAD_REQUEST)
            .entity(
                new ExceptionWrapper(
                    "400", scriptException.getClass(), scriptException.getLocalizedMessage()))
            .build();
      }

    } else if (exception instanceof SQLException) {
      SQLException sqlException = (SQLException) exception;
      logger.error(exception.getLocalizedMessage());
      return Response.status(Response.Status.BAD_REQUEST)
          .entity(
              new ExceptionWrapper(
                  "400", sqlException.getClass(), sqlException.getLocalizedMessage()))
          .build();

    } else if (exception instanceof WegasException) {
      WegasException wegasException = (WegasException) exception;
      logger.error(exception.getLocalizedMessage());
      return Response.status(Response.Status.BAD_REQUEST)
          .entity(
              new ExceptionWrapper(
                  "400", wegasException.getClass(), wegasException.getLocalizedMessage()))
          .build();

    } else if (exception instanceof javax.validation.ConstraintViolationException) {
      javax.validation.ConstraintViolationException constraintViolationException =
          (javax.validation.ConstraintViolationException) exception;

      StringBuilder sb =
          new StringBuilder(
              RequestFacade.lookup()
                  .getBundle("com.wegas.app.errors")
                  .getString("constraint")); // internationalised error (sample)
      for (javax.validation.ConstraintViolation violation :
          constraintViolationException.getConstraintViolations()) {
        sb.append("\n")
            .append(violation.getLeafBean())
            .append(":")
            .append(violation.getRootBean())
            .append(violation.getPropertyPath());
      }
      logger.error(sb.toString());
      // constraintViolationException.getMessage()
      return Response.status(Response.Status.BAD_REQUEST)
          .entity(
              new ExceptionWrapper(
                  "400", exception.getClass(), constraintViolationException.getLocalizedMessage()))
          .build();

    } else {
      logger.error(
          RequestFacade.lookup().getBundle("com.wegas.app.errors").getString("unexpected"),
          exception); // internationalised error (sample)
      return Response.status(Response.Status.BAD_REQUEST)
          .entity(
              new ExceptionWrapper("400", exception.getClass(), exception.getLocalizedMessage()))
          .build();
    }
  }