Exemple #1
0
  public Any exec(Any a) throws AnyException {
    Transaction t = getTransaction();

    Composite sumRoot = (Composite) EvalExpr.evalFunc(t, a, sumRoot_, Composite.class);

    if (sumRoot == null) nullOperand(sumRoot_);

    Any expression = null;
    Any sum = null;
    Any tmp = null;
    Adder adder = null;

    if (takeAverage_ && sumRoot.entries() == 0) return null;

    Iter i = sumRoot.createIterator();

    Any loop = t.getLoop();

    try {
      while (i.hasNext()) {
        Any child = i.next();

        // Set $loop
        t.setLoop(child);

        // Lazy clone of expression
        if (expression == null) {
          expression = expression_.cloneAny();
        }

        if (sum == null) {
          sum = EvalExpr.evalFunc(t, a, expression);

          if (sum == null)
            throw new NullPointerException("Failed to resolve " + expression_ + "during summation");

          // To save on the creation of temporaries, the first sum
          // item is used as the prototype for the result.  The
          // remaining items, if not the same, must be convertible to it.
          adder = new Adder(sum);
          sum = adder.add(sum);
          tmp = sum.buildNew(null);
          adder.setTmp(tmp);
        } else {
          Any next = EvalExpr.evalFunc(t, a, expression);
          if (next == null)
            throw new NullPointerException("Failed to resolve " + expression_ + "during summation");

          adder.add(next);
        }

        // No point in continuing the iteration if we hit a null
        if (adder.isNull()) break;
      }

      if (adder != null && adder.isNull()) return AnyNull.instance();

      if (takeAverage_ && sum != null) return adder.doAvg(sum, sumRoot.entries());

      return sum == null ? AnyNull.instance() : sum;
    } finally {
      t.setLoop(loop);
    }
  }