Line data Source code
1 : /*
2 : * Package : mqtt_client
3 : * Author : S. Hamblett <steve.hamblett@linux.com>
4 : * Date : 19/06/2017
5 : * Copyright : S.Hamblett
6 : */
7 :
8 : part of mqtt_client;
9 :
10 : /// Class that contains details related to an MQTT Unsubscribe messages payload
11 : class MqttUnsubscribePayload extends MqttPayload {
12 : MqttVariableHeader variableHeader;
13 : MqttHeader header;
14 :
15 : /// The collection of subscriptions.
16 : List<String> subscriptions = new List<String>();
17 :
18 : /// Initializes a new instance of the MqttUnsubscribePayload class.
19 2 : MqttUnsubscribePayload();
20 :
21 : /// Initializes a new instance of the MqttUnsubscribePayload class.
22 : MqttUnsubscribePayload.fromByteBuffer(MqttHeader header,
23 : MqttUnsubscribeVariableHeader variableHeader,
24 1 : MqttByteBuffer payloadStream) {
25 1 : this.header = header;
26 1 : this.variableHeader = variableHeader;
27 1 : readFrom(payloadStream);
28 : }
29 :
30 : /// Writes the payload to the supplied stream.
31 : void writeTo(MqttByteBuffer payloadStream) {
32 2 : for (String subscription in subscriptions) {
33 1 : payloadStream.writeMqttStringM(subscription);
34 : }
35 : }
36 :
37 : /// Creates a payload from the specified header stream.
38 : void readFrom(MqttByteBuffer payloadStream) {
39 : int payloadBytesRead = 0;
40 5 : final int payloadLength = header.messageSize - variableHeader.length;
41 : // Read all the topics and qos subscriptions from the message payload
42 1 : while (payloadBytesRead < payloadLength) {
43 1 : final String topic = payloadStream.readMqttStringM();
44 3 : payloadBytesRead += topic.length + 2; // +2 = Mqtt string length bytes
45 1 : addSubscription(topic);
46 : }
47 : }
48 :
49 : /// Gets the length of the payload in bytes when written to a stream.
50 : int getWriteLength() {
51 : int length = 0;
52 1 : final MqttEncoding enc = new MqttEncoding();
53 2 : for (String subscription in subscriptions) {
54 2 : length += enc.getByteCount(subscription);
55 : }
56 : return length;
57 : }
58 :
59 : /// Adds a new subscription to the collection of subscriptions.
60 : void addSubscription(String topic) {
61 4 : subscriptions.add(topic);
62 : }
63 :
64 : /// Clears the subscriptions.
65 : void clearSubscriptions() {
66 2 : subscriptions.clear();
67 : }
68 :
69 : String toString() {
70 2 : final StringBuffer sb = new StringBuffer();
71 8 : sb.writeln("Payload: Unsubscription [{${subscriptions.length}}]");
72 4 : for (String subscription in subscriptions) {
73 4 : sb.writeln("{{ Topic={$subscription}}");
74 : }
75 2 : return sb.toString();
76 : }
77 : }
|