1 package org.hibernate.validator; 3 4 import org.hibernate.mapping.Column; 5 import org.hibernate.mapping.Property; 6 7 11 public class RangeValidator implements Validator<Range>, PropertyConstraint { 12 private long max; 13 private long min; 14 15 public void initialize(Range parameters) { 16 max = parameters.max(); 17 min = parameters.min(); 18 } 19 20 public boolean isValid(Object value) { 21 if (value==null) return true; 22 if (value instanceof String ) { 23 try { 24 double dv = Double.parseDouble( (String ) value ); 25 return dv>=min && dv<= max; 26 } 27 catch (NumberFormatException nfe) { 28 return false; 29 } 30 } 31 else if ( (value instanceof Double ) || (value instanceof Float ) ) { 32 double dv = ( (Number ) value ).doubleValue(); 33 return dv>=min && dv<= max; 34 } 35 else if (value instanceof Number ) { 36 long lv = ( (Number ) value ).longValue(); 37 return lv>=min && lv<= max; 38 } 39 else { 40 return false; 41 } 42 } 43 44 public void apply(Property property) { 45 Column col = (Column) property.getColumnIterator().next(); 46 String check = ""; 47 if (min!=Long.MIN_VALUE) check+= col.getName() + ">" + min; 48 if (max!=Long.MAX_VALUE && min!=Long.MIN_VALUE) check += " and "; 49 if (max!=Long.MAX_VALUE) check += col.getName() + "<" + max; 50 col.setCheckConstraint(check); 51 } 52 53 } 54 | Popular Tags |