01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.net.protocol.tcm;
05:
06: import EDU.oswego.cs.dl.util.concurrent.SynchronizedLong;
07:
08: import com.tc.text.StringFormatter;
09:
10: import java.util.HashMap;
11: import java.util.Iterator;
12: import java.util.Map;
13:
14: public class MessageMonitorImpl implements MessageMonitor {
15:
16: private final Map counters = new HashMap();
17: private final StringFormatter formatter = new StringFormatter();
18:
19: public void newIncomingMessage(TCMessage message) {
20: getOrCreateMessageCounter(message.getMessageType())
21: .newIncomingMessage(message);
22: }
23:
24: public void newOutgoingMessage(TCMessage message) {
25: getOrCreateMessageCounter(message.getMessageType())
26: .newOutgoingMessage(message);
27: }
28:
29: private MessageCounter getOrCreateMessageCounter(Object key) {
30: synchronized (counters) {
31: MessageCounter rv = (MessageCounter) counters.get(key);
32: if (rv == null) {
33: rv = new MessageCounter(formatter, key.toString());
34: counters.put(key, rv);
35: }
36: return rv;
37: }
38: }
39:
40: public String toString() {
41: StringBuffer rv = new StringBuffer();
42: String nl = System.getProperty("line.separator");
43: rv.append("Message monitor").append(nl);
44: synchronized (counters) {
45: for (Iterator i = counters.values().iterator(); i.hasNext();) {
46: rv.append(i.next()).append(nl);
47: }
48: }
49: rv.append(nl);
50: return rv.toString();
51: }
52:
53: private static class MessageCounter {
54:
55: private final String name;
56: private final SynchronizedLong incomingCount = new SynchronizedLong(
57: 0);
58: private final SynchronizedLong incomingData = new SynchronizedLong(
59: 0);
60:
61: private final SynchronizedLong outgoingCount = new SynchronizedLong(
62: 0);
63: private final SynchronizedLong outgoingData = new SynchronizedLong(
64: 0);
65: private final StringFormatter formatter;
66:
67: private MessageCounter(StringFormatter formatter, String name) {
68: this .formatter = formatter;
69: this .name = formatter.rightPad(25, name);
70: }
71:
72: private synchronized void newIncomingMessage(TCMessage message) {
73: incomingCount.increment();
74: incomingData.add(message.getTotalLength());
75: }
76:
77: private synchronized void newOutgoingMessage(TCMessage message) {
78: outgoingCount.increment();
79: outgoingData.add(message.getTotalLength());
80: }
81:
82: public String toString() {
83: return name + "| IN: "
84: + formatter.leftPad(30, incomingCount) + ", "
85: + formatter.leftPad(30, incomingData) + "b"
86: + "| OUT: " + formatter.leftPad(30, outgoingCount)
87: + ", " + formatter.leftPad(30, outgoingData) + "b";
88:
89: }
90: }
91: }
|