Java 类javax.validation.metadata.ConstraintDescriptor 实例源码

项目:gwt-bean-validators    文件:ConstraintDescriptorImpl.java   
protected ConstraintDescriptorImpl(final T annotation, final Set<Class<?>> groups,
    final Set<Class<? extends Payload>> payload,
    final List<Class<? extends ConstraintValidator<T, ?>>> constraintValidatorClasses,
    final Map<String, Object> attributes, final Set<ConstraintDescriptor<?>> composingConstraints,
    final boolean reportAsSingleViolation, final ElementType elementType,
    final ConstraintOrigin definedOn) {
  super();
  this.annotation = annotation;
  this.groups = groups;
  this.payload = payload;
  this.constraintValidatorClasses = constraintValidatorClasses;
  this.attributes = attributes;
  this.composingConstraints = composingConstraints;
  this.reportAsSingleViolation = reportAsSingleViolation;
  this.elementType = elementType;
  this.definedOn = definedOn;
}
项目:lams    文件:SpringValidatorAdapter.java   
/**
 * Return FieldError arguments for a validation error on the given field.
 * Invoked for each violated constraint.
 * <p>The default implementation returns a first argument indicating the field name
 * (of type DefaultMessageSourceResolvable, with "objectName.field" and "field" as codes).
 * Afterwards, it adds all actual constraint annotation attributes (i.e. excluding
 * "message", "groups" and "payload") in alphabetical order of their attribute names.
 * <p>Can be overridden to e.g. add further attributes from the constraint descriptor.
 * @param objectName the name of the target object
 * @param field the field that caused the binding error
 * @param descriptor the JSR-303 constraint descriptor
 * @return the Object array that represents the FieldError arguments
 * @see org.springframework.validation.FieldError#getArguments
 * @see org.springframework.context.support.DefaultMessageSourceResolvable
 * @see org.springframework.validation.DefaultBindingErrorProcessor#getArgumentsForBindError
 */
protected Object[] getArgumentsForConstraint(String objectName, String field, ConstraintDescriptor<?> descriptor) {
    List<Object> arguments = new LinkedList<Object>();
    String[] codes = new String[] {objectName + Errors.NESTED_PATH_SEPARATOR + field, field};
    arguments.add(new DefaultMessageSourceResolvable(codes, field));
    // Using a TreeMap for alphabetical ordering of attribute names
    Map<String, Object> attributesToExpose = new TreeMap<String, Object>();
    for (Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
        String attributeName = entry.getKey();
        Object attributeValue = entry.getValue();
        if (!internalAnnotationAttributes.contains(attributeName)) {
            attributesToExpose.put(attributeName, attributeValue);
        }
    }
    arguments.addAll(attributesToExpose.values());
    return arguments.toArray(new Object[arguments.size()]);
}
项目:bootstrap    文件:ValidationResource.java   
/**
 * Return the validation descriptors of given bean.
 * 
 * @param className
 *            the class to describe.
 * @return the validation descriptors of given bean.
 * @throws ClassNotFoundException
 *             when the bean is not found.
 */
@GET
public Map<String, List<String>> describe(final String className) throws ClassNotFoundException {
    final Class<?> beanClass = Class.forName(className);
    final Map<String, List<String>> result = new HashMap<>();
    for (final PropertyDescriptor property : validator.getValidator().getConstraintsForClass(beanClass).getConstrainedProperties()) {
        final List<String> list = new ArrayList<>();
        result.put(property.getPropertyName(), list);
        for (final ConstraintDescriptor<?> constraint : property.getConstraintDescriptors()) {
            // Since constraints are annotation, get the annotation class (interface)
            list.add(constraint.getAnnotation().getClass().getInterfaces()[0].getName());
        }
    }

    return result;
}
项目:bootstrap    文件:ValidationJsonExceptionTest.java   
@Test
public void testConstraintViolationExceptionParameter() {
    final Wine bean = new Wine();
    final Set<ConstraintViolation<?>> violations = new LinkedHashSet<>();

    final ConstraintHelper helper = new ConstraintHelper();

    final ConstraintDescriptor<NotEmpty> notEmptyNameDescriptor = new ConstraintDescriptorImpl<>(helper, (Member) null,
            getAnnotation("name", NotEmpty.class), ElementType.FIELD);
    PathImpl path = PathImpl.createPathFromString("name");
    violations.add(ConstraintViolationImpl.<Wine> forParameterValidation("name-Empty", null, null, "interpolated", Wine.class, bean, new Object(),
            "value", path, notEmptyNameDescriptor, ElementType.PARAMETER, null, null));
    path.addParameterNode("parameter1", 0);

    final ConstraintViolationException violationException = Mockito.mock(ConstraintViolationException.class);
    Mockito.when(violationException.getConstraintViolations()).thenReturn(violations);

    final ValidationJsonException validationJsonException = new ValidationJsonException(violationException);
    Assert.assertFalse(validationJsonException.getErrors().isEmpty());
    Assert.assertEquals("{parameter1=[{rule=name-Empty}]}", validationJsonException.getErrors().toString());
}
项目:spring4-understanding    文件:SpringValidatorAdapter.java   
/**
 * Return FieldError arguments for a validation error on the given field.
 * Invoked for each violated constraint.
 * <p>The default implementation returns a first argument indicating the field name
 * (of type DefaultMessageSourceResolvable, with "objectName.field" and "field" as codes).
 * Afterwards, it adds all actual constraint annotation attributes (i.e. excluding
 * "message", "groups" and "payload") in alphabetical order of their attribute names.
 * <p>Can be overridden to e.g. add further attributes from the constraint descriptor.
 * @param objectName the name of the target object
 * @param field the field that caused the binding error
 * @param descriptor the JSR-303 constraint descriptor
 * @return the Object array that represents the FieldError arguments
 * @see org.springframework.validation.FieldError#getArguments
 * @see org.springframework.context.support.DefaultMessageSourceResolvable
 * @see org.springframework.validation.DefaultBindingErrorProcessor#getArgumentsForBindError
 */
