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

The following examples show how to use javax.validation.ConstraintViolation#getLeafBean() . 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: ValidationUtil.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
public static String createValidationMessage(Set<ConstraintViolation<?>> constraintViolations) {
    if (constraintViolations.isEmpty()) {
        return "No Constraint Validations!";
    }
    StringBuilder builder = new StringBuilder("Constraint Validations: ");
    for (ConstraintViolation<?> violation : constraintViolations) {
        if (builder.length() > 0) {
            builder.append(", ");
        }
        Object leafBean = violation.getLeafBean();
        if (leafBean instanceof HasMetadata) {
            HasMetadata hasMetadata = (HasMetadata) leafBean;
            ObjectMeta metadata = hasMetadata.getMetadata();
            if (metadata != null) {
                leafBean = "" + hasMetadata.getKind() + ": " + metadata;
            }
        }
        builder.append(violation.getPropertyPath() + " " + violation.getMessage() + " on bean: " + leafBean);
    }
    return builder.toString();
}
 
Example 2
Source File: ValidationUtils.java    From sundrio with Apache License 2.0 6 votes vote down vote up
public static <T> void validate(T item, Validator v) {
    if (v == null) {
        v = getValidator();
    }
    if (v == null) {
       return;
    }
    Set<ConstraintViolation<T>> violations = v.validate(item);
    if (!violations.isEmpty()) {
        StringBuilder sb = new StringBuilder("Constraint Validations: ");
        boolean first = true;
        for (ConstraintViolation violation : violations) {
            if (first) {
                first = false;
            } else {
                sb.append(", ");
            }
            Object leafBean = violation.getLeafBean();
            sb.append(violation.getPropertyPath() + " " + violation.getMessage() + " on bean: " + leafBean);
        }
        throw new ConstraintViolationException(sb.toString(), violations);
    }
}
 
Example 3
Source File: BeanDefinitionDtoConverterServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Take a stab at fixing validation problems ?
 * 
 * @param object
 */
