001    /*******************************************************************************
002     * Portions created by Sebastian Thomschke are copyright (c) 2005-2011 Sebastian
003     * Thomschke.
004     * 
005     * All Rights Reserved. This program and the accompanying materials
006     * are made available under the terms of the Eclipse Public License v1.0
007     * which accompanies this distribution, and is available at
008     * http://www.eclipse.org/legal/epl-v10.html
009     * 
010     * Contributors:
011     *     Sebastian Thomschke - initial implementation.
012     *******************************************************************************/
013    package net.sf.oval.constraint;
014    
015    import java.math.BigDecimal;
016    
017    import net.sf.oval.ConstraintTarget;
018    import net.sf.oval.Validator;
019    import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
020    import net.sf.oval.context.OValContext;
021    
022    /**
023     * @author Sebastian Thomschke
024     */
025    public class NotNegativeCheck extends AbstractAnnotationCheck<NotNegative>
026    {
027            private static final BigDecimal ZERO = BigDecimal.valueOf(0);
028    
029            private static final long serialVersionUID = 1L;
030    
031            /**
032             * {@inheritDoc}
033             */
034            @Override
035            protected ConstraintTarget[] getAppliesToDefault()
036            {
037                    return new ConstraintTarget[]{ConstraintTarget.VALUES};
038            }
039    
040            /**
041             * {@inheritDoc}
042             */
043            public boolean isSatisfied(final Object validatedObject, final Object valueToValidate, final OValContext context,
044                            final Validator validator)
045            {
046                    if (valueToValidate == null) return true;
047    
048                    if (valueToValidate instanceof Number)
049                    {
050                            if (valueToValidate instanceof Float || valueToValidate instanceof Double)
051                                    return ((Number) valueToValidate).doubleValue() >= 0;
052                            if (valueToValidate instanceof BigDecimal) return ((BigDecimal) valueToValidate).compareTo(ZERO) >= 0;
053                            return ((Number) valueToValidate).longValue() >= 0;
054                    }
055    
056                    final String stringValue = valueToValidate.toString();
057                    try
058                    {
059                            return Double.parseDouble(stringValue) >= 0;
060                    }
061                    catch (final NumberFormatException e)
062                    {
063                            return false;
064                    }
065            }
066    }