protected Object[] getArgumentsForConstraint(String objectName, String field, ConstraintDescriptor<?> descriptor) {
    List<Object> arguments = new LinkedList<Object>();
    String[] codes = new String[] {objectName + Errors.NESTED_PATH_SEPARATOR + field, field};
    arguments.add(new DefaultMessageSourceResolvable(codes, field));
    // Using a TreeMap for alphabetical ordering of attribute names
    Map<String, Object> attributesToExpose = new TreeMap<String, Object>();
    for (Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
        String attributeName = entry.getKey();
        Object attributeValue = entry.getValue();
        if (!internalAnnotationAttributes.contains(attributeName)) {
            attributesToExpose.put(attributeName, attributeValue);
        }
    }
    arguments.addAll(attributesToExpose.values());
    return arguments.toArray(new Object[arguments.size()]);
}
项目:my-spring-cache-redis    文件:SpringValidatorAdapter.java   
/**
 * Return FieldError arguments for a validation error on the given field.
 * Invoked for each violated constraint.
 * <p>The default implementation returns a first argument indicating the field name
 * (of type DefaultMessageSourceResolvable, with "objectName.field" and "field" as codes).
 * Afterwards, it adds all actual constraint annotation attributes (i.e. excluding
 * "message", "groups" and "payload") in alphabetical order of their attribute names.
 * <p>Can be overridden to e.g. add further attributes from the constraint descriptor.
 * @param objectName the name of the target object
 * @param field the field that caused the binding error
 * @param descriptor the JSR-303 constraint descriptor
 * @return the Object array that represents the FieldError arguments
 * @see org.springframework.validation.FieldError#getArguments
 * @see org.springframework.context.support.DefaultMessageSourceResolvable
 * @see org.springframework.validation.DefaultBindingErrorProcessor#getArgumentsForBindError
 */
protected Object[] getArgumentsForConstraint(String objectName, String field, ConstraintDescriptor<?> descriptor) {
    List<Object> arguments = new LinkedList<Object>();
    String[] codes = new String[] {objectName + Errors.NESTED_PATH_SEPARATOR + field, field};
    arguments.add(new DefaultMessageSourceResolvable(codes, field));
    // Using a TreeMap for alphabetical ordering of attribute names
    Map<String, Object> attributesToExpose = new TreeMap<String, Object>();
    for (Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
        String attributeName = entry.getKey();
        Object attributeValue = entry.getValue();
        if (!internalAnnotationAttributes.contains(attributeName)) {
            attributesToExpose.put(attributeName, attributeValue);
        }
    }
    arguments.addAll(attributesToExpose.values());
    return arguments.toArray(new Object[arguments.size()]);
}
项目:backstopper    文件:ClientDataValidationErrorHandlerListenerTest.java   
private ConstraintViolation<Object> setupConstraintViolation(Class offendingObjectClass, String path, Class<? extends Annotation> annotationClass, String message) {
    ConstraintViolation<Object> mockConstraintViolation = mock(ConstraintViolation.class);

    Path mockPath = mock(Path.class);
    doReturn(path).when(mockPath).toString();

    Annotation mockAnnotation = mock(Annotation.class);
    doReturn(annotationClass).when(mockAnnotation).annotationType();

    ConstraintDescriptor<?> mockConstraintDescriptor = mock(ConstraintDescriptor.class);
    doReturn(mockAnnotation).when(mockConstraintDescriptor).getAnnotation();

    when(mockConstraintViolation.getPropertyPath()).thenReturn(mockPath);
    doReturn(mockConstraintDescriptor).when(mockConstraintViolation).getConstraintDescriptor();
    when(mockConstraintViolation.getMessage()).thenReturn(message);

    doReturn(offendingObjectClass).when(mockConstraintViolation).getRootBeanClass();

    return mockConstraintViolation;
}
项目:backstopper    文件:ServersideValidationErrorHandlerListenerTest.java   
private ConstraintViolation<Object> setupConstraintViolation(String path, Class<? extends Annotation> annotationClass, String message) {
    ConstraintViolation<Object> mockConstraintViolation = mock(ConstraintViolation.class);

    Path mockPath = mock(Path.class);
    doReturn(path).when(mockPath).toString();

    Annotation mockAnnotation = mock(Annotation.class);
    doReturn(annotationClass).when(mockAnnotation).annotationType();

    ConstraintDescriptor<?> mockConstraintDescriptor = mock(ConstraintDescriptor.class);
    doReturn(mockAnnotation).when(mockConstraintDescriptor).getAnnotation();

    when(mockConstraintViolation.getPropertyPath()).thenReturn(mockPath);
    doReturn(mockConstraintDescriptor).when(mockConstraintViolation).getConstraintDescriptor();
    when(mockConstraintViolation.getMessage()).thenReturn(message);

    return mockConstraintViolation;
}
项目:spring    文件:SpringValidatorAdapter.java   
/**
 * Return FieldError arguments for a validation error on the given field.
 * Invoked for each violated constraint.
 * <p>The default implementation returns a first argument indicating the field name
 * (see {@link #getResolvableField}). Afterwards, it adds all actual constraint
 * annotation attributes (i.e. excluding "message", "groups" and "payload") in
 * alphabetical order of their attribute names.
 * <p>Can be overridden to e.g. add further attributes from the constraint descriptor.
 * @param objectName the name of the target object
 * @param field the field that caused the binding error
 * @param descriptor the JSR-303 constraint descriptor
 * @return the Object array that represents the FieldError arguments
 * @see org.springframework.validation.FieldError#getArguments
 * @see org.springframework.context.support.DefaultMessageSourceResolvable
 * @see org.springframework.validation.DefaultBindingErrorProcessor#getArgumentsForBindError
 */
