javax.validation.ConstraintViolation#getInvalidValue ( )源码实例Demo

下面列出了javax.validation.ConstraintViolation#getInvalidValue ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: osiris   文件: RestViolationProcessor.java
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);
	}
}
 
源代码2 项目: super-csv-annotation   文件: CsvBeanValidator.java
/**
 * 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);
    
}
 
源代码3 项目: cuba   文件: ServiceMethodConstraintViolation.java
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();
}
 
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;
}
 
源代码5 项目: viritin   文件: MBeanFieldGroup.java
/**
 * 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;
}
 
源代码6 项目: cxf   文件: ValidationExceptionMapper.java
protected String buildErrorMessage(ConstraintViolation<?> violation) {
    return "Value "
        + (violation.getInvalidValue() != null ? "'" + violation.getInvalidValue().toString() + "'" : "(null)")
        + " of " + violation.getRootBeanClass().getSimpleName()
        + "." + violation.getPropertyPath()
        + ": " + violation.getMessage();
}
 
/**
 * 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());
    }
}
 
源代码8 项目: Alpine   文件: AlpineResource.java
/**
 * 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;
}
 
ConstraintValidationError(ConstraintViolationException cve) {
    ConstraintViolation<?> violation = cve.getConstraintViolations().iterator().next();
    this.message = violation.getMessage();
    this.path = violation.getPropertyPath().toString();
    this.invalidValue = violation.getInvalidValue();
}
 
源代码10 项目: seed   文件: ValidationExceptionMapper.java
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;
}
 
源代码11 项目: vraptor4   文件: BeanValidatorContext.java
public BeanValidatorContext(ConstraintViolation<?> violation) {
	descriptor = violation.getConstraintDescriptor();
	validatedValue = violation.getInvalidValue();
}
 
/**
 * 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 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;
}
 
源代码14 项目: lams   文件: SpringValidatorAdapter.java
/**
 * 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;
}
 
/**
 * 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;
}
 
源代码16 项目: super-csv-annotation   文件: CsvBeanValidator.java
/**
 * 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());
            
        }
        
    }
    
    
}