protected Response handleConstraintViolationException(ConstraintViolationException cve) { ViolationReport report = new ViolationReport(); for (ConstraintViolation cv : cve.getConstraintViolations()) { report.addConstraintViolation(new RestConstraintViolation( cv.getPropertyPath().toString(), cv.getMessage(), cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString())); } // TODO for now just do xml output return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(report).type(ContentType.TEXT_XML_UTF_8).build(); } }
protected Response handleConstraintViolationException(ConstraintViolationException cve) { ViolationReport report = new ViolationReport(); for (ConstraintViolation cv : cve.getConstraintViolations()) { report.addConstraintViolation(new RestConstraintViolation( cv.getPropertyPath().toString(), cv.getMessage(), cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString())); } // TODO for now just do xml output return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(report).type(ContentType.TEXT_XML_UTF_8).build(); } }
/** * Extract the rejected value behind the given constraint violation, * for exposure through the Spring errors representation. * @param field the field that caused the binding error * @param violation the corresponding JSR-303 ConstraintViolation * @param bindingResult a Spring BindingResult for the backing object * which contains the current field's value * @return the invalid value to expose as part of the field error * @since 4.2 * @see javax.validation.ConstraintViolation#getInvalidValue() * @see org.springframework.validation.FieldError#getRejectedValue() */ @Nullable protected Object getRejectedValue(String field, ConstraintViolation<Object> violation, BindingResult bindingResult) { Object invalidValue = violation.getInvalidValue(); if (!"".equals(field) && !field.contains("[]") && (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); } return invalidValue; }
private static <T> String formatMessage(Set<ConstraintViolation<T>> violations) { StringBuilder sb = new StringBuilder(); sb.append("Configuration task validation failed."); for (ConstraintViolation<T> violation : violations) { sb.append(" "); sb.append(violation.getPropertyPath()); sb.append(" "); sb.append(violation.getMessage()); sb.append(" but got "); sb.append(violation.getInvalidValue()); } return sb.toString(); } }
/** * Extract the rejected value behind the given constraint violation, * for exposure through the Spring errors representation. * @param field the field that caused the binding error * @param violation the corresponding JSR-303 ConstraintViolation * @param bindingResult a Spring BindingResult for the backing object * which contains the current field's value * @return the invalid value to expose as part of the field error * @since 4.2 * @see javax.validation.ConstraintViolation#getInvalidValue() * @see org.springframework.validation.FieldError#getRejectedValue() */ @Nullable protected Object getRejectedValue(String field, ConstraintViolation<Object> violation, BindingResult bindingResult) { Object invalidValue = violation.getInvalidValue(); if (!"".equals(field) && !field.contains("[]") && (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); } return invalidValue; }
/** * Extract {@link ConstraintViolation constraint violations} from given exception and transform them into a list of * {@link ValidationError validation errors}. * * @param violation exception containing constraint violations. * @return list of validation errors (not {@code null}). */ public static List<ValidationError> constraintViolationToValidationErrors(final ConstraintViolationException violation) { return violation.getConstraintViolations().stream().map(violation1 -> new ValidationError( violation1.getMessage(), violation1.getMessageTemplate(), getViolationPath(violation1), getViolationInvalidValue(violation1.getInvalidValue()) )).collect(Collectors.toList()); }
private static ErrorResponse constraintViolationExceptionToErrorResponse(ConstraintViolationException exception) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setStatus(Response.Status.BAD_REQUEST.getStatusCode()); errorResponse.setMessage("Validation failed, check below errors for detail."); List<ValidationError> validationErrors = new ArrayList<>(); exception.getConstraintViolations().forEach(e -> validationErrors.add(new ValidationError(getViolationPath(e), e.getMessage(), getViolationInvalidValue(e.getInvalidValue())))); errorResponse.setValidationErrors(validationErrors); return errorResponse; }
/** * Validate the given value. * * @param value The value, may be null * @param field The name of the field being validated, if applicable * @param context The Ninja request context */ @Override public void validate(Object value, String field, Context context) { if (value != null) { final ValidatorFactory validatorFactory = javax.validation.Validation.buildDefaultValidatorFactory(); final javax.validation.Validator validator = validatorFactory.getValidator(); final Set<javax.validation.ConstraintViolation<Object>> violations = validator.validate(value); final Locale localeToUse = this.requestLanguage.getLocaleFromStringOrDefault(this.requestLanguage.getLanguage(context, Optional.<Result>empty())); final Validation validation = context.getValidation(); for (final javax.validation.ConstraintViolation<Object> violation : violations) { final String violationMessage = validatorFactory.getMessageInterpolator().interpolate( violation.getMessageTemplate(), new NinjaContextMsgInterpolator(value, violation.getConstraintDescriptor()), localeToUse ); final String messageKey = violation.getMessageTemplate().replaceAll("[{}]", ""); final ConstraintViolation constraintViolation = new ConstraintViolation( messageKey, violation.getPropertyPath().toString(), violationMessage, violation.getInvalidValue()); validation.addViolation(constraintViolation); } } }
@Override public Object getValidatedValue() { return violation.getInvalidValue(); }
@JsonProperty("invalidValue") public String getInvalidValue() { return format("%s", violation.getInvalidValue()); }
ResteasyConstraintViolation createResteasyConstraintViolation(ConstraintViolation<?> cv, Type ct) { String path = (suppressPath ? "*" : cv.getPropertyPath().toString()); ResteasyConstraintViolation rcv = new ResteasyConstraintViolation(ct, path, cv.getMessage(), (cv.getInvalidValue() == null ? "null" :cv.getInvalidValue().toString())); return rcv; }
public ConstraintViolationMessage(ConstraintViolation<?> violation, MessageSource msgSrc, Locale locale) { this.violation = violation; this.message = msgSrc.getMessage(violation.getMessageTemplate(), new Object[] { violation.getLeafBean().getClass().getSimpleName(), violation.getPropertyPath().toString(), violation.getInvalidValue() }, violation.getMessage(), locale); }
@Override public ValidationError toValidationError(ConstraintViolation constraintViolation) { return ValidationError.create(constraintViolation.getMessage()) .setField(constraintViolation.getPropertyPath().toString()) .setInvalidValue(constraintViolation.getInvalidValue()); }
protected ResteasyConstraintViolation convertViolation(ConstraintViolation<?> violation) { Type ct = util.getConstraintType(violation); String path = (suppressPath ? "*" : violation.getPropertyPath().toString()); return new ResteasyConstraintViolation(ct, path, violation.getMessage(), convertArrayToString(violation.getInvalidValue())); }
private ViolationExpectation(ConstraintViolation<?> violation, ViolationExpectationPropertiesToTest propertiesToTest) { this.constraintType = violation.getConstraintDescriptor().getAnnotation().annotationType(); if ( propertiesToTest.testRootBeanClass ) { withRootBeanClass( violation.getRootBeanClass() ); } if ( propertiesToTest.testMessage ) { withMessage( violation.getMessage() ); } if ( propertiesToTest.testInvalidValue ) { withInvalidValue( violation.getInvalidValue() ); } if ( propertiesToTest.testPropertyPath ) { withPropertyPath( new PathExpectation( violation.getPropertyPath() ) ); } }
if (cv1.getInvalidValue() != null ? !cv1.getInvalidValue().equals(cv2.getInvalidValue()) : cv2.getInvalidValue() != null)
protected String buildErrorMessage(ConstraintViolation<?> violation) { return "Value " + (violation.getInvalidValue() != null ? "'" + violation.getInvalidValue().toString() + "'" : "(null)") + " of " + violation.getRootBeanClass().getSimpleName() + "." + violation.getPropertyPath() + ": " + violation.getMessage(); }
public static Set<ConstraintViolation> oneMinimalisticMockConstraintViolation() { final ConstraintViolation mockConstraintViolation = Mockito.mock(ConstraintViolation.class, Mockito.RETURNS_SMART_NULLS); final Path mockPath = Mockito.mock(Path.class); Mockito.when(mockPath.toString()).thenReturn("test.property.path"); Mockito.when(mockConstraintViolation.getPropertyPath()).thenReturn(mockPath); Mockito.when(mockConstraintViolation.getMessage()).thenReturn("mockConstraintViolation: error message"); Mockito.when(mockConstraintViolation.getInvalidValue()).thenReturn("mockConstraintViolation: invalid value"); Set<ConstraintViolation> setWithErrors = new TreeSet<ConstraintViolation>(); setWithErrors.add(mockConstraintViolation); return setWithErrors; } }
/** * Add an InvalidValue from Hibernate Validator. The message will * be added with a severity of WARN. * * The name of the property that was validated will be used as the widget ID */ public void addToControl(ConstraintViolation<Object> constraintViolation) { addToControl( constraintViolation.getInvalidValue().toString(), constraintViolation); }
public ConstraintViolationMessage(ConstraintViolation<?> violation, MessageSource msgSrc, Locale locale) { this.violation = violation; this.message = msgSrc.getMessage(violation.getMessageTemplate(), new Object[] { violation.getLeafBean().getClass().getSimpleName(), violation.getPropertyPath().toString(), violation.getInvalidValue() }, violation.getMessage(), locale); }