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 MaxSizeCheck extends AbstractAnnotationCheck<MaxSize> {
27: private static final long serialVersionUID = 1L;
28:
29: private int max;
30:
31: @Override
32: public void configure(final MaxSize constraintAnnotation) {
33: super .configure(constraintAnnotation);
34: setMax(constraintAnnotation.value());
35: }
36:
37: /**
38: * @return the max
39: */
40: public int 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", Integer.toString(max));
49: return messageVariables;
50: }
51:
52: public boolean isSatisfied(final Object validatedObject,
53: final Object value, final OValContext context,
54: final Validator validator) {
55: if (value == null)
56: return true;
57:
58: if (value instanceof Collection) {
59: final int size = ((Collection) value).size();
60: return size <= max;
61: }
62: if (value instanceof Map) {
63: final int size = ((Map) value).size();
64: return size <= max;
65: }
66: if (value.getClass().isArray()) {
67: final int size = Array.getLength(value);
68: return size <= max;
69: }
70: return false;
71: }
72:
73: /**
74: * @param max the max to set
75: */
76: public void setMax(final int max) {
77: this.max = max;
78: }
79: }
|