/**
  * 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);
       }
     }
   }
 }
 private void displayContraintViolations(Set<ConstraintViolation<Book03>> constraintViolations) {
   for (ConstraintViolation constraintViolation : constraintViolations) {
     System.out.println(
         "### "
             + constraintViolation.getRootBeanClass().getSimpleName()
             + "."
             + constraintViolation.getPropertyPath()
             + " - Invalid Value = "
             + constraintViolation.getInvalidValue()
             + " - Error Msg = "
             + constraintViolation.getMessage());
   }
 }
 @POST
 @ValidateOnExecution(type = ExecutableType.NONE)
 public Response formPost(@Valid @BeanParam FormDataBean form) {
   final BindingResult vr = getVr();
   if (vr.isFailed()) {
     final Set<ConstraintViolation<?>> set = vr.getAllViolations();
     final ConstraintViolation<?> cv = set.iterator().next();
     final String property = cv.getPropertyPath().toString();
     error.setProperty(property.substring(property.lastIndexOf('.') + 1));
     error.setValue(cv.getInvalidValue());
     error.setMessage(cv.getMessage());
     return Response.status(BAD_REQUEST).entity("error.jsp").build();
   }
   return Response.status(OK).entity("data.jsp").build();
 }
Beispiel #4
0
  public void init() {
    int from = 0;
    int to = 10;
    data =
        cartRepository
            .findAll(new org.springframework.data.domain.PageRequest(from / to, to))
            .getContent();
    if (data == null) {
      throw new IllegalStateException(
          "Find entries implementation for 'Cart' illegally returned null");
    }
    if (!data.isEmpty()) {
      return;
    }

    data = new ArrayList<Cart>();
    for (int i = 0; i < 10; i++) {
      Cart obj = getNewTransientCart(i);
      try {
        cartRepository.save(obj);
      } catch (ConstraintViolationException e) {
        StringBuilder msg = new StringBuilder();
        for (Iterator<ConstraintViolation<?>> iter = e.getConstraintViolations().iterator();
            iter.hasNext(); ) {
          ConstraintViolation<?> cv = iter.next();
          msg.append("[")
              .append(cv.getConstraintDescriptor())
              .append(":")
              .append(cv.getMessage())
              .append("=")
              .append(cv.getInvalidValue())
              .append("]");
        }
        throw new RuntimeException(msg.toString(), e);
      }
      cartRepository.flush();
      data.add(obj);
    }
  }
  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 init() {
    int from = 0;
    int to = 10;
    data = pizzaService.findPizzaEntries(from, to);
    if (data == null) {
      throw new IllegalStateException(
          "Find entries implementation for 'Pizza' illegally returned null");
    }
    if (!data.isEmpty()) {
      return;
    }

    data = new ArrayList<Pizza>();
    for (int i = 0; i < 10; i++) {
      Pizza obj = getNewTransientPizza(i);
      try {
        pizzaService.savePizza(obj);
      } catch (ConstraintViolationException e) {
        StringBuilder msg = new StringBuilder();
        for (Iterator<ConstraintViolation<?>> iter = e.getConstraintViolations().iterator();
            iter.hasNext(); ) {
          ConstraintViolation<?> cv = iter.next();
          msg.append("[")
              .append(cv.getConstraintDescriptor())
              .append(":")
              .append(cv.getMessage())
              .append("=")
              .append(cv.getInvalidValue())
              .append("]");
        }
        throw new RuntimeException(msg.toString(), e);
      }
      pizzaRepository.flush();
      data.add(obj);
    }
  }
Beispiel #7
0
 /** @param entities */
 public List<T_ENTITY> persistCollection(Collection<T_ENTITY> entities) {
   List<T_ENTITY> ret = new ArrayList<T_ENTITY>();
   try {
     EntityManager em = getEntityManager();
     begin();
     int count = 0;
     for (T_ENTITY entity : entities) {
       if (entity.getId() == 0) {
         em.persist(entity);
       } else {
         entity = em.merge(entity);
       }
       ret.add(entity);
       if (++count % 1000 == 0) {
         em.flush();
         em.clear();
       }
     }
     commit();
   } catch (ConstraintViolationException e) {
     for (@SuppressWarnings("rawtypes") ConstraintViolation v : e.getConstraintViolations()) {
       LOG.warn(
           "ConstraintViolation for "
               + entityClass.getSimpleName()
               + " "
               + "[property: "
               + v.getPropertyPath().iterator().next().getName()
               + "]"
               + " "
               + "[message: "
               + v.getMessage()
               + "]"
               + " "
               + "[invalid value: "
               + v.getInvalidValue()
               + "]");
     }
     throw e;
   } catch (PersistenceException e) { // wrapped in a Persistence Exception
     if (e.getCause() instanceof ConstraintViolationException) {
       ConstraintViolationException cve = (ConstraintViolationException) e.getCause();
       for (@SuppressWarnings("rawtypes") ConstraintViolation v : cve.getConstraintViolations()) {
         LOG.warn(
             "ConstraintViolation for "
                 + entityClass.getSimpleName()
                 + " "
                 + "[property: "
                 + v.getPropertyPath().iterator().next().getName()
                 + "]"
                 + " "
                 + "[message: "
                 + v.getMessage()
                 + "]"
                 + " "
                 + "[invalid value: "
                 + v.getInvalidValue()
                 + "]");
       }
       throw cve;
     }
     throw e;
   } catch (Exception e) {
     LOG.error("Error storing object to persistent storage: " + e.toString(), e);
     throw new RuntimeException(e);
   } finally {
     cleanup();
   }
   return ret;
 }
