How do you create a SimpleBeanInfo in the year 2016? - java

I'd like to create a property editor for my Java Beans. For that I need a class that implements BeanInfo. The problem: I really don't feel comfortable with declaring an attribute name as String like this (floodColor, fillColor, percent):
import java.beans.*;
public class BarChartBeanBeanInfo extends SimpleBeanInfo
{
private final static Class myClass = BarChartBean.class;
public PropertyDescriptor[] getPropertyDescriptors()
{
try {
PropertyDescriptor flc = new PropertyDescriptor("floodColor", myClass);
PropertyDescriptor fic = new PropertyDescriptor("fillColor", myClass);
PropertyDescriptor pct = new PropertyDescriptor("percent", myClass);
PropertyDescriptor[] list = { flc, fic, pct };
return list;
}
catch (IntrospectionException iexErr)
{
throw new Error(iexErr.toString());
}
}
};
I got this from an example article about how to create a custom property editor: The trick to controlling bean customization. The article is from the year 1997.
How do you create a property editor in the year 2016 without using string declarations of variables which obviously will lead to runtime exceptions once someone changes the variable name?
I mean other than to use the Introspector. Is there e. g. some kind of annotation support for attribute names of classes?
Thank you very much for the expertise!

I tried with custom annotations, it seems to work. At least it's typesafe now and coupled to the fields.
Code
ExampleBean.java
import annotations.Descriptor;
import annotations.Property;
#Descriptor(displayName = "Example Bean", shortDescription = "This is an example bean")
public class ExampleBean {
#Property(displayName = "Integer Value", shortDescription = "This is an integer value")
int integerValue;
#Property(displayName = "Double Value", shortDescription = "This is a double value")
double doubleValue;
#Property(displayName = "String Value", shortDescription = "This is a string value")
String stringValue;
public int getIntegerValue() {
return integerValue;
}
public void setIntegerValue(int integerValue) {
this.integerValue = integerValue;
}
public double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(double doubleValue) {
this.doubleValue = doubleValue;
}
public String getStringValue() {
return stringValue;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
}
Descriptor.java
package annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface Descriptor {
public String displayName() default "";
public String shortDescription() default "";
}
Property.java
package annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.FIELD, ElementType.METHOD })
public #interface Property {
public String displayName() default "";
public String shortDescription() default "";
}
ExampleBeanBeanInfo.java
import java.beans.BeanDescriptor;
import java.beans.PropertyDescriptor;
import java.beans.SimpleBeanInfo;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import annotations.Descriptor;
import annotations.Property;
public class ExampleBeanBeanInfo extends SimpleBeanInfo {
private final static Class<ExampleBean> myClass = ExampleBean.class;
public PropertyDescriptor[] getPropertyDescriptors() {
List<PropertyDescriptor> propertyDescriptors = new ArrayList<>();
try {
for (Field field : myClass.getDeclaredFields()) {
if (field.isAnnotationPresent(Property.class)) {
Annotation annotation = field.getAnnotation(Property.class);
Property property = (Property) annotation;
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), myClass);
propertyDescriptor.setDisplayName(property.displayName());
propertyDescriptor.setShortDescription(property.shortDescription());
propertyDescriptors.add(propertyDescriptor);
}
}
return propertyDescriptors.toArray(new PropertyDescriptor[propertyDescriptors.size()]);
} catch (Exception iexErr) {
throw new Error(iexErr.toString());
}
}
public BeanDescriptor getBeanDescriptor() {
BeanDescriptor desc = new BeanDescriptor(myClass);
if (myClass.isAnnotationPresent(Descriptor.class)) {
Annotation annotation = myClass.getAnnotation(Descriptor.class);
Descriptor descriptor = (Descriptor) annotation;
desc.setDisplayName(descriptor.displayName());
desc.setShortDescription(descriptor.shortDescription());
}
return desc;
}
}
Main.java
import java.beans.BeanDescriptor;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public class Main {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, IntrospectionException {
BeanInfo beanInfo = Introspector.getBeanInfo(ExampleBean.class);
BeanDescriptor beanDescriptor = beanInfo.getBeanDescriptor();
System.out.printf( "Bean display name = '%s', description = '%s'\n", beanDescriptor.getDisplayName(), beanDescriptor.getShortDescription());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String propertyName = propertyDescriptor.getName();
System.out.printf("Property field name = '%s', display name = '%s', description = '%s'\n", propertyName, propertyDescriptor.getDisplayName(), propertyDescriptor.getShortDescription());
}
System.exit(0);
;
}
}
Console output:
Bean display name = 'Example Bean', description = 'This is an example bean'
Property field name = 'doubleValue', display name = 'Double Value', description = 'This is a double value'
Property field name = 'integerValue', display name = 'Integer Value', description = 'This is an integer value'
Property field name = 'stringValue', display name = 'String Value', description = 'This is a string value'
This example exposes the displayname and shortdescription methods, one would have to add others of the bean and property descriptor.
If anyone has a better way, please let me know.

