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 java.math.BigDecimal;
16  
17  import net.sf.oval.ConstraintTarget;
18  import net.sf.oval.Validator;
19  import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
20  import net.sf.oval.context.OValContext;
21  
22  /**
23   * @author Sebastian Thomschke
24   */
25  public class NotNegativeCheck extends AbstractAnnotationCheck<NotNegative>
26  {
27  	private static final BigDecimal ZERO = BigDecimal.valueOf(0);
28  
29  	private static final long serialVersionUID = 1L;
30  
31  	/**
32  	 * {@inheritDoc}
33  	 */
34  	@Override
35  	protected ConstraintTarget[] getAppliesToDefault()
36  	{
37  		return new ConstraintTarget[]{ConstraintTarget.VALUES};
38  	}
39  
40  	/**
41  	 * {@inheritDoc}
42  	 */
43  	public boolean isSatisfied(final Object validatedObject, final Object valueToValidate, final OValContext context,
44  			final Validator validator)
45  	{
46  		if (valueToValidate == null) return true;
47  
48  		if (valueToValidate instanceof Number)
49  		{
50  			if (valueToValidate instanceof Float || valueToValidate instanceof Double)
51  				return ((Number) valueToValidate).doubleValue() >= 0;
52  			if (valueToValidate instanceof BigDecimal) return ((BigDecimal) valueToValidate).compareTo(ZERO) >= 0;
53  			return ((Number) valueToValidate).longValue() >= 0;
54  		}
55  
56  		final String stringValue = valueToValidate.toString();
57  		try
58  		{
59  			return Double.parseDouble(stringValue) >= 0;
60  		}
61  		catch (final NumberFormatException e)
62  		{
63  			return false;
64  		}
65  	}
66  }