Class<? extends Integer> targetType, Locale locale)
throws ConversionException {
Number n = convertToNumber(value, targetType, locale);
- return n == null ? null : n.intValue();
+
+ if (n == null) {
+ return null;
+ }
+
+ int intValue = n.intValue();
+ if (intValue == n.longValue()) {
+ // If the value of n is outside the range of long, the return value
+ // of longValue() is either Long.MIN_VALUE or Long.MAX_VALUE. The
+ // above comparison promotes int to long and thus does not need to
+ // consider wrap-around.
+ return intValue;
+ }
+
+ throw new ConversionException("Could not convert '" + value + "' to "
+ + Integer.class.getName() + ": value out of range");
}
import junit.framework.TestCase;
+import com.vaadin.data.util.converter.Converter.ConversionException;
import com.vaadin.data.util.converter.StringToIntegerConverter;
public class TestStringToIntegerConverter extends TestCase {
assertEquals(null, converter.convertToModel("", Integer.class, null));
}
+ public void testValueOutOfRange() {
+ Double[] values = new Double[] { Integer.MAX_VALUE * 2.0,
+ Integer.MIN_VALUE * 2.0, Long.MAX_VALUE * 2.0,
+ Long.MIN_VALUE * 2.0 };
+
+ boolean accepted = false;
+ for (Number value : values) {
+ try {
+ converter.convertToModel(String.format("%.0f", value),
+ Integer.class, null);
+ accepted = true;
+ } catch (ConversionException expected) {
+ }
+ }
+ assertFalse("Accepted value outside range of int", accepted);
+ }
+
public void testValueConversion() {
assertEquals(Integer.valueOf(10),
converter.convertToModel("10", Integer.class, null));