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