access session in custom constraint hibernate validator - java

I have a problem that I've solved but I don't understand why. so maybe someone can help me to understand it. I have create a custom constrain for hibernate validator. when I operate the entity, using update, merge or saveorupdate. it always return stack trace overflow exception. so I google it and then I try some code, than it worked. but I still want to know why it worked and why it throws the exception.
this is the code for custom annotation
#Target({METHOD, FIELD, ANNOTATION_TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = UniqueIDValidator.class)
#Documented
public #interface UniqueKey {
String message() default "{validation.unique}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/**
* The mapped hibernate/jpa entity class
*/
Class<?> entity();
/**
* The property of the entity we want to validate for uniqueness. Default name is "id"
*/
String property() default "id";
}
and this is the custom constraint validator code
public class UniqueIDValidator implements ConstraintValidator<UniqueKey, Serializable>{
private final static Logger LOG= Logger.getLogger(UniqueIDValidator.class);
#Autowired
private SessionFactory sessionFactory;
private Class<?> entityClass;
private String uniqueField;
public void initialize(UniqueKey unique) {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
entityClass = unique.entity();
uniqueField = unique.property();
}
#Override
public boolean isValid(Serializable arg0, ConstraintValidatorContext arg1) {
String query = String.format("from %s where %s = :%s ", entityClass.getName(), uniqueField, uniqueField);
List<?> list = null;
try{
list = sessionFactory.getCurrentSession().createQuery(query).setParameter(uniqueField, arg0).list(); <---- This line cause the exeption
}catch(Exception e){
LOG.error(e);
}
return (list != null && !(list.size() > 1));
}
}
after i follow Here I try to wired the EntityManager but always return null, so I have this code below, and it worked.
#Override
public boolean isValid(Serializable arg0, ConstraintValidatorContext arg1) {
String query = String.format("from %s where %s = :%s ", entityClass.getName(), uniqueField, uniqueField);
List<?> list = null;
try{
// below line of code make it worked
sessionFactory.getCurrentSession().setFlushMode(FlushMode.COMMIT);
list = sessionFactory.getCurrentSession().createQuery(query).setParameter(uniqueField, arg0).list();
}catch(Exception e){
LOG.error(e);
}finally {
// this is to reset the hibernate config I think
sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO);
}
return (list != null && !(list.size() > 1));
}
the exception is
java.lang.StackOverflowError at java.util.HashMap$EntrySet.iterator(HashMap.java:1082) at sun.reflect.annotation.AnnotationInvocationHandler.hashCodeImpl(AnnotationInvoca‌​tionHandler.java:294)
at sun.reflect.annotation.AnnotationInvocationHandler.invoke(AnnotationInvocationHa‌​ndler.java:64)
at com.sun.proxy.$Proxy35.hashCode(Unknown Source) at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidator‌​Manager$CacheKey.createHashCode(ConstraintValidatorManager.java:326)
What I want to ask is:
1. why before I add Flushmode.COMMIT it throws stackoverflow exception?
2. Is this change will affect others hibernate behaviour such as save, persist etc?
I'm sorry for my poor english, english is my not my native language. Thanks in advance.
Now i have new problem, this constraint is evaluated when I do update. I have to check if the object is in dirty state or not. but I don't know how.

Related

Spring MVC validation and Thymeleaf - validating Integer field

