KickJava   Java API By Example, From Geeks To Geeks.

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


1 //$Id: MaxValidator.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  * Do check a max restriction on a numeric (whether and actual number or its string representation,
9  * and apply expected contraints on hibernate metadata.
10  *
11  * @author Gavin King
12  */

13 public class MaxValidator implements Validator<Max>, PropertyConstraint {
14     
15     private int max;
16     
17     public void initialize(Max parameters) {
18         max = parameters.value();
19     }
20
21     public boolean isValid(Object JavaDoc value) {
22         if (value==null) return true;
23         if (value instanceof String JavaDoc) {
24             try {
25                 double dv = Double.parseDouble( (String JavaDoc) value );
26                 return dv<=max;
27             }
28             catch (NumberFormatException JavaDoc nfe) {
29                 return false;
30             }
31         }
32         else if ( (value instanceof Double JavaDoc) || (value instanceof Float JavaDoc) ) {
33             double dv = ( (Number JavaDoc) value ).doubleValue();
34             return dv<=max;
35         }
36         else if (value instanceof Number JavaDoc) {
37             long lv = ( (Number JavaDoc) value ).longValue();
38             return lv<=max;
39         }
40         else {
41             return false;
42         }
43     }
44
45     public void apply(Property property) {
46         Column col = (Column) property.getColumnIterator().next();
47         col.setCheckConstraint( col.getName() + "<=" + max);
48     }
49 }
50
Popular Tags