public class SumFunction extends AbstractExpression {
public Object evaluate(ExpressionContext context) throws ExpressionException {
BigDecimal result = new BigDecimal("0");
for(int i = 0; i < arguments.size(); i++) {
Expression function = (Expression)arguments.get(i);
Object ret = function.evaluate(context);
if (ret instanceof Collection) {
ret = ((Collection)ret).iterator();
}
if (ret instanceof Iterator) {
Iterator iter = (Iterator)ret;
while (iter.hasNext()) {
Object p = iter.next();
BigDecimal db = null;
if (p instanceof BigDecimal) {
db =(BigDecimal)p;
} else if (p instanceof Long) {
db = new BigDecimal(((Long)p).longValue());
} else if (p instanceof Integer) {
db = new BigDecimal(((Integer)p).intValue());
} else if (p instanceof Double) {
db = new BigDecimal(((Double)p).doubleValue());
} else if (p instanceof Float) {
db = new BigDecimal(((Float)p).floatValue());
} else if (p instanceof BigInteger) {
db = new BigDecimal((BigInteger)p);
} else if (p instanceof Number) {
db = new BigDecimal(((Number)p).doubleValue());
} else if (p instanceof String) {
db = new BigDecimal((String)p);
} else {
throw new IllegalArgumentException("Cannot sum an argument of type " + p.getClass().getName());
}
result = result.add(db);
}
} else {
result = result.add((BigDecimal)function.evaluate(context));
}
}
return result;
}