protected Object[] getArgumentsForConstraint(String objectName, String field, ConstraintDescriptor<?> descriptor) {
    List<Object> arguments = new LinkedList<Object>();
    arguments.add(getResolvableField(objectName, field));
    // Using a TreeMap for alphabetical ordering of attribute names
    Map<String, Object> attributesToExpose = new TreeMap<String, Object>();
    for (Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
        String attributeName = entry.getKey();
        Object attributeValue = entry.getValue();
        if (!internalAnnotationAttributes.contains(attributeName)) {
            if (attributeValue instanceof String) {
                attributeValue = new ResolvableAttribute(attributeValue.toString());
            }
            attributesToExpose.put(attributeName, attributeValue);
        }
    }
    arguments.addAll(attributesToExpose.values());
    return arguments.toArray(new Object[arguments.size()]);
}
项目:opencucina    文件:BeanMessageInterpolatorTest.java   
/**
 * JAVADOC Method Level Comments
 */
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void testDefaultConstructor() {
    Context context = mock(Context.class);
    ConstraintDescriptor cd = mock(ConstraintDescriptor.class);
    Map<String, Object> atts = new HashMap<String, Object>();
    String[] properties = { "name", "value" };

    atts.put("properties", properties);

    when(cd.getAttributes()).thenReturn(atts);
    when(context.getConstraintDescriptor()).thenReturn(cd);

    Foo foo = new Foo();

    foo.setName("Name");
    foo.setValue(200);
    when(context.getValidatedValue()).thenReturn(foo);

    BeanMessageInterpolator interpolator = new BeanMessageInterpolator();

    assertEquals("message Name and 200",
        interpolator.interpolate("message {0} and {1}", context));
}
项目:opencucina    文件:BeanMessageInterpolatorTest.java   
/**
 * JAVADOC Method Level Comments
 */
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void testInterpolateStringContext() {
    Context context = mock(Context.class);
    ConstraintDescriptor cd = mock(ConstraintDescriptor.class);
    Map<String, Object> atts = new HashMap<String, Object>();

    when(cd.getAttributes()).thenReturn(atts);
    when(context.getConstraintDescriptor()).thenReturn(cd);

    Foo foo = new Foo();

    when(context.getValidatedValue()).thenReturn(foo);

    MessageInterpolator delegate = mock(MessageInterpolator.class);

    when(delegate.interpolate("message", context)).thenReturn("MEssAGE");

    BeanMessageInterpolator interpolator = new BeanMessageInterpolator(delegate);

    interpolator.interpolate("message", context);
    assertEquals(foo, atts.get("0"));
}
项目:lastaflute    文件:ActionValidator.java   
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));
}
项目:clotho3crud    文件:JSON.java   
@Override
        public void setupModule(SetupContext context) {
            context.setMixInAnnotations(Object.class, DisableGetters.class);
            context.setMixInAnnotations(Collection.class, DisableTypeInfo.class);
            context.setMixInAnnotations(Map.class, DisableTypeInfo.class);
//            context.setMixInAnnotations(Array.class, DisableTypeInfo.class);

            //Default types for interfaces unknown to Jackson
            context.setMixInAnnotations(Bindings.class, UseSimpleBindings.class);
            context.setMixInAnnotations(PrincipalCollection.class, UseSimplePrincipalCollection.class);

            //serializers and typeinfo for shiro classes
            context.setMixInAnnotations(SimpleAuthenticationInfo.class, UseTypeInfoForCredentials.class);
            context.setMixInAnnotations(SimpleHash.class, SimpleHashMixin.class);
            context.setMixInAnnotations(ByteSource.class, UseSimpleByteSource.class);
            context.setMixInAnnotations(SimpleByteSource.class, SimpleByteSourceMixin.class);

            //and it's safer to use public interfaces on some classes
            context.setMixInAnnotations(ConstraintViolation.class, UseDefaultAutoDetect.class);
            context.setMixInAnnotations(ConstraintDescriptor.class, UseDefaultAutoDetect.class);
            context.setMixInAnnotations(Node.class, UseDefaultAutoDetect.class);


        }
