From: Johannes Dahlström Date: Thu, 1 Aug 2013 08:53:34 +0000 (+0300) Subject: Ensure StringToIntegerConverter rejects values outside range of int (#12230) X-Git-Tag: 7.1.2~6 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=7fc105440755357d469d87b9523afc6f84e0bda7;p=vaadin-framework.git Ensure StringToIntegerConverter rejects values outside range of int (#12230) Change-Id: I150bee64144045355bfa75ac10ede663d3feb5ce --- diff --git a/server/src/com/vaadin/data/util/converter/StringToIntegerConverter.java b/server/src/com/vaadin/data/util/converter/StringToIntegerConverter.java index bc436112fe..f6f668ad4d 100644 --- a/server/src/com/vaadin/data/util/converter/StringToIntegerConverter.java +++ b/server/src/com/vaadin/data/util/converter/StringToIntegerConverter.java @@ -62,7 +62,22 @@ public class StringToIntegerConverter extends Class 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"); } diff --git a/server/tests/src/com/vaadin/tests/data/converter/TestStringToIntegerConverter.java b/server/tests/src/com/vaadin/tests/data/converter/TestStringToIntegerConverter.java index c73853578e..e810106631 100644 --- a/server/tests/src/com/vaadin/tests/data/converter/TestStringToIntegerConverter.java +++ b/server/tests/src/com/vaadin/tests/data/converter/TestStringToIntegerConverter.java @@ -2,6 +2,7 @@ package com.vaadin.tests.data.converter; import junit.framework.TestCase; +import com.vaadin.data.util.converter.Converter.ConversionException; import com.vaadin.data.util.converter.StringToIntegerConverter; public class TestStringToIntegerConverter extends TestCase { @@ -16,6 +17,23 @@ 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));