aboutsummaryrefslogtreecommitdiff
path: root/java/com/xagasoft/gats/GatsInputStream.java
blob: e1c4781c832b09965488f6030d763e7fb3abfd13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.xagasoft.gats;

import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;

public class GatsInputStream
{
	private InputStream is;
	private ByteArrayOutputStream baos = new ByteArrayOutputStream();
	private int iVer = 0;
	private int iSize;

	public GatsInputStream( InputStream is )
	{
		this.is = is;
	}

	public GatsObject readObject() throws java.io.IOException
	{
		do
		{
			if( baos.size() < 5 )
			{
				byte aBuf[] = new byte[5-baos.size()];
				int iRead = is.read( aBuf );
				baos.write( aBuf, 0, iRead );

				if( baos.size() < 5 )
					return null;
			}
		} while( !skipReadNulls() );

		if( iVer == 0 )
		{
			ByteArrayInputStream bais = new ByteArrayInputStream(
				baos.toByteArray()
				);
			DataInputStream dis = new DataInputStream( bais );
			iVer = dis.readUnsignedByte();
			iSize = dis.readInt();
		}

		byte aBuf[] = new byte[1500];
		while( baos.size() < iSize )
		{
			int iGoal = iSize-baos.size();
			if( iGoal > 1500 )
				iGoal = 1500;

			int iRead = is.read( aBuf );
			baos.write( aBuf, 0, iRead );

			if( iRead < iGoal )
				return null;
		}

		if( baos.size() < iSize )
			return null;

		ByteArrayInputStream bais = new ByteArrayInputStream(
			baos.toByteArray()
			);
		bais.skip( 5 );
		
		GatsObject goRet = GatsObject.read( bais );
		iVer = 0;

		return goRet;
	}

	private boolean skipReadNulls()
	{
		if( baos.size() == 0 )
			return false;

		byte aBuf[] = baos.toByteArray();
		if( aBuf[0] != 0 )
			return true;

		for( int j = 1; j < aBuf.length; j++ )
		{
			if( aBuf[j] != 0 )
			{
				baos.reset();
				baos.write( aBuf, j, aBuf.length-j );
				return true;
			}
		}

		baos.reset();
		return true;
	}
};