Check for a behavior change in the buildValidatorFactory and buildDefaultValidatorFactory methods

This rule flags any use of javax.validation.Validation.buildDefaultValidatorFactory() or Validation.byDefaultProvider().configure().buildValidatorFactory() . The Liberty beanValidation-1.0 and beanValidation-1.1 implementations are provided by Apache Bean Validation. In Java EE 8, the Bean Validation implementation provided by Liberty feature beanValidation-2.0 was changed to Hibernate Validator. The Apache Bean Validation implementation requires an application to create an unmanaged ValidatorFactory object and the ConstraintValidatorFactory returns a CDI managed ConstraintValidator instance. However, Hibernate Validator only supports generating CDI managed ConstraintValidator objects with a default ValidatorFactory provided by the server runtime. This server managed ValidatorFactory can be obtained through the use of @Resource , @Inject , or direct JNDI lookup.

Applications could see a change in behavior when using javax.validation.Validation.buildDefaultValidatorFactory() or Validation.byDefaultProvider().configure().buildValidatorFactory() . Note that other customization methods may be called before buildValidatorFactory() is invoked, such as messageInterpolator() , traversableResolver() , parameterNameProvider() , or constraintValidatorFactory() .

In summary, users that expect the objects returned by ConstraintValidatorFactory to be CDI managed will need to implement changes to their existing Bean Validation code.

The following code is an example of Bean Validation usage that should be refactored:


//Original application behavior
Validator validator = Validation.byDefaultProvider().configure().messageInterpolator(messageResourceInterpolator).buildValidatorFactory().getValidator();

The following code shows the fix for the problematic code:


//Recommended application behavior (potential Automated Fix)
@Inject    //@Resource or a jndi lookup of java:comp/ValidatorFactory could also be used to obtain the container's default ValidatorFactory
ValidatorFactory validatorFactory;
Validator validator =  validatorFactory.usingContext().messageInterpolator(messageResourceInterpolator).getValidator();

For more information on configuring validation in WebSphere Liberty, see the Bean Validation 2.0 documentation.