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  package org.xnap.plugin.opennap.net.msg;
21  
22  import java.util.LinkedList;
23  
24  import org.xnap.plugin.opennap.net.OpenNapServer;
25  import org.xnap.plugin.opennap.net.msg.server.ServerMessage;
26  
27  public class MessageStream implements MessageListener {
28  
29      //--- Data field(s) ---
30      
31      protected Object lock = new Object();
32      protected LinkedList queue = new LinkedList();
33      protected OpenNapServer server;
34  
35      //--- Constructor(s) ---
36  
37      public MessageStream(OpenNapServer server)
38      {
39  	this.server = server;
40      }
41  
42      public MessageStream()
43      {
44  	this(null);
45      }
46  
47      //--- Method(s) ---
48  
49      public synchronized void messageReceived(ServerMessage msg)
50      {
51  	if (isCompetent(msg.getServer())) {
52  	    queue.addLast(msg);
53  	    wakeup();
54  	}
55      }
56  
57      public boolean isCompetent(OpenNapServer server)
58      {
59  	return server == null || this.server == server;
60      }
61  
62      /***
63       * Waits for new msg at most timeout ms without timesteps of length step.
64       */
65      public boolean hasNext(long timeout) 
66      {
67          if (hasNext()) {
68  	    return true;
69  	}
70  
71          try {
72              synchronized (lock) {
73  		if (timeout > 0) {
74  		    lock.wait(timeout);
75  		}
76  		else {
77  		    lock.wait();
78  		}
79              }
80          } 
81  	catch (InterruptedException ie) {
82          }
83  	
84          return hasNext();
85      }
86  
87      public synchronized boolean hasNext() 
88      {
89          return queue.size() > 0;
90      }
91  
92      public synchronized ServerMessage next() 
93      {
94          return (ServerMessage)queue.removeFirst();
95      }
96  
97      public void wakeup()
98      {
99          synchronized (lock) {
100             lock.notify();
101         }
102     }
103 
104 }