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.msg.client;
21  
22  import java.nio.ByteBuffer;
23  import java.nio.ByteOrder;
24  
25  import org.xnap.plugin.overnet.net.OvernetCore;
26  import org.xnap.plugin.overnet.net.msg.OvernetMessage;
27  
28  public abstract class OvernetClientMessage extends OvernetMessage
29  {
30  	private ByteBuffer buffer;
31  	private boolean finalized = false;
32  
33  	public OvernetClientMessage(byte type)
34  	{
35  		super(type);
36  		buffer = ByteBuffer.allocate(69);
37  		buffer.order(ByteOrder.LITTLE_ENDIAN);
38  		put(OvernetCore.ED2K_BYTE);
39  		buffer.position(5);
40  		put(type);
41  	}
42  	
43  	public void putString(String s)
44  	{
45  		checkSize(2 + s.getBytes().length);
46  		buffer.putShort((short)s.length());
47  		buffer.put(s.getBytes());
48  	}
49  
50  	public void putShort(short s)
51  	{
52  		checkSize(2);
53  		buffer.putShort(s);
54  	}
55  
56  	public void putInt(int i)
57  	{
58  		checkSize(4);
59  		buffer.putInt(i);
60  	}
61  
62  	public void put(byte b)
63  	{
64  		checkSize(1);
65  		buffer.put(b);
66  	}
67  
68  	public void put(byte[] bytes)
69  	{
70  		checkSize(bytes.length);
71  		buffer.put(bytes);
72  	}
73  
74  	private void checkSize(int req)
75  	{
76  		int free = buffer.capacity() - buffer.position();
77  		
78  		if (free < req ) {
79  			ByteBuffer buf = ByteBuffer.allocate((buffer.capacity() + req) 
80  												 * 2);
81  			buf.order(ByteOrder.LITTLE_ENDIAN);
82  			buffer.flip();
83  			byte[] bytes = new byte[buffer.remaining()];
84  			buffer.get(bytes);
85  			buf.put(bytes);
86  			buffer = buf;
87  		}
88  	}
89  
90  	/***
91  	 * Called once to set the final size and flip the buffer.
92  	 */
93  	private void finalizeMessage()
94  	{
95  		buffer.flip();
96  		int size = buffer.limit() - 5;
97  		buffer.putInt(1, size);
98  	}
99  
100 	public final ByteBuffer getBuffer()
101 	{
102 		if (!finalized) {
103 			finalizeMessage();
104 			finalized = true;
105 		}
106 		return buffer;
107 	}
108 }