本文整理汇总了Java中javax.validation.metadata.ConstraintDescriptor类的典型用法代码示例。如果您正苦于以下问题:Java ConstraintDescriptor类的具体用法?Java ConstraintDescriptor怎么用?Java ConstraintDescriptor使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ConstraintDescriptor类属于javax.validation.metadata包,在下文中一共展示了ConstraintDescriptor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: ConstraintDescriptorImpl
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
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;
}
示例2: getArgumentsForConstraint
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
/**
* 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()]);
}
示例3: describe
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
/**
* 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;
}
示例4: testConstraintViolationExceptionParameter
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
@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());
}
示例5: setupConstraintViolation
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
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;
}
示例6: setupConstraintViolation
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
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;
}
示例7: getArgumentsForConstraint
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
/**
* 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()]);
}
示例8: testDefaultConstructor
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
/**
* 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));
}
示例9: testInterpolateStringContext
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
/**
* 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"));
}
示例10: registerActionMessage
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
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));
}
示例11: setupModule
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
@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);
}
示例12: findMatchingDescriptors
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
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);
}
}
}
示例13: getValidatorForType
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
/**
* 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);
}
示例14: isPropertyConstrained
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
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;
}
示例15: instantiate
import javax.validation.metadata.ConstraintDescriptor; //导入依赖的package包/类
/**
* 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);
}
开发者ID:ManfredTremmel,项目名称:gwt-bean-validators,代码行数:26,代码来源:ConstraintViolationImpl_CustomFieldSerializer.java