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; } };