1 20 package org.apache.mina.handler.demux; 21 22 import java.util.Collections ; 23 import java.util.Map ; 24 import java.util.Set ; 25 import java.util.concurrent.ConcurrentHashMap ; 26 27 import org.apache.mina.common.IoHandler; 28 import org.apache.mina.common.IoHandlerAdapter; 29 import org.apache.mina.common.IoSession; 30 import org.apache.mina.util.IdentityHashSet; 31 32 79 public class DemuxingIoHandler extends IoHandlerAdapter { 80 private final Map <Class , MessageHandler> findHandlerCache = new ConcurrentHashMap <Class , MessageHandler>(); 81 82 private final Map <Class , MessageHandler> type2handler = new ConcurrentHashMap <Class , MessageHandler>(); 83 84 87 public DemuxingIoHandler() { 88 } 89 90 97 @SuppressWarnings ("unchecked") 98 public <E> MessageHandler<? super E> addMessageHandler(Class <E> type, 99 MessageHandler<? super E> handler) { 100 findHandlerCache.clear(); 101 return type2handler.put(type, handler); 102 } 103 104 110 @SuppressWarnings ("unchecked") 111 public <E> MessageHandler<? super E> removeMessageHandler(Class <E> type) { 112 findHandlerCache.clear(); 113 return type2handler.remove(type); 114 } 115 116 120 @SuppressWarnings ("unchecked") 121 public <E> MessageHandler<? super E> getMessageHandler(Class <E> type) { 122 return type2handler.get(type); 123 } 124 125 129 public Map <Class , MessageHandler> getMessageHandlerMap() { 130 return Collections.unmodifiableMap(type2handler); 131 } 132 133 137 public void messageReceived(IoSession session, Object message) 138 throws Exception { 139 MessageHandler<Object > handler = findHandler(message.getClass()); 140 if (handler != null) { 141 handler.messageReceived(session, message); 142 } else { 143 throw new UnknownMessageTypeException( 144 "No message handler found for message: " + message); 145 } 146 } 147 148 protected MessageHandler<Object > findHandler(Class type) { 149 return findHandler(type, null); 150 } 151 152 @SuppressWarnings ("unchecked") 153 private MessageHandler<Object > findHandler(Class type, 154 Set <Class > triedClasses) { 155 MessageHandler handler = null; 156 157 if (triedClasses != null && triedClasses.contains(type)) 158 return null; 159 160 163 handler = findHandlerCache.get(type); 164 if (handler != null) 165 return handler; 166 167 170 handler = type2handler.get(type); 171 172 if (handler == null) { 173 176 177 if (triedClasses == null) 178 triedClasses = new IdentityHashSet<Class >(); 179 triedClasses.add(type); 180 181 Class [] interfaces = type.getInterfaces(); 182 for (int i = 0; i < interfaces.length; i++) { 183 handler = findHandler(interfaces[i], triedClasses); 184 if (handler != null) 185 break; 186 } 187 } 188 189 if (handler == null) { 190 194 195 Class superclass = type.getSuperclass(); 196 if (superclass != null) 197 handler = findHandler(superclass); 198 } 199 200 205 if (handler != null) 206 findHandlerCache.put(type, handler); 207 208 return handler; 209 } 210 } 211 | Popular Tags |