1 package org.apache.slide.projector.descriptor; 2 3 import java.math.BigDecimal ; 4 import java.util.ArrayList ; 5 import java.util.Arrays ; 6 import java.util.Iterator ; 7 import java.util.List ; 8 9 import org.apache.slide.projector.Context; 10 import org.apache.slide.projector.i18n.ErrorMessage; 11 import org.apache.slide.projector.value.NumberValue; 12 import org.apache.slide.projector.value.Value; 13 14 public class NumberValueDescriptor implements ValueDescriptor { 15 protected boolean constrained; 16 protected List allowedValues = new ArrayList (); 17 protected Number minimum, maximum; 18 19 public NumberValueDescriptor() { 20 this.constrained = false; 21 } 22 23 public NumberValueDescriptor(Number minimum, Number maximum) { 24 constrained = true; 25 this.minimum = minimum; 26 this.maximum = maximum; 27 } 28 29 public NumberValueDescriptor(Number [] allowedValues) { 30 this.constrained = true; 31 this.allowedValues = new ArrayList (Arrays.asList(allowedValues)); 32 } 33 34 public boolean isConstrained() { 35 return constrained; 36 } 37 38 public void addAllowedValue(Number value) { 39 allowedValues.add(value); 40 } 41 42 public Number [] getAllowedValues() { 43 if ( allowedValues.isEmpty() ) return null; 44 return (Number [])allowedValues.toArray(new Number [0]); 45 } 46 47 public void setMinimum(Number minimum) { 48 this.minimum = minimum; 49 } 50 51 public Number getMinimum() { 52 return minimum; 53 } 54 55 public void setMaximum(Number maximum) { 56 this.maximum = maximum; 57 } 58 59 public Number getMaximum() { 60 return maximum; 61 } 62 63 public Value valueOf(Object value, Context context) throws ValueCastException { 64 if ( value instanceof NumberValue ) { 65 return (NumberValue)value; 66 } else { 67 try { 68 return new NumberValue(new BigDecimal (StringValueDescriptor.ANY.valueOf(value, null).toString())); 69 } catch ( ValueCastException exception ) { 70 throw new ValueCastException(new ErrorMessage("uncastableNumberValue", new Object [] { value }), exception); 71 } 72 } 73 } 74 75 public void validate(Value value, Context context) throws ValidationException { 76 if ( constrained ) { 77 Number number = ((NumberValue)value).getNumber(); 78 if ( getAllowedValues() != null ) { 79 for ( Iterator i = allowedValues.iterator(); i.hasNext(); ) { 80 Number allowedNumber = (Number )i.next(); 81 if ( allowedNumber.equals(number) ) { 82 return; 83 } 84 } 85 throw new ValidationException(new ErrorMessage("invalidNumber", new Object [] { value })); 86 } else { 87 if ( minimum.longValue() > number.longValue() || maximum.longValue() < number.longValue()) { 88 throw new ValidationException(new ErrorMessage("invalidNumberRange", new Object [] { number, minimum, maximum })); 89 } 90 } 91 } 92 } 93 } | Popular Tags |