项目:gwt-bean-validators    文件:ConstraintFinderImpl.java   
private void findMatchingDescriptors(final Set<ConstraintDescriptor<?>> matchingDescriptors) {
  if (this.groups.isEmpty()) {
    for (final ConstraintDescriptorImpl<?> descriptor : this.constraintDescriptors) {
      if (this.definedInSet.contains(descriptor.getDefinedOn())
          && this.elementTypes.contains(descriptor.getElementType())) {
        matchingDescriptors.add(descriptor);
      }
    }
  } else {
    final GroupChain groupChain =
        new GroupChainGenerator(this.validationGroupsMetadata).getGroupChainFor(this.groups);
    final Iterator<Group> groupIterator = groupChain.getGroupIterator();
    while (groupIterator.hasNext()) {
      final Group g = groupIterator.next();
      this.addMatchingDescriptorsForGroup(g.getGroup(), matchingDescriptors);
    }
  }
}
项目:gwt-bean-validators    文件:GwtSpecificValidatorCreator.java   
/**
 * Gets the best {@link ConstraintValidator}.
 *
 * <p>
 * The ConstraintValidator chosen to validate a declared type {@code targetType} is the one where
 * the type supported by the ConstraintValidator is a supertype of {@code targetType} and where
 * there is no other ConstraintValidator whose supported type is a supertype of {@code type} and
 * not a supertype of the chosen ConstraintValidator supported type.
 * </p>
 *
 * @param constraint the constraint to find ConstraintValidators for.
 * @param targetType The type to find a ConstraintValidator for.
 * @return ConstraintValidator
 *
 * @throws UnexpectedTypeException if there is not exactly one maximally specific constraint
 *         validator for targetType.
 */
private static <A extends Annotation> Class<? extends ConstraintValidator<A, ?>> //
    getValidatorForType(final ConstraintDescriptor<A> constraint, final Class<?> targetType)
        throws UnexpectedTypeException {
  final List<Class<? extends ConstraintValidator<A, ?>>> constraintValidatorClasses =
      constraint.getConstraintValidatorClasses();
  if (constraintValidatorClasses.isEmpty()) {
    throw new UnexpectedTypeException(
        "No ConstraintValidator found for  " + constraint.getAnnotation());
  }
  final ImmutableSet<Class<? extends ConstraintValidator<A, ?>>> best =
      getValidatorForType(targetType, constraintValidatorClasses);
  if (best.isEmpty()) {
    throw new UnexpectedTypeException(
        "No " + constraint.getAnnotation() + " ConstraintValidator for type " + targetType);
  }
  if (best.size() > 1) {
    throw new UnexpectedTypeException("More than one maximally specific "
        + constraint.getAnnotation() + " ConstraintValidator for type " + targetType + ", found "
        + Ordering.usingToString().sortedCopy(best));
  }
  return Iterables.get(best, 0);
}
项目:gwt-bean-validators    文件:GwtSpecificValidatorCreator.java   
private boolean isPropertyConstrained(final PropertyDescriptor ppropertyDescription,
    final boolean useField) {
  // cascaded counts as constrained
  // we must know if the @Valid annotation is on a field or a getter
  final JClassType jClass = this.beanHelper.getJClass();
  if (useField && jClass.findField(ppropertyDescription.getPropertyName())
      .isAnnotationPresent(Valid.class)) {
    return true;
  } else if (!useField && jClass.findMethod(asGetter(ppropertyDescription), NO_ARGS)
      .isAnnotationPresent(Valid.class)) {
    return true;
  }
  // for non-cascaded properties
  for (final ConstraintDescriptor<?> constraint : ppropertyDescription
      .getConstraintDescriptors()) {
    final org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl<?> constraintHibernate =
        (org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl<?>) constraint;
    if (constraintHibernate
        .getElementType() == (useField ? ElementType.FIELD : ElementType.METHOD)) {
      return true;
    }
  }
  return false;
}
项目:gwt-bean-validators    文件:ConstraintViolationImpl_CustomFieldSerializer.java   
/**
 * instantiate a ConstraintViolationImpl.
 *
 * @param streamReader serialized stream reader to take data from
 * @return ConstraintViolationImpl
 * @throws SerializationException if deserialization fails
 */
