javax.validation.ConstraintValidator Java Examples

The following examples show how to use javax.validation.ConstraintValidator. 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: ValidationPlugin.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected InitState initialize(InitContext initContext) {
    if (isValidationEnabled()) {
        for (Class<?> candidate : initContext.scannedTypesByPredicate()
                .get(ConstraintValidatorPredicate.INSTANCE)) {
            if (ConstraintValidator.class.isAssignableFrom(candidate)) {
                LOGGER.debug("Detected constraint validator {}", candidate.getCanonicalName());
                constraintValidators.add(candidate.asSubclass(ConstraintValidator.class));
            }
        }
        LOGGER.info("Bean validation is enabled at level {}", level);
    } else {
        LOGGER.info("Bean validation is disabled");
    }
    return InitState.INITIALIZED;
}
 
Example #2
Source File: CDIAwareConstraintValidatorFactory.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
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 #3
Source File: EntitySanitizerBuilder.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public EntitySanitizerBuilder addValidatorFactory(Function<Class<?>, Optional<ConstraintValidator<?, ?>>> newValidatorFactory) {
    Function<Class<?>, Optional<ConstraintValidator<?, ?>>> previous = applicationValidatorFactory;
    this.applicationValidatorFactory = type -> {
        Optional<ConstraintValidator<?, ?>> result = previous.apply(type);
        if (!result.isPresent()) {
            return newValidatorFactory.apply(type);
        }
        return result;
    };
    return this;
}
 
Example #4
Source File: ConstraintValidatorFactoryWrapper.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public void releaseInstance(ConstraintValidator<?, ?> instance) {
    if (instance instanceof SpELFieldValidator || instance instanceof SpELClassValidator) {
        return;
    }
    delegate.releaseInstance(instance);
}
 
Example #5
Source File: ConstraintValidatorFactoryWrapper.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
    if (key == SpELClassValidator.class) {
        return (T) new SpELClassValidator(verifierMode, spelContextFactory);
    }
    if (key == SpELFieldValidator.class) {
        return (T) new SpELFieldValidator(verifierMode, spelContextFactory);
    }
    ConstraintValidator<?, ?> instance = applicationConstraintValidatorFactory.apply(key).orElseGet(() -> delegate.getInstance(key));
    return (T) instance;
}
 
Example #6
Source File: ConstraintValidatorFactoryWrapper.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public ConstraintValidatorFactoryWrapper(VerifierMode verifierMode,
                                         Function<Class<?>, Optional<ConstraintValidator<?, ?>>> applicationConstraintValidatorFactory,
                                         Supplier<EvaluationContext> spelContextFactory) {
    this.verifierMode = verifierMode;
    this.applicationConstraintValidatorFactory = applicationConstraintValidatorFactory;
    this.spelContextFactory = spelContextFactory;
    this.delegate = new ConstraintValidatorFactoryImpl();
}
 
Example #7
Source File: DefaultEntitySanitizer.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public DefaultEntitySanitizer(VerifierMode verifierMode,
                              List<Function<Object, Optional<Object>>> sanitizers,
                              boolean annotationSanitizersEnabled,
                              boolean stdValueSanitizersEnabled,
                              Function<Class<?>, Boolean> includesPredicate,
                              Function<String, Optional<Object>> templateResolver,
                              Map<String, Method> registeredFunctions,
                              Map<String, Object> registeredBeans,
                              Function<Class<?>, Optional<ConstraintValidator<?, ?>>> applicationValidatorFactory) {

    Supplier<EvaluationContext> spelContextFactory = () -> {
        StandardEvaluationContext context = new StandardEvaluationContext();
        registeredFunctions.forEach(context::registerFunction);
        context.setBeanResolver((ctx, beanName) -> registeredBeans.get(beanName));
        context.setMethodResolvers(Collections.singletonList(new ReflectiveMethodResolver()));
        return context;
    };

    this.validator = Validation.buildDefaultValidatorFactory()
            .usingContext()
            .constraintValidatorFactory(new ConstraintValidatorFactoryWrapper(verifierMode, applicationValidatorFactory, spelContextFactory))
            .messageInterpolator(new SpELMessageInterpolator(spelContextFactory))
            .getValidator();

    List<Function<Object, Optional<Object>>> allSanitizers = new ArrayList<>();
    if (annotationSanitizersEnabled) {
        allSanitizers.add(new AnnotationBasedSanitizer(spelContextFactory.get(), includesPredicate));
    }
    if (stdValueSanitizersEnabled) {
        allSanitizers.add(new StdValueSanitizer(includesPredicate));
    }
    allSanitizers.add(new TemplateSanitizer(templateResolver, includesPredicate));
    allSanitizers.addAll(sanitizers);
    this.sanitizers = allSanitizers;
}
 
