root / src / Message.java
History | View | Annotate | Download (2.77 KB)
1 |
import java.net.DatagramPacket; |
---|---|
2 |
import java.net.InetAddress; |
3 |
|
4 |
public class Message { |
5 |
|
6 |
private static final String CRLF = "\r\n"; |
7 |
|
8 |
public String header; |
9 |
public byte[] body; |
10 |
|
11 |
public enum MessageType { |
12 |
PUTCHUNK, STORED, GETCHUNK, CHUNK, DELETE, REMOVED |
13 |
}; |
14 |
|
15 |
public MessageType type;
|
16 |
|
17 |
public Message() {
|
18 |
} |
19 |
|
20 |
// Build a message
|
21 |
public Message(MessageType type, String senderId, String fileId, int chunkN, int replicationDeg, byte[] bytes) { |
22 |
|
23 |
// Reset body
|
24 |
body = new byte[0]; |
25 |
|
26 |
// Add chunk
|
27 |
body = bytes; |
28 |
|
29 |
// Assign type
|
30 |
this.type = type;
|
31 |
|
32 |
// Prepare type
|
33 |
switch (type) {
|
34 |
case PUTCHUNK:
|
35 |
header = "PUTCHUNK";
|
36 |
break;
|
37 |
case STORED:
|
38 |
header = "STORED";
|
39 |
break;
|
40 |
case GETCHUNK:
|
41 |
header = "GETCHUNK";
|
42 |
break;
|
43 |
case CHUNK:
|
44 |
header = "CHUNK";
|
45 |
break;
|
46 |
case DELETE:
|
47 |
header = "DELETE";
|
48 |
break;
|
49 |
case REMOVED:
|
50 |
header = "REMOVED";
|
51 |
break;
|
52 |
default:
|
53 |
break;
|
54 |
} |
55 |
|
56 |
// Version, SenderId and FileId are shared
|
57 |
// TODO hardcoded version 1.0
|
58 |
header += " 1.0";
|
59 |
header += " " + senderId;
|
60 |
header += " " + fileId;
|
61 |
|
62 |
// Remaining message header
|
63 |
// Technically it would be more efficient to add chunkN to all types and remove
|
64 |
// in DELETE but eh
|
65 |
switch (type) {
|
66 |
case PUTCHUNK:
|
67 |
header += " " + Integer.toString(chunkN); |
68 |
header += " " + Integer.toString(replicationDeg); |
69 |
break;
|
70 |
case STORED:
|
71 |
header += " " + Integer.toString(chunkN); |
72 |
break;
|
73 |
case GETCHUNK:
|
74 |
header += " " + Integer.toString(chunkN); |
75 |
break;
|
76 |
case CHUNK:
|
77 |
header += " " + Integer.toString(chunkN); |
78 |
break;
|
79 |
case DELETE:
|
80 |
// Nothing to add
|
81 |
break;
|
82 |
case REMOVED:
|
83 |
header += " " + Integer.toString(chunkN); |
84 |
break;
|
85 |
default:
|
86 |
break;
|
87 |
} |
88 |
|
89 |
// Finalize with double CRLF
|
90 |
header += CRLF + CRLF; |
91 |
|
92 |
} |
93 |
|
94 |
// Pack a datagram from message
|
95 |
public DatagramPacket packit(InetAddress address, int port) { |
96 |
|
97 |
byte[] headerBytes = header.getBytes(); |
98 |
|
99 |
byte[] full = new byte[headerBytes.length + body.length]; |
100 |
|
101 |
System.arraycopy(headerBytes, 0, full, 0, headerBytes.length); |
102 |
System.arraycopy(body, 0, full, headerBytes.length, body.length); |
103 |
|
104 |
DatagramPacket packet = new DatagramPacket(full, full.length, address, port); |
105 |
|
106 |
return packet;
|
107 |
|
108 |
} |
109 |
|
110 |
} |