How to handle multiple combination of Java bean validation in Spring - java

I've use case where I've to validate certain fields with different combination, I'm using javax validation API in my spring. Please find my list of fields String name; String type; String userId; String userAltId; Date userBuyDate; Date userSellDate;
Input param conditions are:
name, type and gender -> Always required field
userId, userAltId -> Either userID or altID should have value or both
can have value
userBuyDate, userSellDate -> If userID or altID is null, then
userBuyDate and userSellDate must have values
Pseudo if condition
if (user.getName().isBlank() || user.getName().isEmpty() &&
user.getType().isEmpty() || user.getType().isBlank() &&
user.getGender().isEmpty() || user.getGender().isBlank()) {
if (user.getUserId().isEmpty() || user.getUserId().isBlank() ||
user.getUserAltId().isEmpty() || user.getUserAltId().isBlank() ||
user.getUserSellDate() == null && user.getUserBuyDate() == null) {
throw new NullPointerException("input validation failed");
} else {
System.out.println("validation success");
}
}
I'm struggling to apply these combination of validation in Java bean using javax validation API, please find my code below. Can someone please help how can I achieve these combination of validation with sample example. In my current code for all the fields I'm using #NotNull annotation, I don't know how to use the combination of optional and required annotation in the Java bean. Any help would be much appreciated. Thanks!
User.java
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.validation.constraints.NotNull;
import java.util.Date;
#Getter
#Setter
#ToString
public class User {
#NotNull(message = "Name cannot be null")
private String name;
#NotNull(message = "Type cannot be null")
private String type;
#NotNull(message = "Gender cannot be null")
private String gender;
#NotNull(message = "User ID cannot be null")
private String userId;
#NotNull(message = "User Alt ID cannot be null")
private String userAltId;
#NotNull(message = "User Buy Date cannot be null")
private Date userBuyDate;
#NotNull(message = "User Sell Date cannot be null")
private Date userSellDate;
}
Test.java
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Date;
import java.util.Set;
public class Test {
public static void main(String[] args) {
User user = new User();
// Always mandatory field
user.setName("test");
user.setType("Admin");
user.setGender("Female");
// Either userID or altID should have value or both can contain value
user.setUserId("U1213");
user.setUserAltId("UA93093");
// If userID or altID is null, then userBuyDate and userSellDate are mandatory
user.setUserSellDate(new Date());
user.setUserBuyDate(new Date());
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(user);
for (ConstraintViolation<User> violation : violations) {
System.out.println(violation.getMessage());
}
/*if (user.getName().isBlank() || user.getName().isEmpty() &&
user.getType().isEmpty() || user.getType().isBlank() &&
user.getGender().isEmpty() || user.getGender().isBlank()) {
if (user.getUserId().isEmpty() || user.getUserId().isBlank() ||
user.getUserAltId().isEmpty() || user.getUserAltId().isBlank() ||
user.getUserSellDate() == null && user.getUserBuyDate() == null) {
throw new NullPointerException("input validation failed");
} else {
System.out.println("validation success");
}
}*/
}
}

In order to achieve this, you need to create your own validation annotation to be applied to your User class as whole.
#Documented
#Constraint(validatedBy = UserValidator.class)
#Target({ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
public #interface ValidUser {
String message() default "Invalid User data.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Mind the #Constraint(validatedBy = UserValidator.class). This means that you now need to implement UserValidator that will in fact validate your User object:
public class UserValidator implements ConstraintValidator<ValidUser, Object> {
#Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
String name = (String) new BeanWrapperImpl(value).getPropertyValue("name");
// Your custom logic here
}
}
Finally, the last thing is to use the custom annotation to your User class:
#Getter
#Setter
#ToString
#ValidUser
public class User {
(...)
}
You could have more advanced annotation that would accept parameters, but I decided to show the simple solution as it seems to me that this is what you need. You can find an example of this at https://www.baeldung.com/spring-mvc-custom-validator#custom-class-level-validation.

Related

What is the best way to Validate one field in Java based on another field using hibernate-validator?

I have a class that consists of many fields and these fields have the hibernate-validator Annotations so if the invalid data enters then it can throw the respective message.
Some of the fields are interdependent meaning the field has to be Non-null if another field has a certain value. Is there a way this can be achieved using the hibernate-validator directly or do we need to write the custom validations for it?
#Data
#ToString
public class Source implements Serializable {
#NotNull(message = "Type cannot be Null for source")
private String type;
//If type has any value apart from "MANUAL" then this should not be NULL #NotNull(message = "groundValue cannot be Null")
private String groundValue;
//If type value is "MANUAL" then this should not be NULL #NotNull(message = "manualType value cannot be Null")
private String manualType;
//If type value is "MANUAL" then this should not be NULL #NotNull(message = "manualURI value cannot be Null")
private String manualURI;
}
As mentioned in the above code snipped if the conditions for groundValue, manualType and manualURI is based on the value provided to the type.
Is it possible to achieve something similar directly using the Javax valdidation? Following is the Maven dependency that I am using in my project:
<!-- For adding the validation annotations -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-validator</artifactId>
</dependency>
Yes you can create your own validator.
package spike;
public interface ISource {
String getType();
String getGroundValue();
String getManualType();
String getManualURI();
}
package spike;
import java.io.Serializable;
import javax.validation.constraints.NotNull;
#SourceType
public class Source implements Serializable, ISource {
#NotNull(message = "Type cannot be Null for source")
private String type;
//If type has any value apart from "MANUAL" then this should not be NULL #NotNull(message = "groundValue cannot be Null")
private String groundValue;
//If type value is "MANUAL" then this should not be NULL #NotNull(message = "manualType value cannot be Null")
private String manualType;
//If type value is "MANUAL" then this should not be NULL #NotNull(message = "manualURI value cannot be Null")
private String manualURI;
#Override
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String getGroundValue() {
return groundValue;
}
public void setGroundValue(String groundValue) {
this.groundValue = groundValue;
}
#Override
public String getManualType() {
return manualType;
}
public void setManualType(String manualType) {
this.manualType = manualType;
}
#Override
public String getManualURI() {
return manualURI;
}
public void setManualURI(String manualURI) {
this.manualURI = manualURI;
}
#Override
public String toString() {
return "Source{" +
"type='" + type + '\'' +
", groundValue='" + groundValue + '\'' +
", manualType='" + manualType + '\'' +
", manualURI='" + manualURI + '\'' +
'}';
}
}
package spike;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
#Constraint(validatedBy = SourceTypeValidator.class)
public #interface SourceType {
String message() default "{SourceTypeError}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
package spike;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class SourceTypeValidator implements ConstraintValidator<SourceType, ISource> {
private String message;
#Override
public void initialize(SourceType constraintAnnotation) {
message = constraintAnnotation.message();
}
#Override
public boolean isValid(ISource value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
if ("MANUAL".equals(value.getType())) {
return true;
}
boolean valid = true;
if (value.getGroundValue() == null) {
addConstraintViolation(context, "groundValue");
valid = false;
}
if (value.getManualType() == null) {
addConstraintViolation(context, "manualType");
valid = false;
}
if (value.getManualURI() == null) {
addConstraintViolation(context, "manualURI");
valid = false;
}
return valid;
}
private void addConstraintViolation(ConstraintValidatorContext context, String p) {
context.buildConstraintViolationWithTemplate(p + " cannot be Null")
.addPropertyNode(p)
.addConstraintViolation();
}
}