I am moving .net project to Spring Boot.
So the question is on how to properly validate Integer fields in Spring.
I have an entity with an Integer field:
#Entity
#Table(name = "tb_employee")
public class EmployeeDev {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "empl_id")
private int emplId;
#Range(min = 10, max = 50, message="Numbers only between 10 and 50")
#Column(name = "default_vacation_days", nullable = true)
private Integer defaultVacationDays;
... and a controller capturing the errors:
// update employee
#PostMapping("/edit")
public String showFormForUpdate(#Valid #ModelAttribute("employee") EmployeeDev employee, Errors errors,
RedirectAttributes redirectAttributes,
Model theModel) {
if (null != errors && errors.getErrorCount() > 0) {
List<ObjectError> errs = errors.getAllErrors();
String errMsg = "";
for (ObjectError e :errs)
errMsg += e.getDefaultMessage();
theModel.addAttribute("message", "Employee Edit failed. " + errMsg );
theModel.addAttribute("alertClass", "alert-danger");
return "employeesdev/employee-form-edit";
}
Now the problem is when I type into the default vacation days field any number outside of the range
it shows the correct validation message: Numbers only between 10 and 50.
However if I try to insert something like 1A (possible user typo) I get this message:
Failed to convert property value of type java.lang.String to required type java.lang.Integer for property defaultVacationDays; nested exception is java.lang.NumberFormatException: For input string: "1A"
I understand this is the correct message but I hate to show a message like this to a user.
I would prefer to show just "Numbers only between 10 and 50" instead of data type conversion problems.
Why bother users with Java data types?
I would appreciate any suggestions.
If you want get custom behaviour from the annotation you need to define your own constriant annotation and validator for this annotation.
Here is basic example of custom constraint annotation:
#Target({TYPE, ANNOTATION_TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = CheckCalculationTypeValidator.class)
#Documented
public #interface CheckCalculationType {
String message() default "calculation_type shall be not NULL if status = active";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
and validator:
public class CheckCalculationTypeValidator implements ConstraintValidator<CheckCalculationType, RequestDto> {
#Override
public boolean isValid(RequestDto dto, ConstraintValidatorContext constraintValidatorContext) {
if (dto == null) {
return true;
}
return !(Status.ACTIVE.equals(dto.getStatus()) && dto.getCalculationType() == null);
}
#Override
public void initialize(CheckCalculationType constraintAnnotation) {
// NOP
}
}
Required dependency for Hibernate Validator:
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.2.Final</version>
</dependency>

TYPE_USE annotation in hibernate validator

I know hibernate validator supports TYPE_USE annotations: though it does not define its own, it lets you define and use custom ones.
I could define and validate correctly such an annotation (code soon), but then I want to map the error into a path that is used to display the error to the user.
Given then following sample
public class SampleTest {
private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
public static class LimitedSizeStringValidator implements ConstraintValidator<LimitedSize, String> {
private LimitedSize constraint;
#Override
public void initialize(LimitedSize constraintAnnotation) {
this.constraint = constraintAnnotation;
}
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
String s = Ensure.notNull(value);
return s.length() >= constraint.min() &&
s.length() <= constraint.max();
}
}
#Retention(RUNTIME)
#Documented
#Target({TYPE_USE})
#Constraint(validatedBy = {LimitedSizeStringValidator.class})
public #interface LimitedSize {
String message() default "{javax.validation.constraints.Size.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int min() default 0;
int max() default Integer.MAX_VALUE;
}
private static class TestBean {
#Valid
private Collection<#LimitedSize(max = 3) String> strings = new ArrayList<>();
#Valid
private Collection<InnerBean> beans = new ArrayList<>();
}
private static class InnerBean {
#Min(3)
private final int value;
private InnerBean(int value) {
this.value = value;
}
}
#Test
public void testBeanInvalid() {
TestBean testBean = new TestBean();
assertThat(validator.validate(testBean)).isEmpty();
testBean.strings.add("ok");
testBean.strings.add("ok2");
testBean.beans.add(new InnerBean(4));
assertThat(validator.validate(testBean)).isEmpty();
testBean.strings.add("not_ok");
testBean.beans.add(new InnerBean(2));
Set<ConstraintViolation<TestBean>> violations = validator.validate(testBean);
assertThat(violations).hasSize(2);
StreamSupport.stream(violations.spliterator(), false)
.forEach(v -> {
System.out.println(v.getPropertyPath());
System.out.println(v.getMessage());
v.getPropertyPath().forEach(p -> System.out.print("'" + p.getName() + (p.getIndex() != null ? "[" + p.getIndex() + "]" : "") + "' -> "));
System.out.println();
});
}
}
I would like map the errors in an object like
errors: [
["beans", "1", "value"],
["strings", "2"]
]
As in my sample, my approach at the moment is by navigating the violation path (http://docs.oracle.com/javaee/7/api/javax/validation/ConstraintViolation.html#getPropertyPath--) which works perfectly for the first case, but fails for the second (I cannot find a way to retrieve the index of the failing object). I think the reason is in the implementation of javax.validation.Path.PropertyNode in hibernate-validator (I am currently on version 5.2.4.Final, and the code looks the same as in the linked 5.2.1.Final. For reference:
#Override
public final Integer getIndex() {
if ( parent == null ) {
return null;
}
else {
return parent.index;
}
}
With TYPE_USE this approach cannot work in my opinion, because the failing object is a leaf, thus no child node can retrieve the index from it.
Nice enough, hibernate implementation of javax.validation.Path overrides the toString method is way such that violation.getPropertyPath().toString() is beans[1].value and strings[2] (in the sample code above).
So, to the question(s): is my navigation approach wrong and there is another way to extract such a mapping from the ConstraintViolation? Or is this a feature request for hibernate developers (I can see that before TYPE_USE annotations the getIndex approach they implemented was totally fine?
It just feels strange I am the first one with this problem (I tried to google and could not find anything related, the closest being: https://github.com/hibernate/hibernate-validator/pull/441) so I am wondering whether the mistake is mine rather than a hibernate limitation
I agree that the index should be set for that value and think you uncovered an issue in Hibernate Validator. Could you open an issue in our JIRA tracker?
Btw. the notion of TYPE_USE level constraints will be standardized as of Bean Validation 2.0. So there may be some more changes coming up in this area, specifically I'm wondering what Kind that node should have (currently it's PROPERTY which seems questionable).

call further validators from isValid() method?

suppose i have the following scenario:
public class EntityA {
private List<EntityB> listOfBs;
}
im trying to cascade validation to the list of Bs only if running under a certain validation group. so ideally, this:
public class EntityA {
#Valid(groups = {SomeSpecificGroup.class})
private List<EntityB> listOfBs;
}
unfortunately, #Valid does not have a groups() property. so i figured i'd try something like:
#Constraint(validatedBy = { CascadedValidator.class })
#Target({ ElementType.METHOD, ElementType.FIELD})
#Retention(RetentionPolicy.RUNTIME)
public #interface CascadedValidation {
Class<?>[] groups() default { };
}
and write a validator (CascadedValidator) that upon activation will do the cascade (==will validate all elements of the collection its placed on).
my issue is how do i perform the cascaded validation?
so far i have this:
public class CascadedValidator implements ConstraintValidator<CascadedValidation, Object>{
private Class<?>[] groups;
#Override public void initialize(CascadedValidation constraintAnnotation) {
groups = constraintAnnotation.groups();
}
#Override public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value == null || !(value instanceof Iterable)) {
return true;
}
for (Object item : (Iterable)value) {
//validate item using the groups?!
}
}
}
i know i could implement the actual validation by creating another Validator "inline":
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Object>> violations;
if (decideIfCascade(groups)) {
for (Object item : (Iterable)value) {
if (groups!=null && groups.length>0) {
violations = validator.validate(item, groups);
} else {
violations = validator.validate(item);
}
if (!violations.isEmpty()) {
return false;
}
}
}
return true;
but this just smells bad to me.
surely there's a sane/normal/easy way of doing this?
EDIT - the actual use case
my API accept both EntityA (which has a list of Bs) and EntityB as top-level entities (so you can send a single B directly). both A and B have an id property, but i only require a non-null id on the top level object submitted. so if the service gets an A with an idea and several "blank" Bs its ok, but if i get a B as a top level parameter it must have an id.
You should not invoke the validation engine from within a ConstraintValidator implementation.
If you are on Bean Validation 1.1, have a look at group conversions which give you control over the validation groups propagated upon cascaded validation. E.g. you could do the following:
#Valid
#ConvertGroup(from = Default.class, to = SomeSpecificGroup.class)
private List<EntityB> listOfBs;

