KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > validator > RangeValidator


1 //$Id: RangeValidator.java,v 1.1 2005/05/27 08:58:54 epbernard Exp $
2
package org.hibernate.validator;
3
4 import org.hibernate.mapping.Column;
5 import org.hibernate.mapping.Property;
6
7 /**
8  * The value has to be in a defined range, the constraint is also applied on DB
9  * @author Gavin King
10  */

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 JavaDoc value) {
21         if (value==null) return true;
22         if (value instanceof String JavaDoc) {
23             try {
24                 double dv = Double.parseDouble( (String JavaDoc) value );
25                 return dv>=min && dv<= max;
26             }
27             catch (NumberFormatException JavaDoc nfe) {
28                 return false;
29             }
30         }
31         else if ( (value instanceof Double JavaDoc) || (value instanceof Float JavaDoc) ) {
32             double dv = ( (Number JavaDoc) value ).doubleValue();
33             return dv>=min && dv<= max;
34         }
35         else if (value instanceof Number JavaDoc) {
36             long lv = ( (Number JavaDoc) 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 JavaDoc 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