How to perform a custom JSON deserialization with Jackson that respects a custom annotation?

I am trying to deserialize JSON into a custom POJO that I am not able to modify. That POJO has annotations from a different custom internal serialization framework that I'm not able to use. How can I create a custom deserializer that will respect these annotations?
Here is an example POJO:
public class ExampleClass {
#Property(name = "id")
public String id;
#Property(name = "time_windows")
#NotNull
public List<TimeWindow> timeWindows = new ArrayList<>();
public static class TimeWindow {
#Property(name = "start")
public Long start;
#Property(name = "end")
public Long end;
}
}
So in this case, the deserializer would look for fields in the JSON that correspond to the Property annotations, and use the value in that annotation to decide what field to grab. If a property doesn't have the Property annotation, it should be ignored.
I have been going through the Jackson docs but haven't been able to find exactly what I need. Is this a place where an AnnotationIntrospector would be useful? Or possibly a ContextualDeserializer?
Any pointers in the right direction would be greatly appreciated!
Update: I tried implementing the advice in the comments, but without success.
Here is my initial implementation of the introspector:
class CustomAnnotationInspector : JacksonAnnotationIntrospector () {
override fun hasIgnoreMarker(m: AnnotatedMember?): Boolean {
val property = m?.getAnnotation(Property::class.java)
return property == null
}
override fun findNameForDeserialization(a: Annotated?): PropertyName {
val property = a?.getAnnotation(Property::class.java)
return if (property == null) {
super.findNameForDeserialization(a)
} else {
PropertyName(property.name)
}
}
}
And here is where I actually use it:
// Create an empty instance of the request object.
val paramInstance = nonPathParams?.type?.getDeclaredConstructor()?.newInstance()
// Create new object mapper that will write values from
// JSON into the empty object.
val mapper = ObjectMapper()
// Tells the mapper to respect custom annotations.
mapper.setAnnotationIntrospector(CustomAnnotationInspector())
// Write the contents of the request body into the StringWriter
// (this is required for the mapper.writeValue method
val sw = StringWriter()
sw.write(context.bodyAsString)
// Deserialize the contents of the StringWriter
// into the empty POJO.
mapper.writeValue(sw, paramInstance)
Unfortunately it seems that findNameForDeserialization is never called, and none of the JSON values are written into paramInstance. Can anybody spot where I'm going wrong?
Thank you!
Update 2: I changed the code slightly, I'm now able to identify the property names but Jackson is failing to create an instance of the object.
Here's my new code:
val mapper = ObjectMapper()
// Tells the mapper to respect CoreNg annotations.
val introspector = CustomAnnotationInspector()
mapper.setAnnotationIntrospector(introspector)
val paramInstance = mapper.readValue(context.bodyAsString,nonPathParams?.type)
My breakpoints in the custom annotation introspector are getting hit. But I'm getting the following exception:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `app.employee.api.employee.BOUpsertEmployeeRequest` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
Here is the POJO I'm trying to deserialize:
public class BOUpsertEmployeeRequest {
public BOUpsertEmployeeRequest () { }
#NotNull
#Property(name = "xref_code")
public String xrefCode;
#Property(name = "first_name")
public String firstName;
#Property(name = "last_name")
public String lastName;
#Property(name = "email_address")
public String emailAddress;
#Property(name = "phone")
public String phone;
#Property(name = "address")
public List<String> address;
#Property(name = "employment_status")
public String employmentStatus;
#Property(name = "pay_type")
public String payType;
#Property(name = "position")
public String position;
#Property(name = "skills")
public List<String> skills;
#Property(name = "gender")
public String gender;
}
As far as I can tell it has a default constructor. Anybody have any idea what the problem is?
Thank you!
Method hasIgnoreMarker is called not only for fields, but also for the constructor, including the virtual one:
Method called to check whether given property is marked to be ignored. This is used to determine whether to ignore properties, on per-property basis, usually combining annotations from multiple accessors (getters, setters, fields, constructor parameters).
In this case you should ignore only fields, that are not marked properly:
static class CustomAnnotationIntrospector extends JacksonAnnotationIntrospector {
#Override
public PropertyName findNameForDeserialization(Annotated a) {
Property property = a.getAnnotation(Property.class);
if (property == null) {
return PropertyName.USE_DEFAULT;
} else {
return PropertyName.construct(property.name());
}
}
#Override
public boolean hasIgnoreMarker(AnnotatedMember m) {
return m instanceof AnnotatedField
&& m.getAnnotation(Property.class) == null;
}
}
Example:
class Pojo {
// #Property(name = "id")
Integer id;
// #Property(name = "number")
Integer number;
#Property(name = "assure")
Boolean assure;
#Property(name = "person")
Map<String, String> person;
}
String json =
"{\"id\" : 1, \"number\" : 12345, \"assure\" : true," +
" \"person\" : {\"name\" : \"John\", \"age\" : 23}}";
ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new CustomAnnotationIntrospector());
Pojo pojo = mapper.readValue(json, Pojo.class);
System.out.println(pojo);
Pojo{id=null, number=null, assure=true, person={name=John, age=23}}
Note: Custom Property annotation should have RetentionPolicy.RUNTIME (same as JsonProperty annotation):
#Retention(RetentionPolicy.RUNTIME)
public #interface Property {
String name();
}
I will suggest a different approach:
In the runtime, with the bytecode instrumentation library Byte Buddy and its Java agent, re-annotate the fields with the proper Jackson Annotations. Simply implement the logic via reflection. See the following example:
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.dynamic.DynamicType.Builder;
import net.bytebuddy.dynamic.DynamicType.Builder.FieldDefinition.Valuable;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.matcher.ElementMatchers;
#Target(ElementType.FIELD)
#Retention(RetentionPolicy.RUNTIME)
#interface MyJsonIgnore {
}
#Target(ElementType.FIELD)
#Retention(RetentionPolicy.RUNTIME)
#interface MyJsonProperty {
String name();
}
public class Sample {
public static void main(String[] args) throws JsonProcessingException {
ByteBuddyAgent.install();
ClassReloadingStrategy classReloadingStrategy = ClassReloadingStrategy.fromInstalledAgent();
ByteBuddy byteBuddy = new ByteBuddy();
AnnotationDescription jsonIgnoreDesc =
AnnotationDescription.Builder.ofType(JsonIgnore.class).build();
Builder<Person> personBuilder = byteBuddy.redefine(Person.class);
for (Field declaredField : Person.class.getDeclaredFields()) {
Valuable<Person> field = personBuilder.field(ElementMatchers.named(declaredField.getName()));
MyJsonProperty myJsonProperty = declaredField.getAnnotation(MyJsonProperty.class);
if (myJsonProperty != null) {
AnnotationDescription jsonPropertyDesc =
AnnotationDescription.Builder.ofType(JsonProperty.class)
.define("value", myJsonProperty.name())
.build();
personBuilder = field.annotateField(jsonPropertyDesc);
}
MyJsonIgnore myJsonIgnore = declaredField.getAnnotation(MyJsonIgnore.class);
if (myJsonIgnore != null) {
personBuilder = field.annotateField(jsonIgnoreDesc);
}
}
personBuilder.make().load(Sample.class.getClassLoader(), classReloadingStrategy);
Person person = new Person("Utku", "Ozdemir", "Berlin");
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(person);
System.out.println(jsonString);
}
}
class Person {
#MyJsonProperty(name = "FIRST")
private String firstName;
#MyJsonProperty(name = "LAST")
private String lastName;
#MyJsonIgnore private String city;
public Person(String firstName, String lastName, String city) {
this.firstName = firstName;
this.lastName = lastName;
this.city = city;
}
}
In the example above, I
create MyJsonProperty and MyJsonIgnore annotations and a Person class for the demonstration purpose
instrument the current Java process with the Byte buddy agent
create a bytebuddy builder to redefine the Person class
loop over the fields of the Person class and check for these annotations
add an additional annotation to each of those fields (on the builder), Jackson's JsonProperty (with the correct field name mapping) and JsonIgnore.
after being done with the fields, make the new class bytecode and load it to the current classloader using the byte buddy agent's class reloading mechanism
write a person object to the stdout.
It prints, as expected:
{"FIRST":"Utku","LAST":"Ozdemir"}
(the field city is ignored)
This solution might feel like an overkill, but on the other side, it is pretty generic solution - with a few changes in the logic, you could handle all the 3rd party classes (which you are not able to modify) instead of handling them case by case.

