01: /*
02: * Copyright 2007 JBoss Inc
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: *
16: * Created on Jun 21, 2007
17: */
18: package org.drools.base.accumulators;
19:
20: /**
21: * An implementation of an accumulator capable of calculating average values
22: *
23: * @author etirelli
24: *
25: */
26: public class AverageAccumulateFunction implements AccumulateFunction {
27:
28: protected static class AverageData {
29: public int count = 0;
30: public double total = 0;
31: }
32:
33: /* (non-Javadoc)
34: * @see org.drools.base.accumulators.AccumulateFunction#createContext()
35: */
36: public Object createContext() {
37: return new AverageData();
38: }
39:
40: /* (non-Javadoc)
41: * @see org.drools.base.accumulators.AccumulateFunction#init(java.lang.Object)
42: */
43: public void init(Object context) throws Exception {
44: AverageData data = (AverageData) context;
45: data.count = 0;
46: data.total = 0;
47: }
48:
49: /* (non-Javadoc)
50: * @see org.drools.base.accumulators.AccumulateFunction#accumulate(java.lang.Object, java.lang.Object)
51: */
52: public void accumulate(Object context, Object value) {
53: AverageData data = (AverageData) context;
54: data.count++;
55: data.total += ((Number) value).doubleValue();
56: }
57:
58: /* (non-Javadoc)
59: * @see org.drools.base.accumulators.AccumulateFunction#reverse(java.lang.Object, java.lang.Object)
60: */
61: public void reverse(Object context, Object value) throws Exception {
62: AverageData data = (AverageData) context;
63: data.count--;
64: data.total -= ((Number) value).doubleValue();
65: }
66:
67: /* (non-Javadoc)
68: * @see org.drools.base.accumulators.AccumulateFunction#getResult(java.lang.Object)
69: */
70: public Object getResult(Object context) throws Exception {
71: AverageData data = (AverageData) context;
72: return new Double(data.count == 0 ? 0 : data.total / data.count);
73: }
74:
75: /* (non-Javadoc)
76: * @see org.drools.base.accumulators.AccumulateFunction#supportsReverse()
77: */
78: public boolean supportsReverse() {
79: return true;
80: }
81:
82: }
|