summaryrefslogtreecommitdiff
path: root/sdl_android_lib/src/com/smartdevicelink/transport/utl/ByteAraryMessageAssembler.java
blob: 98b8b666ecc59954a0dc7575946136a260d3f4f0 (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
package com.smartdevicelink.transport.utl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import android.util.Log;

import com.smartdevicelink.transport.TransportConstants;

public class ByteAraryMessageAssembler {
	private static final String TAG = "ByteAraryMessageAssembler";
	ByteArrayOutputStream buffer;
	boolean isFinished;
	
	public void init(){
		close();
		this.isFinished = false;
		buffer = new ByteArrayOutputStream();
	}
	
	public boolean close(){
		if(buffer!=null){
			try {
				buffer.close();
				buffer = null;
				return true;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}
	
	public void append(byte[] bytes){
		try {
			buffer.write(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public synchronized boolean handleMessage(int flags, byte[] packet){
			switch(flags){
			case TransportConstants.BYTES_TO_SEND_FLAG_LARGE_PACKET_START: //Fall through to write the bytes after they buffer was init'ed
			case TransportConstants.BYTES_TO_SEND_FLAG_LARGE_PACKET_CONT:	
				append(packet);
				break;
			case TransportConstants.BYTES_TO_SEND_FLAG_LARGE_PACKET_END:
				append(packet);
				this.isFinished = true;
				break;
			default: 
				Log.e(TAG, "Error handling message");
				return false;
			}
			
			return true;
	}

	public byte[] getBytes(){
		if(buffer == null){
			return null;
		}
		return this.buffer.toByteArray();
	}
	
	public boolean isFinished(){
		return this.isFinished;
	}
}