final DataOutput dOutSum = abvsSum.getDataOutput();
final ArrayBackedValueStorage abvsCount = new ArrayBackedValueStorage();
final DataOutput dOutCount = abvsCount.getDataOutput();
final AddOperation aOp = new AddOperation();
final DivideOperation aOpDivide = new DivideOperation();
final TypedPointables tp1 = new TypedPointables();
final TypedPointables tp2 = new TypedPointables();
return new AbstractTaggedValueArgumentAggregateEvaluator(args) {
long count;
TaggedValuePointable tvpSum = (TaggedValuePointable) TaggedValuePointable.FACTORY.createPointable();
@Override
public void init() throws AlgebricksException {
count = 0;
}
@Override
public void finishPartial(IPointable result) throws AlgebricksException {
finish(result);
}
@Override
public void finish(IPointable result) throws AlgebricksException {
if (count == 0) {
XDMConstants.setEmptySequence(result);
} else {
// Set count as a TaggedValuePointable.
try {
abvsCount.reset();
dOutCount.write(ValueTag.XS_INTEGER_TAG);
dOutCount.writeLong(count);
tvpCount.set(abvsCount);
FunctionHelper.arithmeticOperation(aOpDivide, dCtx, tvpSum, tvpCount, tvpSum, tp1, tp2);
result.set(tvpSum);
} catch (Exception e) {
throw new AlgebricksException(e);
}
}
}
@Override
protected void step(TaggedValuePointable[] args) throws SystemException {
TaggedValuePointable tvp = args[0];
if (count == 0) {
// Init.
try {
abvsSum.reset();
dOutSum.write(tvp.getByteArray(), tvp.getStartOffset(), tvp.getLength());
tvpSum.set(abvsSum);
} catch (IOException e) {
throw new SystemException(ErrorCode.SYSE0001, e.toString());
}
} else {
FunctionHelper.arithmeticOperation(aOp, dCtx, tvp, tvpSum, tvpSum, new TypedPointables(), new TypedPointables());
}
count++;
}
};
}