Example #8
Source File: SeedConstraintValidatorFactory.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
    if (key.getName().startsWith("org.hibernate.validator")) {
        // Hibernate constraint validators are instantiated directly (no injection possible nor needed)
        return Classes.instantiateDefault(key);
    } else {
        try {
            return injector.getInstance(key);
        } catch (ProvisionException e) {
            LOGGER.warn("Constraint validator {} was not detected by SeedStack and is not injectable",
                    key.getName());
            return Classes.instantiateDefault(key);
        }
    }
}
 
Example #9
Source File: ConstraintValidatorPredicate.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public boolean test(Class<?> candidate) {
    return ClassPredicates.classIsAssignableFrom(ConstraintValidator.class)
            .and(ClassPredicates.classIsInterface().negate())
            .and(ClassPredicates.classModifierIs(Modifier.ABSTRACT).negate())
            .test(candidate);
}
 
Example #10
Source File: BeanConstraintValidatorFactory.java    From cm_ext with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
  try {
    String beanName = getBeanName(key);
    if (!beanFactory.isPrototype(beanName)) {
      String msg = "Bean [%s] must be of prototype scope.";
      throw new IllegalArgumentException(String.format(msg, beanName));
    }
    return beanFactory.getBean(beanName, key);
  } catch (NoSuchElementException e) {
    // The factory does not know about the bean it creates it.
    return beanFactory.createBean(key);
  }
}
 
Example #11
Source File: NoDuplicateValidatorTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings( "unchecked" )
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
    if (key == NotNullValidator.class) {
        return (T) new NotNullValidator();
    } else if (key == NoDuplicateIntegrationValidator.class) {
        return (T) noDupIntValidator;
    } else if (key == NoDuplicateExtensionValidator.class) {
        return (T) noDupExtValidator;
    }

    throw new UnsupportedOperationException();
}
 
Example #12
Source File: GuiceConstraintValidatorFactory.java    From guice-validator with MIT License 5 votes vote down vote up
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(final Class<T> key) {
    /* By default, all beans are in prototype scope, so new instance will be obtained each time.
     Validator implementer may declare it as singleton and manually maintain internal state
     (to re-use validators and simplify life for GC) */
    return injector.getInstance(key);
}
 
Example #13
Source File: CustomConfigurationViaBeansTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
    try {
        return key.getConstructor().newInstance();
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
            | NoSuchMethodException | SecurityException e) {
        throw new ValidationException("Unable to create constraint validator instance", e);
    }
}
 
Example #14
Source File: ArcConstraintValidatorFactoryImpl.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void releaseInstance(ConstraintValidator<?, ?> instance) {
    InstanceHandle<?> destroyableHandle = destroyableConstraintValidators.remove(instance);
    if (destroyableHandle != null) {
        destroyableHandle.destroy();
    }
}
 
Example #15
Source File: CDIAwareConstraintValidatorFactory.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
public void releaseInstance(ConstraintValidator<?, ?> constraintValidator)
{
    if (releaseInstanceMethodFound == null)
    {
        lazyInit();
    }
    if (Boolean.TRUE.equals(releaseInstanceMethodFound))
    {
        ReflectionUtils.invokeMethod(this.delegate, releaseInstanceMethod, Void.class, true, constraintValidator);
    }
}
 
Example #16
Source File: CDIAwareConstraintValidatorFactory.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> validatorClass)
{
    T resolvedInst = BeanProvider.getContextualReference(validatorClass, true);
    if (resolvedInst == null)
    {
        if (log.isLoggable(Level.CONFIG))
        {
            log.config("No contextual instances found for class " + validatorClass.getCanonicalName() +
                     " delegating to DefaultProvider behavior.");
        }
        resolvedInst = this.delegate.getInstance(validatorClass);
    }
    return resolvedInst;
}
 
Example #17
Source File: NetworkConfigurationValidatorTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public List<Class<? extends ConstraintValidator<DummyAnnotation, ?>>> getConstraintValidatorClasses() {
    return Collections.emptyList();
}
 
