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.ConcurrentReaderHashMap;
07:
08: import com.tc.logging.TCLogger;
09: import com.tc.logging.TCLogging;
10:
11: import java.util.Map;
12:
13: /**
14: * @author orion
15: */
16: public class TCMessageRouterImpl implements TCMessageRouter {
17: private static final TCLogger logger = TCLogging
18: .getLogger(TCMessageRouter.class);
19: private final Map routesByType = new ConcurrentReaderHashMap();
20: private final TCMessageSink defaultRoute;
21:
22: public TCMessageRouterImpl() {
23: this (null);
24: }
25:
26: public TCMessageRouterImpl(TCMessageSink defRoute) {
27: if (null == defRoute) {
28: defaultRoute = new TCMessageSink() {
29: public void putMessage(TCMessage message)
30: throws UnsupportedMessageTypeException {
31: throw new UnsupportedMessageTypeException(message
32: .getMessageType());
33: }
34: };
35: } else {
36: defaultRoute = defRoute;
37: }
38: }
39:
40: public void putMessage(TCMessage msg) {
41: final boolean debug = logger.isDebugEnabled();
42:
43: if (debug)
44: logger.debug("Received a message: " + msg.toString());
45:
46: // try routing by message type
47: final TCMessageSink route = (TCMessageSink) routesByType
48: .get(msg.getMessageType());
49:
50: if (route != null) {
51: if (debug)
52: logger.debug(msg.getMessageType().toString()
53: + " message being routed by message type");
54: route.putMessage(msg);
55: } else {
56:
57: defaultRoute.putMessage(msg);
58: }
59: }
60:
61: public void routeMessageType(TCMessageType type, TCMessageSink sink) {
62: if (null == sink) {
63: throw new IllegalArgumentException("Sink cannot be null");
64: }
65: routesByType.put(type, sink);
66: }
67:
68: public void unrouteMessageType(TCMessageType type) {
69: routesByType.remove(type);
70: }
71: }
|