root / src / utils / Chunk.java
History | View | Annotate | Download (1.87 KB)
1 | 1 | up20140508 | package utils; |
---|---|---|---|
2 | |||
3 | import peer.Peer; |
||
4 | |||
5 | import java.io.IOException; |
||
6 | import java.util.Arrays; |
||
7 | |||
8 | public class Chunk { |
||
9 | private static int SIZE = 64000; |
||
10 | |||
11 | private byte[] header; |
||
12 | private byte[] data; |
||
13 | private byte[] buffer; |
||
14 | |||
15 | private int chunkDataLength; |
||
16 | private int chunkLength; |
||
17 | |||
18 | private String headerMsg; |
||
19 | |||
20 | public Chunk(byte[] h, FileController fileController) throws IOException{ //Chunk to backup |
||
21 | this.header = h;
|
||
22 | this.data = getChunkData(fileController);
|
||
23 | this.buffer = mergeByteArrays(this.header, this.data); |
||
24 | this.chunkLength = this.chunkDataLength + this.header.length; |
||
25 | } |
||
26 | |||
27 | public Chunk(byte[] dataBuffer, String messageType, String hashFileId, String chunkNo){ //Chunk to restore |
||
28 | this.data = dataBuffer;
|
||
29 | this.chunkDataLength = this.data.length; |
||
30 | String headerMsg = messageType + " " + Utils.version + " " + Peer.getSenderId() + " " + hashFileId + " " + chunkNo + " " + "\r\n\r\n"; |
||
31 | byte[] buf = headerMsg.getBytes(); |
||
32 | this.headerMsg = headerMsg;
|
||
33 | this.header = buf;
|
||
34 | this.buffer = mergeByteArrays(this.header, this.data); |
||
35 | this.chunkLength = this.header.length + this.chunkDataLength; |
||
36 | } |
||
37 | |||
38 | public byte[] getChunkData(FileController fileController) throws IOException{ |
||
39 | byte[] dataBuffer = new byte[SIZE]; |
||
40 | this.chunkDataLength = fileController.getFileStream().read(dataBuffer,0,SIZE); |
||
41 | return dataBuffer;
|
||
42 | } |
||
43 | |||
44 | public byte[] getBuffer(){ |
||
45 | this.buffer = Arrays.copyOf(this.buffer,this.chunkLength); |
||
46 | return buffer;
|
||
47 | } |
||
48 | |||
49 | public byte[] mergeByteArrays(byte[] header, byte[] content){ |
||
50 | |||
51 | byte[] ret = new byte[header.length + content.length]; |
||
52 | System.arraycopy(header, 0, ret, 0, header.length); |
||
53 | System.arraycopy(content, 0, ret, header.length, content.length); |
||
54 | |||
55 | return ret;
|
||
56 | } |
||
57 | |||
58 | public String getHeaderMsg(){ |
||
59 | return headerMsg;
|
||
60 | } |
||
61 | } |