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.lang.reflect.Array;
15: import java.util.Collection;
16: import java.util.Map;
17:
18: import net.sf.oval.Validator;
19: import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
20: import net.sf.oval.context.OValContext;
21: import net.sf.oval.internal.CollectionFactoryHolder;
22:
23: /**
24: * @author Sebastian Thomschke
25: */
26: public class SizeCheck extends AbstractAnnotationCheck<Size> {
27: private static final long serialVersionUID = 1L;
28:
29: private int min;
30: private int max;
31:
32: @Override
33: public void configure(final Size constraintAnnotation) {
34: super .configure(constraintAnnotation);
35: setMax(constraintAnnotation.max());
36: setMin(constraintAnnotation.min());
37: }
38:
39: /**
40: * @return the max
41: */
42: public int getMax() {
43: return max;
44: }
45:
46: @Override
47: public Map<String, String> getMessageVariables() {
48: final Map<String, String> messageVariables = CollectionFactoryHolder
49: .getFactory().createMap(2);
50: messageVariables.put("max", Integer.toString(max));
51: messageVariables.put("min", Integer.toString(min));
52: return messageVariables;
53: }
54:
55: /**
56: * @return the min
57: */
58: public int getMin() {
59: return min;
60: }
61:
62: public boolean isSatisfied(final Object validatedObject,
63: final Object value, final OValContext context,
64: final Validator validator) {
65: if (value == null)
66: return true;
67:
68: if (value instanceof Collection) {
69: final int size = ((Collection) value).size();
70: return size >= min && size <= max;
71: }
72: if (value instanceof Map) {
73: final int size = ((Map) value).size();
74: return size >= min && size <= max;
75: }
76: if (value.getClass().isArray()) {
77: final int size = Array.getLength(value);
78: return size >= min && size <= max;
79: }
80: return false;
81: }
82:
83: /**
84: * @param max the max to set
85: */
86: public void setMax(final int max) {
87: this .max = max;
88: }
89:
90: /**
91: * @param min the min to set
92: */
93: public void setMin(final int min) {
94: this.min = min;
95: }
96: }
|