How to apply custom validation on a field using javax validation only if it is not null?

I am working on javax validation API in Spring Boot Application. I have a User bean and i have to validate that username given in request is unique and doesn't exist into Database.
I have created custom annotation (UniqueUser.java) and custom Validator(UniqueUserValidator.java) for this requirement.
public class User {
#NotNull
#UniqueUser
private String username;
#NotNull
private String password;
#NotNull
#Email
private String email;
#NotNull
private String phone;
}
UniqueUser.java
#Target({TYPE, ANNOTATION_TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = UniqueUserValidator.class)
#Documented
public #interface NameMatch
{
String message() default "User id already exists";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
UniqueUserValidator.java
public class UniqueUserValidator implements ConstraintValidator<NameMatch, Object>
{
#Autowired
UserRepository userRepository;
#Override
public boolean isValid(String userName, final ConstraintValidatorContext context)
{
boolean isValidUser = false;
if(userName!=null && !userName.isEmpty()) {
Optional<User> user= userRepository.findByUserId(userName);
isValidUser = !user.isPresent();
}
return isValidUser;
}
}
In above code, the unique user validation get called for username field even if the field is null and shows Username already exists error message. I want the custom validator to get called only when username has some value. Is it possible to avoid this call.
I can fix the error by modifying the below method and returning true if username is null, but i want't to avoid this unnecessary call.
public class UniqueUserValidator implements ConstraintValidator<NameMatch, Object>
{
#Autowired
UserRepository userRepository;
#Override
public boolean isValid(String userName, final ConstraintValidatorContext context)
{
boolean isValidUser = false;
if(userName!=null && !userName.isEmpty()) {
Optional<User> user= userRepository.findByUserId(userName);
isValidUser = !user.isPresent();
} else {
isValidUser = true;
}
return isValidUser;
}
}
I think what you are looking for is Grouping constraints;
Groups allow you to restrict the set of constraints applied during
validation. One use case for validation groups are UI wizards where in
each step only a specified subset of constraints should get validated.
The groups targeted are passed as var-arg parameters to the
appropriate validate method.
In your case it should look like this:
#GroupSequence({ FirstConstaint.class, SecondConstaint.class })
public class User {
#NotNull(groups = FirstConstaint.class)
#UniqueUser(groups = SecondConstaint.class)
private String username;
// the rest of your fields
}
interface FirstConstaint {
}
interface SecondConstaint {
}
This way, it will check #UniqueUser only if the field is not null, otherwise, it will return the message of #NotNull validation.
Otherwise like #User said you can use this checks in service layer ^^

Bean validation based on another field value using hibernate validator and javax.validation [duplicate]

Is there an implementation of (or third-party implementation for) cross field validation in Hibernate Validator 4.x? If not, what is the cleanest way to implement a cross field validator?
As an example, how can you use the API to validate two bean properties are equal (such as validating a password field matches the password verify field).
In annotations, I'd expect something like:
public class MyBean {
#Size(min=6, max=50)
private String pass;
#Equals(property="pass")
private String passVerify;
}
Each field constraint should be handled by a distinct validator annotation, or in other words it's not suggested practice to have one field's validation annotation checking against other fields; cross-field validation should be done at the class level. Additionally, the JSR-303 Section 2.2 preferred way to express multiple validations of the same type is via a list of annotations. This allows the error message to be specified per match.
For example, validating a common form:
#FieldMatch.List({
#FieldMatch(first = "password", second = "confirmPassword", message = "The password fields must match"),
#FieldMatch(first = "email", second = "confirmEmail", message = "The email fields must match")
})
public class UserRegistrationForm {
#NotNull
#Size(min=8, max=25)
private String password;
#NotNull
#Size(min=8, max=25)
private String confirmPassword;
#NotNull
#Email
private String email;
#NotNull
#Email
private String confirmEmail;
}
The Annotation:
package constraints;
import constraints.impl.FieldMatchValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
* Validation annotation to validate that 2 fields have the same value.
* An array of fields and their matching confirmation fields can be supplied.
*
* Example, compare 1 pair of fields:
* #FieldMatch(first = "password", second = "confirmPassword", message = "The password fields must match")
*
* Example, compare more than 1 pair of fields:
* #FieldMatch.List({
* #FieldMatch(first = "password", second = "confirmPassword", message = "The password fields must match"),
* #FieldMatch(first = "email", second = "confirmEmail", message = "The email fields must match")})
*/
#Target({TYPE, ANNOTATION_TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = FieldMatchValidator.class)
#Documented
public #interface FieldMatch
{
String message() default "{constraints.fieldmatch}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* #return The first field
*/
String first();
/**
* #return The second field
*/
String second();
/**
* Defines several <code>#FieldMatch</code> annotations on the same element
*
* #see FieldMatch
*/
#Target({TYPE, ANNOTATION_TYPE})
#Retention(RUNTIME)
#Documented
#interface List
{
FieldMatch[] value();
}
}
The Validator:
package constraints.impl;
import constraints.FieldMatch;
import org.apache.commons.beanutils.BeanUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object>
{
private String firstFieldName;
private String secondFieldName;
#Override
public void initialize(final FieldMatch constraintAnnotation)
{
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
}
#Override
public boolean isValid(final Object value, final ConstraintValidatorContext context)
{
try
{
final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, secondFieldName);
return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
}
catch (final Exception ignore)
{
// ignore
}
return true;
}
}
I suggest you another possible solution. Perhaps less elegant, but easier!
public class MyBean {
#Size(min=6, max=50)
private String pass;
private String passVerify;
#NotNull
private LocalDate passExpiry;
#NotNull
private LocalDate dateOfJoining;
#AssertTrue(message = "Fields `pass` and `passVerify` should be equal")
// Any method name is ok als long it begins with `is`
private boolean isValidPass() {
//return pass == null && passVerify == null || pass.equals(passVerify);
// Since Java 7:
return Objects.equals(pass, passVerify);
}
#AssertTrue(message = "Field `passExpiry` should be later than `dateOfJoining`")
// Other rules can also be validated in other methods
private boolean isPassExpiryAfterDateOfJoining() {
return dateOfJoining.isBefore(passExpiry);
}
}
The isValid() and isPassExpiryAfterDateOfJoining() methods are invoked automatically by the validator. The property paths reported in the ConstraintViolations will be extracted from the method names: valid and passExpiryAfterDateOfJoining.
I'm surprised this isn't available out of the box. Anyway, here is a possible solution.
I've created a class level validator, not the field level as described in the original question.
Here is the annotation code:
package com.moa.podium.util.constraints;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
#Target({TYPE, ANNOTATION_TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = MatchesValidator.class)
#Documented
public #interface Matches {
String message() default "{com.moa.podium.util.constraints.matches}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String field();
String verifyField();
}
And the validator itself:
package com.moa.podium.util.constraints;
import org.mvel2.MVEL;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class MatchesValidator implements ConstraintValidator<Matches, Object> {
private String field;
private String verifyField;
public void initialize(Matches constraintAnnotation) {
this.field = constraintAnnotation.field();
this.verifyField = constraintAnnotation.verifyField();
}
public boolean isValid(Object value, ConstraintValidatorContext context) {
Object fieldObj = MVEL.getProperty(field, value);
Object verifyFieldObj = MVEL.getProperty(verifyField, value);
boolean neitherSet = (fieldObj == null) && (verifyFieldObj == null);
if (neitherSet) {
return true;
}
boolean matches = (fieldObj != null) && fieldObj.equals(verifyFieldObj);
if (!matches) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("message")
.addNode(verifyField)
.addConstraintViolation();
}
return matches;
}
}
Note that I've used MVEL to inspect the properties of the object being validated. This could be replaced with the standard reflection APIs or if it is a specific class you are validating, the accessor methods themselves.
The #Matches annotation can then be used used on a bean as follows:
#Matches(field="pass", verifyField="passRepeat")
public class AccountCreateForm {
#Size(min=6, max=50)
private String pass;
private String passRepeat;
...
}
As a disclaimer, I wrote this in the last 5 minutes, so I probably haven't ironed out all the bugs yet. I'll update the answer if anything goes wrong.
With Hibernate Validator 4.1.0.Final I recommend using #ScriptAssert. Exceprt from its JavaDoc:
Script expressions can be written in any scripting or expression
language, for which a JSR 223 ("Scripting for the JavaTM Platform")
compatible engine can be found on the classpath.
Note: the evaluation is being performed by a scripting "engine" running in the Java VM, therefore on Java "server side", not on "client side" as stated in some comments.
Example:
#ScriptAssert(lang = "javascript", script = "_this.passVerify.equals(_this.pass)")
public class MyBean {
#Size(min=6, max=50)
private String pass;
private String passVerify;
}
or with shorter alias and null-safe:
#ScriptAssert(lang = "javascript", alias = "_",
script = "_.passVerify != null && _.passVerify.equals(_.pass)")
public class MyBean {
#Size(min=6, max=50)
private String pass;
private String passVerify;
}
or with Java 7+ null-safe Objects.equals():
#ScriptAssert(lang = "javascript", script = "Objects.equals(_this.passVerify, _this.pass)")
public class MyBean {
#Size(min=6, max=50)
private String pass;
private String passVerify;
}
Nevertheless, there is nothing wrong with a custom class level validator #Matches solution.
Cross fields validations can be done by creating custom constraints.
Example:- Compare password and confirmPassword fields of User instance.
CompareStrings
#Target({TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy=CompareStringsValidator.class)
#Documented
public #interface CompareStrings {
String[] propertyNames();
StringComparisonMode matchMode() default EQUAL;
boolean allowNull() default false;
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
StringComparisonMode
public enum StringComparisonMode {
EQUAL, EQUAL_IGNORE_CASE, NOT_EQUAL, NOT_EQUAL_IGNORE_CASE
}
CompareStringsValidator
public class CompareStringsValidator implements ConstraintValidator<CompareStrings, Object> {
private String[] propertyNames;
private StringComparisonMode comparisonMode;
private boolean allowNull;
#Override
public void initialize(CompareStrings constraintAnnotation) {
this.propertyNames = constraintAnnotation.propertyNames();
this.comparisonMode = constraintAnnotation.matchMode();
this.allowNull = constraintAnnotation.allowNull();
}
#Override
public boolean isValid(Object target, ConstraintValidatorContext context) {
boolean isValid = true;
List<String> propertyValues = new ArrayList<String> (propertyNames.length);
for(int i=0; i<propertyNames.length; i++) {
String propertyValue = ConstraintValidatorHelper.getPropertyValue(String.class, propertyNames[i], target);
if(propertyValue == null) {
if(!allowNull) {
isValid = false;
break;
}
} else {
propertyValues.add(propertyValue);
}
}
if(isValid) {
isValid = ConstraintValidatorHelper.isValid(propertyValues, comparisonMode);
}
if (!isValid) {
/*
* if custom message was provided, don't touch it, otherwise build the
* default message
*/
String message = context.getDefaultConstraintMessageTemplate();
message = (message.isEmpty()) ? ConstraintValidatorHelper.resolveMessage(propertyNames, comparisonMode) : message;
context.disableDefaultConstraintViolation();
ConstraintViolationBuilder violationBuilder = context.buildConstraintViolationWithTemplate(message);
for (String propertyName : propertyNames) {
NodeBuilderDefinedContext nbdc = violationBuilder.addNode(propertyName);
nbdc.addConstraintViolation();
}
}
return isValid;
}
}
ConstraintValidatorHelper
public abstract class ConstraintValidatorHelper {
public static <T> T getPropertyValue(Class<T> requiredType, String propertyName, Object instance) {
if(requiredType == null) {
throw new IllegalArgumentException("Invalid argument. requiredType must NOT be null!");
}
if(propertyName == null) {
throw new IllegalArgumentException("Invalid argument. PropertyName must NOT be null!");
}
if(instance == null) {
throw new IllegalArgumentException("Invalid argument. Object instance must NOT be null!");
}
T returnValue = null;
try {
PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, instance.getClass());
Method readMethod = descriptor.getReadMethod();
if(readMethod == null) {
throw new IllegalStateException("Property '" + propertyName + "' of " + instance.getClass().getName() + " is NOT readable!");
}
if(requiredType.isAssignableFrom(readMethod.getReturnType())) {
try {
Object propertyValue = readMethod.invoke(instance);
returnValue = requiredType.cast(propertyValue);
} catch (Exception e) {
e.printStackTrace(); // unable to invoke readMethod
}
}
} catch (IntrospectionException e) {
throw new IllegalArgumentException("Property '" + propertyName + "' is NOT defined in " + instance.getClass().getName() + "!", e);
}
return returnValue;
}
public static boolean isValid(Collection<String> propertyValues, StringComparisonMode comparisonMode) {
boolean ignoreCase = false;
switch (comparisonMode) {
case EQUAL_IGNORE_CASE:
case NOT_EQUAL_IGNORE_CASE:
ignoreCase = true;
}
List<String> values = new ArrayList<String> (propertyValues.size());
for(String propertyValue : propertyValues) {
if(ignoreCase) {
values.add(propertyValue.toLowerCase());
} else {
values.add(propertyValue);
}
}
switch (comparisonMode) {
case EQUAL:
case EQUAL_IGNORE_CASE:
Set<String> uniqueValues = new HashSet<String> (values);
return uniqueValues.size() == 1 ? true : false;
case NOT_EQUAL:
case NOT_EQUAL_IGNORE_CASE:
Set<String> allValues = new HashSet<String> (values);
return allValues.size() == values.size() ? true : false;
}
return true;
}
public static String resolveMessage(String[] propertyNames, StringComparisonMode comparisonMode) {
StringBuffer buffer = concatPropertyNames(propertyNames);
buffer.append(" must");
switch(comparisonMode) {
case EQUAL:
case EQUAL_IGNORE_CASE:
buffer.append(" be equal");
break;
case NOT_EQUAL:
case NOT_EQUAL_IGNORE_CASE:
buffer.append(" not be equal");
break;
}
buffer.append('.');
return buffer.toString();
}
private static StringBuffer concatPropertyNames(String[] propertyNames) {
//TODO improve concating algorithm
StringBuffer buffer = new StringBuffer();
buffer.append('[');
for(String propertyName : propertyNames) {
char firstChar = Character.toUpperCase(propertyName.charAt(0));
buffer.append(firstChar);
buffer.append(propertyName.substring(1));
buffer.append(", ");
}
buffer.delete(buffer.length()-2, buffer.length());
buffer.append("]");
return buffer;
}
}
User
#CompareStrings(propertyNames={"password", "confirmPassword"})
public class User {
private String password;
private String confirmPassword;
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getConfirmPassword() { return confirmPassword; }
public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; }
}
Test
public void test() {
User user = new User();
user.setPassword("password");
user.setConfirmPassword("paSSword");
Set<ConstraintViolation<User>> violations = beanValidator.validate(user);
for(ConstraintViolation<User> violation : violations) {
logger.debug("Message:- " + violation.getMessage());
}
Assert.assertEquals(violations.size(), 1);
}
Output Message:- [Password, ConfirmPassword] must be equal.
By using the CompareStrings validation constraint, we can also compare more than two properties and we can mix any of four string comparison methods.
ColorChoice
#CompareStrings(propertyNames={"color1", "color2", "color3"}, matchMode=StringComparisonMode.NOT_EQUAL, message="Please choose three different colors.")
public class ColorChoice {
private String color1;
private String color2;
private String color3;
......
}
Test
ColorChoice colorChoice = new ColorChoice();
colorChoice.setColor1("black");
colorChoice.setColor2("white");
colorChoice.setColor3("white");
Set<ConstraintViolation<ColorChoice>> colorChoiceviolations = beanValidator.validate(colorChoice);
for(ConstraintViolation<ColorChoice> violation : colorChoiceviolations) {
logger.debug("Message:- " + violation.getMessage());
}
Output Message:- Please choose three different colors.
Similarly, we can have CompareNumbers, CompareDates, etc cross-fields validation constraints.
P.S. I have not tested this code under production environment (though I tested it under dev environment), so consider this code as Milestone Release. If you find a bug, please write a nice comment. :)
If you’re using the Spring Framework then you can use the Spring Expression Language (SpEL) for that. I’ve wrote a small library that provides JSR-303 validator based on SpEL – it makes cross-field validations a breeze! Take a look at https://github.com/jirutka/validator-spring.
This will validate length and equality of the password fields.
#SpELAssert(value = "pass.equals(passVerify)",
message = "{validator.passwords_not_same}")
public class MyBean {
#Size(min = 6, max = 50)
private String pass;
private String passVerify;
}
You can also easily modify this to validate the password fields only when not both empty.
#SpELAssert(value = "pass.equals(passVerify)",
applyIf = "pass || passVerify",
message = "{validator.passwords_not_same}")
public class MyBean {
#Size(min = 6, max = 50)
private String pass;
private String passVerify;
}
I have tried Alberthoven's example (hibernate-validator 4.0.2.GA) and i get an ValidationException: „Annotated methods must follow the JavaBeans naming convention. match() does not.“ too. After I renamed the method from „match“ to "isValid" it works.
public class Password {
private String password;
private String retypedPassword;
public Password(String password, String retypedPassword) {
super();
this.password = password;
this.retypedPassword = retypedPassword;
}
#AssertTrue(message="password should match retyped password")
private boolean isValid(){
if (password == null) {
return retypedPassword == null;
} else {
return password.equals(retypedPassword);
}
}
public String getPassword() {
return password;
}
public String getRetypedPassword() {
return retypedPassword;
}
}
I like the idea from Jakub Jirutka to use Spring Expression Language. If you don't want to add another library/dependency (assuming that you already use Spring), here is a simplified implementation of his idea.
The constraint:
#Constraint(validatedBy=ExpressionAssertValidator.class)
#Target({ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
public #interface ExpressionAssert {
String message() default "expression must evaluate to true";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String value();
}
The validator:
public class ExpressionAssertValidator implements ConstraintValidator<ExpressionAssert, Object> {
private Expression exp;
public void initialize(ExpressionAssert annotation) {
ExpressionParser parser = new SpelExpressionParser();
exp = parser.parseExpression(annotation.value());
}
public boolean isValid(Object value, ConstraintValidatorContext context) {
return exp.getValue(value, Boolean.class);
}
}
Apply like this:
#ExpressionAssert(value="pass == passVerify", message="passwords must be same")
public class MyBean {
#Size(min=6, max=50)
private String pass;
private String passVerify;
}
I made a small adaptation in Nicko's solution so that it is not necessary to use the Apache Commons BeanUtils library and replace it with the solution already available in spring, for those using it as I can be simpler:
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {
private String firstFieldName;
private String secondFieldName;
#Override
public void initialize(final FieldMatch constraintAnnotation) {
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
}
#Override
public boolean isValid(final Object object, final ConstraintValidatorContext context) {
BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
final Object firstObj = beanWrapper.getPropertyValue(firstFieldName);
final Object secondObj = beanWrapper.getPropertyValue(secondFieldName);
boolean isValid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
if (!isValid) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
.addPropertyNode(firstFieldName)
.addConstraintViolation();
}
return isValid;
}
}
I don't have the reputation for commenting on the first answer but wanted to add that I have added unit tests for the winning answer and have the following observations:
If you get the first or field names wrong then you get a validation error as though the values don't match. Don't get tripped up by spelling mistakes e.g.
#FieldMatch(first="invalidFieldName1", second="validFieldName2")
The validator will accept equivalent data types i.e. these will all pass with FieldMatch:
private String stringField = "1";
private Integer integerField = new Integer(1)
private int intField = 1;
If the fields are of an object type which does not implement equals, the validation will fail.
Very nice solution bradhouse. Is there any way to apply the #Matches annotation to more than one field?
EDIT:
Here's the solution I came up with to answer this question, I modified the Constraint to accept an array instead of a single value:
#Matches(fields={"password", "email"}, verifyFields={"confirmPassword", "confirmEmail"})
public class UserRegistrationForm {
#NotNull
#Size(min=8, max=25)
private String password;
#NotNull
#Size(min=8, max=25)
private String confirmPassword;
#NotNull
#Email
private String email;
#NotNull
#Email
private String confirmEmail;
}
The code for the annotation:
package springapp.util.constraints;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
#Target({TYPE, ANNOTATION_TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = MatchesValidator.class)
#Documented
public #interface Matches {
String message() default "{springapp.util.constraints.matches}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String[] fields();
String[] verifyFields();
}
And the implementation:
package springapp.util.constraints;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.apache.commons.beanutils.BeanUtils;
public class MatchesValidator implements ConstraintValidator<Matches, Object> {
private String[] fields;
private String[] verifyFields;
public void initialize(Matches constraintAnnotation) {
fields = constraintAnnotation.fields();
verifyFields = constraintAnnotation.verifyFields();
}
public boolean isValid(Object value, ConstraintValidatorContext context) {
boolean matches = true;
for (int i=0; i<fields.length; i++) {
Object fieldObj, verifyFieldObj;
try {
fieldObj = BeanUtils.getProperty(value, fields[i]);
verifyFieldObj = BeanUtils.getProperty(value, verifyFields[i]);
} catch (Exception e) {
//ignore
continue;
}
boolean neitherSet = (fieldObj == null) && (verifyFieldObj == null);
if (neitherSet) {
continue;
}
boolean tempMatches = (fieldObj != null) && fieldObj.equals(verifyFieldObj);
if (!tempMatches) {
addConstraintViolation(context, fields[i]+ " fields do not match", verifyFields[i]);
}
matches = matches?tempMatches:matches;
}
return matches;
}
private void addConstraintViolation(ConstraintValidatorContext context, String message, String field) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message).addNode(field).addConstraintViolation();
}
}
You need to call it explicitly. In the example above, bradhouse has given you all the steps to write a custom constraint.
Add this code in your caller class.
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
Set<ConstraintViolation<yourObjectClass>> constraintViolations = validator.validate(yourObject);
in the above case it would be
Set<ConstraintViolation<AccountCreateForm>> constraintViolations = validator.validate(objAccountCreateForm);
Why not try Oval: http://oval.sourceforge.net/
I looks like it supports OGNL so maybe you could do it by a more natural
#Assert(expr = "_value ==_this.pass").
You guys are awesome. Really amazing ideas. I like Alberthoven's and McGin's most, so I decided to combine both ideas. And develop some generic solution to cater all cases. Here is my proposed solution.
#Documented
#Constraint(validatedBy = NotFalseValidator.class)
#Target({ElementType.METHOD, ElementType.FIELD,ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
public #interface NotFalse {
String message() default "NotFalse";
String[] messages();
String[] properties();
String[] verifiers();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class NotFalseValidator implements ConstraintValidator<NotFalse, Object> {
private String[] properties;
private String[] messages;
private String[] verifiers;
#Override
public void initialize(NotFalse flag) {
properties = flag.properties();
messages = flag.messages();
verifiers = flag.verifiers();
}
#Override
public boolean isValid(Object bean, ConstraintValidatorContext cxt) {
if(bean == null) {
return true;
}
boolean valid = true;
BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);
for(int i = 0; i< properties.length; i++) {
Boolean verified = (Boolean) beanWrapper.getPropertyValue(verifiers[i]);
valid &= isValidProperty(verified,messages[i],properties[i],cxt);
}
return valid;
}
boolean isValidProperty(Boolean flag,String message, String property, ConstraintValidatorContext cxt) {
if(flag == null || flag) {
return true;
} else {
cxt.disableDefaultConstraintViolation();
cxt.buildConstraintViolationWithTemplate(message)
.addPropertyNode(property)
.addConstraintViolation();
return false;
}
}
}
#NotFalse(
messages = {"End Date Before Start Date" , "Start Date Before End Date" } ,
properties={"endDateTime" , "startDateTime"},
verifiers = {"validDateRange" , "validDateRange"})
public class SyncSessionDTO implements ControllableNode {
#NotEmpty #NotPastDate
private Date startDateTime;
#NotEmpty
private Date endDateTime;
public Date getStartDateTime() {
return startDateTime;
}
public void setStartDateTime(Date startDateTime) {
this.startDateTime = startDateTime;
}
public Date getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(Date endDateTime) {
this.endDateTime = endDateTime;
}
public Boolean getValidDateRange(){
if(startDateTime != null && endDateTime != null) {
return startDateTime.getTime() <= endDateTime.getTime();
}
return null;
}
}
Solution realated with question:
How to access a field which is described in annotation property
#Target(ElementType.FIELD)
#Retention(RetentionPolicy.RUNTIME)
#Documented
public #interface Match {
String field();
String message() default "";
}
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
#Constraint(validatedBy = MatchValidator.class)
#Documented
public #interface EnableMatchConstraint {
String message() default "Fields must match!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class MatchValidator implements ConstraintValidator<EnableMatchConstraint, Object> {
#Override
public void initialize(final EnableMatchConstraint constraint) {}
#Override
public boolean isValid(final Object o, final ConstraintValidatorContext context) {
boolean result = true;
try {
String mainField, secondField, message;
Object firstObj, secondObj;
final Class<?> clazz = o.getClass();
final Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Match.class)) {
mainField = field.getName();
secondField = field.getAnnotation(Match.class).field();
message = field.getAnnotation(Match.class).message();
if (message == null || "".equals(message))
message = "Fields " + mainField + " and " + secondField + " must match!";
firstObj = BeanUtils.getProperty(o, mainField);
secondObj = BeanUtils.getProperty(o, secondField);
result = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
if (!result) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message).addPropertyNode(mainField).addConstraintViolation();
break;
}
}
}
} catch (final Exception e) {
// ignore
//e.printStackTrace();
}
return result;
}
}
And how to use it...? Like this:
#Entity
#EnableMatchConstraint
public class User {
#NotBlank
private String password;
#Match(field = "password")
private String passwordConfirmation;
}

