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.overnet.net;
21  
22  import java.util.LinkedList;
23  
24  import org.apache.log4j.Logger;
25  import org.xnap.plugin.overnet.net.msg.client.OvernetClientMessage;
26  
27  /***
28   * Queues client messages and removes them from its list only if all bytes are
29   * written out.
30   *
31   * Addition and removal of messages is synchronized.
32   */
33  public class MessageQueue
34  {
35  	//--- Constant(s) ---
36  
37  	//--- Data field(s) ---
38  
39  	private LinkedList list = new LinkedList();
40  
41      private static Logger logger = Logger.getLogger(MessageQueue.class);
42  	
43  	//--- Constructor(s) ---
44  
45      public MessageQueue()
46  	{
47  
48  	}
49  
50      //--- Method(s) ---
51  
52  	/***
53  	 * Returns next message which has still some bytes to be written out.
54  	 *
55  	 * The message is removed from the list only after it's been totally
56  	 * written out. Hence a call to <code>getNextMessage()</code> which
57  	 * doesn't write it out, doesn't remove the message from the queue.
58  	 *
59  	 * @return null if there are no messages to be written.
60  	 */
61  	public synchronized OvernetClientMessage getNextMessage()
62  	{
63  		while (list.size() > 0) {
64  			OvernetClientMessage msg = (OvernetClientMessage)list.getFirst();
65  			if (msg.getBuffer().hasRemaining()) {
66  				return msg;
67  			}
68  			else {
69  				list.removeFirst();
70  			}
71  		}
72  		return null;
73  	}
74  
75  	/***
76  	 * Adds a new message to the queue.
77  	 */
78  	public synchronized void add(OvernetClientMessage msg)
79  	{
80  		list.add(msg);
81  	}
82  
83  	/***
84  	 * Returns true if there is still a message available which must be
85  	 * written out.
86  	 */
87  	public synchronized boolean hasRemaining()
88  	{
89  		OvernetClientMessage msg = getNextMessage();
90  		return (msg != null) ? true : false;
91  	}
92  
93  	public synchronized void clear()
94  	{
95  		list.clear();
96  	}
97  }