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

The following examples show how to use javax.validation.ConstraintViolation#getConstraintDescriptor() . 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: ConstraintViolationExceptionMapper.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
private String toCode(ConstraintViolation<?> violation) {
	if (violation.getConstraintDescriptor() != null) {
		Annotation annotation = violation.getConstraintDescriptor().getAnnotation();

		if (annotation != null) {
			Class<?> clazz = annotation.getClass();
			Class<?> superclass = annotation.getClass().getSuperclass();
			Class<?>[] interfaces = annotation.getClass().getInterfaces();
			if (superclass == Proxy.class && interfaces.length == 1) {
				clazz = interfaces[0];
			}

			return clazz.getName();
		}
	}
	if (violation.getMessageTemplate() != null) {
		return violation.getMessageTemplate().replace("{", "").replaceAll("}", "");
	}
	return null;
}
 
Example 2
Source File: ViolationExceptionMapper.java    From pay-publicapi with MIT License 6 votes vote down vote up
@Override
public Response toResponse(JerseyViolationException exception) {
    LOGGER.info(exception.getMessage());
    ConstraintViolation<?> firstException = exception.getConstraintViolations().iterator().next();
    String fieldName = getApiFieldName(firstException.getPropertyPath());
    
    PaymentError paymentError;
    if (firstException.getConstraintDescriptor() != null &&
            firstException.getConstraintDescriptor().getAnnotation() != null &&
            firstException.getConstraintDescriptor().getAnnotation().annotationType() == NotBlank.class ||
            firstException.getConstraintDescriptor().getAnnotation().annotationType() == NotEmpty.class ||
            firstException.getConstraintDescriptor().getAnnotation().annotationType() == NotNull.class) {
        paymentError = PaymentError.aPaymentError(fieldName, CREATE_PAYMENT_MISSING_FIELD_ERROR);
    } else {
        paymentError = PaymentError.aPaymentError(fieldName, CREATE_PAYMENT_VALIDATION_ERROR, firstException.getMessage());
    }
    
    return Response.status(422)
            .entity(paymentError)
            .build();
}
 
Example 3
Source File: ActionValidator.java    From lastaflute with Apache License 2.0 6 votes vote down vote up
protected void registerActionMessage(UserMessages messages, ConstraintViolation<Object> vio) {
    final String propertyPath = extractPropertyPath(vio);
    final String plainMessage = filterMessageItem(extractMessage(vio), propertyPath);
    final String delimiter = MESSAGE_HINT_DELIMITER;
    final String messageItself;
    final String messageKey;
    if (plainMessage.contains(delimiter)) { // basically here
        messageItself = Srl.substringFirstRear(plainMessage, delimiter);
        messageKey = Srl.substringFirstFront(plainMessage, delimiter);
    } else { // just in case
        messageItself = plainMessage;
        messageKey = null;
    }
    final ConstraintDescriptor<?> descriptor = vio.getConstraintDescriptor();
    final Annotation annotation = descriptor.getAnnotation();
    final Set<Class<?>> groupSet = descriptor.getGroups();
    final Class<?>[] groups = groupSet.toArray(new Class<?>[groupSet.size()]);
    messages.add(propertyPath, createDirectMessage(messageItself, annotation, groups, messageKey));
}
 
Example 4
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 5
Source File: Violation.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public static Violation fromConstraintViolation(final ConstraintViolation<?> constraintViolation) {
    final String property = constraintViolation.getPropertyPath().toString();
    final ConstraintDescriptor<?> constraintDescriptor = constraintViolation.getConstraintDescriptor();
    final Annotation annotation = constraintDescriptor.getAnnotation();
    final Class<? extends Annotation> annotationType = annotation.annotationType();
    final String error = annotationType.getSimpleName();
    final String message = constraintViolation.getMessage();

    return new Builder().property(property).error(error).message(message).build();
}
 
Example 6
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 7
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 8
Source File: ParcelDescriptorValidatorImplTest.java    From cm_ext with Apache License 2.0 4 votes vote down vote up
private void assertConstraint(ConstraintViolation<?> violation, Class<?> constraint) {
  ConstraintDescriptor<?> descriptor = violation.getConstraintDescriptor();
  assertEquals(constraint, descriptor.getAnnotation().annotationType());
}
 
Example 9
Source File: ServiceDescriptorValidatorImplTest.java    From cm_ext with Apache License 2.0 4 votes vote down vote up
private void assertConstraint(ConstraintViolation<?> violation, Class<?> constraint) {
  ConstraintDescriptor<?> descriptor = violation.getConstraintDescriptor();
  assertEquals(constraint, descriptor.getAnnotation().annotationType());
}
 
Example 10
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 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: 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());
            
        }
        
    }
    
    
}