-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStorage.java
More file actions
75 lines (66 loc) · 2.9 KB
/
Storage.java
File metadata and controls
75 lines (66 loc) · 2.9 KB
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
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
public class Storage {
HashMap<String, ArrayList<String>> subscriptions;
BlockingQueue<byte[]> storageQueue;
public Storage(BlockingQueue<byte[]> storageQueue){
this.subscriptions = new HashMap<String, ArrayList<String>>();
this.storageQueue = storageQueue;
}
private byte[] intToByteArray(int packetId) {
return new byte[] {
(byte)(packetId>> 8),
(byte) packetId};
}
public void addSubscribe(String topic, String client_id){
if (subscriptions.containsKey(topic)){
ArrayList<String> subscriberIds = subscriptions.get(topic);
subscriberIds.add(client_id);
subscriptions.replace(topic,subscriberIds);
}
else{
ArrayList<String> subscriberId = new ArrayList<>();
subscriberId.add(client_id);
subscriptions.put(topic, subscriberId);
}
}
public void removeSubscribe(String topic, String client_id){
if (subscriptions.containsKey(topic)){
ArrayList<String> subscriberIds = subscriptions.get(topic);
subscriberIds.remove(client_id);
subscriptions.replace(topic,subscriberIds);
}
else{
System.out.println("Unsubscribe could not be done as topic doesn't exist");
}
}
public void transmitMessage(String topic, byte[] message){
if (subscriptions.containsKey(topic)){
ArrayList<String> subscriberIds = subscriptions.get(topic);
for(int i =0; i<subscriberIds.size(); i++){
byte[] ids = new byte[0];
try{
ids = subscriberIds.get(i).getBytes("UTF8");
}catch(UnsupportedEncodingException e) {
System.out.println("Error of encoding");
}
int idsLength = ids.length;
byte[] idsLengthByte = intToByteArray(idsLength);
byte[] messageTransmitted = new byte[message.length + 2 + idsLength];
//Generates a byte array with client identifier as the first bytes
System.arraycopy(idsLengthByte, 0, messageTransmitted,0, 2);
System.arraycopy(ids, 0, messageTransmitted,2,idsLength);
System.arraycopy(message, 0, messageTransmitted,2+idsLength, message.length);
for(int b =0; b<message.length; b++){
System.out.println(String.format("%8s", Integer.toBinaryString(message[b] & 0xFF)).replace(' ', '0'));
}
storageQueue.add(messageTransmitted);
}
}
}
public HashMap<String, ArrayList<String>> getSubscriptions() {
return subscriptions;
}
}