Related

How to get fields names of a class inside another class?

We are creating CSV files from DTO classes, using reflection to get the names of all the column names. ClassName.class.getDeclaredFields() gives us array of all column names.
We have a use case where, we have classes with composition relation, like below:
public class Book {
private String title;
private Author author;
}
public class Author {
private String name;
private Integer age:
}
Here Book is the root class, i.e., final CSV will be named books.csv
With Book.class.getDeclaredFields(), we only get field names title and author, but we also want field names from Author class (name and age), is there a way to get those?
Notes:
It is far from optimal.
Circular reference problem is not considered.
Given your model it would return a list with this elements:
title
author.name
author.age
Usage:
ClassMetadataService cms = new ClassMetadataService();
List<String> properties = cms.getProperties(Book.class);
Class definition:
package io.metadata;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ClassMetadataService {
public List<String> getProperties(Class clazz) {
List<String> properties = new ArrayList<>();
this.collectProperties(new ArrayList<>(), clazz, properties);
return properties;
}
private void collectProperties(List<String> pathNodes, Class clazz, List<String> properties) {
for (Field field : clazz.getDeclaredFields()) {
List<String> localPathNodes = new ArrayList<>(pathNodes);
localPathNodes.add(field.getName());
if (clazz.isPrimitive() || isJavaClass(field.getType())) {
properties.add(localPathNodes.stream().collect(Collectors.joining(".")));
} else {
collectProperties(localPathNodes, field.getType(), properties);
}
}
}
private Boolean isJavaClass(Class clazz) {
List<Class> javaClass = Arrays.asList(
// ....
Boolean.class,
Byte.class,
Short.class,
Integer.class,
Long.class,
Float.class,
Double.class,
BigDecimal.class,
BigInteger.class,
Character.class,
String.class,
LocalDate.class,
LocalDateTime.class
// ....
);
return javaClass.stream().anyMatch(jc -> jc.equals(clazz));
}
}

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;
}

JsonMappingException: No suitable constructor found for type [simple type, class car.Car$Parts]