Java Annotation at runtime

the following class exists which consist from predefined UUID's that describe possible entires of the database.
public class Predefined {
#NotNull
#Size(min = 1, max = 25)
public UUID phone = UUID.fromString("47b58767-c0ad-43fe-8e87-c7dae489a4f0");
#NotNull
#Size(min = 1, max = 40)
public UUID company = UUID.fromString("f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2");
}
Those values are received as a key pair value trough web service: and then they are put to a hashmap.
47b58767-c0ad-43fe-8e87-c7dae489a4f0 = +00112233445566778899
f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2 = someVirtualCompnayName
When i receive an UUID that i know i am creating an instance of the Predefined class and then getting the annotations of the filed in the Predefined class i.e.:
Annotation[] annon = field.getDeclaredAnnotations();
Now I need to check those annotation agains the values that I got from the web services i.e. “+00112233445566778899” and “someVirtualCompnayName” at runtime
Is this possible?
I am especially interesting in example covering JSR 303.
Shortly why I have such construct:
The DAO , #Repository classes have different structure i.e.
contact
contact_attrbute
contact_attibute_type
where the databse “contact_attibute_type” is meant for “company” and “phone”. The second table i.e. “contact_attrbute” is meant for the actual values of “company” and “phone”.
Now I need a way to validate those values before I write them in hibernate, thus I am getting the “public UUID phone” and then trying to apply those constrains to the actual value I got from the user i.e. “+00112233445566778899”.
I'll post the complete code I have come up with to validate your test-case (including a simple executable demo):
Annotations:
package annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Target( {ElementType.FIELD })
#Retention(RetentionPolicy.RUNTIME)
public #interface NotNull
{
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Target( {ElementType.FIELD })
#Retention(RetentionPolicy.RUNTIME)
public #interface Size
{
int min() default 0;
int max();
}
The Predefined class:
public class Predefined
{
#NotNull
#Size(min = 1, max = 25)
public UUID phone;
#NotNull
#Size(min = 1, max = 40)
public UUID company;
public Predefined(UUID phone, UUID company)
{
this.phone = phone;
this.company = company;
}
}
The validator class which iterates through the declared fields and checks their annotation and field/value mappings:
public class PredefinedValidator
{
public boolean validate(Predefined predefined, Map<UUID, String> mappings)
{
if (predefined == null)
return false;
for (Field field :predefined.getClass().getDeclaredFields())
{
if (field.getType().equals(UUID.class))
{
try
{
Annotation[] annotations = field.getDeclaredAnnotations();
UUID uuid = (UUID)field.get(predefined);
if (!this.validateField(uuid, annotations, mappings))
return false;
}
catch (IllegalArgumentException | IllegalAccessException ex)
{
Logger.getLogger(PredefinedValidator.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return true;
}
private boolean validateField(UUID field, Annotation[] annotations, Map<UUID, String> mapping)
{
boolean containsSize = false;
boolean containsNotNull = false;
int minSize = -1;
int maxSize = -1;
// fetch which annotations are available for the provided field
for (Annotation annotation : annotations)
{
if (annotation instanceof Size)
{
containsSize = true;
Size size = (Size)annotation;
minSize = size.min();
maxSize = size.max();
}
else if (annotation instanceof NotNull)
containsNotNull = true;
}
// check if the provided value is null and an annotatition for #NotNull
// is set
if (field == null && containsNotNull)
return false;
if (containsSize)
{
// get the value of the mapped UUID which we are going to validate
String value = mapping.get(field);
if (value == null && containsNotNull)
return false;
else if (value == null)
return true;
// check if the length of the value matches
if (value.length() <= minSize || value.length() >= maxSize)
return false;
}
// passed all tests
return true;
}
}
Last but not least a simple demo:
public static void main(String ... args)
{
Map<UUID, String> mappings = new HashMap<>();
mappings.put(UUID.fromString("47b58767-c0ad-43fe-8e87-c7dae489a4f0"), "+00112233445566778899");
mappings.put(UUID.fromString("f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2"), "someVirtualCompnayName");
Predefined predefined = new Predefined(
UUID.fromString("47b58767-c0ad-43fe-8e87-c7dae489a4f0"),
UUID.fromString("f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2"));
Predefined predefined2 = new Predefined(
UUID.randomUUID(),
UUID.fromString("f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2"));
Predefined predefined3 = new Predefined(
null,
UUID.fromString("f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2"));
PredefinedValidator validator = new PredefinedValidator();
System.out.println("predefined is valid: "+validator.validate(predefined, mappings));
System.out.println("predefined is valid: "+validator.validate(predefined2, mappings));
System.out.println("predefined is valid: "+validator.validate(predefined3, mappings));
mappings.put(UUID.fromString("f9a1e8f4-b8c0-41f2-a626-49c11da8d5c2"), "someVirtualCompnayNamesomeVirtualCompnayNamesomeVirtualCompnayNamesomeVirtualCompnayName");
System.out.println("predefined is valid: "+validator.validate(predefined, mappings));
}
HTH

Categories