1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 *
19 */
20 package org.apache.mina.handler.demux;
21
22 import java.util.Collections;
23 import java.util.Map;
24 import java.util.Set;
25
26 import org.apache.mina.common.IoHandler;
27 import org.apache.mina.common.IoHandlerAdapter;
28 import org.apache.mina.common.IoSession;
29 import org.apache.mina.util.IdentityHashSet;
30
31 import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap;
32
33 /**
34 * A {@link IoHandler} that demuxes <code>messageReceived</code> events
35 * to the appropriate {@link MessageHandler}.
36 * <p>
37 * You can freely register and deregister {@link MessageHandler}s using
38 * {@link #addMessageHandler(Class, MessageHandler)} and
39 * {@link #removeMessageHandler(Class)}.
40 * </p>
41 * <p>
42 * When <code>message</code> is received through a call to
43 * {@link #messageReceived(IoSession, Object)} the class of the
44 * <code>message</code> object will be used to find a {@link MessageHandler} for
45 * that particular message type. If no {@link MessageHandler} instance can be
46 * found for the immediate class (i.e. <code>message.getClass()</code>) the
47 * interfaces implemented by the immediate class will be searched in depth-first
48 * order. If no match can be found for any of the interfaces the search will be
49 * repeated recursively for the superclass of the immediate class
50 * (i.e. <code>message.getClass().getSuperclass()</code>).
51 * </p>
52 * <p>
53 * Consider the following type hierarchy (<code>Cx</code> are classes while
54 * <code>Ix</code> are interfaces):
55 * <pre>
56 * C3 - I7 - I9
57 * | | /\
58 * | I8 I3 I4
59 * |
60 * C2 - I5 - I6
61 * |
62 * C1 - I1 - I2 - I4
63 * | |
64 * | I3
65 * Object
66 * </pre>
67 * When <code>message</code> is of type <code>C3</code> this hierarchy will be
68 * searched in the following order:
69 * <code>C3, I7, I8, I9, I3, I4, C2, I5, I6, C1, I1, I2, I3, I4, Object</code>.
70 * </p>
71 * <p>
72 * For efficiency searches will be cached. Calls to
73 * {@link #addMessageHandler(Class, MessageHandler)} and
74 * {@link #removeMessageHandler(Class)} clear this cache.
75 * </p>
76 *
77 * @author The Apache Directory Project (mina-dev@directory.apache.org)
78 * @version $Rev: 555855 $, $Date: 2007-07-13 12:19:00 +0900 (Fri, 13 Jul 2007) $
79 */
80 public class DemuxingIoHandler extends IoHandlerAdapter {
81 private final Map findHandlerCache = new ConcurrentHashMap();
82
83 private final Map type2handler = new ConcurrentHashMap();
84
85 /**
86 * Creates a new instance with no registered {@link MessageHandler}s.
87 */
88 public DemuxingIoHandler() {
89 }
90
91 /**
92 * Registers a {@link MessageHandler} that receives the messages of
93 * the specified <code>type</code>.
94 *
95 * @return the old handler if there is already a registered handler for
96 * the specified <tt>type</tt>. <tt>null</tt> otherwise.
97 */
98 public MessageHandler addMessageHandler(Class type, MessageHandler handler) {
99 findHandlerCache.clear();
100 return (MessageHandler) type2handler.put(type, handler);
101 }
102
103 /**
104 * Deregisters a {@link MessageHandler} that receives the messages of
105 * the specified <code>type</code>.
106 *
107 * @return the removed handler if successfully removed. <tt>null</tt> otherwise.
108 */
109 public MessageHandler removeMessageHandler(Class type) {
110 findHandlerCache.clear();
111 return (MessageHandler) type2handler.remove(type);
112 }
113
114 /**
115 * Returns the {@link MessageHandler} which is registered to process
116 * the specified <code>type</code>.
117 */
118 public MessageHandler getMessageHandler(Class type) {
119 return (MessageHandler) type2handler.get(type);
120 }
121
122 /**
123 * Returns the {@link Map} which contains all messageType-{@link MessageHandler}
124 * pairs registered to this handler.
125 */
126 public Map getMessageHandlerMap() {
127 return Collections.unmodifiableMap(type2handler);
128 }
129
130 /**
131 * Forwards the received events into the appropriate {@link MessageHandler}
132 * which is registered by {@link #addMessageHandler(Class, MessageHandler)}.
133 */
134 public void messageReceived(IoSession session, Object message)
135 throws Exception {
136 MessageHandler handler = findHandler(message.getClass());
137 if (handler != null) {
138 handler.messageReceived(session, message);
139 } else {
140 throw new UnknownMessageTypeException(
141 "No message handler found for message: " + message);
142 }
143 }
144
145 protected MessageHandler findHandler(Class type) {
146 return findHandler(type, null);
147 }
148
149 private MessageHandler findHandler(Class type, Set triedClasses) {
150 MessageHandler handler = null;
151
152 if (triedClasses != null && triedClasses.contains(type))
153 return null;
154
155 /*
156 * Try the cache first.
157 */
158 handler = (MessageHandler) findHandlerCache.get(type);
159 if (handler != null)
160 return handler;
161
162 /*
163 * Try the registered handlers for an immediate match.
164 */
165 handler = (MessageHandler) type2handler.get(type);
166
167 if (handler == null) {
168 /*
169 * No immediate match could be found. Search the type's interfaces.
170 */
171
172 if (triedClasses == null)
173 triedClasses = new IdentityHashSet();
174 triedClasses.add(type);
175
176 Class[] interfaces = type.getInterfaces();
177 for (int i = 0; i < interfaces.length; i++) {
178 handler = findHandler(interfaces[i], triedClasses);
179 if (handler != null)
180 break;
181 }
182 }
183
184 if (handler == null) {
185 /*
186 * No match in type's interfaces could be found. Search the
187 * superclass.
188 */
189
190 Class superclass = type.getSuperclass();
191 if (superclass != null)
192 handler = findHandler(superclass);
193 }
194
195 /*
196 * Make sure the handler is added to the cache. By updating the cache
197 * here all the types (superclasses and interfaces) in the path which
198 * led to a match will be cached along with the immediate message type.
199 */
200 if (handler != null)
201 findHandlerCache.put(type, handler);
202
203 return handler;
204 }
205 }