diff --git a/src/main/java/no/nibio/vips/util/ModelUtil.java b/src/main/java/no/nibio/vips/util/ModelUtil.java index 4781caec68dd179311c4567adb3641db424e185c..55ea86ffa9f5380c4a8d55cc3a53407ae04de675 100755 --- a/src/main/java/no/nibio/vips/util/ModelUtil.java +++ b/src/main/java/no/nibio/vips/util/ModelUtil.java @@ -24,11 +24,14 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; +import java.math.BigDecimal; +import java.math.BigInteger; import java.net.URLConnection; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import no.nibio.vips.entity.WeatherObservation; +import no.nibio.vips.model.ConfigValidationException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; @@ -145,4 +148,54 @@ public class ModelUtil { return mapper.convertValue(unknownClassList, new TypeReference<List<WeatherObservation>>(){}); } } + + public Double getDouble(Object possibleNumber) throws ConfigValidationException + { + if(possibleNumber == null) + { + return null; + } + + if(possibleNumber instanceof String) + { + try + { + return Double.valueOf((String) possibleNumber); + } + catch(NumberFormatException ex) + { + throw new ConfigValidationException(ex.getMessage()); + } + } + if(possibleNumber instanceof Integer) + { + return ((Integer) possibleNumber).doubleValue(); + } + if(possibleNumber instanceof Float) + { + return ((Float) possibleNumber).doubleValue(); + } + if(possibleNumber instanceof Double) + { + return (Double) possibleNumber; + } + // Clutching at straws + if(possibleNumber instanceof BigInteger) + { + return ((BigInteger) possibleNumber).doubleValue(); + } + if(possibleNumber instanceof BigDecimal) + { + return ((BigDecimal) possibleNumber).doubleValue(); + } + // Out of options. Throw Exception + try + { + return (Double) possibleNumber; + } + catch(ClassCastException ex) + { + throw new ConfigValidationException(ex.getMessage()); + } + } } diff --git a/src/test/java/no/nibio/vips/util/ModelUtilTest.java b/src/test/java/no/nibio/vips/util/ModelUtilTest.java index 5bd06145731d50a7ecb094cf9f5f335bce2f13e0..271e77bb66aa2ea1a5d1ac8f19eb208b015542b8 100755 --- a/src/test/java/no/nibio/vips/util/ModelUtilTest.java +++ b/src/test/java/no/nibio/vips/util/ModelUtilTest.java @@ -20,7 +20,10 @@ package no.nibio.vips.util; import java.io.BufferedInputStream; import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; import junit.framework.TestCase; +import no.nibio.vips.model.ConfigValidationException; /** * @@ -80,6 +83,6 @@ public class ModelUtilTest extends TestCase { } - + }