private void validate(Object object) {
	Set<ConstraintViolation<Object>> viols = validator.validate(object);
	for (ConstraintViolation<Object> constraintViolation : viols) {
		if (Null.class.isAssignableFrom(constraintViolation.getConstraintDescriptor().getAnnotation().getClass())) {
			Object o = constraintViolation.getLeafBean();
			Iterator<Node> iterator = constraintViolation.getPropertyPath().iterator();
			String propertyName = null;
			while (iterator.hasNext()) {
				propertyName = iterator.next().getName();
			}
			if (propertyName != null) {
				try {
					PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(o.getClass(), propertyName);
					descriptor.getWriteMethod().invoke(o, new Object[] { null });
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
 
Example 4
Source File: BeanValidationInterceptor.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
@AroundInvoke
public Object validateMethodInvocation(InvocationContext invocationContext) throws Exception {

	Validator validator = validatorFactory.getValidator();

	if (validator == null) {
		return invocationContext.proceed();
	}

	Set<ConstraintViolation<Object>> constraintViolations = validator.validate(invocationContext.getTarget());

	for (ConstraintViolation<Object> constraintViolation : constraintViolations) {

		Path propertyPath = constraintViolation.getPropertyPath();

		Path.Node lastPathNode = null;

		for (Path.Node pathNode : propertyPath) {
			lastPathNode = pathNode;
		}

		if ((lastPathNode != null) && (lastPathNode.getKind() == ElementKind.PROPERTY)) {

			Object leafBean = constraintViolation.getLeafBean();
			Class<?> leafBeanClass = leafBean.getClass();

			BeanInfo beanInfo = Introspector.getBeanInfo(leafBean.getClass());

			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

			for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
				String propertyDescriptorName = propertyDescriptor.getName();

				if (propertyDescriptorName.equals("targetClass")) {
					Method readMethod = propertyDescriptor.getReadMethod();
					leafBeanClass = (Class<?>) readMethod.invoke(leafBean);
				}
			}

			Field leafBeanField = leafBeanClass.getDeclaredField(lastPathNode.getName());

			String paramName = null;

			Annotation[] annotations = leafBeanField.getAnnotations();

			for (Annotation annotation : annotations) {

				if (annotation instanceof CookieParam) {
					CookieParam cookieParam = (CookieParam) annotation;
					paramName = cookieParam.value();

					break;
				}
				else if (annotation instanceof FormParam) {
					FormParam formParam = (FormParam) annotation;
					paramName = formParam.value();

					break;
				}
				else if (annotation instanceof HeaderParam) {
					HeaderParam headerParam = (HeaderParam) annotation;
					paramName = headerParam.value();

					break;
				}
				else if (annotation instanceof QueryParam) {
					QueryParam queryParam = (QueryParam) annotation;
					paramName = queryParam.value();
				}
			}

			String interpolatedMessage = constraintViolation.getMessage();

			if (messageInterpolator != null) {
				interpolatedMessage = messageInterpolator.interpolate(constraintViolation.getMessageTemplate(),
						new MessageInterpolatorContextImpl(constraintViolation), mvcContext.getLocale());
			}

			mutableBindingResult.addValidationError(new ValidationErrorImpl(paramName, interpolatedMessage,
					constraintViolation));
		}

	}

	return invocationContext.proceed();
}
 
Example 5
Source File: SheetBeanValidator.java    From xlsmapper with Apache License 2.0 4 votes vote down vote up
/**
 * BeanValidationの検証結果をSheet用のエラーに変換する
 * @param violations BeanValidationの検証結果
 * @param errors シートのエラー
 */
protected void processConstraintViolation(final Set<ConstraintViolation<Object>> violations,
        final SheetBindingErrors<?> errors) {
    
    for(ConstraintViolation<Object> violation : violations) {
        
        final String fieldName = violation.getPropertyPath().toString();
        final Optional<FieldError> fieldError = errors.getFirstFieldError(fieldName);
        
        if(fieldError.isPresent() && fieldError.get().isConversionFailure()) {
            // 型変換エラーが既存のエラーにある場合は、処理をスキップする。
            continue;
        }
        
        final ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
        
        /*
         * エラーメッセージのコードは、後から再変換できるよう、BeanValidationの形式のエラーコードも付けておく。
         */
        final String[] errorCodes = new String[]{
                cd.getAnnotation().annotationType().getSimpleName(),
                cd.getAnnotation().annotationType().getCanonicalName(),
                cd.getAnnotation().annotationType().getCanonicalName() + ".message"
                };
        
        final Map<String, Object> errorVars = createVariableForConstraint(cd);
        
        final String nestedPath = errors.buildFieldPath(fieldName);
        if(Utils.isEmpty(nestedPath)) {
            // オブジェクトエラーの場合
            errors.createGlobalError(errorCodes)
                .variables(errorVars)
                .defaultMessage(violation.getMessage())
                .buildAndAddError();
            
        } else {
            // フィールドエラーの場合
            
            // 親のオブジェクトから、セルの座標を取得する
            final Object parentObj = violation.getLeafBean();
            final Path path = violation.getPropertyPath();
            Optional<CellPosition> cellAddress = Optional.empty();
            Optional<String> label = Optional.empty();
            if(path instanceof PathImpl) {
                final PathImpl pathImpl = (PathImpl) path;
                cellAddress = new PositionGetterFactory().create(parentObj.getClass(), pathImpl.getLeafNode().getName())
                        .map(getter -> getter.get(parentObj)).orElse(Optional.empty());
                
                label = new LabelGetterFactory().create(parentObj.getClass(), pathImpl.getLeafNode().getName())
                        .map(getter -> getter.get(parentObj)).orElse(Optional.empty());
                
            }
            
            // フィールドフォーマッタ
            Class<?> fieldType = errors.getFieldType(nestedPath);
            if(fieldType != null) {
                FieldFormatter<?> fieldFormatter = errors.findFieldFormatter(nestedPath, fieldType);
                if(fieldFormatter != null) {
                    errorVars.putIfAbsent("fieldFormatter", fieldFormatter);
                }
            }
            
            // 実際の値を取得する
            errorVars.putIfAbsent("validatedValue", violation.getInvalidValue());
            
            errors.createFieldError(fieldName, errorCodes)
                .variables(errorVars)
                .address(cellAddress)
                .label(label)
                .defaultMessage(violation.getMessage())
                .buildAndAddError();
            
        }
        
    }
    
}
 
Example 6
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 7
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 8
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 9
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;
}