View Javadoc
1   /*******************************************************************************
2    * Portions created by Sebastian Thomschke are copyright (c) 2005-2011 Sebastian
3    * Thomschke.
4    * 
5    * All Rights Reserved. This program and the accompanying materials
6    * are made available under the terms of the Eclipse Public License v1.0
7    * which accompanies this distribution, and is available at
8    * http://www.eclipse.org/legal/epl-v10.html
9    * 
10   * Contributors:
11   *     Sebastian Thomschke - initial implementation.
12   *******************************************************************************/
13  package net.sf.oval.constraint;
14  
15  import static net.sf.oval.Validator.getCollectionFactory;
16  
17  import java.lang.reflect.Array;
18  import java.util.Collection;
19  import java.util.Map;
20  
21  import net.sf.oval.Validator;
22  import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
23  import net.sf.oval.context.OValContext;
24  
25  /**
26   * @author Sebastian Thomschke
27   */
28  public class MinSizeCheck extends AbstractAnnotationCheck<MinSize>
29  {
30  	private static final long serialVersionUID = 1L;
31  
32  	private int min;
33  
34  	/**
35  	 * {@inheritDoc}
36  	 */
37  	@Override
38  	public void configure(final MinSize constraintAnnotation)
39  	{
40  		super.configure(constraintAnnotation);
41  		setMin(constraintAnnotation.value());
42  	}
43  
44  	/**
45  	 * {@inheritDoc}
46  	 */
47  	@Override
48  	protected Map<String, String> createMessageVariables()
49  	{
50  		final Map<String, String> messageVariables = getCollectionFactory().createMap(2);
51  		messageVariables.put("min", Integer.toString(min));
52  		return messageVariables;
53  	}
54  
55  	/**
56  	 * @return the min
57  	 */
58  	public int getMin()
59  	{
60  		return min;
61  	}
62  
63  	/**
64  	 * {@inheritDoc}
65  	 */
66  	public boolean isSatisfied(final Object validatedObject, final Object valueToValidate, final OValContext context,
67  			final Validator validator)
68  	{
69  		if (valueToValidate == null) return true;
70  
71  		if (valueToValidate instanceof Collection)
72  		{
73  			final int size = ((Collection< ? >) valueToValidate).size();
74  			return size >= min;
75  		}
76  		if (valueToValidate instanceof Map)
77  		{
78  			final int size = ((Map< ? , ? >) valueToValidate).size();
79  			return size >= min;
80  		}
81  		if (valueToValidate.getClass().isArray())
82  		{
83  			final int size = Array.getLength(valueToValidate);
84  			return size >= min;
85  		}
86  		return false;
87  	}
88  
89  	/**
90  	 * @param min the min to set
91  	 */
92  	public void setMin(final int min)
93  	{
94  		this.min = min;
95  		requireMessageVariablesRecreation();
96  	}
97  }