Java Code Examples for javax.validation.ConstraintViolation#getInvalidValue()

The following examples show how to use javax.validation.ConstraintViolation#getInvalidValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RestViolationProcessor.java    From osiris with Apache License 2.0 6 votes vote down vote up
public void processMethodParameterValidation(Collection<ConstraintViolation<Object>> violations) throws Exception {
	String constraintMessage =  "";
	if (!violations.isEmpty()){
		try {
			for (ConstraintViolation<Object> constraintViolation : violations) {
				if(!(constraintViolation.getInvalidValue() instanceof Collection)){
					constraintMessage += constraintViolation.getMessage() + " Value:" +constraintViolation.getInvalidValue() + " ,";
				}else{
					constraintMessage += constraintViolation.getMessage() + " ,";
				}
			}
			constraintMessage = constraintMessage.substring(0, constraintMessage.length() - 2);
		} catch (Throwable e) {// I don't trust it works in every case
			e.printStackTrace();
		}
		throw new InvalidParametersException(constraintMessage);
	}
}
 
Example 2
Source File: CsvBeanValidator.java    From super-csv-annotation with Apache License 2.0 6 votes vote down vote up
/**
 * CSVの標準メッセージを取得する。
 * <p>CSVメッセージ変数で、再度フォーマットを試みる。</p>
 * 
 * @param errorVars エラー時の変数
 * @param violation エラー情報
 * @return デフォルトメッセージ
 */
protected String determineDefaltMessage(final Map<String, Object> errorVars, ConstraintViolation<Object> violation) {
    
    String message = violation.getMessage();
    if(messageInterpolator == null) {
        return message;
        
    } else if(!(message.contains("{") && message.contains("}"))) {
        // 変数形式が含まれていない場合は、そのまま返す。
        return message;
    }
    
    MessageInterpolatorContext context = new MessageInterpolatorContext(
            violation.getConstraintDescriptor(),
            violation.getInvalidValue(),
            violation.getRootBeanClass(),
            errorVars,
            Collections.emptyMap());
    
    return messageInterpolator.interpolate(violation.getMessageTemplate(), context);
    
}
 
Example 3
Source File: ServiceMethodConstraintViolation.java    From cuba with Apache License 2.0 5 votes vote down vote up
public ServiceMethodConstraintViolation(Class serviceInterface, ConstraintViolation violation) {
    this.message = violation.getMessage();
    this.messageTemplate = violation.getMessageTemplate();
    this.invalidValue = violation.getInvalidValue();
    this.constraintDescriptor = violation.getConstraintDescriptor();
    this.executableParameters = violation.getExecutableParameters();
    this.executableReturnValue = violation.getExecutableReturnValue();
    this.rootBeanClass = serviceInterface;
    this.propertyPath = violation.getPropertyPath();
}
 
Example 4
Source File: ConstraintValidationExceptionMapper.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private ErrorResponse buildErrorList(ConstraintViolationException cve) {
    ErrorResponse response = new ErrorResponse();
    for(ConstraintViolation<?> violation:cve.getConstraintViolations()) {
        String detail = violation.getMessage();
        Object invalidValue = violation.getInvalidValue();
        if(invalidValue != null) {
            detail += "\n"+invalidValue;
        }
        Error error = new Error()
                .code(violation.getPropertyPath().toString())
                .message(detail);
        response.addErrorsItem(error);
    }
    return response;
}
 
Example 5
Source File: MBeanFieldGroup.java    From viritin with Apache License 2.0 5 votes vote down vote up
/**
 * A helper method that returns "bean level" validation errors, i.e. errors
 * that are not tied to a specific property/field.
 *
 * @return error messages from "bean level validation"
 */
public Collection<String> getBeanLevelValidationErrors() {
    Collection<String> errors = new ArrayList<>();
    if (getConstraintViolations() != null) {
        for (final ConstraintViolation<T> constraintViolation : getConstraintViolations()) {
            final MessageInterpolator.Context context = new MessageInterpolator.Context() {
                @Override
                public ConstraintDescriptor<?> getConstraintDescriptor() {
                    return constraintViolation.getConstraintDescriptor();
                }

                @Override
                public Object getValidatedValue() {
                    return constraintViolation.getInvalidValue();
                }

                @Override
                public <T> T unwrap(Class<T> type) {
                    throw new ValidationException();
                }
            };

            final String msg = getJavaxBeanValidatorFactory().getMessageInterpolator().interpolate(
                constraintViolation.getMessageTemplate(),
                context, getLocale());
            errors.add(msg);
        }
    }
    if (getBasicConstraintViolations() != null) {
        for (Validator.InvalidValueException cv : getBasicConstraintViolations()) {
            errors.add(cv.getMessage());
        }
    }
    return errors;
}
 
