View Javadoc

1   /*
2    *  XNap - A P2P framework and client.
3    *
4    *  See the file AUTHORS for copyright information.
5    *
6    *  This program is free software; you can redistribute it and/or modify
7    *  it under the terms of the GNU General Public License as published by
8    *  the Free Software Foundation.
9    *
10   *  This program is distributed in the hope that it will be useful,
11   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   *  GNU General Public License for more details.
14   *
15   *  You should have received a copy of the GNU General Public License
16   *  along with this program; if not, write to the Free Software
17   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18   */
19  
20  
21  package org.xnap.plugin.overnet.net.msg;
22  
23  import java.util.Collections;
24  import java.util.Hashtable;
25  import java.util.LinkedList;
26  import java.util.List;
27  
28  import org.xnap.plugin.overnet.net.msg.core.MessageListener;
29  
30  public class MessageHandler
31  {
32  
33      //--- Constant(s) ---
34  	
35      //--- Data field(s) ---
36  	
37      /***
38       * Maps message types to <code>MessageListener</code> objects.
39       */
40      private Hashtable listeners = new Hashtable();
41  
42  	public MessageHandler()
43      {
44      }
45      
46      //--- Method(s) ---
47  
48  
49      /***
50       * Handles message itself first and then sends it to all listeners. A
51       * listener can consume the message to prevent other listeners from
52       * getting it.
53       */
54      public void handle(OvernetMessage msg)
55      {
56  		msg.receive();
57  
58  		Object[] listeners = getListeners(msg.type).toArray();
59  		for (int i = 0; i < listeners.length; i++) {
60  			((MessageListener)listeners[i]).messageReceived(msg);
61  		}
62      }	
63  
64      public void subscribe(byte type, MessageListener listener)
65      {
66  		getListeners(type).add(listener);
67      }
68  
69      public void unsubscribe(byte type, MessageListener listener) 
70      {
71  		getListeners(type).remove(listener);
72      }
73  
74      private synchronized List getListeners(byte type) 
75      {
76  		List list = (List)listeners.get(new Byte(type));
77  
78  		if (list == null) {
79  			list = Collections.synchronizedList(new LinkedList());
80  			listeners.put(new Byte(type), list);
81  		}		
82  		return list;
83      }
84  }