How to add annotations on a classes properties, and iterate on properties?

I want to add annotations on my classes properties, and then iterate all my properties with the ability to lookup the annotations also.
So for example, I have a class like:
public class User {
#Annotation1
private int id;
#Annotation2
private String name;
private int age;
// getters and setters
}
Now I want to be able to loop through my properties, and be able to know what annotation (if any) is on the property.
I want to know how to do this using just java, but also curious if using either spring, guava or google guice would make this any easier (if they have any helpers to do this easier).
Here is an example that utilizes the (barely maintained) bean instrospection framework. It's an all Java solution that you can extend to fit your needs.
public class BeanProcessor {
public static void main(String[] args) {
try {
final Class<?> beanClazz = BBean.class;
BeanInfo info = Introspector.getBeanInfo(beanClazz);
PropertyDescriptor[] propertyInfo = info.getPropertyDescriptors();
for (final PropertyDescriptor descriptor : propertyInfo) {
try {
final Field field = beanClazz.getDeclaredField(descriptor
.getName());
System.out.println(field);
for (final Annotation annotation : field
.getDeclaredAnnotations()) {
System.out.println("Annotation: " + annotation);
}
} catch (final NoSuchFieldException nsfe) {
// ignore these
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Below is the way to create your own annotation
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface Annotation1 {
public String name();
public String value();
}
After defining your annotation, use the annotation as you mentioned in your question and you can use the below reflection method to get the annotated class details
Class aClass = User.class;
Annotation[] annotations = aClass.getAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof Annotation1){
Annotation1 myAnnotation = (Annotation1) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
}
I created the method below which creates a stream of all fields in a class and it's superclasses which have a specific annotation.
There are other ways to do it. But I think this solution is very easy to reuse and practical because when you need to know those fields, it is usually to do an action on each field. And a Stream is exactly what you need to do that.
public static Stream<Field> getAnnotatedFieldStream(Class<?> theClass, Class<? extends Annotation> annotationType) {
Class<?> classOrSuperClass = theClass;
Stream<Field> stream = Stream.empty();
while(classOrSuperClass != Object.class) {
stream = Stream.concat(stream, Stream.of(classOrSuperClass.getDeclaredFields()));
classOrSuperClass = classOrSuperClass.getSuperclass();
}
return stream.filter(f -> f.isAnnotationPresent(annotationType));
}
you would use reflection to get the fields of the class and then call something like getAnnotations() on each field.

hibernate unique key validation

I have a field, say, user_name, that should be unique in a table.
What is the best way for validating it using Spring/Hibernate validation?
One of the possible solutions is to create custom #UniqueKey constraint (and corresponding validator); and to look-up the existing records in database, provide an instance of EntityManager (or Hibernate Session)to UniqueKeyValidator.
EntityManagerAwareValidator
public interface EntityManagerAwareValidator {
void setEntityManager(EntityManager entityManager);
}
ConstraintValidatorFactoryImpl
public class ConstraintValidatorFactoryImpl implements ConstraintValidatorFactory {
private EntityManagerFactory entityManagerFactory;
public ConstraintValidatorFactoryImpl(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
#Override
public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
T instance = null;
try {
instance = key.newInstance();
} catch (Exception e) {
// could not instantiate class
e.printStackTrace();
}
if(EntityManagerAwareValidator.class.isAssignableFrom(key)) {
EntityManagerAwareValidator validator = (EntityManagerAwareValidator) instance;
validator.setEntityManager(entityManagerFactory.createEntityManager());
}
return instance;
}
}
UniqueKey
#Constraint(validatedBy={UniqueKeyValidator.class})
#Target({ElementType.TYPE})
#Retention(RUNTIME)
public #interface UniqueKey {
String[] columnNames();
String message() default "{UniqueKey.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
#Target({ ElementType.TYPE })
#Retention(RUNTIME)
#Documented
#interface List {
UniqueKey[] value();
}
}
UniqueKeyValidator
public class UniqueKeyValidator implements ConstraintValidator<UniqueKey, Serializable>, EntityManagerAwareValidator {
private EntityManager entityManager;
#Override
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
private String[] columnNames;
#Override
public void initialize(UniqueKey constraintAnnotation) {
this.columnNames = constraintAnnotation.columnNames();
}
#Override
public boolean isValid(Serializable target, ConstraintValidatorContext context) {
Class<?> entityClass = target.getClass();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<?> root = criteriaQuery.from(entityClass);
List<Predicate> predicates = new ArrayList<Predicate> (columnNames.length);
try {
for(int i=0; i<columnNames.length; i++) {
String propertyName = columnNames[i];
PropertyDescriptor desc = new PropertyDescriptor(propertyName, entityClass);
Method readMethod = desc.getReadMethod();
Object propertyValue = readMethod.invoke(target);
Predicate predicate = criteriaBuilder.equal(root.get(propertyName), propertyValue);
predicates.add(predicate);
}
} catch (Exception e) {
e.printStackTrace();
}
criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
TypedQuery<Object> typedQuery = entityManager.createQuery(criteriaQuery);
List<Object> resultSet = typedQuery.getResultList();
return resultSet.size() == 0;
}
}
Usage
#UniqueKey(columnNames={"userName"})
// #UniqueKey(columnNames={"userName", "emailId"}) // composite unique key
//#UniqueKey.List(value = {#UniqueKey(columnNames = { "userName" }), #UniqueKey(columnNames = { "emailId" })}) // more than one unique keys
public class User implements Serializable {
private String userName;
private String password;
private String emailId;
protected User() {
super();
}
public User(String userName) {
this.userName = userName;
}
....
}
Test
public void uniqueKey() {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("default");
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
ValidatorContext validatorContext = validatorFactory.usingContext();
validatorContext.constraintValidatorFactory(new ConstraintValidatorFactoryImpl(entityManagerFactory));
Validator validator = validatorContext.getValidator();
EntityManager em = entityManagerFactory.createEntityManager();
User se = new User("abc", poizon);
Set<ConstraintViolation<User>> violations = validator.validate(se);
System.out.println("Size:- " + violations.size());
em.getTransaction().begin();
em.persist(se);
em.getTransaction().commit();
User se1 = new User("abc");
violations = validator.validate(se1);
System.out.println("Size:- " + violations.size());
}
I think it is not wise to use Hibernate Validator (JSR 303) for this purpose.
Or better it is not the goal of Hibernate Validator.
The JSR 303 is about bean validation. This means to check if a field is set correct. But what you want is in a much wider scope than a single bean. It is somehow in a global scope (regarding all Beans of this type). -- I think you should let the database handle this problem. Set a unique constraint to the column in your database (for example by annotate the field with #Column(unique=true)) and the database will make sure that the field is unique.
Anyway, if you really want to use JSR303 for this, than you need to create your own Annotation and own Validator. The Validator have to access the Database and check if there is no other entity with the specified value. - But I believe there would be some problems to access the database from the Validator in the right session.
One possibility is to annotate the field as #NaturalId
You could use the #Column attribute which can be set as unique.
I've found kind of a tricky solution.
First, I've implemented the unique contraint to my MySql database :
CREATE TABLE XMLTAG
(
ID INTEGER NOT NULL AUTO_INCREMENT,
LABEL VARCHAR(64) NOT NULL,
XPATH VARCHAR(128),
PRIMARY KEY (ID),
UNIQUE UQ_XMLTAG_LABEL(LABEL)
) ;
You see that I manage XML Tags that are defined by a unique label and a text field named "XPath".
Anyway, the second step is to simply catch the error raised when the user tries to do a bad update. A bad update is when trying to replace the current label by an existing label. If you leave the label untouched, no problemo. So, in my controller :
#RequestMapping(value = "/updatetag", method = RequestMethod.POST)
public String updateTag(
#ModelAttribute("tag") Tag tag,
#Valid Tag validTag,
BindingResult result,
ModelMap map) {
if(result.hasErrors()) { // you don't care : validation of other
return "editTag"; // constraints like #NotEmpty
}
try {
tagService.updateTag(tag); // try to update
return "redirect:/tags"; // <- if it works
}
catch (DataIntegrityViolationException ex) { // if it doesn't work
result.rejectValue("label", "Unique.tag.label"); // pass an error message to the view
return "editTag"; // same treatment as other validation errors
}
}
This may conflict with the #Unique pattern but you can use this dirty method to valid the adding too.
Note : there is still one problem : if other validation errors are catched before the exception, the message about unicity will not be displayed.
This code is based on the previous one implemented using EntityManager.
In case anyone need to use Hibernate Session.
Custom Annotation using Hibernate Session.
#UniqueKey.java
import java.lang.annotation.*;
import javax.validation.Constraint;
import javax.validation.Payload;
#Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD})
#Retention(RetentionPolicy.RUNTIME)
#Constraint(validatedBy = UniqueKeyValidator.class)
#Documented
public #interface UniqueKey {
String columnName();
Class<?> className();
String message() default "{UniqueKey.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
UnqieKeyValidator.java
import ch.qos.logback.classic.gaffer.PropertyUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
#Transactional
#Repository
public class UniqueKeyValidator implements ConstraintValidator<UniqueKey, String> {
#Autowired
private SessionFactory sessionFactory;
public Session getSession() {
return sessionFactory.getCurrentSession();
}
private String columnName;
private Class<?> entityClass;
#Override
public void initialize(UniqueKey constraintAnnotation) {
this.columnNames = constraintAnnotation.columnNames();
this.entityClass = constraintAnnotation.className();
}
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
Class<?> entityClass = this.entityClass;
System.out.println("class: " + entityClass.toString());
Criteria criteria = getSession().createCriteria(entityClass);
try {
criteria.add(Restrictions.eq(this.columnName, value));
} catch (Exception e) {
e.printStackTrace();
}
return criteria.list().size()==0;
}
}
Usage
#UniqueKey(columnNames="userName", className = UserEntity.class)
// #UniqueKey(columnNames="userName") // unique key

Categories

Resources