Example 6
Source File: ValidationExceptionMapper.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String buildErrorMessage(ConstraintViolation<?> violation) {
    return "Value "
        + (violation.getInvalidValue() != null ? "'" + violation.getInvalidValue().toString() + "'" : "(null)")
        + " of " + violation.getRootBeanClass().getSimpleName()
        + "." + violation.getPropertyPath()
        + ": " + violation.getMessage();
}
 
Example 7
Source File: EntityValidator.java    From dropwizard-spring-di-security-onejar-example with Apache License 2.0 5 votes vote down vote up
/**
 * Validates an entity against its Hibernate validators
 * @param entity Entity
 * @param idFieldName  The name of its primary Id field (used for sorting error messages)
 */
public <E> void validate(E entity, String idFieldName) {
    Validator v = validatorFactory.getValidator();

    Set<ConstraintViolation<E>> violations = v.validate(entity);
    if (violations.size() > 0) {
        ConstraintViolation   cv = getFirstContraintViolation(violations, idFieldName);
        //return first error
        throw new EntityConstraintViolationException(cv.getRootBeanClass().getSimpleName(),
                cv.getPropertyPath().toString(),cv.getInvalidValue(),cv.getMessage());
    }
}
 
Example 8
Source File: AlpineResource.java    From Alpine with Apache License 2.0 4 votes vote down vote up
/**
 * Accepts the result from one of the many validation methods available and
 * returns a List of ValidationErrors. If the size of the List is 0, no errors
 * were encounter during validation.
 *
 * Usage:
 * <pre>
 *     Validator validator = getValidator();
 *     List&lt;ValidationError&gt; errors = contOnValidationError(
 *         validator.validateProperty(myObject, "uuid"),
 *         validator.validateProperty(myObject, "name")
 *      );
 *      // If validation fails, this line will be reached.
 * </pre>
 *
 * @param violationsArray a Set of one or more ConstraintViolations
 * @return a List of zero or more ValidationErrors
 * @since 1.0.0
 */
@SafeVarargs
protected final List<ValidationError> contOnValidationError(final Set<ConstraintViolation<Object>>... violationsArray) {
    final List<ValidationError> errors = new ArrayList<>();
    for (final Set<ConstraintViolation<Object>> violations : violationsArray) {
        for (final ConstraintViolation violation : violations) {
            if (violation.getPropertyPath().iterator().next().getName() != null) {
                final String path = violation.getPropertyPath() != null ? violation.getPropertyPath().toString() : null;
                final String message = violation.getMessage() != null ? StringUtils.removeStart(violation.getMessage(), path + ".") : null;
                final String messageTemplate = violation.getMessageTemplate();
                final String invalidValue = violation.getInvalidValue() != null ? violation.getInvalidValue().toString() : null;
                final ValidationError error = new ValidationError(message, messageTemplate, path, invalidValue);
                errors.add(error);
            }
        }
    }
    return errors;
}
 
Example 9
Source File: ConstraintValidationExceptionMapper.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
ConstraintValidationError(ConstraintViolationException cve) {
    ConstraintViolation<?> violation = cve.getConstraintViolations().iterator().next();
    this.message = violation.getMessage();
    this.path = violation.getPropertyPath().toString();
    this.invalidValue = violation.getInvalidValue();
}
 
