View Javadoc
1 /*** 2 * SumOperator.java 3 * 4 * $Author: mballesteros $ 5 * $Date: 2003/11/28 19:18:03 $ 6 * $Revision: 1.1 $ 7 */ 8 package net.sf.jec.namedop; 9 10 import java.util.Collection; 11 import java.util.Iterator; 12 import java.util.Map; 13 14 import net.sf.jec.ConversionException; 15 import net.sf.jec.EvaluationException; 16 import net.sf.jec.ObjectConverter; 17 18 19 /*** SumOperator acts over a collection of elements, applying its argument operator 20 * to each element, and adding the results into a total sum. 21 * 22 * @author mballesteros 23 */ 24 public class SumOperator extends GroupOperator { 25 26 private boolean throwExceptions; 27 28 /*** Creates a new SumOperator 29 */ 30 public SumOperator() { } 31 32 /*** Returns a function representation String for this operator 33 */ 34 public String toFunctionString() { 35 return "Sum(" + argOps[0] 36 + (nestedOp == null? "" : ", "+nestedOp) + ")"; 37 } 38 39 /*** Returns an expression String representation for this operator 40 */ 41 public String toExpressionString() { 42 return (nestedOp == null? "" : nestedOp.toString()) + ".sum(" + argOps[0] + ")"; 43 } 44 45 46 /*** Returns the associated value to the given context and root context 47 * @param rootCtx The root context, needed for operators that require 48 * expression evaluation from root point. Example: Indexer operators 49 * @param ctx The current context where the operator will work over 50 */ 51 protected Object directMap(Object rootCtx, Object ctx) throws EvaluationException { 52 try { 53 if (ctx instanceof Collection) { 54 double acc = 0; 55 Iterator it = ((Collection)ctx).iterator(); 56 while (it.hasNext()) { 57 acc += ObjectConverter.toDouble(argOps[0].apply(rootCtx, it.next())); 58 } 59 return new Double(acc); 60 } else if (ctx instanceof Map) { 61 return applyToGroup(rootCtx, (Map)ctx ); 62 } else { 63 return null; 64 } 65 } catch (ConversionException ce) { 66 if (throwExceptions) throw new EvaluationException("Error converting value: "+ce.getMessage()); 67 else return null; 68 } 69 } 70 }

This page was automatically generated by Maven