01: /*******************************************************************************
02: * Portions created by Sebastian Thomschke are copyright (c) 2005-2007 Sebastian
03: * Thomschke.
04: *
05: * All Rights Reserved. This program and the accompanying materials
06: * are made available under the terms of the Eclipse Public License v1.0
07: * which accompanies this distribution, and is available at
08: * http://www.eclipse.org/legal/epl-v10.html
09: *
10: * Contributors:
11: * Sebastian Thomschke - initial implementation.
12: *******************************************************************************/package net.sf.oval.constraint;
13:
14: import java.util.Map;
15:
16: import net.sf.oval.Validator;
17: import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
18: import net.sf.oval.context.OValContext;
19: import net.sf.oval.internal.CollectionFactoryHolder;
20:
21: /**
22: * @author Sebastian Thomschke
23: */
24: public class RangeCheck extends AbstractAnnotationCheck<Range> {
25: private static final long serialVersionUID = 1L;
26:
27: private long min = Long.MIN_VALUE;
28: private long max = Long.MAX_VALUE;
29:
30: @Override
31: public void configure(final Range constraintAnnotation) {
32: super .configure(constraintAnnotation);
33: setMax(constraintAnnotation.max());
34: setMin(constraintAnnotation.min());
35: }
36:
37: /**
38: * @return the max
39: */
40: public long getMax() {
41: return max;
42: }
43:
44: @Override
45: public Map<String, String> getMessageVariables() {
46: final Map<String, String> messageVariables = CollectionFactoryHolder
47: .getFactory().createMap(2);
48: messageVariables.put("max", Long.toString(max));
49: messageVariables.put("min", Long.toString(min));
50: return messageVariables;
51: }
52:
53: /**
54: * @return the min
55: */
56: public long getMin() {
57: return min;
58: }
59:
60: public boolean isSatisfied(final Object validatedObject,
61: final Object value, final OValContext context,
62: final Validator validator) {
63: if (value == null)
64: return true;
65:
66: if (value instanceof Number) {
67: if (value instanceof Float || value instanceof Double) {
68: final double doubleValue = ((Number) value)
69: .doubleValue();
70: return doubleValue >= min && doubleValue <= max;
71: }
72: final long longValue = ((Number) value).longValue();
73: return longValue >= min && longValue <= max;
74: }
75:
76: final String stringValue = value.toString();
77: try {
78: final double doubleValue = Double.parseDouble(stringValue);
79: return doubleValue >= min && doubleValue <= max;
80: } catch (NumberFormatException e) {
81: return false;
82: }
83: }
84:
85: /**
86: * @param max the max to set
87: */
88: public void setMax(final long max) {
89: this .max = max;
90: }
91:
92: /**
93: * @param min the min to set
94: */
95: public void setMin(final long min) {
96: this.min = min;
97: }
98: }
|