I am new to Java and play. going through the sample applications. can you help me understand what it is going on in this file. https://github.com/playframework/Play20/blob/master/samples/java/forms/app/models/User.java
I don't understand why we declare this interface "public interface All {}" and how it is being used in this validation. "#Required(groups = {All.class, Step1.class})"
#Required is a custom JSR-303 annotation, created within the Play framework. JSR-303 is a specification for validation of Javabeans, which allows for ensuring that a given Java bean's values fall within a set of constraints. Examples of some standard validation annotations:
#Max - The annotated element must be a number whose value must be lower or equal to the specified maximum.
#Min - The annotated element must be a number whose value must be higher or equal to the specified minimum.
#NotNull - The annotated element must not be null.
Each JSR-303 annotation is allowed to define groups, where each group is really just a class. These groups can be used to execute a subset of validations for a given bean. In your particular example, the implementors have defined two interfaces to represent these groups - All and Step1. Then they add the groups to the validation annotations, in order to indicate that those validations belong to the group. So for the below class:
public class MyBean {
#Required(groups = {All.class, Step1.class})
#MinLength(value = 4, groups = {All.class})
public String username;
}
MyBean bean = new MyBean();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
The following will execute the #Required and #MinLength validation for the username field:
validator.validate(bean, All.class);
Whereas the following will execute just the #Required validation (for the username field):
validator.validate(bean, Step1.class);
Related
Is it possible to enable default validation of fields without specifying group?
For example, I have the bean:
class User {
#NotEmpty
private String name;
#NotEmpty(groups = UserGroup.ShouldHaveSurName.class)
private String surname;
}
I want the field "name" to be validated in any case - if the group not specified for #Validated annotation in the controller, or if "ShouldHaveSurName" group specified. I believe there was the configuration for this but can't find it.
From JSR-303 specification:
3.4. Group and group sequence
A group defines a subset of constraints. Instead of validating all
constraints for a given object graph, only a subset is validated. This
subset is defined by the the group or groups targeted. Each constraint
declaration defines the list of groups it belongs to. If no group is
explicitly declared, a constraint belongs to the Default group.
So doing following in controller should suffice:
#Validated({UserGroup.ShouldHaveSurName.class, Default.class})
I am using spring to validate a form. The model for the form is similar to this:
public class FormModel {
#NotBlank
private String name;
#NotNull
#ImageSizeConstraint
private MultipartFile image;
}
The '#ImageSizeConstraint' is a custom constraint. What I want is for the #NotNull to be evaluated first and if this evaluates to false, not to evaluate #ImageSizeConstraint.
If this is not possible, I will have to check for null in the custom constraint as well. Which is not a problem, but I would like to seperate the concerns (not null / image size / image / aspectratio / etc).
You may use constraints grouping and group sequences to define the validation order. According to JSR-303 (part 3.5. Validation routine):
Unless ordered by group sequences, groups can be validated in no
particular order. This implies that the validation routine can be run
for several groups in the same pass.
As Hibernate Validator documentation says:
In order to implement such a validation order you just need to define
an interface and annotate it with #GroupSequence, defining the order
in which the groups have to be validated (see Defining a group
sequence). If at least one constraint fails in a sequenced group, none
of the constraints of the following groups in the sequence get
validated.
First, you have to define constraint groups and apply them to the constraints:
public interface CheckItFirst {}
public interface ThenCheckIt {}
public class FormModel {
#NotBlank
private String name;
#NotNull(groups = CheckItFirst.class)
#ImageSizeConstraint(groups = ThenCheckIt.class)
private MultipartFile image;
}
And then, as constraints are evaluated in no particular order, regardless of which groups they belong to (Default group too), you have to create #GroupSequence for your image field constraints groups.
#GroupSequence({ CheckItFirst.class, ThenCheckIt.class })
public interface OrderedChecks {}
You can test it with
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<FormModel>> constraintViolations =
validator.validate(formModel, OrderedChecks.class);
To apply this validation in Spring MVC Controller methods, you may use the #Validated annotation, which can specify the validation groups for method-level validation:
#PostMapping(value = "/processFormModel")
public String processFormModel(#Validated(OrderedChecks.class) FormModel formModel) {
<...>
}
Easy just return true for isValid if image is null for your custom constraint.
Read the specification of JSR-303, you will see that this is normal behaviour and it makes sense as there is "NotNull".
I have a post method receiving an object as parameter, in this object I have an attribute with annotations #ValidDate and #NotEmpty.
in another method I want to use the same object but I just want annotation #ValidDate on the attribute.
It's possible ?
the attribute :
#NotEmpty
#ValidDate
private String installDate;
the function :
public String findLinksByCriteria(#Valid #ModelAttribute LinkForm link, BindingResult bindingResult, Model uiModel) {
if (bindingResult.hasErrors()) {
return ViewConstants.LINK_SEARCH_VIEW;
}
Probably one of these thing with multiple solutions. You can remove the optional constraint and do it manually however if you want to keep it strictly within the context of the Bean Validation API then you can do it using validation groups.
https://docs.oracle.com/cd/E19798-01/821-1841/gkahp/index.html
Constraints may be added to one or more groups. Constraint groups are
used to create subsets of constraints, so only certain constraints
will be validated for a particular object. By default, all constraints
are included in the Default constraint group.
By using Spring's #Validated annotation rather than #Valid you can specify one or more groups of constraints to be applied for any given case.
There is a detailed example here:
http://blog.codeleak.pl/2014/08/validation-groups-in-spring-mvc.html
I'm new to using Java Bean validation (JSR-303/JSR-349/Hibernate Validator), and understand the general concepts. However, I'm not sure how to validate the contents of an composed type vs the type itself.
For example:
#NotNull
private List<String> myString;
will validate that the List myString is not null, but does nothing for validating the contents of the list itself. Or given other types of validators (Min/Max/etc), how do I validate the individual elements of the List? Is there a generic solution for any composed type?
There is no easy generic solution as of Bean Validation 1.0/1.1. You could implement a custom constraint like #NoNullElements:
#NoNullElements
private List<String> myStrings;
The constraint's validator would iterate over the list and check that no element is null. Another approach is to wrap your String into a more domain-specific type:
public class EmailAddress {
#NotNull
#Email
private String value;
//...
}
And apply cascaded validation to the list via #Valid:
#Valid
private List<EmailAddress> addresses;
Having such a domain-specific data type is often helpful anyways to convey a data element's meaning as it is passed through an application.
In the future a generic solution for the issue may be to use annotations on type parameters as supported by Java 8 but that's only an idea at this point:
private List<#NotNull String> myStrings;
Take a look at validator-collection – it’s very easy to use any Constraint Annotation on a collection of simple types with this library. Also see https://stackoverflow.com/a/16023061/2217862.
Upcoming jsr 380 (bean validation 2.0) will allow to put constraints annotation to argument type.
#Valid
private List<#NotNull String> myString;
For now Bean Validation 1.1 in you can create custom constraints that checks null condition.
Bean Validation 2.0/Hibernate Validator 6.0
Bean Validation 2.0 (of which Hibernate Validator 6.0 is the reference implementation) allows using its validation annotations directly on generic type arguments. This is noted in the Hibernate 6.0 release documentation:
Hibernate Validator 6.0 is the Reference Implementation of the Bean Validation 2.0 specification so it comes with all its new features:
First class support of container element constraints and cascaded validation (think private Map<#Valid #NotNull OrderCategory, List<#Valid #NotNull Order>> orderByCategories;);
If the project is using Java 8 with Bean Validation 2.0, this feature can be used to validate each element of the list:
private List<#NotNull String> myString; // Validate that none of the list items is null
Bean Validation 1.2/Hibernate Validator 5.2
Hibernate 5.2 (with Bean Validation 1.2) added a limited version of the feature to allow validation annotations directly on generic type arguments. However, none of its built-in Bean Validation or Hibernate Validation constraints could be used in this manner, as the annotations do not specify ElementType.TYPE_USE for backwards-compatibility reasons. Additionally, type argument constraints could be specified for map values but not map keys. This is all described in the Hibernate Validator 5.2 documentation:
Starting from Java 8, it is possible to specify constraints directly on the type argument of a parameterized type. However, this requires that ElementType.TYPE_USE is specified via #Target in the constraint definition. To maintain backwards compatibility, built-in Bean Validation as well as Hibernate Validator specific constraints do not yet specify ElementType.TYPE_USE.
[...]
When applying constraints on an Iterable type argument, Hibernate Validator will validate each element.
[...]
Type argument constraints are also validated for map values. Constraints on the key are ignored.
Summary
In summary, if the code is using Java 8 with Bean Validation 2.0 (such as Hibernate Validator 6), the generic list & map type arguments can be annotated:
private List<#NotNull String> myString;
If the code is using Java 8 with Bean Validation 1.2 and Hibernate Validator 5.2, custom validation annotations can be written with TYPE_USE in its definition, and applied to the generic type of the collection or map value:
private List<#MyCustomNotNull String> myString;
If the code is not using Java 8 or is on a version of Hibernate Validator prior to 5.2, a custom constraint could be written which verifies every element of a collection or map and applied to the collection or map itself.
#MyCustomNotNullElements
private List<String> myString;
I have a bean like:
#Data
public static class ClassUnderTest {
#NotNull
private String field1;
#NotNull
#Since(2.0)
private String field2;
#NotNull
#Until(3.0)
private String field3;
}
#Since and #Until are Gson annotations that permits to avoid serializing / deserializing some fields on my REST API, for certain API versions.
I perform bean validation on the input payload of this API to raise constraint violations.
I'd like to be able to not raise the same violations per version, based on the Gson annotations (and not groups!).
Is there a way, from a ConstraintViolation<T>, to get the Member (like Method / Field) which produced the violation, so that I check if it is annotated by something?
Is there a way to handle validation versionning with Bean Validation?
The only solution I have seems to retrieve that member from the path (getPropertyPath), but it seems not easy to do...
You could retrieve the property name from the violation via getPropertyPath(). That said, assigning your constraints to groups corresponding to the versions might be the better approach. Note that validation groups can also extend existing groups, this might be helpful to model constraints added in a newer version.