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 counting occurences
22: *
23: * @author etirelli
24: *
25: */
26: public class CountAccumulateFunction implements AccumulateFunction {
27:
28: protected static class CountData {
29: public long count = 0;
30: }
31:
32: /* (non-Javadoc)
33: * @see org.drools.base.accumulators.AccumulateFunction#createContext()
34: */
35: public Object createContext() {
36: return new CountData();
37: }
38:
39: /* (non-Javadoc)
40: * @see org.drools.base.accumulators.AccumulateFunction#init(java.lang.Object)
41: */
42: public void init(Object context) throws Exception {
43: CountData data = (CountData) context;
44: data.count = 0;
45: }
46:
47: /* (non-Javadoc)
48: * @see org.drools.base.accumulators.AccumulateFunction#accumulate(java.lang.Object, java.lang.Object)
49: */
50: public void accumulate(Object context, Object value) {
51: CountData data = (CountData) context;
52: data.count++;
53: }
54:
55: /* (non-Javadoc)
56: * @see org.drools.base.accumulators.AccumulateFunction#reverse(java.lang.Object, java.lang.Object)
57: */
58: public void reverse(Object context, Object value) throws Exception {
59: CountData data = (CountData) context;
60: data.count--;
61: }
62:
63: /* (non-Javadoc)
64: * @see org.drools.base.accumulators.AccumulateFunction#getResult(java.lang.Object)
65: */
66: public Object getResult(Object context) throws Exception {
67: CountData data = (CountData) context;
68: return new Long(data.count);
69: }
70:
71: /* (non-Javadoc)
72: * @see org.drools.base.accumulators.AccumulateFunction#supportsReverse()
73: */
74: public boolean supportsReverse() {
75: return true;
76: }
77:
78: }
|