Beispiel #8
0
 /**
  * Persist or update the entity. Persist if the primary key is null update otherwise.
  *
  * @param entity the entity to persist
  * @return the persisted unattached entity.
  * @throws HibernateException if there is an error in persistence
  */
 @Nonnull
 public T_ENTITY saveOrUpdate(@Nonnull T_ENTITY entity) throws HibernateException {
   try {
     EntityManager em = getEntityManager();
     begin();
     if (entity.getId() == 0) {
       em.persist(entity);
     } else {
       entity = em.merge(entity);
     }
     commit();
   } catch (ConstraintViolationException e) {
     for (@SuppressWarnings("rawtypes") ConstraintViolation v : e.getConstraintViolations()) {
       LOG.warn(
           "ConstraintViolation for "
               + entityClass.getSimpleName()
               + " "
               + "[property: "
               + v.getPropertyPath().iterator().next().getName()
               + "]"
               + " "
               + "[message: "
               + v.getMessage()
               + "]"
               + " "
               + "[invalid value: "
               + v.getInvalidValue()
               + "]");
     }
     throw e;
   } catch (PersistenceException e) { // wrapped in a Persistence Exception
     if (e.getCause() instanceof ConstraintViolationException) {
       ConstraintViolationException cve = (ConstraintViolationException) e.getCause();
       for (@SuppressWarnings("rawtypes") ConstraintViolation v : cve.getConstraintViolations()) {
         LOG.warn(
             "ConstraintViolation for "
                 + entityClass.getSimpleName()
                 + " "
                 + "[property: "
                 + v.getPropertyPath().iterator().next().getName()
                 + "]"
                 + " "
                 + "[message: "
                 + v.getMessage()
                 + "]"
                 + " "
                 + "[invalid value: "
                 + v.getInvalidValue()
                 + "]");
       }
       throw cve;
     }
     throw e;
   } catch (Exception e) {
     e.printStackTrace();
     throw new RuntimeException(e);
   } finally {
     cleanup();
   }
   return entity;
 }
 public static BeanValidatorContext of(ConstraintViolation<Object> violation) {
   return new BeanValidatorContext(
       violation.getConstraintDescriptor(), violation.getInvalidValue());
 }