Hibernate Books

All times are UTC - 5 hours [ DST ]



Post new topic Reply to topic  [ 2 posts ] 
Author Message
 Post subject: Custom validator of a bean field using other field
PostPosted: Mon May 07, 2012 1:59 pm 
Newbie

Joined: Thu Dec 18, 2008 1:40 pm
Posts: 8
Not sure if this possible. Wondering if I can create a custom constraint for a bean's field where it would use values of other field of the same class object. Tried writing the codes below -

Code:
public final class AWRRecordObject extends DoaAbstract implements java.io.Serializable {
   
     private static final long serialVersionUID = 1L;
   
    @ValidateApplicationType
    private String applicationType;
   
    private String recordData;

    private String programSource;

    Class<AWRRecordObject> value(); //?

...


Code:
public class ApplicationTypeValidator implements ConstraintValidator<ValidateApplicationType, AWRRecordObject> {

   private Class<AWRRecordObject> awrRecObj; // ?
      
   @Override
   public void initialize(ValidateApplicationType constraintAnnotation) {
      
      this.awrRecObj = constraintAnnotation.value();
   }

   @Override
   public boolean isValid(String arg0, ConstraintValidatorContext arg1) {
            
      
      // verify if the application type is A1 and length is 512   
      if ((awrRecObj.getApplicationType().equalsIgnoreCase(AWRConstant.AWR_W2))
            && (awrRecObj.getRecordData().toString().length() != AWRConstant.W2_RECORD_LEN)
            && (awrRecObj.getProgramSource().equalsIgnoreCase(AWRConstant.SOURCE_BATCH))) {
         
         // create AWRRequestError Object and add it to  AWRRecordObject
         AWRUtility.createAWRRequestErrorObject(awrRecObj, AWRErrorTypeCode.W2_RECORD_LENGTH_ERROR, awrRecObj.getRecordData());
         return false;
         ...
      }
      
      return true;
...
   }

Code:
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {ApplicationTypeValidator.class})
public @interface ValidateApplicationType {

   String message() default "{com.myproject.validation.ApplicationType.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
   
    Class<AWRRecordObject> value();

}


The code that reads fixed length file and store parsed values into a bean -
Code:
public static AWRRecordObject bufferedReader() throws IOException {
      
   int lineCount = 0;
   long time1 = System.currentTimeMillis();
   File file = new File("D://TestData/test.txt");
   BufferedReader br = new BufferedReader(new FileReader(file), 8192);
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
   String line;
   
   while((line = br.readLine()) != null) {
         
      String type = line.length() > 2 ? line.substring(0, 2) : line;

      AWRRecordObject record = new AWRRecordObject(line, type, lineCount);

      Set<ConstraintViolation<AWRRecordObject>> constraintViolations = validator.validate(record);

               if (constraintViolations.size() > 0) {
               
                  Iterator it = constraintViolations.iterator();
                  while (it.hasNext()) {
                     ConstraintViolation<AWRRecordObject> cv = (ConstraintViolation<AWRRecordObject>) it.next();
                     System.out.println(cv.getInvalidValue());
                     System.out.println(cv.getMessage());
                  
                  
                  }

               }


            return record;
   }

...


Getting the error message -
Code:
Exception in thread "main" javax.validation.UnexpectedTypeException: No validator could be found for type: java.lang.String
   at org.hibernate.validator.engine.ConstraintTree.verifyResolveWasUnique(ConstraintTree.java:383)


Top
 Profile  
 
 Post subject: Re: Custom validator of a bean field using other field
PostPosted: Thu Jun 14, 2012 7:19 am 
Newbie

Joined: Tue Jul 10, 2007 10:32 am
Posts: 4
Hello,
I don't know really what your problem has to do with accessing other fields (also referred to as cross-field validation, see https://hibernate.onjira.com/browse/BVAL-240), but anyway I think the cause of the exception is that you didn't declare your ConstraintValidator implementation correctly:

Code:
public class ApplicationTypeValidator implements ConstraintValidator<ValidateApplicationType, AWRRecordObject>


should probably be:

Code:
public class ApplicationTypeValidator implements ConstraintValidator<ValidateApplicationType, String>


I wonder if your code actually compiles this way?

Hope that helps,
best regards,
vivian

PS: if you really have a cross-field validation issue, please vote on the issue https://hibernate.onjira.com/browse/BVAL-240, so that we can get some improvements in this area. Thanks!


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.