Example #18
Source File: GuiceConstraintValidatorFactory.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void releaseInstance(final ConstraintValidator<?, ?> instance) {
  // empty
}
 
Example #19
Source File: InjectingConstraintValidatorFactory.java    From pay-publicapi with MIT License 4 votes vote down vote up
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
    return injector.getInstance(key);
}
 
Example #20
Source File: InjectingConstraintValidatorFactory.java    From pay-publicapi with MIT License 4 votes vote down vote up
@Override
public void releaseInstance(ConstraintValidator<?, ?> instance) {
}
 
Example #21
Source File: MockConstraintViolation.java    From lastaflute with Apache License 2.0 4 votes vote down vote up
@Required
@Override
public ConstraintDescriptor<?> getConstraintDescriptor() {
    String methodName = "getConstraintDescriptor";
    Method method;
    try {
        method = MockConstraintViolation.class.getMethod(methodName, new Class<?>[] {});
    } catch (NoSuchMethodException | SecurityException e) {
        throw new IllegalStateException("Failed to get the method: " + methodName, e);
    }
    Required annotation = method.getAnnotation(Required.class);
    return new ConstraintDescriptor<Annotation>() {

        @Override
        public Annotation getAnnotation() {
            return annotation;
        }

        @Override
        public String getMessageTemplate() {
            return null;
        }

        @Override
        public Set<Class<?>> getGroups() {
            return DfCollectionUtil.newHashSet(ClientError.class);
        }

        @Override
        public Set<Class<? extends Payload>> getPayload() {
            return null;
        }

        @Override
        public ConstraintTarget getValidationAppliesTo() {
            return null;
        }

        @Override
        public List<Class<? extends ConstraintValidator<Annotation, ?>>> getConstraintValidatorClasses() {
            return null;
        }

        @Override
        public Map<String, Object> getAttributes() {
            return null;
        }

        @Override
        public Set<ConstraintDescriptor<?>> getComposingConstraints() {
            return null;
        }

        @Override
        public boolean isReportAsSingleViolation() {
            return false;
        }

        @Override
        public ValidateUnwrappedValue getValueUnwrapping() {
            return null;
        }

        @Override
        public <U> U unwrap(Class<U> type) {
            return null;
        }
    };
}
 
Example #22
Source File: SpringConstraintValidatorFactory.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
	return this.beanFactory.createBean(key);
}
 
Example #23
Source File: UpdateStackRequestValidatorTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public List<Class<? extends ConstraintValidator<DummyAnnotation, ?>>> getConstraintValidatorClasses() {
    return Collections.emptyList();
}
 
Example #24
Source File: AbstractValidatorTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public List<Class<? extends ConstraintValidator<DummyAnnotation, ?>>> getConstraintValidatorClasses() {
    return Collections.emptyList();
}
 
Example #25
Source File: SeedConstraintValidatorFactory.java    From seed with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void releaseInstance(ConstraintValidator<?, ?> instance) {
    // nothing to do
}
 
Example #26
Source File: ValidationModule.java    From seed with Mozilla Public License 2.0 4 votes vote down vote up
ValidationModule(ValidationManager.ValidationLevel level,
        Set<Class<? extends ConstraintValidator>> constraintValidators) {
    this.level = level;
    this.constraintValidators = constraintValidators;
}
 
Example #27
Source File: GuiceConstraintValidatorFactory.java    From guice-validator with MIT License 4 votes vote down vote up
@Override
public void releaseInstance(final ConstraintValidator<?, ?> instance) {
    /* Garbage collector will do it */
}
 
Example #28
Source File: BeanConstraintValidatorFactory.java    From cm_ext with Apache License 2.0 4 votes vote down vote up
@Override
public void releaseInstance(ConstraintValidator <?, ?> instance) {
  String beanName = getBeanName(instance.getClass());
  beanFactory.destroyBean(beanName, instance);
}
 
Example #29
Source File: T212MapFieldValidator.java    From hj-t212-parser with Apache License 2.0 4 votes vote down vote up
public T212MapFieldValidator(ConstraintValidator<AF, String> constraintValidator) {
    super(constraintValidator);
}
 
Example #30
Source File: SpringConstraintValidatorFactory.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public void releaseInstance(ConstraintValidator<?, ?> instance) {
	this.beanFactory.destroyBean(instance);
}