01: /*_############################################################################
02: _##
03: _## SNMP4J - DefaultCounterListener.java
04: _##
05: _## Copyright (C) 2003-2008 Frank Fock and Jochen Katz (SNMP4J.org)
06: _##
07: _## Licensed under the Apache License, Version 2.0 (the "License");
08: _## you may not use this file except in compliance with the License.
09: _## You may obtain a copy of the License at
10: _##
11: _## http://www.apache.org/licenses/LICENSE-2.0
12: _##
13: _## Unless required by applicable law or agreed to in writing, software
14: _## distributed under the License is distributed on an "AS IS" BASIS,
15: _## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16: _## See the License for the specific language governing permissions and
17: _## limitations under the License.
18: _##
19: _##########################################################################*/
20:
21: package org.snmp4j.mp;
22:
23: import org.snmp4j.event.CounterListener;
24: import org.snmp4j.event.CounterEvent;
25: import java.util.Hashtable;
26: import org.snmp4j.smi.OID;
27: import org.snmp4j.smi.VariableBinding;
28: import org.snmp4j.smi.Counter32;
29: import org.snmp4j.smi.Variable;
30:
31: /**
32: * The <code>DefaultCounterListener</code> is the default implementation of
33: * the <code>CounterListener</code> interface. For any counter incrementation
34: * event it checks whether the referenced counter object already exists. If not,
35: * it will be created and initialized with one. Otherwise, the current value
36: * will be incremented by one. In either case, the current value will be
37: * returned in the event object.
38: * <p>
39: * To use a <code>DefaultCounterListener</code> with SNMP4J, add it to the
40: * default <code>CounterSupport</code> by:
41: * <pre>
42: * CounterSupport.getInstance().addCounterListener(new DefaultCounterListener());
43: * </pre>
44: *
45: * @author Frank Fock
46: * @version 1.0.1
47: */
48: public class DefaultCounterListener implements CounterListener {
49:
50: private Hashtable counters = new Hashtable(50);
51:
52: /**
53: * Default constructor.
54: */
55: public DefaultCounterListener() {
56: }
57:
58: public synchronized void incrementCounter(CounterEvent event) {
59: OID id = event.getOid();
60: VariableBinding counter = (VariableBinding) counters.get(id);
61: if (counter == null) {
62: counter = new VariableBinding(id, new Counter32(1));
63: counters.put(id, counter);
64: } else {
65: ((Counter32) counter.getVariable()).increment();
66: }
67: // write back current value
68: event.setCurrentValue((Variable) ((VariableBinding) counter)
69: .getVariable().clone());
70: }
71: }
|