public static ConstraintViolationImpl<Object> instantiate(
    final SerializationStreamReader streamReader) throws SerializationException {

  final String messageTemplate = null;
  final String interpolatedMessage = streamReader.readString();
  final Class<Object> rootBeanClass = null;
  final Object rootBean = null;
  final Object leafBeanInstance = null;
  final Object value = null;
  final Path propertyPath = (Path) streamReader.readObject();
  final ConstraintDescriptor<?> constraintDescriptor = null;
  final ElementType elementType = null;
  final Map<String, Object> messageParameters = new HashMap<>();
  final Map<String, Object> expressionVariables = new HashMap<>();
  return (ConstraintViolationImpl<Object>) ConstraintViolationImpl.forBeanValidation(
      messageTemplate, messageParameters, expressionVariables, interpolatedMessage, rootBeanClass,
      rootBean, leafBeanInstance, value, propertyPath, constraintDescriptor, elementType, null);
}
项目:gwt-bean-validators    文件:ConstraintViolationImpl.java   
private ConstraintViolationImpl(final String messageTemplate,
    final Map<String, Object> messageParameters, final Map<String, Object> expressionVariables,
    final String interpolatedMessage, final Class<T> rootBeanClass, final T rootBean,
    final Object leafBeanInstance, final Object value, final Path propertyPath,
    final ConstraintDescriptor<?> constraintDescriptor, final ElementType elementType,
    final Object[] executableParameters, final Object executableReturnValue,
    final Object dynamicPayload) {
  this.messageTemplate = messageTemplate;
  this.messageParameters = messageParameters;
  this.expressionVariables = expressionVariables;
  this.interpolatedMessage = interpolatedMessage;
  this.rootBean = rootBean;
  this.value = value;
  this.propertyPath = propertyPath;
  this.leafBeanInstance = leafBeanInstance;
  this.constraintDescriptor = constraintDescriptor;
  this.rootBeanClass = rootBeanClass;
  this.elementType = elementType;
  this.executableParameters = executableParameters;
  this.executableReturnValue = executableReturnValue;
  this.dynamicPayload = dynamicPayload;
  // pre-calculate hash code, the class is immutable and hashCode is needed often
  this.hashCodeValue = this.createHashCode();
}
项目:Introspect-Framework    文件:ConstrainViolationFactory.java   
private static ConstraintViolation<Object> createConstraintViolations(
        LanguageProvider languageProvider, ClassInfo classInfo,
        Object domainObject, ValidationViolation validationViolation) {
    String messageTemplateKey = validationViolation.getMessageTemplateKey();
    String messageTemplateDefault = validationViolation
            .getMessageTemplateInEnglish();
    String messageTemplate = languageProvider.getText(messageTemplateKey,
            messageTemplateDefault);
    Object invalidValue = validationViolation.getInvalidValue();
    String message = String.format(messageTemplate, invalidValue);
    Path path = PathImpl.create(classInfo.getSimpleName());
    @SuppressWarnings("unchecked")
    Class<Object> rootBeanClass = (Class<Object>) domainObject.getClass();
    ConstraintDescriptor<?> constraintDescriptor = null;
    ElementType elementType = null;
    ConstraintViolationImpl<Object> constraintViolation = new ConstraintViolationImpl<Object>(
            messageTemplate, message, domainObject, domainObject, path,
            domainObject, constraintDescriptor, rootBeanClass, elementType);
    return constraintViolation;
}
项目:class-guard    文件:SpringValidatorAdapter.java   
/**
 * Return FieldError arguments for a validation error on the given field.
 * Invoked for each violated constraint.
 * <p>The default implementation returns a first argument indicating the field name
 * (of type DefaultMessageSourceResolvable, with "objectName.field" and "field" as codes).
 * Afterwards, it adds all actual constraint annotation attributes (i.e. excluding
 * "message", "groups" and "payload") in alphabetical order of their attribute names.
 * <p>Can be overridden to e.g. add further attributes from the constraint descriptor.
 * @param objectName the name of the target object
 * @param field the field that caused the binding error
 * @param descriptor the JSR-303 constraint descriptor
 * @return the Object array that represents the FieldError arguments
 * @see org.springframework.validation.FieldError#getArguments
 * @see org.springframework.context.support.DefaultMessageSourceResolvable
 * @see org.springframework.validation.DefaultBindingErrorProcessor#getArgumentsForBindError
 */
