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.util.Map;
18  
19  import net.sf.oval.ConstraintTarget;
20  import net.sf.oval.Validator;
21  import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
22  import net.sf.oval.context.OValContext;
23  
24  /**
25   * @author Sebastian Thomschke
26   */
27  public class MinCheck extends AbstractAnnotationCheck<Min>
28  {
29  	private static final long serialVersionUID = 1L;
30  
31  	private double min;
32  
33  	/**
34  	 * {@inheritDoc}
35  	 */
36  	@Override
37  	public void configure(final Min constraintAnnotation)
38  	{
39  		super.configure(constraintAnnotation);
40  		setMin(constraintAnnotation.value());
41  	}
42  
43  	/**
44  	 * {@inheritDoc}
45  	 */
46  	@Override
47  	protected Map<String, String> createMessageVariables()
48  	{
49  		final Map<String, String> messageVariables = getCollectionFactory().createMap(2);
50  		messageVariables.put("min", Double.toString(min));
51  		return messageVariables;
52  	}
53  
54  	/**
55  	 * {@inheritDoc}
56  	 */
57  	@Override
58  	protected ConstraintTarget[] getAppliesToDefault()
59  	{
60  		return new ConstraintTarget[]{ConstraintTarget.VALUES};
61  	}
62  
63  	/**
64  	 * @return the min
65  	 */
66  	public double getMin()
67  	{
68  		return min;
69  	}
70  
71  	/**
72  	 * {@inheritDoc}
73  	 */
74  	public boolean isSatisfied(final Object validatedObject, final Object valueToValidate, final OValContext context,
75  			final Validator validator)
76  	{
77  		if (valueToValidate == null) return true;
78  
79  		if (valueToValidate instanceof Number)
80  		{
81  			final double doubleValue = ((Number) valueToValidate).doubleValue();
82  			return doubleValue >= min;
83  		}
84  
85  		final String stringValue = valueToValidate.toString();
86  		try
87  		{
88  			final double doubleValue = Double.parseDouble(stringValue);
89  			return doubleValue >= min;
90  		}
91  		catch (final NumberFormatException e)
92  		{
93  			return false;
94  		}
95  	}
96  
97  	/**
98  	 * @param min the min to set
99  	 */
100 	public void setMin(final double min)
101 	{
102 		this.min = min;
103 		requireMessageVariablesRecreation();
104 	}
105 }