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.core;
21  
22  import java.nio.ByteBuffer;
23  
24  import org.xnap.plugin.overnet.net.msg.OvernetMessage;
25  
26  public abstract class OvernetCoreMessage extends OvernetMessage
27  {
28  	private int size;
29  	private ByteBuffer buffer;
30  	private int read;
31  
32  	public boolean isValid()
33  	{
34  		return true;
35  	}
36  
37  	protected OvernetCoreMessage(byte type, ByteBuffer buffer)
38  	{
39  		super(type);
40  		this.size = buffer.getInt(1);
41  		this.buffer = buffer;
42  		// skip header
43  		buffer.position(6);
44  		read = 1;
45  	}
46  
47  	protected String getString()
48  	{
49  		short length = getShort();
50  		byte[] buf = new byte[length];
51  		get(buf);
52  		return new String(buf);
53  	}
54  
55  	protected void skip(int length)
56  	{
57  		if (check(length)) {
58  			buffer.position(buffer.position() + length);
59  		}
60  	}
61  
62  	protected short getShort()
63  	{
64  		if (check(2)) {
65  			return buffer.getShort();
66  		}
67  		return 0;
68  	}
69  
70  	protected int getInt()
71  	{
72  		if (check(4)) {
73  			return buffer.getInt();
74  		}
75  		return 0;
76  	}
77  
78  	protected float getFloat()
79  	{
80  		if (check(4)) {
81  			return buffer.getFloat();
82  		}
83  		return 0;
84  	}
85  
86  	protected byte get()
87  	{
88  		if (check(1)) {
89  			return buffer.get();
90  		}
91  		return 0;
92  	}
93  
94  	protected void get(byte[] array)
95  	{
96  		if (check(array.length)) {
97  			buffer.get(array);
98  		}
99  	}
100 
101 	private boolean check(int req)
102 	{
103 		if (req + read <= size && req <= buffer.remaining()) {
104 			read += req;
105 			return true;
106 		}
107 		return false;
108 	}
109 
110 	protected int remaining()
111 	{
112 		return size - read;
113 	}
114 
115 	protected Tags readTags()
116 	{
117 		int num = getInt();
118 		if (num > 0) {
119 			return new Tags(num, buffer);
120 		}
121 		else {
122 			return new Tags(0, buffer);
123 		}
124 	}
125 }