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;
    }
  }
  private String getMessage(
      Member member, Object[] args, Set<? extends ConstraintViolation<?>> violations) {

    StringBuilder message = new StringBuilder();
    message.append(violations.size());
    message.append(" constraint violation(s) occurred during method validation.");
    message.append("\nConstructor or Method: ");
    message.append(member);
    message.append("\nArgument values: ");
    message.append(Arrays.toString(args));
    message.append("\nConstraint violations: ");

    int i = 1;
    for (ConstraintViolation<?> constraintViolation : violations) {
      Path.Node leafNode = getLeafNode(constraintViolation);

      message.append("\n (");
      message.append(i);
      message.append(")");
      message.append(" Kind: ");
      message.append(leafNode.getKind());
      if (leafNode.getKind() == ElementKind.PARAMETER) {
        message.append("\n parameter index: ");
        message.append(leafNode.as(Path.ParameterNode.class).getParameterIndex());
      }
      message.append("\n message: ");
      message.append(constraintViolation.getMessage());
      message.append("\n root bean: ");
      message.append(constraintViolation.getRootBean());
      message.append("\n property path: ");
      message.append(constraintViolation.getPropertyPath());
      message.append("\n constraint: ");
      message.append(constraintViolation.getConstraintDescriptor().getAnnotation());

      i++;
    }

    return message.toString();
  }
Exemplo n.º 3
0
  public void init() {
    int from = 0;
    int to = 10;
    data = encounterService.findEncounterEntries(from, to);
    if (data == null) {
      throw new IllegalStateException(
          "Find entries implementation for 'Encounter' illegally returned null");
    }
    if (!data.isEmpty()) {
      return;
    }

    data = new ArrayList<Encounter>();
    for (int i = 0; i < 10; i++) {
      Encounter obj = getNewTransientEncounter(i);
      try {
        encounterService.saveEncounter(obj);
      } catch (final ConstraintViolationException e) {
        final StringBuilder msg = new StringBuilder();
        for (Iterator<ConstraintViolation<?>> iter = e.getConstraintViolations().iterator();
            iter.hasNext(); ) {
          final ConstraintViolation<?> cv = iter.next();
          msg.append("[")
              .append(cv.getRootBean().getClass().getName())
              .append(".")
              .append(cv.getPropertyPath())
              .append(": ")
              .append(cv.getMessage())
              .append(" (invalid value = ")
              .append(cv.getInvalidValue())
              .append(")")
              .append("]");
        }
        throw new IllegalStateException(msg.toString(), e);
      }
      encounterRepository.flush();
      data.add(obj);
    }
  }
  public void testEntityValidatorsAsHibernateAnnotation() throws Exception {
    Product p = new Product();
    p.setNumber(66);
    p.setDescription("BUENO, BONITO, BARATO"); // It's cheap ('BARATO') thus...
    p.setFamilyNumber(1);
    p.setSubfamilyNumber(1);
    p.setWarehouseKey(new Warehouse());
    p.setUnitPrice(new BigDecimal("900")); // ... it cannot cost 900 (max 100)

    XPersistence.getManager().persist(p);
    try {
      XPersistence.commit();
    } catch (RollbackException ex) {
      if (ex.getCause() instanceof ConstraintViolationException) {
        ConstraintViolationException cex = (ConstraintViolationException) ex.getCause();
        assertEquals("1 constraint violation expected", 1, cex.getConstraintViolations().size());
        ConstraintViolation v = cex.getConstraintViolations().iterator().next();
        assertEquals("Bean", "Product", v.getRootBean().getClass().getSimpleName());
        assertEquals("Message text", "", v.getMessage());
        return;
      }
    }
    fail("A constraint violation exception should be thrown");
  }
 private String buildViolationMessage(ConstraintViolation<?> violation) {
   return String.format(
       "bean: %s, property: %s, error: %s",
       violation.getRootBean(), violation.getPropertyPath(), violation.getMessage());
 }
Exemplo n.º 6
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();
    }
  }
Exemplo n.º 7
0
 @Override
 public Object getKey() {
   return v.getRootBean();
 }