Java Examples for javax.validation.ConstraintValidator
The following java examples will help you to understand the usage of javax.validation.ConstraintValidator. These source code samples are taken from different open source projects.
Example 1
| Project: InSpider-master File: ValidCollectionValidator.java View source code |
/* (non-Javadoc) * @see javax.validation.ConstraintValidator#isValid(java.lang.Object, javax.validation.ConstraintValidatorContext) */ @Override public boolean isValid(List<?> entries, ConstraintValidatorContext context) { boolean valid = true; if (entries == null) { return valid; } if (ArrayUtils.getLength(constraints) != ArrayUtils.getLength(messages)) { throw new ConstraintDeclarationException("Number of messages must be the same as number of constraints"); } ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); ConstraintValidatorFactory constraintValidatorFactory = validatorFactory.getConstraintValidatorFactory(); for (Object element : entries) { for (Class<?> constraint : constraints) { Constraint constraintAnnotation = constraint.getAnnotation(Constraint.class); Class<? extends ConstraintValidator<?, ?>>[] constraintValidators = constraintAnnotation.validatedBy(); for (int i = 0; i < constraintValidators.length; i++) { ConstraintValidator constraintValidator = constraintValidatorFactory.getInstance(constraintValidators[i]); if (!constraintValidator.isValid(element, context)) { context.buildConstraintViolationWithTemplate(messages[i]).addConstraintViolation().disableDefaultConstraintViolation(); valid = false; } } } } return valid; }
Example 2
| Project: guit-master File: RequestFactoryModule.java View source code |
@Provides
@Singleton
public ValidatorFactory getValidatorFactory(final Injector injector) {
return Validation.byDefaultProvider().configure().constraintValidatorFactory(new ConstraintValidatorFactory() {
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
return injector.getInstance(key);
}
}).buildValidatorFactory();
}Example 3
| Project: hibernate-validator-master File: ConstraintHelper.java View source code |
/**
* Returns the default validators for the given constraint type.
*
* @param annotationType The constraint annotation type.
*
* @return A list with the default validators as retrieved from
* {@link Constraint#validatedBy()} or the list of validators for
* built-in constraints.
*/
@SuppressWarnings("unchecked")
private <A extends Annotation> List<ConstraintValidatorDescriptor<A>> getDefaultValidatorDescriptors(Class<A> annotationType) {
//safe cause all CV for a given annotation A are CV<A, ?>
final List<ConstraintValidatorDescriptor<A>> builtInValidators = (List<ConstraintValidatorDescriptor<A>>) builtinConstraints.get(annotationType);
if (builtInValidators != null) {
return builtInValidators;
}
Class<? extends ConstraintValidator<A, ?>>[] validatedBy = (Class<? extends ConstraintValidator<A, ?>>[]) annotationType.getAnnotation(Constraint.class).validatedBy();
return Stream.of(validatedBy).map( c -> ConstraintValidatorDescriptor.forClass(c)).collect(Collectors.collectingAndThen(Collectors.toList(), CollectionHelper::toImmutableList));
}Example 4
| Project: vraptor-master File: DIConstraintValidatorFactory.java View source code |
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) { if (container.canProvide(key)) { logger.debug("we can provide instance for ConstraintValidator {}", key); return container.instanceFor(key); } // GH583 - we need to use reflection to instantiate constraints return new ReflectionInstanceCreator().instanceFor(key); }
Example 5
| Project: casser-master File: MappingUtil.java View source code |
public static ConstraintValidator<? extends Annotation, ?>[] getValidators(Method getterMethod) { List<ConstraintValidator<? extends Annotation, ?>> list = null; for (Annotation constraintAnnotation : getterMethod.getDeclaredAnnotations()) { list = addValidators(constraintAnnotation, list); Class<? extends Annotation> annotationType = constraintAnnotation.annotationType(); for (Annotation possibleConstraint : annotationType.getDeclaredAnnotations()) { list = addValidators(possibleConstraint, list); } } if (list == null) { return EMPTY_VALIDATORS; } else { return list.toArray(EMPTY_VALIDATORS); } }
Example 6
| Project: jooby-master File: HbvConstraintValidatorFactoryTest.java View source code |
@Test
public void getInstance() throws Exception {
new MockUnit(Injector.class, ConstraintValidator.class).expect( unit -> {
Injector injector = unit.get(Injector.class);
expect(injector.getInstance(ConstraintValidator.class)).andReturn(unit.get(ConstraintValidator.class));
}).run( unit -> {
assertEquals(unit.get(ConstraintValidator.class), new HbvConstraintValidatorFactory(unit.get(Injector.class)).getInstance(ConstraintValidator.class));
});
}Example 7
| Project: myfaces-ext-cdi-master File: CdiAwareValidatorFactory.java View source code |
@SuppressWarnings({ "unchecked" })
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> targetClass) {
BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager();
Set<? extends Bean> foundBeans = beanManager.getBeans(targetClass);
if (foundBeans.isEmpty()) {
return wrappedValidatorFactory.getConstraintValidatorFactory().getInstance(targetClass);
} else if (foundBeans.size() > 1) {
throw new IllegalStateException(foundBeans.size() + " beans are available for the class: " + targetClass);
}
Bean<ConstraintValidator> constraintValidatorBean = foundBeans.iterator().next();
CreationalContext<ConstraintValidator> creationalContext = beanManager.createCreationalContext(constraintValidatorBean);
return (T) constraintValidatorBean.create(creationalContext);
}Example 8
| Project: beanvalidation-tck-master File: XmlConfiguredConstraintValidatorTest.java View source code |
@Test
@SpecAssertion(section = Sections.CONSTRAINTMETADATA_CONSTRAINTDESCRIPTOR, id = "o")
@SpecAssertion(section = Sections.XML_MAPPING_CONSTRAINTDEFINITION, id = "b")
@SpecAssertion(section = Sections.XML_MAPPING_CONSTRAINTDEFINITION, id = "e")
public <T extends Annotation> void testExcludeExistingValidators() {
Configuration<?> config = TestUtil.getConfigurationUnderTest();
config.addMapping(TestUtil.getInputStreamForPath(packageName + mappingFile1));
Validator validator = config.buildValidatorFactory().getValidator();
PropertyDescriptor propDescriptor = validator.getConstraintsForClass(Name.class).getConstraintsForProperty("name");
Set<ConstraintDescriptor<?>> descriptors = propDescriptor.getConstraintDescriptors();
assertEquals(descriptors.size(), 1, "There should only be one constraint.");
@SuppressWarnings("unchecked") ConstraintDescriptor<T> descriptor = (ConstraintDescriptor<T>) descriptors.iterator().next();
List<Class<? extends ConstraintValidator<T, ?>>> validators = descriptor.getConstraintValidatorClasses();
assertEquals(validators.size(), 0, "No xml defined validator and annotations are ignored -> no validator");
}Example 9
| Project: deltaspike-master File: CDIAwareConstraintValidatorFactory.java View source code |
private synchronized void lazyInit() {
if (releaseInstanceMethodFound != null) {
return;
}
Class<?> currentClass = delegate.getClass();
while (currentClass != null && !Object.class.getName().equals(currentClass.getName())) {
for (Method currentMethod : currentClass.getDeclaredMethods()) {
if (RELEASE_INSTANCE_METHOD_NAME.equals(currentMethod.getName()) && currentMethod.getParameterTypes().length == 1 && currentMethod.getParameterTypes()[0].equals(ConstraintValidator.class)) {
releaseInstanceMethod = currentMethod;
releaseInstanceMethodFound = true;
return;
}
}
currentClass = currentClass.getSuperclass();
}
releaseInstanceMethodFound = false;
}Example 10
| Project: errai-master File: DynamicValidatorBodyGenerator.java View source code |
private MetaClass getConstraintValidatorIface(final MetaClass validator) {
final Optional<MetaClass> ifaceOptional = validator.getAllSuperTypesAndInterfaces().stream().filter( iface -> iface.getFullyQualifiedName().equals(ConstraintValidator.class.getName())).findAny();
if (!ifaceOptional.isPresent()) {
throw new RuntimeException("Tried to generate dynamic validator for type that isn't a ConstraintValidator: " + validator.getFullyQualifiedName());
}
return ifaceOptional.get();
}Example 11
| Project: google-web-toolkit-svnmirror-master File: GwtSpecificValidatorCreator.java View source code |
static <T extends Annotation> Class<?> getTypeOfConstraintValidator(Class<? extends ConstraintValidator<T, ?>> constraintClass) {
for (Method method : constraintClass.getMethods()) {
if (method.getName().equals("isValid") && method.getParameterTypes().length == 2 && method.getReturnType().isAssignableFrom(Boolean.TYPE)) {
return method.getParameterTypes()[0];
}
}
throw new IllegalStateException("ConstraintValidators must have a isValid method");
}Example 12
| Project: gwt-bootstrap-master File: ValidationErrorsActivity.java View source code |
@Override
public ConstraintDescriptor<?> getConstraintDescriptor() {
return new ConstraintDescriptor<NotNull>() {
private NotNull annotation = new NotNull() {
public Class<? extends Annotation> annotationType() {
return NotNull.class;
}
public Class[] groups() {
return new Class[] {};
}
public String message() {
return "{javax.validation.constraints.NotNull.message}";
}
public Class[] payload() {
return new Class[] {};
}
};
@Override
public NotNull getAnnotation() {
return annotation;
}
@Override
public Set<Class<?>> getGroups() {
return new HashSet(Arrays.asList(new Class[] { javax.validation.groups.Default.class }));
}
@Override
public Set<Class<? extends Payload>> getPayload() {
return new HashSet(Arrays.asList(new Class[] {}));
}
@Override
public List<Class<? extends ConstraintValidator<NotNull, ?>>> getConstraintValidatorClasses() {
return null;
}
@Override
public Map<String, Object> getAttributes() {
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("message", "{javax.validation.constraints.NotNull.message}");
attributes.put("payload", new java.lang.Class[] {});
attributes.put("groups", new java.lang.Class[] { javax.validation.groups.Default.class });
return attributes;
}
@Override
public Set<ConstraintDescriptor<?>> getComposingConstraints() {
return null;
}
@Override
public boolean isReportAsSingleViolation() {
return false;
}
};
}Example 13
| Project: java-sproc-wrapper-master File: ValidationExecutorWrapper.java View source code |
private void validateParameters(final InvocationContext invocationContext, final Validator validator, final Object[] originalArgs, final Set<ConstraintViolation<?>> constraintViolations) {
if (originalArgs != null) {
Invokable<?, Object> invokable = Invokable.from(invocationContext.getMethod());
for (int i = 0; i < originalArgs.length; i++) {
Object arg = originalArgs[i];
if (!NOT_NULL_VALIDATOR.isValid(arg, null)) {
// JSR 303 doesn't support method level validation
// we should provide at least a dummy implementation to detect @NotNull annotations
// we should migrate our implementation to bean validation 1.1 when possible
final Parameter parameter = invokable.getParameters().get(i);
final NotNull annotation = parameter.getAnnotation(NotNull.class);
if (annotation != null) {
final String parameterName = "arg" + i;
final ConstraintDescriptor<NotNull> descriptor = new SimpleConstraintDescriptor<NotNull>(annotation, ImmutableSet.<Class<?>>of(Default.class), ImmutableList.<Class<? extends ConstraintValidator<NotNull, ?>>>of(NotNullValidator.class), null);
final ConstraintViolation<Object> violation = new MethodConstraintValidationHolder<Object>(// message
"may not be null", // messageTemplate
annotation.message(), // rootBean
invocationContext.getProxy(), // leafBean (the object the method is executed on)
invocationContext.getProxy(), // propertyPath
SimplePath.createPathForMethodParameter(invocationContext.getMethod(), parameterName), // invalidValue
null, // constraintDescriptor
descriptor, // elementType
ElementType.PARAMETER, // method
invocationContext.getMethod(), // parameterIndex
i, // parameterName
parameterName);
constraintViolations.add(violation);
}
} else {
constraintViolations.addAll(validator.validate(arg));
}
}
}
}Example 14
| Project: scalagwt-gwt-master File: GwtSpecificValidatorCreator.java View source code |
static <T extends Annotation> Class<?> getTypeOfConstraintValidator(Class<? extends ConstraintValidator<T, ?>> constraintClass) {
for (Method method : constraintClass.getMethods()) {
if (method.getName().equals("isValid") && method.getParameterTypes().length == 2 && method.getReturnType().isAssignableFrom(Boolean.TYPE)) {
return method.getParameterTypes()[0];
}
}
throw new IllegalStateException("ConstraintValidators must have a isValid method");
}Example 15
| Project: gwt-bean-validators-master File: GwtSpecificValidatorCreator.java View source code |
/** * Finds the type that a constraint validator will check. * * <p> * This type comes from the first parameter of the isValid() method on the constraint validator. * However, this is a bit tricky because ConstraintValidator has a parameterized type. When using * Java reflection, we will see multiple isValid() methods, including one that checks * java.lang.Object. * </p> * * <p> * Strategy: for now, assume there are at most two isValid() methods. If there are two, assume one * of them has a type that is assignable from the other. (Most likely, one of them will be * java.lang.Object.) * </p> * * @throws IllegalStateException if there isn't any isValid() method or there are more than two. */ static <T extends Annotation> Class<?> getTypeOfConstraintValidator(final Class<? extends ConstraintValidator<T, ?>> constraintClass) { int candidateCount = 0; Class<?> result = null; for (final Method method : constraintClass.getMethods()) { if (method.getName().equals("isValid") && method.getParameterTypes().length == 2 && method.getReturnType().isAssignableFrom(Boolean.TYPE)) { final Class<?> firstArgType = method.getParameterTypes()[0]; if (result == null || result.isAssignableFrom(firstArgType)) { result = firstArgType; } candidateCount++; } } if (candidateCount == 0) { throw new IllegalStateException("ConstraintValidators must have a isValid method"); } else if (candidateCount > 2) { throw new IllegalStateException("ConstraintValidators must have no more than two isValid methods"); } return result; }
Example 16
| Project: gwt-master File: GwtSpecificValidatorCreator.java View source code |
/** * Finds the type that a constraint validator will check. * * <p>This type comes from the first parameter of the isValid() method on * the constraint validator. However, this is a bit tricky because ConstraintValidator * has a parameterized type. When using Java reflection, we will see multiple isValid() * methods, including one that checks java.lang.Object.</p> * * <p>Strategy: for now, assume there are at most two isValid() methods. If there are two, * assume one of them has a type that is assignable from the other. (Most likely, * one of them will be java.lang.Object.)</p> * * @throws IllegalStateException if there isn't any isValid() method or there are more than two. */ static <T extends Annotation> Class<?> getTypeOfConstraintValidator(Class<? extends ConstraintValidator<T, ?>> constraintClass) { int candidateCount = 0; Class<?> result = null; for (Method method : constraintClass.getMethods()) { if (method.getName().equals("isValid") && method.getParameterTypes().length == 2 && method.getReturnType().isAssignableFrom(Boolean.TYPE)) { Class<?> firstArgType = method.getParameterTypes()[0]; if (result == null || result.isAssignableFrom(firstArgType)) { result = firstArgType; } candidateCount++; } } if (candidateCount == 0) { throw new IllegalStateException("ConstraintValidators must have a isValid method"); } else if (candidateCount > 2) { throw new IllegalStateException("ConstraintValidators must have no more than two isValid methods"); } return result; }
Example 17
| Project: gwt-sandbox-master File: GwtSpecificValidatorCreator.java View source code |
/** * Finds the type that a constraint validator will check. * * <p>This type comes from the first parameter of the isValid() method on * the constraint validator. However, this is a bit tricky because ConstraintValidator * has a parameterized type. When using Java reflection, we will see multiple isValid() * methods, including one that checks java.lang.Object.</p> * * <p>Strategy: for now, assume there are at most two isValid() methods. If there are two, * assume one of them has a type that is assignable from the other. (Most likely, * one of them will be java.lang.Object.)</p> * * @throws IllegalStateException if there isn't any isValid() method or there are more than two. */ static <T extends Annotation> Class<?> getTypeOfConstraintValidator(Class<? extends ConstraintValidator<T, ?>> constraintClass) { int candidateCount = 0; Class<?> result = null; for (Method method : constraintClass.getMethods()) { if (method.getName().equals("isValid") && method.getParameterTypes().length == 2 && method.getReturnType().isAssignableFrom(Boolean.TYPE)) { Class<?> firstArgType = method.getParameterTypes()[0]; if (result == null || result.isAssignableFrom(firstArgType)) { result = firstArgType; } candidateCount++; } } if (candidateCount == 0) { throw new IllegalStateException("ConstraintValidators must have a isValid method"); } else if (candidateCount > 2) { throw new IllegalStateException("ConstraintValidators must have no more than two isValid methods"); } return result; }
Example 18
| Project: gwt.svn-master File: GwtSpecificValidatorCreator.java View source code |
/** * Finds the type that a constraint validator will check. * * <p>This type comes from the first parameter of the isValid() method on * the constraint validator. However, this is a bit tricky because ConstraintValidator * has a parameterized type. When using Java reflection, we will see multiple isValid() * methods, including one that checks java.lang.Object.</p> * * <p>Strategy: for now, assume there are at most two isValid() methods. If there are two, * assume one of them has a type that is assignable from the other. (Most likely, * one of them will be java.lang.Object.)</p> * * @throws IllegalStateException if there isn't any isValid() method or there are more than two. */ static <T extends Annotation> Class<?> getTypeOfConstraintValidator(Class<? extends ConstraintValidator<T, ?>> constraintClass) { int candidateCount = 0; Class<?> result = null; for (Method method : constraintClass.getMethods()) { if (method.getName().equals("isValid") && method.getParameterTypes().length == 2 && method.getReturnType().isAssignableFrom(Boolean.TYPE)) { Class<?> firstArgType = method.getParameterTypes()[0]; if (result == null || result.isAssignableFrom(firstArgType)) { result = firstArgType; } candidateCount++; } } if (candidateCount == 0) { throw new IllegalStateException("ConstraintValidators must have a isValid method"); } else if (candidateCount > 2) { throw new IllegalStateException("ConstraintValidators must have no more than two isValid methods"); } return result; }
Example 19
| Project: validator-collection-master File: CommonEachValidator.java View source code |
public boolean isValid(Collection<?> collection, ConstraintValidatorContext context) {
if (collection == null || collection.isEmpty()) {
//nothing to validate here
return true;
}
//do not add wrapper's message
context.disableDefaultConstraintViolation();
int index = 0;
for (Iterator<?> it = collection.iterator(); it.hasNext(); index++) {
Object element = it.next();
ConstraintValidator validator = element != null ? getValidatorInstance(element.getClass()) : getAnyValidatorInstance();
for (ConstraintDescriptor descriptor : descriptors) {
validator.initialize(descriptor.getAnnotation());
if (!validator.isValid(element, context)) {
LOG.debug("Element [{}] = '{}' is invalid according to: {}", index, element, validator.getClass().getName());
// early interpolation hack is needed only for legacy annotations
// and will go away with them
String message = earlyInterpolation ? createInterpolatedMessage(descriptor, element) : readAttribute(descriptor.getAnnotation(), "message", String.class);
addConstraintViolationInIterable(context, message, index);
return false;
}
}
}
return true;
}Example 20
| Project: databene-benerator-master File: DescriptorUtil.java View source code |
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Validator getValidator(String validatorSpec, BeneratorContext context) {
try {
if (StringUtil.isEmpty(validatorSpec))
return null;
Validator result = null;
Expression[] beanExpressions = DatabeneScriptParser.parseBeanSpecList(validatorSpec);
Object[] beans = ExpressionUtil.evaluateAll(beanExpressions, context);
for (Object bean : beans) {
// check validator type
Validator validator;
if (bean instanceof Validator)
validator = (Validator<?>) bean;
else if (bean instanceof ConstraintValidator)
validator = new BeanConstraintValidator((ConstraintValidator) bean);
else
throw new ConfigurationError("Unknown validator type: " + BeanUtil.simpleClassName(bean));
// compose one or more validators
if (// if it is the first or even only validator, simply use it
result == null)
result = validator;
else if (// else compose all validators to an AndValidator
result instanceof AndValidator)
((AndValidator) result).add(validator);
else
result = new AndValidator(result, validator);
}
return result;
} catch (ParseException e) {
throw new ConfigurationError("Invalid validator definition", e);
}
}Example 21
| Project: open-data-service-master File: GuiceConstraintValidatorFactory.java View source code |
@Override
public void releaseInstance(ConstraintValidator<?, ?> instance) {
// not using any caching at the moment
}Example 22
| Project: moonshine-master File: GuiceConstraintValidatorFactory.java View source code |
@Override
public void releaseInstance(ConstraintValidator<?, ?> cv) {
}Example 23
| Project: ovirt-engine-master File: NetworkLabelFormatConstraint.java View source code |
@Override
public void initialize(ValidNetworkLabelFormat constraintAnnotation) {
// Unimplemented method, required for interface ConstraintValidator
}Example 24
| Project: guice-validator-master File: GuiceConstraintValidatorFactory.java View source code |
@Override
public void releaseInstance(final ConstraintValidator<?, ?> instance) {
/* Garbage collector will do it */
}Example 25
| Project: capedwarf-green-master File: SimpleConstraintDescriptor.java View source code |
@SuppressWarnings({ "unchecked" })
public List<Class<? extends ConstraintValidator<T, ?>>> getConstraintValidatorClasses() {
return new ArrayList(factory.getConstraintValidatorClasses());
}Example 26
| Project: cloudbreak-master File: NetworkConfigurationValidatorTest.java View source code |
@Override
public List<Class<? extends ConstraintValidator<DummyAnnotation, ?>>> getConstraintValidatorClasses() {
return new ArrayList<>();
}Example 27
| Project: Repository-master File: GuiceConstraintValidatorFactory.java View source code |
@Override
public void releaseInstance(final ConstraintValidator<?, ?> instance) {
// empty
}Example 28
| Project: spring-framework-master File: SpringConstraintValidatorFactory.java View source code |
// Bean Validation 1.1 releaseInstance method
public void releaseInstance(ConstraintValidator<?, ?> instance) {
this.beanFactory.destroyBean(instance);
}Example 29
| Project: camel-master File: BeanValidatorConfigurationTest.java View source code |
@Override
public void releaseInstance(ConstraintValidator<?, ?> arg0) {
// noop
}Example 30
| Project: FXForm2-master File: NotAdaptableConstraintDescriptor.java View source code |
@Override
public List<Class<? extends ConstraintValidator>> getConstraintValidatorClasses() {
return Collections.emptyList();
}Example 31
| Project: jersey-master File: InjectingConstraintValidatorFactory.java View source code |
@Override
public void releaseInstance(final ConstraintValidator<?, ?> instance) {
// NOOP
}Example 32
| Project: wildfly-master File: BootStrapValidationTestCase.java View source code |
@Override
public void releaseInstance(ConstraintValidator<?, ?> instance) {
delegate.releaseInstance(instance);
}Example 33
| Project: spring4-showcase-master File: ConstraintDescriptorImpl.java View source code |
@Override
public List<Class<? extends ConstraintValidator<T, ?>>> getConstraintValidatorClasses() {
return constraintValidatorClasses;
}