Example 10
Source File: ValidationExceptionMapper.java    From seed with Mozilla Public License 2.0 4 votes vote down vote up
private boolean addErrorsToList(ConstraintViolationException exception,
        List<ValidationExceptionRepresentation.ValidationError> validationErrors) {
    boolean responseError = false;
    Class<?> resourceClass = ProxyUtils.cleanProxy(resourceInfo.getResourceClass());

    for (ConstraintViolation<?> constraintViolation : exception.getConstraintViolations()) {
        ValidationExceptionRepresentation.ValidationError validationError =
                new ValidationExceptionRepresentation.ValidationError();

        boolean appendToPath = false;
        StringBuilder path = new StringBuilder();
        Method method = null;
        for (Path.Node node : constraintViolation.getPropertyPath()) {
            switch (node.getKind()) {
                case METHOD:
                    method = resolveMethod(resourceClass, node.as(Path.MethodNode.class));
                    continue;
                case RETURN_VALUE:
                    validationError.setLocation(Location.RESPONSE_BODY.toString());
                    responseError = true;
                    appendToPath = true;
                    continue;
                case PARAMETER:
                    ParameterInfo parameterInfo = resolveParameterInfo(
                            node.as(Path.ParameterNode.class),
                            method);
                    validationError.setLocation(parameterInfo.getLocation().toString());
                    if (!parameterInfo.isBody()) {
                        path.append(parameterInfo.getName()).append(".");
                    }
                    appendToPath = true;
                    continue;
                default:
                    break;
            }
            if (appendToPath) {
                path.append(node.getName()).append(".");
            }
        }

        if (path.length() > 0) {
            validationError.setPath(path.substring(0, path.length() - 1));
        }

        validationError.setMessage(constraintViolation.getMessage());

        Object invalidValue = constraintViolation.getInvalidValue();
        if (invalidValue != null) {
            validationError.setInvalidValue(String.valueOf(invalidValue));
        }

        validationErrors.add(validationError);
    }

    return responseError;
}
 
Example 11
Source File: BeanValidatorContext.java    From vraptor4 with Apache License 2.0 4 votes vote down vote up
public BeanValidatorContext(ConstraintViolation<?> violation) {
	descriptor = violation.getConstraintDescriptor();
	validatedValue = violation.getInvalidValue();
}
 
Example 12
Source File: SpringValidatorAdapter.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * 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;
}
 
Example 13
Source File: SpringValidatorAdapter.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * 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;
}
 
Example 14
Source File: SpringValidatorAdapter.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * 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()
 */
protected Object getRejectedValue(String field, ConstraintViolation<Object> violation, BindingResult bindingResult) {
	Object invalidValue = violation.getInvalidValue();
	if (!"".equals(field) && (invalidValue == violation.getLeafBean() ||
			(!field.contains("[]") && (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;
}
 
Example 15
Source File: SpringValidatorAdapter.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * 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()
 */
protected Object getRejectedValue(String field, ConstraintViolation<Object> violation, BindingResult bindingResult) {
	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);
	}
	return invalidValue;
}
 
Example 16
Source File: CsvBeanValidator.java    From super-csv-annotation with Apache License 2.0 2 votes vote down vote up
/**
 * BeanValidationの検証結果をSheet用のエラーに変換する
 * @param violations BeanValidationの検証結果
 * @param bindingErrors エラー情報
 * @param validationContext 入力値検証のためのコンテキスト情報
 */
private void processConstraintViolation(final Set<ConstraintViolation<Object>> violations,
        final CsvBindingErrors bindingErrors, final ValidationContext<Object> validationContext) {
    
    for(ConstraintViolation<Object> violation : violations) {
        
        final String field = violation.getPropertyPath().toString();
        final ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
        
        final String[] errorCodes = determineErrorCode(cd);
        
        final Map<String, Object> errorVars = createVariableForConstraint(cd);
        
        if(isCsvField(field, validationContext)) {
            // フィールドエラーの場合
            
            final CsvFieldError fieldError = bindingErrors.getFirstFieldError(field);
            if(fieldError != null && fieldError.isProcessingFailure()) {
                // CellProcessorで発生したエラーが既ににある場合は、処理をスキップする。
                continue;
            }
            
            final ColumnMapping columnMapping = validationContext.getBeanMapping().getColumnMapping(field).get();
            
            errorVars.put("lineNumber", validationContext.getCsvContext().getLineNumber());
            errorVars.put("rowNumber", validationContext.getCsvContext().getRowNumber());
            errorVars.put("columnNumber", columnMapping.getNumber());
            errorVars.put("label", columnMapping.getLabel());
            errorVars.computeIfAbsent("printer", key -> columnMapping.getFormatter());
            
            // 実際の値を取得する
            final Object fieldValue = violation.getInvalidValue();
            errorVars.computeIfAbsent("validatedValue", key -> fieldValue);
            
            String defaultMessage = determineDefaltMessage(errorVars, violation);
            
            bindingErrors.rejectValue(field, columnMapping.getField().getType(), 
                    errorCodes, errorVars, defaultMessage);
            
        } else {
            // オブジェクトエラーの場合
            bindingErrors.reject(errorCodes, errorVars, violation.getMessage());
            
        }
        
    }
    
    
}