protected Object[] getArgumentsForConstraint(String objectName, String field, ConstraintDescriptor<?> descriptor) {
    List<Object> arguments = new LinkedList<Object>();
    String[] codes = new String[] {objectName + Errors.NESTED_PATH_SEPARATOR + field, field};
    arguments.add(new DefaultMessageSourceResolvable(codes, field));
    // Using a TreeMap for alphabetical ordering of attribute names
    Map<String, Object> attributesToExpose = new TreeMap<String, Object>();
    for (Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
        String attributeName = entry.getKey();
        Object attributeValue = entry.getValue();
        if (!internalAnnotationAttributes.contains(attributeName)) {
            attributesToExpose.put(attributeName, attributeValue);
        }
    }
    arguments.addAll(attributesToExpose.values());
    return arguments.toArray(new Object[arguments.size()]);
}
项目:cm_ext    文件:MonitoringConstraintViolation.java   
public MonitoringConstraintViolation(
    String messageTemplate,
    String interpolatedMessage,
    Class<T> rootBeanClass,
    T rootBean,
    Object leafBeanInstance,
    Object value,
    DescriptorPath propertyPath,
    ConstraintDescriptor<?> constraintDescriptor,
    ElementType elementType,
    Object[] executableParameters,
    Object executableReturnValue) {
  this.messageTemplate = messageTemplate;
  this.interpolatedMessage = interpolatedMessage;
  this.rootBean = rootBean;
  this.value = value;
  this.propertyPath = propertyPath;
  this.leafBeanInstance = leafBeanInstance;
  this.constraintDescriptor = constraintDescriptor;
  this.rootBeanClass = rootBeanClass;
  this.elementType = elementType;
  this.executableParameters = executableParameters;
  this.executableReturnValue = executableReturnValue;
}
项目:cm_ext    文件:ReferenceConstraintViolation.java   
public ReferenceConstraintViolation(String messageTemplate,
                                    String interpolatedMessage,
                                    Class<T> rootBeanClass,
                                    T rootBean,
                                    Object leafBeanInstance,
                                    Object value,
                                    DescriptorPath propertyPath,
                                    ConstraintDescriptor<?> constraintDescriptor,
                                    ElementType elementType,
                                    Object[] executableParameters,
                                    Object executableReturnValue) {
  this.messageTemplate = messageTemplate;
  this.interpolatedMessage = interpolatedMessage;
  this.rootBean = rootBean;
  this.value = value;
  this.propertyPath = propertyPath;
  this.leafBeanInstance = leafBeanInstance;
  this.constraintDescriptor = constraintDescriptor;
  this.rootBeanClass = rootBeanClass;
  this.elementType = elementType;
  this.executableParameters = executableParameters;
  this.executableReturnValue = executableReturnValue;
}
项目:xlsmapper    文件:SheetBeanValidator.java   
/**
 * BeanValidationのアノテーションの値を元に、メッセージ変数を作成する。
 * @param descriptor
 * @return メッセージ変数
 */
protected Map<String, Object> createVariableForConstraint(final ConstraintDescriptor<?> descriptor) {

    final Map<String, Object> vars = new LinkedHashMap<String, Object>();

    for(Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
        final String attrName = entry.getKey();
        final Object attrValue = entry.getValue();

        // メッセージ変数で必要ないものを除外する
        if(EXCLUDE_MESSAGE_ANNOTATION_ATTRIBUTES.contains(attrName)) {
            continue;
        }

        vars.put(attrName, attrValue);
    }

    return vars;

}
项目:xlsmapper    文件:MessageInterpolatorAdapter.java   
protected Map<String, Object> createMessageVars(final Context context) {
    final Map<String, Object> vars = new LinkedHashMap<String, Object>();

    final ConstraintDescriptor<?> descriptor = context.getConstraintDescriptor();
    for(Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
        final String attrName = entry.getKey();
        final Object attrValue = entry.getValue();

        vars.put(attrName, attrValue);
    }

    // 検証対象の値
    vars.put("validatedValue", context.getValidatedValue());

    // デフォルトのメッセージ
    final String defaultCode = String.format("%s.message", descriptor.getAnnotation().annotationType().getCanonicalName());
    final String defaultMessage = messageResolver.getMessage(defaultCode);
    if(defaultMessage == null) {
        throw new RuntimeException(String.format("not found message code '%s'", defaultCode));
    }
    vars.put(defaultCode, defaultMessage);

    return vars;
}
项目:super-csv-annotation    文件:CsvBeanValidator.java   
/**
 * BeanValidationのアノテーションの値を元に、メッセージ変数を作成する。
 * @param descriptor
 * @return メッセージ変数
 */
