How do I write PMD rule which will search for javax.validation.constraints.NotNull
annotation and validate if it has message attribute?
Bad:
@NotNull
private int value;
Good
@NotNull(message = "value cannot be null.")
private int value;
Main concern for me is that this annotation can be placed basicaly anywhere
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
Here's the xpath query to find NotNull annotations without a message:
//Annotation[*/Name/@Image = 'NotNull' and not(.//MemberValuePair/@Image = 'message')]
I've tested all cases except for ANNOTATION_TYPE, which I'm not sure how to test in the PMD builder app.
If you want all javax.validation.constraints
I've come up with this:
//Annotation[*/Name/@Image = tokenize(replace(string-join(//ImportDeclaration/Name/@Image[starts-with(., "javax.validation.constraints.")], "|"), "javax.validation.constraints.", ""), '[|]') and not(.//MemberValuePair/@Image = 'message')]
So: take all imports that start with javax.validation.constraints.
, convert to string with string-join
, remove javax.validation.constraints.
with replace
and split back into a set of values with tokenize
.