jdaugherty commented on code in PR #16624: URL: https://github.com/apache/grails-core/pull/16624#discussion_r4350655154
########## grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/validation/jakarta/JakartaConstraintsTranslator.groovy: ########## @@ -0,0 +1,508 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.grails.datastore.gorm.validation.jakarta + +import java.lang.annotation.Annotation +import java.math.RoundingMode + +import groovy.transform.CompileStatic +import groovy.util.logging.Slf4j + +import jakarta.validation.GroupSequence +import jakarta.validation.constraints.AssertFalse +import jakarta.validation.constraints.AssertTrue +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.Negative +import jakarta.validation.constraints.NegativeOrZero +import jakarta.validation.constraints.NotBlank +import jakarta.validation.constraints.NotEmpty +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Null +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Positive +import jakarta.validation.constraints.PositiveOrZero +import jakarta.validation.constraints.Size +import jakarta.validation.groups.Default +import jakarta.validation.metadata.BeanDescriptor +import jakarta.validation.metadata.ConstraintDescriptor +import jakarta.validation.metadata.PropertyDescriptor + +import org.springframework.context.support.StaticMessageSource +import org.springframework.util.ClassUtils +import org.springframework.util.ReflectionUtils + +import grails.gorm.validation.ConstrainedProperty +import grails.gorm.validation.DefaultConstrainedProperty +import grails.gorm.validation.exceptions.ValidationConfigurationException +import org.grails.datastore.gorm.validation.constraints.registry.ConstraintRegistry +import org.grails.datastore.gorm.validation.constraints.registry.DefaultConstraintRegistry +import org.grails.datastore.mapping.reflect.ClassPropertyFetcher + +/** + * Describes the Jakarta Bean Validation constraints of a class in terms of GORM constraints, so that the constraint + * metadata of an entity annotated with them ({@link grails.gorm.validation.ConstrainedEntity}) reflects the + * annotations as well as the {@code constraints} block. The annotations themselves are still validated by Bean + * Validation, the translated constraints only describe them: a property annotated with {@code @NotNull} reports + * {@code nullable == false}, one annotated with {@code @Size(max = 10)} reports {@code maxSize == 10}, and so on. + * <p> + * The constraints are read from the {@link BeanDescriptor} of the class, as the Bean Validation provider sees them: + * a composed constraint is described through the constraints composing it, with its attribute overrides applied, + * and only the constraints of the default group of the class are described, as {@code validate()} validates no + * other group. A constraint on a getter without a backing field, such as a cross field {@code @AssertTrue}, is + * validated but not described, unless the {@code constraints} block constrains the property. Annotations without + * a GORM equivalent (such as {@code @Past}, {@code @Digits} or custom constraints) are left out. + * + * @since 8.0.1 + */ +@Slf4j +@CompileStatic +class JakartaConstraintsTranslator { + + /** + * The descriptor of the class + */ + final BeanDescriptor beanDescriptor + + /** + * The constraints of the default group by property name, the properties without any left out + */ + final Map<String, List<ConstraintDescriptor<?>>> constraintDescriptors + + /** + * @param beanDescriptor The descriptor of the class, from {@link jakarta.validation.Validator#getConstraintsForClass} + */ + JakartaConstraintsTranslator(BeanDescriptor beanDescriptor) { + this.beanDescriptor = beanDescriptor + this.constraintDescriptors = Collections.unmodifiableMap(findConstraintDescriptors(beanDescriptor)) + } + + /** + * @return The described class + */ + Class<?> getBeanClass() { + return beanDescriptor.elementClass + } + + private static Map<String, List<ConstraintDescriptor<?>>> findConstraintDescriptors(BeanDescriptor beanDescriptor) { + Set<Class<?>> defaultGroups = defaultGroupsOf(beanDescriptor.elementClass) + Map<String, List<ConstraintDescriptor<?>>> result = new LinkedHashMap<>() + List<PropertyDescriptor> properties = beanDescriptor.constrainedProperties.toSorted { PropertyDescriptor a, PropertyDescriptor b -> + a.propertyName <=> b.propertyName + } + for (PropertyDescriptor property in properties) { + Collection<ConstraintDescriptor<?>> descriptors = property.constraintDescriptors.findAll { ConstraintDescriptor<?> descriptor -> Review Comment: Fixed in 74cebef5fc ([diff against d4f19e4a3f](https://github.com/apache/grails-core/compare/d4f19e4a3f..74cebef5fc)). Before filtering, the translator now expands the redefined default sequence the way Hibernate Validator does. Each group of the sequence brings the groups it extends, recursively. A nested `@GroupSequence` brings its own groups. The class itself stands for `Default`. I didn't use `ConstraintFinder.unorderedAndMatchingGroups(Default)` for this. It handles inherited groups, but it skips a nested sequence inside the redefined default sequence, because it reads only the group iterator of the validation order. Regressions: - **TCK `BeanValidationSpec`** (run locally on Hibernate 5, Hibernate 7 and MongoDB): `BeanValidatedArticle` has `@GroupSequence([DraftChecks, BeanValidatedArticle])` with `DraftChecks extends ContentChecks`. It declares `@NotNull(groups = ContentChecks) String title` with `title nullable: false` in the block, and `@Size(max = 5, groups = ContentChecks) String slug`. A null title is now reported once, as `NotNull`; before the fix it was reported twice, as `nullable` and `NotNull`. The constraints now report `nullable: false` and `maxSize: 5`. - **`JakartaConstraintsTranslatorSpec`**: covers your `@Null(groups = ParentChecks)` case with `ChildChecks extends ParentChecks`, plus a group reached through a nested sequence. The spec first asserts that the provider itself runs those constraints. It then asserts that the translator describes the same constraints and relaxes the block's `nullable: false` for the `@Null`. All three tests fail without the translator change. The guide now says that when a class redefines its default group, the default group also includes the groups that the sequence's groups extend and the groups of a nested sequence. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