private Map<String, Object> createVariableForConstraint(final ConstraintDescriptor<?> descriptor) {

    final Map<String, Object> vars = new HashMap<>();

    for(Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
        final String attrName = entry.getKey();
        final Object attrValue = entry.getValue();

        // メッセージ変数で必要ないものを除外する
        if(EXCLUDE_MESSAGE_ANNOTATION_ATTRIBUTES.contains(attrName)) {
            continue;
        }

        vars.put(attrName, attrValue);
    }

    return vars;

}
项目:syndesis    文件:Violation.java   
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();
}
项目:lams    文件:TypeSafeActivator.java   
private static boolean applyConstraints(
        Set<ConstraintDescriptor<?>> constraintDescriptors,
        Property property,
        PropertyDescriptor propertyDesc,
        Set<Class<?>> groups,
        boolean canApplyNotNull,
        Dialect dialect) {
    boolean hasNotNull = false;
    for ( ConstraintDescriptor<?> descriptor : constraintDescriptors ) {
        if ( groups != null && Collections.disjoint( descriptor.getGroups(), groups ) ) {
            continue;
        }

        if ( canApplyNotNull ) {
            hasNotNull = hasNotNull || applyNotNull( property, descriptor );
        }

        // apply bean validation specific constraints
        applyDigits( property, descriptor );
        applySize( property, descriptor, propertyDesc );
        applyMin( property, descriptor, dialect );
        applyMax( property, descriptor, dialect );

        // apply hibernate validator specific constraints - we cannot import any HV specific classes though!
        // no need to check explicitly for @Range. @Range is a composed constraint using @Min and @Max which
        // will be taken care later
        applyLength( property, descriptor, propertyDesc );

        // pass an empty set as composing constraints inherit the main constraint and thus are matching already
        hasNotNull = hasNotNull || applyConstraints(
                descriptor.getComposingConstraints(),
                property, propertyDesc, null,
                canApplyNotNull,
                   dialect
        );
    }
    return hasNotNull;
}
项目:lams    文件:TypeSafeActivator.java   
private static void applyMin(Property property, ConstraintDescriptor<?> descriptor, Dialect dialect) {
    if ( Min.class.equals( descriptor.getAnnotation().annotationType() ) ) {
        @SuppressWarnings("unchecked")
        ConstraintDescriptor<Min> minConstraint = (ConstraintDescriptor<Min>) descriptor;
        long min = minConstraint.getAnnotation().value();

        Column col = (Column) property.getColumnIterator().next();
        String checkConstraint = col.getQuotedName(dialect) + ">=" + min;
        applySQLCheck( col, checkConstraint );
    }
}
项目:lams    文件:TypeSafeActivator.java   
private static void applyMax(Property property, ConstraintDescriptor<?> descriptor, Dialect dialect) {
    if ( Max.class.equals( descriptor.getAnnotation().annotationType() ) ) {
        @SuppressWarnings("unchecked")
        ConstraintDescriptor<Max> maxConstraint = (ConstraintDescriptor<Max>) descriptor;
        long max = maxConstraint.getAnnotation().value();
        Column col = (Column) property.getColumnIterator().next();
        String checkConstraint = col.getQuotedName(dialect) + "<=" + max;
        applySQLCheck( col, checkConstraint );
    }
}
项目:lams    文件:TypeSafeActivator.java   
private static boolean applyNotNull(Property property, ConstraintDescriptor<?> descriptor) {
    boolean hasNotNull = false;
    if ( NotNull.class.equals( descriptor.getAnnotation().annotationType() ) ) {
        // single table inheritance should not be forced to null due to shared state
        if ( !( property.getPersistentClass() instanceof SingleTableSubclass ) ) {
            //composite should not add not-null on all columns
            if ( !property.isComposite() ) {
                final Iterator<Selectable> iter = property.getColumnIterator();
                while ( iter.hasNext() ) {
                    final Selectable selectable = iter.next();
                    if ( Column.class.isInstance( selectable ) ) {
                        Column.class.cast( selectable ).setNullable( false );
                    }
                    else {
                        LOG.debugf(
                                "@NotNull was applied to attribute [%s] which is defined (at least partially) " +
                                        "by formula(s); formula portions will be skipped",
                                property.getName()
                        );
                    }
                }
            }
        }
        hasNotNull = true;
    }
    return hasNotNull;
}
项目:lams    文件:TypeSafeActivator.java   
private static void applyDigits(Property property, ConstraintDescriptor<?> descriptor) {
    if ( Digits.class.equals( descriptor.getAnnotation().annotationType() ) ) {
        @SuppressWarnings("unchecked")
        ConstraintDescriptor<Digits> digitsConstraint = (ConstraintDescriptor<Digits>) descriptor;
        int integerDigits = digitsConstraint.getAnnotation().integer();
        int fractionalDigits = digitsConstraint.getAnnotation().fraction();
        Column col = (Column) property.getColumnIterator().next();
        col.setPrecision( integerDigits + fractionalDigits );
        col.setScale( fractionalDigits );
    }
}
项目:lams    文件:TypeSafeActivator.java   
private static void applySize(Property property, ConstraintDescriptor<?> descriptor, PropertyDescriptor propertyDescriptor) {
    if ( Size.class.equals( descriptor.getAnnotation().annotationType() )
            && String.class.equals( propertyDescriptor.getElementClass() ) ) {
        @SuppressWarnings("unchecked")
        ConstraintDescriptor<Size> sizeConstraint = (ConstraintDescriptor<Size>) descriptor;
        int max = sizeConstraint.getAnnotation().max();
        Column col = (Column) property.getColumnIterator().next();
        if ( max < Integer.MAX_VALUE ) {
            col.setLength( max );
        }
    }
}
项目:lams    文件:TypeSafeActivator.java   
private static void applyLength(Property property, ConstraintDescriptor<?> descriptor, PropertyDescriptor propertyDescriptor) {
    if ( "org.hibernate.validator.constraints.Length".equals(
            descriptor.getAnnotation().annotationType().getName()
    )
            && String.class.equals( propertyDescriptor.getElementClass() ) ) {
        @SuppressWarnings("unchecked")
        int max = (Integer) descriptor.getAttributes().get( "max" );
        Column col = (Column) property.getColumnIterator().next();
        if ( max < Integer.MAX_VALUE ) {
            col.setLength( max );
        }
    }
}
项目:minijax    文件:MinijaxValidator.java   
@SuppressWarnings({ "rawtypes", "unchecked" })
private <T> void validatePropertyConstraints(
        final MinijaxConstraintValidatorContext<T> context,
        final PropertyDescriptor property,
        final Object value) {

    for (final ConstraintDescriptor constraint : property.getConstraintDescriptors()) {
        final ConstraintValidator validator = ((MinijaxConstraintDescriptor) constraint).getValidator();
        if (!validator.isValid(value, context)) {
            context.buildViolation(constraint, value);
        }
    }
}
项目:minijax    文件:MinijaxValidator.java   
@SuppressWarnings("rawtypes")
private <T> void validatePropertyElementConstraints(
        final MinijaxConstraintValidatorContext<T> context,
        final PropertyDescriptor property,
        final Object value) {

    for (final ContainerElementTypeDescriptor descriptor : property.getConstrainedContainerElementTypes()) {
        for (final ConstraintDescriptor constraint : descriptor.getConstraintDescriptors()) {
            final ConstraintValidator validator = ((MinijaxConstraintDescriptor) constraint).getValidator();

            if (value instanceof List) {
                validateList(context, constraint, validator, (List) value);

            } else if (value instanceof Iterable) {
                validateIterable(context, constraint, validator, (Iterable) value);

            } else if (value instanceof Map && descriptor.getTypeArgumentIndex() == 0) {
                validateMapKeys(context, constraint, validator, (Map<?, ?>) value);

            } else if (value instanceof Map) {
                validateMapValues(context, constraint, validator, (Map<?, ?>) value);

            } else if (value instanceof Optional) {
                validateOptional(context, constraint, validator, (Optional) value);
            }
        }
    }
}
项目:minijax    文件:MinijaxValidator.java   
@SuppressWarnings({ "rawtypes", "unchecked" })
private <T> void validateList(
        final MinijaxConstraintValidatorContext<T> context,
        final ConstraintDescriptor constraint,
        final ConstraintValidator validator,
        final List list) {

    for (int i = 0; i < list.size(); i++) {
        if (!validator.isValid(list.get(i), context)) {
            context.buildViolation(constraint, list.get(i), "[" + i + "].<list element>");
        }
    }
}
项目:minijax    文件:MinijaxValidator.java   
@SuppressWarnings({ "rawtypes", "unchecked" })
private <T> void validateIterable(
        final MinijaxConstraintValidatorContext<T> context,
        final ConstraintDescriptor constraint,
        final ConstraintValidator validator,
        final Iterable iterable) {

    for (final Object element : iterable) {
        if (!validator.isValid(element, context)) {
            context.buildViolation(constraint, element, "[].<iterable element>");
        }
    }
}
项目:minijax    文件:MinijaxValidator.java   
@SuppressWarnings({ "rawtypes", "unchecked" })
private <T> void validateMapKeys(
        final MinijaxConstraintValidatorContext<T> context,
        final ConstraintDescriptor constraint,
        final ConstraintValidator validator,
        final Map<?, ?> map) {

    for (final Object element : map.keySet()) {
        if (!validator.isValid(element, context)) {
            context.buildViolation(constraint, element, "<K>[].<map key>");
        }
    }
}
项目:minijax    文件:MinijaxValidator.java   
@SuppressWarnings({ "rawtypes", "unchecked" })
private <T> void validateMapValues(
        final MinijaxConstraintValidatorContext<T> context,
        final ConstraintDescriptor constraint,
        final ConstraintValidator validator,
        final Map<?, ?> map) {

    for (final Entry<?, ?> entry : map.entrySet()) {
        if (!validator.isValid(entry.getValue(), context)) {
            context.buildViolation(constraint, entry.getValue(), "[" + entry.getKey() + "].<map value>");
        }
    }
}
项目:minijax    文件:MinijaxValidator.java   
@SuppressWarnings({ "rawtypes", "unchecked" })
private <T> void validateOptional(
        final MinijaxConstraintValidatorContext<T> context,
        final ConstraintDescriptor constraint,
        final ConstraintValidator validator,
        final Optional optional) {

    if (optional.isPresent() && !validator.isValid(optional.get(), context)) {
        context.buildViolation(constraint, optional.get());
    }
}