I'm trying to deserialize this XML into a Parts object:
<Parts>
<Part>
<Name>gearbox</Name>
<Year>1990</Year>
</Part>
<Part>
<Name>wheel</Name>
<Year>2000</Year>
</Part>
</Parts>
Car.java:
package problem.car;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Car {
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"Parts"
})
public class Parts {
#JsonProperty("parts")
private List<Part> parts = new ArrayList<>();
#JsonProperty("parts")
public List<Part> getParts() {
return parts;
}
#JsonProperty("parts")
public void setParts(List<Part> parts) {
this.parts = parts;
}
}
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"Name",
"Year"
})
public class Part {
#JsonProperty("Name")
private String Name;
#JsonProperty("Year")
private String Year;
#JsonProperty("Name")
public String getName() {
return Name;
}
#JsonProperty("Name")
public void setName(String Name) {
this.Name = Name;
}
#JsonProperty("Year")
public String getYear() {
return Year;
}
#JsonProperty("Year")
public void setYear(String Year) {
this.Year = Year;
}
}
public static void main(String args[]) {
try {
String xml = "<Parts>\n"
+ " <Part>\n"
+ " <Name>gearbox</Name>\n"
+ " <Year>1990</Year>\n"
+ " </Part>\n"
+ " <Part>\n"
+ " <Name>wheel</Name>\n"
+ " <Year>2000</Year>\n"
+ " </Part>\n"
+ "</Parts>";
Parts parts = (Parts) deserialize(Parts.class, xml);
} catch (IOException ex) {
Logger.getLogger(Car.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static final Object deserialize(final Class clazz, final String xml) throws IOException {
ObjectMapper xmlMapper = new XmlMapper();
xmlMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz"));
Object object;
try {
object = xmlMapper.readValue(xml, clazz);
} catch (com.fasterxml.jackson.databind.exc.InvalidFormatException ex) {
xmlMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
object = xmlMapper.readValue(xml, clazz);
}
return object;
}
}
I don't see anything wrong with my code though so why does it keep giving me the following?
com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class problem.car.Car$Parts]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)
The answer
The Part class is a nested, non-static class.
In order to instantiate it, you must have an instance of the outer class.
Here is an inner class tutorial
I-hate-reading answer
Move the Part and Parts classes to their own java files, named Part.java and Parts.java.
Try writing it in uppercase, just like in class body:
#XmlType(name = "Parts", propOrder = {
"Part"
})
Because jackson deserialization is case sensitive.

JAVA-JAXB/ define class as field

