use of javax.validation.valueextraction.ValueExtractor in project micronaut-core by micronaut-projects.
the class DefaultValidator method validateBeanArgument.
@Override
public <T> void validateBeanArgument(@NonNull BeanResolutionContext resolutionContext, @NonNull InjectionPoint injectionPoint, @NonNull Argument<T> argument, int index, @Nullable T value) throws BeanInstantiationException {
final AnnotationMetadata annotationMetadata = argument.getAnnotationMetadata();
final boolean hasValid = annotationMetadata.hasStereotype(Valid.class);
final boolean hasConstraint = annotationMetadata.hasStereotype(Constraint.class);
final Class<T> parameterType = argument.getType();
final Class rootClass = injectionPoint.getDeclaringBean().getBeanType();
DefaultConstraintValidatorContext context = new DefaultConstraintValidatorContext(value);
Set overallViolations = new HashSet<>(5);
if (hasConstraint) {
final Path.Node parentNode = context.addConstructorNode(rootClass.getName(), injectionPoint.getDeclaringBean().getConstructor().getArguments());
ValueExtractor<Object> valueExtractor = (ValueExtractor<Object>) valueExtractorRegistry.findValueExtractor(parameterType).orElse(null);
if (valueExtractor != null) {
valueExtractor.extractValues(value, new ValueExtractor.ValueReceiver() {
@Override
public void value(String nodeName, Object object1) {
}
@Override
public void iterableValue(String nodeName, Object iterableValue) {
if (iterableValue != null && context.validatedObjects.contains(iterableValue)) {
return;
}
cascadeToIterableValue(context, rootClass, null, value, parentNode, argument, iterableValue, overallViolations, null, null, true);
}
@Override
public void indexedValue(String nodeName, int i, Object iterableValue) {
if (iterableValue != null && context.validatedObjects.contains(iterableValue)) {
return;
}
cascadeToIterableValue(context, rootClass, null, value, parentNode, argument, iterableValue, overallViolations, i, null, true);
}
@Override
public void keyedValue(String nodeName, Object key, Object keyedValue) {
if (keyedValue != null && context.validatedObjects.contains(keyedValue)) {
return;
}
cascadeToIterableValue(context, rootClass, null, value, parentNode, argument, keyedValue, overallViolations, null, key, false);
}
});
} else {
validateParameterInternal(rootClass, null, ArrayUtils.EMPTY_OBJECT_ARRAY, context, overallViolations, argument.getName(), parameterType, index, annotationMetadata, value);
}
context.removeLast();
} else if (hasValid && value != null) {
final BeanIntrospection<Object> beanIntrospection = getBeanIntrospection(value, parameterType);
if (beanIntrospection != null) {
try {
context.addParameterNode(argument.getName(), index);
cascadeToOneIntrospection(context, null, value, beanIntrospection, overallViolations);
} finally {
context.removeLast();
}
}
}
failOnError(resolutionContext, overallViolations, rootClass);
}
use of javax.validation.valueextraction.ValueExtractor in project micronaut-core by micronaut-projects.
the class DefaultValidator method validatePropertyInternal.
private <T> void validatePropertyInternal(@Nullable Class<T> rootBeanClass, @Nullable T rootBean, @Nullable Object object, @NonNull DefaultConstraintValidatorContext context, @NonNull Set<ConstraintViolation<Object>> overallViolations, @NonNull Class propertyType, @NonNull AnnotatedElement constrainedProperty, @Nullable Object propertyValue) {
final AnnotationMetadata annotationMetadata = constrainedProperty.getAnnotationMetadata();
final List<Class<? extends Annotation>> constraintTypes = annotationMetadata.getAnnotationTypesByStereotype(Constraint.class);
for (Class<? extends Annotation> constraintType : constraintTypes) {
ValueExtractor<Object> valueExtractor = null;
if (propertyValue != null && !annotationMetadata.hasAnnotation(Valid.class)) {
// noinspection unchecked
valueExtractor = valueExtractorRegistry.findUnwrapValueExtractor((Class<Object>) propertyValue.getClass()).orElse(null);
}
if (valueExtractor != null) {
valueExtractor.extractValues(propertyValue, (SimpleValueReceiver) (nodeName, extractedValue) -> valueConstraintOnProperty(rootBeanClass, rootBean, object, context, overallViolations, constrainedProperty, propertyType, extractedValue, constraintType));
} else {
valueConstraintOnProperty(rootBeanClass, rootBean, object, context, overallViolations, constrainedProperty, propertyType, propertyValue, constraintType);
}
}
}
use of javax.validation.valueextraction.ValueExtractor in project tomee by apache.
the class ValidatorBuilder method getConfig.
@SuppressWarnings("unchecked")
private static Configuration<?> getConfig(final ValidationInfo info) {
Configuration<?> target = null;
final Thread thread = Thread.currentThread();
final ClassLoader classLoader = thread.getContextClassLoader();
String providerClassName = info.providerClassName;
if (providerClassName == null) {
providerClassName = SystemInstance.get().getOptions().get(VALIDATION_PROVIDER_KEY, (String) null);
}
if (providerClassName != null) {
try {
@SuppressWarnings({ "unchecked", "rawtypes" }) final Class clazz = classLoader.loadClass(providerClassName);
target = Validation.byProvider(clazz).configure();
logger.info("Using " + providerClassName + " as validation provider.");
} catch (final ClassNotFoundException e) {
logger.warning("Unable to load provider class " + providerClassName, e);
} catch (final ValidationException ve) {
logger.warning("Unable create validator factory with provider " + providerClassName + " (" + ve.getMessage() + ")." + " Default one will be used.");
}
}
if (target == null) {
// force to use container provider to ignore any conflicting configuration
thread.setContextClassLoader(ValidatorBuilder.class.getClassLoader());
target = Validation.byDefaultProvider().configure();
thread.setContextClassLoader(classLoader);
}
final Set<ExecutableType> types = EnumSet.noneOf(ExecutableType.class);
for (final String type : info.validatedTypes) {
types.add(ExecutableType.valueOf(type));
}
final Map<String, String> props = new HashMap<>();
for (final Map.Entry<Object, Object> entry : info.propertyTypes.entrySet()) {
final PropertyType property = new PropertyType();
property.setName((String) entry.getKey());
property.setValue((String) entry.getValue());
props.put(property.getName(), property.getValue());
if (logger.isDebugEnabled()) {
logger.debug("Found property '" + property.getName() + "' with value '" + property.getValue());
}
target.addProperty(property.getName(), property.getValue());
}
final OpenEjbBootstrapConfig bootstrapConfig = new OpenEjbBootstrapConfig(providerClassName, info.constraintFactoryClass, info.messageInterpolatorClass, info.traversableResolverClass, info.parameterNameProviderClass, new LinkedHashSet<>(info.constraintMappings), info.executableValidationEnabled, types, props, info.clockProviderClassName, info.valueExtractorClassNames == null ? null : new LinkedHashSet<>(info.valueExtractorClassNames));
final OpenEjbConfig config = new OpenEjbConfig(bootstrapConfig, target);
target.ignoreXmlConfiguration();
final String messageInterpolatorClass = info.messageInterpolatorClass;
if (messageInterpolatorClass != null) {
try {
@SuppressWarnings("unchecked") final Class<MessageInterpolator> clazz = (Class<MessageInterpolator>) classLoader.loadClass(messageInterpolatorClass);
target.messageInterpolator(newInstance(config, clazz));
logger.info("Using " + messageInterpolatorClass + " as message interpolator.");
} catch (final Exception e) {
logger.warning("Unable to set " + messageInterpolatorClass + " as message interpolator.", e);
}
}
final String traversableResolverClass = info.traversableResolverClass;
if (traversableResolverClass != null) {
try {
@SuppressWarnings("unchecked") final Class<TraversableResolver> clazz = (Class<TraversableResolver>) classLoader.loadClass(traversableResolverClass);
target.traversableResolver(newInstance(config, clazz));
logger.info("Using " + traversableResolverClass + " as traversable resolver.");
} catch (final Exception e) {
logger.warning("Unable to set " + traversableResolverClass + " as traversable resolver.", e);
}
}
final String constraintFactoryClass = info.constraintFactoryClass;
if (constraintFactoryClass != null) {
try {
@SuppressWarnings("unchecked") final Class<ConstraintValidatorFactory> clazz = (Class<ConstraintValidatorFactory>) classLoader.loadClass(constraintFactoryClass);
target.constraintValidatorFactory(newInstance(config, clazz));
} catch (final Exception e) {
logger.warning("Unable to set " + constraintFactoryClass + " as constraint factory.", e);
}
logger.info("Using " + constraintFactoryClass + " as constraint factory.");
}
for (final String mappingFileName : info.constraintMappings) {
if (logger.isDebugEnabled()) {
logger.debug("Opening input stream for " + mappingFileName);
}
final InputStream in = classLoader.getResourceAsStream(mappingFileName);
if (in == null) {
logger.warning("Unable to open input stream for mapping file " + mappingFileName + ". It will be ignored");
} else {
target.addMapping(in);
}
}
if (info.parameterNameProviderClass != null) {
try {
final Class<ParameterNameProvider> clazz = (Class<ParameterNameProvider>) classLoader.loadClass(info.parameterNameProviderClass);
target.parameterNameProvider(newInstance(config, clazz));
logger.info("Using " + info.parameterNameProviderClass + " as parameter name provider.");
} catch (final Exception e) {
logger.warning("Unable to set " + info.parameterNameProviderClass + " as parameter name provider.", e);
}
}
if (info.valueExtractorClassNames != null) {
try {
info.valueExtractorClassNames.stream().map(it -> {
try {
return (ValueExtractor<?>) newInstance(config, classLoader.loadClass(it));
} catch (final Exception e) {
logger.warning("Unable to load " + it, e);
return null;
}
}).filter(Objects::nonNull).forEach(target::addValueExtractor);
logger.info("Using " + info.valueExtractorClassNames + " value extractors.");
} catch (final Exception e) {
logger.warning("Unable to set " + info.valueExtractorClassNames + " as parameter name provider.", e);
}
}
if (info.clockProviderClassName != null) {
try {
final Class<ClockProvider> clazz = (Class<ClockProvider>) classLoader.loadClass(info.clockProviderClassName);
target.clockProvider(newInstance(config, clazz));
logger.info("Using " + info.clockProviderClassName + " as clock provider.");
} catch (final Exception e) {
logger.warning("Unable to set " + info.clockProviderClassName + " as clock provider.", e);
}
}
return config;
}
use of javax.validation.valueextraction.ValueExtractor in project micronaut-core by micronaut-projects.
the class DefaultValidator method validateParametersInternal.
private <T> void validateParametersInternal(@NonNull Class<T> rootClass, @Nullable T object, @NonNull Object[] parameters, Argument[] arguments, int argLen, DefaultConstraintValidatorContext context, Set overallViolations, Path.Node parentNode) {
for (int i = 0; i < argLen; i++) {
Argument argument = arguments[i];
final Class<?> parameterType = argument.getType();
final AnnotationMetadata annotationMetadata = argument.getAnnotationMetadata();
final boolean hasValid = annotationMetadata.hasStereotype(Validator.ANN_VALID);
final boolean hasConstraint = annotationMetadata.hasStereotype(Validator.ANN_CONSTRAINT);
if (!hasValid && !hasConstraint) {
continue;
}
Object parameterValue = parameters[i];
ValueExtractor<Object> valueExtractor = null;
final boolean hasValue = parameterValue != null;
final boolean isValid = hasValue && hasValid;
final boolean isPublisher = hasValue && Publishers.isConvertibleToPublisher(parameterType);
if (isPublisher) {
instrumentPublisherArgumentWithValidation(rootClass, object, parameters, context, i, argument, parameterType, annotationMetadata, parameterValue, isValid);
} else {
final boolean isCompletionStage = hasValue && CompletionStage.class.isAssignableFrom(parameterType);
if (isCompletionStage) {
instrumentCompletionStageArgumentWithValidation(rootClass, object, parameters, context, i, argument, annotationMetadata, parameterValue, isValid);
} else {
if (hasValue) {
// noinspection unchecked
valueExtractor = (ValueExtractor<Object>) valueExtractorRegistry.findUnwrapValueExtractor(parameterType).orElse(null);
}
int finalIndex = i;
if (valueExtractor != null) {
valueExtractor.extractValues(parameterValue, (SimpleValueReceiver) (nodeName, unwrappedValue) -> validateParameterInternal(rootClass, object, parameters, context, overallViolations, argument.getName(), unwrappedValue == null ? Object.class : unwrappedValue.getClass(), finalIndex, annotationMetadata, unwrappedValue));
} else {
validateParameterInternal(rootClass, object, parameters, context, overallViolations, argument.getName(), parameterType, finalIndex, annotationMetadata, parameterValue);
}
if (isValid) {
if (context.validatedObjects.contains(parameterValue)) {
// already validated
continue;
}
// cascade to bean
// noinspection unchecked
valueExtractor = (ValueExtractor<Object>) valueExtractorRegistry.findValueExtractor(parameterType).orElse(null);
if (valueExtractor != null) {
valueExtractor.extractValues(parameterValue, new ValueExtractor.ValueReceiver() {
@Override
public void value(String nodeName, Object object1) {
}
@Override
public void iterableValue(String nodeName, Object iterableValue) {
if (iterableValue != null && context.validatedObjects.contains(iterableValue)) {
return;
}
cascadeToIterableValue(context, rootClass, object, parameterValue, parentNode, argument, iterableValue, overallViolations, null, null, true);
}
@Override
public void indexedValue(String nodeName, int i, Object iterableValue) {
if (iterableValue != null && context.validatedObjects.contains(iterableValue)) {
return;
}
cascadeToIterableValue(context, rootClass, object, parameterValue, parentNode, argument, iterableValue, overallViolations, i, null, true);
}
@Override
public void keyedValue(String nodeName, Object key, Object keyedValue) {
if (keyedValue != null && context.validatedObjects.contains(keyedValue)) {
return;
}
cascadeToIterableValue(context, rootClass, object, parameterValue, parentNode, argument, keyedValue, overallViolations, null, key, false);
}
});
} else {
final BeanIntrospection<Object> beanIntrospection = getBeanIntrospection(parameterValue, parameterType);
if (beanIntrospection != null) {
try {
context.addParameterNode(argument.getName(), i);
cascadeToOneIntrospection(context, object, parameterValue, beanIntrospection, overallViolations);
} finally {
context.removeLast();
}
} else {
context.addParameterNode(argument.getName(), i);
overallViolations.add(createIntrospectionConstraintViolation(rootClass, object, context, parameterType, parameterValue, parameters));
context.removeLast();
}
}
}
}
}
}
}
Aggregations