KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > net > protocol > tcm > TCMessageRouterImpl


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.net.protocol.tcm;
5
6 import EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap;
7
8 import com.tc.logging.TCLogger;
9 import com.tc.logging.TCLogging;
10
11 import java.util.Map JavaDoc;
12
13 /**
14  * @author orion
15  */

16 public class TCMessageRouterImpl implements TCMessageRouter {
17   private static final TCLogger logger = TCLogging.getLogger(TCMessageRouter.class);
18   private final Map routesByType = new ConcurrentReaderHashMap();
19   private final TCMessageSink defaultRoute;
20
21   public TCMessageRouterImpl() {
22     this(null);
23   }
24
25   public TCMessageRouterImpl(TCMessageSink defRoute) {
26     if (null == defRoute) {
27       defaultRoute = new TCMessageSink() {
28         public void putMessage(TCMessage message) throws UnsupportedMessageTypeException {
29           throw new UnsupportedMessageTypeException(message.getMessageType());
30         }
31       };
32     } else {
33       defaultRoute = defRoute;
34     }
35   }
36
37   public void putMessage(TCMessage msg) {
38     final boolean debug = logger.isDebugEnabled();
39
40     if (debug) logger.debug("Received a message: " + msg.toString());
41
42     // try routing by message type
43
final TCMessageSink route = (TCMessageSink) routesByType.get(msg.getMessageType());
44
45     if (route != null) {
46       if (debug) logger.debug(msg.getMessageType().toString() + " message being routed by message type");
47       route.putMessage(msg);
48     } else {
49
50       defaultRoute.putMessage(msg);
51     }
52   }
53
54   public void routeMessageType(TCMessageType type, TCMessageSink sink) {
55     if (null == sink) { throw new IllegalArgumentException JavaDoc("Sink cannot be null"); }
56     routesByType.put(type, sink);
57   }
58
59   public void unrouteMessageType(TCMessageType type) {
60     routesByType.remove(type);
61   }
62 }
Popular Tags