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 static net.sf.oval.Validator.getCollectionFactory; 016 017 import java.util.Map; 018 019 import net.sf.oval.ConstraintTarget; 020 import net.sf.oval.Validator; 021 import net.sf.oval.configuration.annotation.AbstractAnnotationCheck; 022 import net.sf.oval.context.OValContext; 023 024 /** 025 * @author Sebastian Thomschke 026 */ 027 public class MinCheck extends AbstractAnnotationCheck<Min> 028 { 029 private static final long serialVersionUID = 1L; 030 031 private double min; 032 033 /** 034 * {@inheritDoc} 035 */ 036 @Override 037 public void configure(final Min constraintAnnotation) 038 { 039 super.configure(constraintAnnotation); 040 setMin(constraintAnnotation.value()); 041 } 042 043 /** 044 * {@inheritDoc} 045 */ 046 @Override 047 protected Map<String, String> createMessageVariables() 048 { 049 final Map<String, String> messageVariables = getCollectionFactory().createMap(2); 050 messageVariables.put("min", Double.toString(min)); 051 return messageVariables; 052 } 053 054 /** 055 * {@inheritDoc} 056 */ 057 @Override 058 protected ConstraintTarget[] getAppliesToDefault() 059 { 060 return new ConstraintTarget[]{ConstraintTarget.VALUES}; 061 } 062 063 /** 064 * @return the min 065 */ 066 public double getMin() 067 { 068 return min; 069 } 070 071 /** 072 * {@inheritDoc} 073 */ 074 public boolean isSatisfied(final Object validatedObject, final Object valueToValidate, final OValContext context, 075 final Validator validator) 076 { 077 if (valueToValidate == null) return true; 078 079 if (valueToValidate instanceof Number) 080 { 081 final double doubleValue = ((Number) valueToValidate).doubleValue(); 082 return doubleValue >= min; 083 } 084 085 final String stringValue = valueToValidate.toString(); 086 try 087 { 088 final double doubleValue = Double.parseDouble(stringValue); 089 return doubleValue >= min; 090 } 091 catch (final NumberFormatException e) 092 { 093 return false; 094 } 095 } 096 097 /** 098 * @param min the min to set 099 */ 100 public void setMin(final double min) 101 { 102 this.min = min; 103 requireMessageVariablesRecreation(); 104 } 105 }