I'm using jaxb, and as I understood, we define for each element and attribute field, and jaxb reconize this attribute, and put it value into this elemnt. My problem that one of my attribute is class:
<div class="hello"> Hi </div>
so I want to define in the class div, the next:
String class;
public String getClass() {
return class;
}
#XmlAttribute
public void setClass(String class) {
this.class = class;
}
But I can't because - Syntax error on token "class", invalid VariableDeclarator
What can I do?
You can use the name property of XmlAttribute to specify a different name for the mapping variable.
String className;
public String getClassName() {
return clazz;
}
#XmlAttribute(name="class")
public void setClassName(String className) {
this.className = className;
}
It is working perfectly fine
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
public class Test {
public static void main(String[] args) throws Exception {
JAXBContext context = JAXBContext.newInstance(Div.class);
Div div = new Div();
div.setClassName("new-item");
StringWriter sw = new StringWriter();
context.createMarshaller().marshal(div, sw);
System.out.println(sw.toString());
String s = "<div class=\"hello\"> Hi </div>";
Div object = (Div) context.createUnmarshaller().unmarshal(new StringReader(s));
System.out.println(object.getClassName());
}
#XmlType(name = "div")
#XmlRootElement(name = "div")
public static class Div {
private String className;
#XmlAttribute(name = "class")
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
}

Hibernate validation annotation - validate that at least one field is not null

Is there a way to define a Hibernate validation rule using annotations as defined here, stating that at least one field shall be not null?
This would be a hypothetical example (#OneFieldMustBeNotNullConstraint does not really exist):
#Entity
#OneFieldMustBeNotNullConstraint(list={fieldA,fieldB})
public class Card {
#Id
#GeneratedValue
private Integer card_id;
#Column(nullable = true)
private Long fieldA;
#Column(nullable = true)
private Long fieldB;
}
In the illustrated case, fieldA can be null or fieldB can be null, but not both.
One way would be to create my own validator, but I'd like to avoid if it already exists. Please share one validator if you have one already made... thanks!
I finally wrote the whole validator:
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import org.apache.commons.beanutils.PropertyUtils;
#Target( { TYPE })
#Retention(RUNTIME)
#Constraint(validatedBy = CheckAtLeastOneNotNull.CheckAtLeastOneNotNullValidator.class)
#Documented
public #interface CheckAtLeastOneNotNull {
String message() default "{com.xxx.constraints.checkatleastnotnull}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String[] fieldNames();
public static class CheckAtLeastOneNotNullValidator implements ConstraintValidator<CheckAtLeastOneNotNull, Object> {
private String[] fieldNames;
public void initialize(CheckAtLeastOneNotNull constraintAnnotation) {
this.fieldNames = constraintAnnotation.fieldNames();
}
public boolean isValid(Object object, ConstraintValidatorContext constraintContext) {
if (object == null) {
return true;
}
try {
for (String fieldName:fieldNames){
Object property = PropertyUtils.getProperty(object, fieldName);
if (property != null) return true;
}
return false;
} catch (Exception e) {
return false;
}
}
}
}
Example of usage:
#Entity
#CheckAtLeastOneNotNull(fieldNames={"fieldA","fieldB"})
public class Reward {
#Id
#GeneratedValue
private Integer id;
private Integer fieldA;
private Integer fieldB;
[...] // accessors, other fields, etc.
}
Just write your own validator. Is't should be pretty simple: iterate over field names and get field values by using reflection.
Concept:
Collection<String> values = Arrays.asList(
BeanUtils.getProperty(obj, fieldA),
BeanUtils.getProperty(obj, fieldB),
);
return CollectionUtils.exists(values, PredicateUtils.notNullPredicate());
There I used methods from commons-beanutils and commons-collections.
This is a bit like Resh32's answer but this will also bind the validation message with a specific field of the validated object.
The validation annotation class will be like the following one.
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* #author rumman
* #since 9/23/19
*/
#Target(TYPE)
#Retention(RUNTIME)
#Documented
#Constraint(validatedBy = NotNullAnyValidator.class)
public #interface NotNullAny {
String[] fieldNames();
String errorOnProperty();
String messageKey() default "{error.required}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
The validator class will be like the following.
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Objects;
import static org.springframework.beans.BeanUtils.getPropertyDescriptor;
/**
* #author rumman
* #since 9/23/19
*/
public class NotNullAnyValidator implements ConstraintValidator<NotNullAny, Object> {
private String[] fieldNames;
private String errorOnProperty;
private String messageKey;
#Override
public void initialize(NotNullAny validateDateRange) {
fieldNames = validateDateRange.fieldNames();
errorOnProperty = validateDateRange.errorOnProperty();
messageKey = validateDateRange.messageKey();
}
#Override
public boolean isValid(Object obj, ConstraintValidatorContext validatorContext) {
Object[] fieldValues = new Object[fieldNames.length];
try {
for (int i = 0; i < fieldValues.length; i++) {
fieldValues[i] = getPropertyDescriptor(obj.getClass(), fieldNames[i]).getReadMethod().invoke(obj);
}
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
if (Arrays.stream(fieldValues).noneMatch(Objects::nonNull)) {
validatorContext.buildConstraintViolationWithTemplate(messageKey)
.addPropertyNode(errorOnProperty)
.addConstraintViolation()
.disableDefaultConstraintViolation();
return false;
}
return true;
}
}
Pay attention to the last if condition block, this checks if no non null value is found then specifies the error message, the property with which the error message will be bound to and will add the constraint violation.
To use the annotation in a class
/**
* #author rumman
* #since 9/23/19
*/
#NotNullAny(fieldNames = {"field1", "field2", "field3"},
errorOnProperty = "field1",
messageKey = "my.error.msg.key")
public class TestEntityForValidation {
private String field1;
private String field2;
private String field3;
// standard constructor(s) and getter & setters below
}
If you could use javax.validation then I would use #AssertTrue.
Using javax.validation shouldn't be a problem since hibernate-validation is an implementation of javax.validation's interfaces/annotations which itself is an "implementation" of the Bean Validation 2.0 specification
#Entity
#OneFieldMustBeNotNullConstraint(list={fieldA,fieldB})
public class Card {
#Id
#GeneratedValue
private Integer card_id;
#Column(nullable = true)
private Long fieldA;
#Column(nullable = true)
private Long fieldB;
#AssertTrue(message = "at least one should be non-null")
public boolean isValid1() {
return Objects.nonNull(fieldA) || Objects.nonNull(fieldB);
}
}

Categories