-
Notifications
You must be signed in to change notification settings - Fork 912
/
PublishTests.java
1656 lines (1484 loc) · 69.9 KB
/
PublishTests.java
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.mqtt5.spec.controlpackets;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import io.netty.handler.codec.mqtt.MqttMessageType;
import org.apache.activemq.artemis.api.core.QueueConfiguration;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.core.protocol.mqtt.MQTTInterceptor;
import org.apache.activemq.artemis.core.protocol.mqtt.MQTTUtil;
import org.apache.activemq.artemis.tests.integration.mqtt5.MQTT5TestSupport;
import org.apache.activemq.artemis.tests.util.RandomUtil;
import org.apache.activemq.artemis.tests.util.Wait;
import org.eclipse.paho.mqttv5.client.IMqttToken;
import org.eclipse.paho.mqttv5.client.MqttAsyncClient;
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;
import org.eclipse.paho.mqttv5.client.MqttConnectionOptionsBuilder;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.common.MqttSubscription;
import org.eclipse.paho.mqttv5.common.packet.MqttProperties;
import org.eclipse.paho.mqttv5.common.packet.MqttPublish;
import org.eclipse.paho.mqttv5.common.packet.MqttWireMessage;
import org.eclipse.paho.mqttv5.common.packet.UserProperty;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandles;
/**
* Fulfilled by client or Netty codec (i.e. not tested here):
*
* [MQTT-3.3.2-1] The Topic Name MUST be present as the first field in the PUBLISH packet Variable Header. It MUST be a UTF-8 Encoded String.
* [MQTT-3.3.2-9] A Client MUST NOT send a PUBLISH packet with a Topic Alias greater than the Topic Alias Maximum value returned by the Server in the CONNACK packet.
* [MQTT-3.3.2-10] A Client MUST accept all Topic Alias values greater than 0 and less than or equal to the Topic Alias Maximum value that it sent in the CONNECT packet.
* [MQTT-3.3.2-13] The Response Topic MUST be a UTF-8 Encoded String.
* [MQTT-3.3.2-14] The Response Topic MUST NOT contain wildcard characters.
* [MQTT-3.3.2-19] The Content Type MUST be a UTF-8 Encoded String.
* [MQTT-3.3.4-6] A PUBLISH packet sent from a Client to a Server MUST NOT contain a Subscription Identifier.
* [MQTT-3.3.4-7] The Client MUST NOT send more than Receive Maximum QoS 1 and QoS 2 PUBLISH packets for which it has not received PUBACK, PUBCOMP, or PUBREC with a Reason Code of 128 or greater from the Server.
* [MQTT-3.3.4-8] The Client MUST NOT delay the sending of any packets other than PUBLISH packets due to having sent Receive Maximum PUBLISH packets without receiving acknowledgements for them.
*
*
* Unsure how to test this since it's a negative:
*
* [MQTT-3.3.1-4] A PUBLISH Packet MUST NOT have both QoS bits set to 1.
* [MQTT-3.3.2-2] The Topic Name in the PUBLISH packet MUST NOT contain wildcard characters.
*
*
* I can't force the Paho client to set a Topic Alias of 0. It automatically adjusts it to 1 (confirmed via Wireshark), therefore this is not tested:
*
* [MQTT-3.3.2-8] A sender MUST NOT send a PUBLISH packet containing a Topic Alias which has the value 0.
*/
public class PublishTests extends MQTT5TestSupport {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
public PublishTests(String protocol) {
super(protocol);
}
/*
* [MQTT-3.3.1-1] The DUP flag MUST be set to 1 by the Client or Server when it attempts to re-deliver a PUBLISH
* packet.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testDupFlag() throws Exception {
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
final AtomicBoolean intercepted = new AtomicBoolean(false);
// prevent the first ack from working so redelivery happens
MQTTInterceptor incomingInterceptor = (packet, connection) -> {
if (!intercepted.get() && packet.fixedHeader().messageType() == MqttMessageType.PUBACK) {
intercepted.set(true);
return false;
}
return true;
};
server.getRemotingService().addIncomingInterceptor(incomingInterceptor);
final CountDownLatch latch = new CountDownLatch(1);
MqttClient producer = createPahoClient("producer");
MqttClient consumer = createPahoClient(CONSUMER_ID);
MqttConnectionOptions options = new MqttConnectionOptionsBuilder()
.cleanStart(false)
.sessionExpiryInterval(300L)
.build();
consumer.connect(options);
consumer.subscribe(TOPIC, 1);
consumer.disconnect();
// session should still exist since session expiry interval > 0
assertEquals(1, getSessionStates().size());
assertNotNull(getSessionStates().get(CONSUMER_ID));
producer.connect();
producer.publish(TOPIC, "hello".getBytes(), 1, false);
producer.disconnect();
producer.close();
// session should still exist since session expiry interval > 0
assertEquals(1, getSessionStates().size());
assertNotNull(getSessionStates().get(CONSUMER_ID));
// consumer should resume previous session (i.e. get the messages sent to the queue where it was previously subscribed)
consumer.setCallback(new LatchedMqttCallback(latch, true));
consumer.connect(options);
waitForLatch(latch);
consumer.disconnect();
// session should still exist since session expiry interval > 0
assertEquals(1, getSessionStates().size());
assertNotNull(getSessionStates().get(CONSUMER_ID));
final CountDownLatch latch2 = new CountDownLatch(1);
consumer.setCallback(new LatchedMqttCallback(latch2, false));
consumer.connect(options);
waitForLatch(latch2);
consumer.disconnect();
consumer.close();
}
/*
* [MQTT-3.3.1-2] The DUP flag MUST be set to 0 for all QoS 0 messages.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testDupFlagQoSZero() throws Exception {
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
final CountDownLatch latch = new CountDownLatch(1);
MqttClient consumer = createPahoClient(CONSUMER_ID);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
assertFalse(message.isDuplicate());
latch.countDown();
}
});
consumer.connect();
consumer.subscribe(TOPIC, 2);
MqttClient producer = createPahoClient("producer");
producer.connect();
producer.publish(TOPIC, new byte[0], 0, false);
producer.disconnect();
producer.close();
assertTrue(latch.await(3, TimeUnit.SECONDS));
consumer.disconnect();
consumer.close();
}
/*
* [MQTT-3.3.1-3] The DUP flag in the outgoing PUBLISH packet is set independently to the incoming PUBLISH packet,
* its value MUST be determined solely by whether the outgoing PUBLISH packet is a retransmission.
*
* The value of the DUP flag from an incoming PUBLISH packet is not propagated when the PUBLISH packet is sent to
* subscribers by the Server.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testDupFlagNotPropagated() throws Exception {
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
final CountDownLatch latch = new CountDownLatch(1);
MqttClient producer = createPahoClient("producer");
MqttClient consumer = createPahoClient(CONSUMER_ID);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
assertFalse(message.isDuplicate());
latch.countDown();
}
});
consumer.connect();
consumer.subscribe(TOPIC, 2);
producer.connect();
MqttMessage m = new MqttMessage();
m.setDuplicate(true);
m.setPayload("hello".getBytes());
m.setQos(2);
m.setRetained(false);
producer.publish(TOPIC, m);
producer.disconnect();
producer.close();
assertTrue(latch.await(3, TimeUnit.SECONDS));
consumer.disconnect();
consumer.close();
}
/*
* [MQTT-3.3.1-5] If the RETAIN flag is set to 1 in a PUBLISH packet sent by a Client to a Server, the Server MUST
* replace any existing retained message for this topic and store the Application Message.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testRetainFlag() throws Exception {
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
MqttClient producer = createPahoClient("producer");
producer.connect();
// send first retained message
producer.publish(TOPIC, "retain1".getBytes(), 2, true);
// send second retained message; should replace the first
producer.publish(TOPIC, "retain2".getBytes(), 2, true);
producer.disconnect();
producer.close();
final CountDownLatch latch = new CountDownLatch(1);
MqttClient consumer = createPahoClient(CONSUMER_ID);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
assertEqualsByteArrays("retain2".getBytes(StandardCharsets.UTF_8), message.getPayload());
latch.countDown();
}
});
consumer.connect();
consumer.subscribe(TOPIC, 2);
assertTrue(latch.await(3, TimeUnit.SECONDS));
consumer.disconnect();
consumer.close();
}
/*
* [MQTT-3.3.1-6] If the Payload contains zero bytes it is processed normally by the Server but any retained message
* with the same topic name MUST be removed and any future subscribers for the topic will not receive a retained
* message.
*
* [MQTT-3.3.1-7] A retained message with a Payload containing zero bytes MUST NOT be stored as a retained message on
* the Server.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testRetainFlagWithEmptyMessage() throws Exception {
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
MqttClient producer = createPahoClient("producer");
producer.connect();
// send first retained message
producer.publish(TOPIC, "retain1".getBytes(), 2, true);
Wait.assertTrue(() -> server.locateQueue(MQTTUtil.convertMqttTopicFilterToCoreAddress(MQTTUtil.MQTT_RETAIN_ADDRESS_PREFIX, TOPIC, MQTTUtil.MQTT_WILDCARD)).getMessageCount() == 1, 2000, 100);
// send second retained message; should *remove* the first
producer.publish(TOPIC, new byte[0], 2, true);
producer.disconnect();
producer.close();
Wait.assertTrue(() -> server.locateQueue(MQTTUtil.convertMqttTopicFilterToCoreAddress(MQTTUtil.MQTT_RETAIN_ADDRESS_PREFIX, TOPIC, MQTTUtil.MQTT_WILDCARD)).getMessageCount() == 0, 2000, 100);
final CountDownLatch latch = new CountDownLatch(1);
MqttClient consumer = createPahoClient(CONSUMER_ID);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
latch.countDown();
}
});
consumer.connect();
consumer.subscribe(TOPIC, 2);
assertFalse(latch.await(2, TimeUnit.SECONDS));
consumer.disconnect();
consumer.close();
}
/*
* [MQTT-3.3.1-8] If the RETAIN flag is 0 in a PUBLISH packet sent by a Client to a Server, the Server MUST NOT store
* the message as a retained message and MUST NOT remove or replace any existing retained message.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testRetainFlagFalse() throws Exception {
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
final String RETAINED_PAYLOAD = RandomUtil.randomString();
final String UNRETAINED_PAYLOAD = RandomUtil.randomString();
MqttClient producer = createPahoClient("producer");
producer.connect();
// send retained message
producer.publish(TOPIC, RETAINED_PAYLOAD.getBytes(), 2, true);
Wait.assertTrue(() -> server.locateQueue(MQTTUtil.convertMqttTopicFilterToCoreAddress(MQTTUtil.MQTT_RETAIN_ADDRESS_PREFIX, TOPIC, MQTTUtil.MQTT_WILDCARD)).getMessageCount() == 1, 1000, 100);
// send an unretained message; should *not* remove the existing retained message
producer.publish(TOPIC, UNRETAINED_PAYLOAD.getBytes(), 2, false);
producer.disconnect();
producer.close();
Wait.assertFalse(() -> server.locateQueue(MQTTUtil.convertMqttTopicFilterToCoreAddress(MQTTUtil.MQTT_RETAIN_ADDRESS_PREFIX, TOPIC, MQTTUtil.MQTT_WILDCARD)).getMessageCount() > 1, 1000, 100);
final CountDownLatch latch = new CountDownLatch(1);
MqttClient consumer = createPahoClient(CONSUMER_ID);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
assertEqualsByteArrays(RETAINED_PAYLOAD.getBytes(StandardCharsets.UTF_8), message.getPayload());
latch.countDown();
}
});
consumer.connect();
consumer.subscribe(TOPIC, 2);
assertTrue(latch.await(2, TimeUnit.SECONDS));
consumer.disconnect();
consumer.close();
}
/*
* When a new Non‑shared Subscription is made, the last retained message, if any, on each matching topic name is sent
* to the Client as directed by the Retain Handling Subscription Option. These messages are sent with the RETAIN flag
* set to 1. Which retained messages are sent is controlled by the Retain Handling Subscription Option. At the time
* of the Subscription...
*
* [MQTT-3.3.1-9] If Retain Handling is set to 0 the Server MUST send the retained messages matching the Topic Filter
* of the subscription to the Client.
*
* Simple test with just one subscription.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testRetainHandlingZeroWithOneSubscription() throws Exception {
internalTestRetainHandlingZero(false, 1);
}
/*
* When a new Non‑shared Subscription is made, the last retained message, if any, on each matching topic name is sent
* to the Client as directed by the Retain Handling Subscription Option. These messages are sent with the RETAIN flag
* set to 1. Which retained messages are sent is controlled by the Retain Handling Subscription Option. At the time
* of the Subscription...
*
* [MQTT-3.3.1-9] If Retain Handling is set to 0 the Server MUST send the retained messages matching the Topic Filter
* of the subscription to the Client.
*
* Testing with lots of individual subscriptions from a single client.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testRetainHandlingZeroWithMultipleSubscriptions() throws Exception {
internalTestRetainHandlingZero(false, 25);
}
/*
* When a new Non‑shared Subscription is made, the last retained message, if any, on each matching topic name is sent
* to the Client as directed by the Retain Handling Subscription Option. These messages are sent with the RETAIN flag
* set to 1. Which retained messages are sent is controlled by the Retain Handling Subscription Option. At the time
* of the Subscription...
*
* [MQTT-3.3.1-9] If Retain Handling is set to 0 the Server MUST send the retained messages matching the Topic Filter
* of the subscription to the Client.
*
* Testing topic filter subscription.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testRetainHandlingZeroWithTopicFilterSubscription() throws Exception {
internalTestRetainHandlingZero(true, 25);
}
public void internalTestRetainHandlingZero(boolean filter, int subscriptionCount) throws Exception {
final int SUBSCRIPTION_COUNT = subscriptionCount;
final String CONSUMER_ID = RandomUtil.randomString();
final String PREFIX = "myTopic/";
String[] topicNames = new String[SUBSCRIPTION_COUNT];
for (int i = 0; i < SUBSCRIPTION_COUNT; i++) {
topicNames[i] = PREFIX + this.getTopicName() + i;
}
String[] retainedPayloads = new String[SUBSCRIPTION_COUNT];
for (int i = 0; i < SUBSCRIPTION_COUNT; i++) {
retainedPayloads[i] = RandomUtil.randomString();
}
// send retained messages
MqttClient producer = createPahoClient("producer");
producer.connect();
for (int i = 0; i < SUBSCRIPTION_COUNT; i++) {
final String topicName = topicNames[i];
producer.publish(topicName, retainedPayloads[i].getBytes(), 2, true);
Wait.assertTrue(() -> server.locateQueue(MQTTUtil.convertMqttTopicFilterToCoreAddress(MQTTUtil.MQTT_RETAIN_ADDRESS_PREFIX, topicName, server.getConfiguration().getWildcardConfiguration())).getMessageCount() == 1, 2000, 100);
}
producer.disconnect();
producer.close();
final CountDownLatch latch = new CountDownLatch(SUBSCRIPTION_COUNT);
MqttClient consumer = createPahoClient(CONSUMER_ID);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
boolean payloadMatched = false;
for (int i = 0; i < SUBSCRIPTION_COUNT; i++) {
if (new String(message.getPayload()).equals(retainedPayloads[i])) {
payloadMatched = true;
break;
}
}
assertTrue(payloadMatched);
assertTrue(message.isRetained());
latch.countDown();
}
});
consumer.connect();
if (filter) { // use a filter instead of bunch of individual subscriptions
MqttSubscription sub = new MqttSubscription(PREFIX + "#", 2);
sub.setRetainHandling(0);
consumer.subscribe(new MqttSubscription[]{sub});
} else {
MqttSubscription[] subscriptions = new MqttSubscription[SUBSCRIPTION_COUNT];
for (int i = 0; i < SUBSCRIPTION_COUNT; i++) {
MqttSubscription subscription = new MqttSubscription(topicNames[i], 2);
subscription.setRetainHandling(0);
subscriptions[i] = subscription;
}
consumer.subscribe(subscriptions);
}
assertTrue(latch.await(2, TimeUnit.SECONDS));
consumer.disconnect();
consumer.close();
}
/*
* When a new Non‑shared Subscription is made, the last retained message, if any, on each matching topic name is sent
* to the Client as directed by the Retain Handling Subscription Option. These messages are sent with the RETAIN flag
* set to 1. Which retained messages are sent is controlled by the Retain Handling Subscription Option. At the time
* of the Subscription...
*
* [MQTT-3.3.1-10] If Retain Handling is set to 1 then if the subscription did not already exist, the Server MUST
* send all retained message matching the Topic Filter of the subscription to the Client, and if the subscription did
* exist the Server MUST NOT send the retained messages.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testRetainHandlingOne() throws Exception {
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
// send retained messages
MqttClient producer = createPahoClient("producer");
producer.connect();
producer.publish(TOPIC, "retained".getBytes(), 2, true);
Wait.assertTrue(() -> server.locateQueue(MQTTUtil.convertMqttTopicFilterToCoreAddress(MQTTUtil.MQTT_RETAIN_ADDRESS_PREFIX, TOPIC, server.getConfiguration().getWildcardConfiguration())).getMessageCount() == 1, 2000, 100);
producer.disconnect();
producer.close();
// options for consumers
MqttConnectionOptions options = new MqttConnectionOptionsBuilder()
.cleanStart(false)
.sessionExpiryInterval(300L)
.build();
// consume retained message
MqttClient consumer = createPahoClient(CONSUMER_ID);
consumer.connect(options);
final CountDownLatch latch = new CountDownLatch(1);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) {
assertEqualsByteArrays("retained".getBytes(StandardCharsets.UTF_8), message.getPayload());
assertTrue(message.isRetained());
latch.countDown();
}
});
MqttSubscription subscription = new MqttSubscription(TOPIC, 2);
subscription.setRetainHandling(1);
consumer.subscribe(new MqttSubscription[]{subscription});
assertTrue(latch.await(2, TimeUnit.SECONDS));
// ensure the retained message has been successfully acknowledge and removed from the subscription queue
Wait.assertTrue(() -> getSubscriptionQueue(TOPIC).getMessageCount() == 0, 2000, 100);
consumer.disconnect();
// consumer should resume previous session but it should *not* get the retained message again
final CountDownLatch latch2 = new CountDownLatch(1);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
latch2.countDown();
}
});
consumer.connect(options);
assertFalse(latch2.await(2, TimeUnit.SECONDS));
consumer.disconnect();
consumer.close();
}
/*
* When a new Non‑shared Subscription is made, the last retained message, if any, on each matching topic name is sent
* to the Client as directed by the Retain Handling Subscription Option. These messages are sent with the RETAIN flag
* set to 1. Which retained messages are sent is controlled by the Retain Handling Subscription Option. At the time
* of the Subscription...
*
* [MQTT-3.3.1-11] If Retain Handling is set to 2, the Server MUST NOT send the retained messages
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testRetainHandlingTwo() throws Exception {
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
// send first retained message
MqttClient producer = createPahoClient("producer");
producer.connect();
producer.publish(TOPIC, "retained".getBytes(), 2, true);
Wait.assertTrue(() -> server.locateQueue(MQTTUtil.convertMqttTopicFilterToCoreAddress(MQTTUtil.MQTT_RETAIN_ADDRESS_PREFIX, TOPIC, MQTTUtil.MQTT_WILDCARD)).getMessageCount() == 1, 2000, 100);
producer.disconnect();
producer.close();
// create consumer
final CountDownLatch latch = new CountDownLatch(1);
MqttClient consumer = createPahoClient(CONSUMER_ID);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
latch.countDown();
}
});
consumer.connect();
MqttSubscription subscription = new MqttSubscription(TOPIC, 2);
subscription.setRetainHandling(2);
consumer.subscribe(new MqttSubscription[]{subscription});
assertFalse(latch.await(2, TimeUnit.SECONDS));
consumer.disconnect();
consumer.close();
}
/*
* The setting of the RETAIN flag in an Application Message forwarded by the Server from an *established* connection
* is controlled by the Retain As Published subscription option.
*
* [MQTT-3.3.1-12] If the value of Retain As Published subscription option is set to 0, the Server MUST set the
* RETAIN flag to 0 when forwarding an Application Message regardless of how the RETAIN flag was set in the received
* PUBLISH packet.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testRetainAsPublishedZeroOnEstablishedSubscription() throws Exception {
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
// create consumer
final CountDownLatch latch = new CountDownLatch(1);
MqttClient consumer = createPahoClient(CONSUMER_ID);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
assertEqualsByteArrays("retained".getBytes(StandardCharsets.UTF_8), message.getPayload());
assertFalse(message.isRetained());
latch.countDown();
}
});
consumer.connect();
MqttSubscription subscription = new MqttSubscription(TOPIC, 2);
subscription.setRetainAsPublished(false);
consumer.subscribe(new MqttSubscription[]{subscription});
// send retained message
MqttClient producer = createPahoClient("producer");
producer.connect();
producer.publish(TOPIC, "retained".getBytes(), 2, true);
Wait.assertTrue(() -> server.locateQueue(MQTTUtil.convertMqttTopicFilterToCoreAddress(MQTTUtil.MQTT_RETAIN_ADDRESS_PREFIX, TOPIC, MQTTUtil.MQTT_WILDCARD)).getMessageCount() == 1, 2000, 100);
producer.disconnect();
producer.close();
assertTrue(latch.await(2, TimeUnit.SECONDS));
consumer.disconnect();
consumer.close();
}
/*
* The setting of the RETAIN flag in an Application Message forwarded by the Server from an *established* connection
* is controlled by the Retain As Published subscription option.
*
* [MQTT-3.3.1-13] If the value of Retain As Published subscription option is set to 1, the Server MUST set the
* RETAIN flag equal to the RETAIN flag in the received PUBLISH packet.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testRetainAsPublishedOneOnEstablishedSubscription() throws Exception {
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
// create consumer
final CountDownLatch latchOne = new CountDownLatch(1);
final CountDownLatch latchTwo = new CountDownLatch(1);
MqttClient consumer = createPahoClient(CONSUMER_ID);
final AtomicBoolean first = new AtomicBoolean(true);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
if (first.getAndSet(false)) {
assertEqualsByteArrays("retained".getBytes(StandardCharsets.UTF_8), message.getPayload());
assertTrue(message.isRetained());
latchOne.countDown();
} else {
assertEqualsByteArrays("unretained".getBytes(StandardCharsets.UTF_8), message.getPayload());
assertFalse(message.isRetained());
latchTwo.countDown();
}
}
});
consumer.connect();
MqttSubscription subscription = new MqttSubscription(TOPIC, 2);
subscription.setRetainAsPublished(true);
consumer.subscribe(new MqttSubscription[]{subscription});
// send retained message
MqttClient producer = createPahoClient("producer");
producer.connect();
producer.publish(TOPIC, "retained".getBytes(), 2, true);
Wait.assertTrue(() -> server.locateQueue(MQTTUtil.convertMqttTopicFilterToCoreAddress(MQTTUtil.MQTT_RETAIN_ADDRESS_PREFIX, TOPIC, MQTTUtil.MQTT_WILDCARD)).getMessageCount() == 1, 2000, 100);
producer.disconnect();
producer.close();
assertTrue(latchOne.await(2, TimeUnit.SECONDS));
producer = createPahoClient("producer");
producer.connect();
producer.publish(TOPIC, "unretained".getBytes(), 2, false);
producer.disconnect();
producer.close();
assertTrue(latchTwo.await(2, TimeUnit.SECONDS));
consumer.disconnect();
consumer.close();
}
/*
* [MQTT-3.3.2-3] The Topic Name in a PUBLISH packet sent by a Server to a subscribing Client MUST match the
* Subscription’s Topic Filter.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testTopicFilter() throws Exception {
final String PREFIX = "myTopic/";
final String TOPIC = PREFIX + RandomUtil.randomString();
final String TOPIC_FILTER = PREFIX + "#";
final CountDownLatch latch = new CountDownLatch(1);
MqttClient consumer = createPahoClient("consumer");
MqttConnectionOptions options = new MqttConnectionOptionsBuilder()
.cleanStart(false)
.sessionExpiryInterval(300L)
.build();
consumer.connect(options);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println(topic + ", " + PREFIX);
assertTrue(topic.startsWith(PREFIX));
latch.countDown();
}
});
consumer.subscribe(TOPIC_FILTER, 1);
MqttClient producer = createPahoClient("producer");
producer.connect();
producer.publish(TOPIC, "hello".getBytes(), 1, false);
producer.disconnect();
producer.close();
assertTrue(latch.await(2, TimeUnit.SECONDS));
consumer.disconnect();
consumer.close();
}
/*
* [MQTT-3.3.2-3] The Topic Name in a PUBLISH packet sent by a Server to a subscribing Client MUST match the
* Subscription’s Topic Filter.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testX() throws Exception {
final String PREFIX = "";
final String TOPIC = PREFIX + RandomUtil.randomString();
final CountDownLatch latch = new CountDownLatch(1);
MqttClient consumer = createPahoClient("consumer");
MqttConnectionOptions options = new MqttConnectionOptionsBuilder()
.cleanStart(false)
.sessionExpiryInterval(300L)
.build();
consumer.connect(options);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println(topic + ", " + PREFIX);
assertTrue(topic.startsWith(PREFIX));
latch.countDown();
}
});
consumer.subscribe(TOPIC, 1);
MqttClient producer = createPahoClient("producer");
producer.connect();
producer.publish(TOPIC, "hello".getBytes(), 1, false);
producer.disconnect();
producer.close();
assertTrue(latch.await(2, TimeUnit.SECONDS));
consumer.disconnect();
consumer.close();
}
/*
* [MQTT-3.3.2-4] A Server MUST send the Payload Format Indicator unaltered to all subscribers receiving the message.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testPayloadFormatIndicatorTrue() throws Exception {
internalTestPayloadFormatIndicator(true);
}
/*
* [MQTT-3.3.2-4] A Server MUST send the Payload Format Indicator unaltered to all subscribers receiving the message.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testPayloadFormatIndicatorFalse() throws Exception {
internalTestPayloadFormatIndicator(false);
}
private void internalTestPayloadFormatIndicator(boolean payloadFormatIndicator) throws Exception {
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
final CountDownLatch latch = new CountDownLatch(1);
MqttClient consumer = createPahoClient(CONSUMER_ID);
MqttConnectionOptions options = new MqttConnectionOptionsBuilder()
.cleanStart(false)
.sessionExpiryInterval(300L)
.build();
consumer.connect(options);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
if (payloadFormatIndicator) {
assertTrue(message.getProperties().getPayloadFormat());
} else {
assertFalse(message.getProperties().getPayloadFormat());
}
latch.countDown();
}
});
consumer.subscribe(TOPIC, 2);
MqttClient producer = createPahoClient("producer");
producer.connect();
MqttMessage m = new MqttMessage();
MqttProperties props = new MqttProperties();
props.setPayloadFormat(payloadFormatIndicator);
m.setProperties(props);
m.setQos(2);
m.setPayload("foo".getBytes(StandardCharsets.UTF_8));
producer.publish(TOPIC, m);
producer.disconnect();
producer.close();
assertTrue(latch.await(2, TimeUnit.SECONDS));
consumer.disconnect();
consumer.close();
}
/*
* [MQTT-3.3.2-5] If the Message Expiry Interval has passed and the Server has not managed to start onward delivery
* to a matching subscriber, then it MUST delete the copy of the message for that subscriber.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testMessageExpiryIntervalElapsed() throws Exception {
server.createQueue(new QueueConfiguration(EXPIRY_ADDRESS).setRoutingType(RoutingType.ANYCAST));
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
final CountDownLatch latch = new CountDownLatch(1);
MqttClient consumer = createPahoClient(CONSUMER_ID);
MqttConnectionOptions options = new MqttConnectionOptionsBuilder()
.cleanStart(false)
.sessionExpiryInterval(300L)
.build();
consumer.connect(options);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
latch.countDown();
}
});
consumer.subscribe(TOPIC, 2);
consumer.disconnect();
MqttClient producer = createPahoClient("producer");
producer.connect();
MqttMessage m = new MqttMessage();
MqttProperties props = new MqttProperties();
props.setMessageExpiryInterval(2L);
m.setProperties(props);
m.setQos(2);
m.setPayload("foo".getBytes(StandardCharsets.UTF_8));
producer.publish(TOPIC, m);
producer.disconnect();
producer.close();
Wait.assertEquals(1L, () -> getSubscriptionQueue(TOPIC).getMessageCount(), 1000, 100);
Wait.assertEquals(1L, () -> server.locateQueue("EXPIRY").getMessageCount(), 3000, 100);
Wait.assertEquals(0L, () -> getSubscriptionQueue(TOPIC).getMessageCount(), 1000, 100);
consumer.connect(options);
assertFalse(latch.await(1, TimeUnit.SECONDS));
consumer.disconnect();
}
/*
* [MQTT-3.3.2-6] The PUBLISH packet sent to a Client by the Server MUST contain a Message Expiry Interval set to the
* received value minus the time that the message has been waiting in the Server.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testMessageExpiryIntervalReturnValue() throws Exception {
server.createQueue(new QueueConfiguration(EXPIRY_ADDRESS).setRoutingType(RoutingType.ANYCAST));
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
final long EXPIRY_INTERVAL = 5L;
final long SLEEP = 1000;
final CountDownLatch latch = new CountDownLatch(1);
MqttClient consumer = createPahoClient(CONSUMER_ID);
MqttConnectionOptions options = new MqttConnectionOptionsBuilder()
.cleanStart(false)
.sessionExpiryInterval(300L)
.build();
consumer.connect(options);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
long messageExpiryInterval = message.getProperties().getMessageExpiryInterval();
System.out.println(messageExpiryInterval);
assertTrue(messageExpiryInterval <= EXPIRY_INTERVAL + (SLEEP / 1000));
assertTrue(messageExpiryInterval > 0);
latch.countDown();
}
});
consumer.subscribe(TOPIC, 2);
consumer.disconnect();
MqttClient producer = createPahoClient("producer");
producer.connect();
MqttMessage m = new MqttMessage();
MqttProperties props = new MqttProperties();
props.setMessageExpiryInterval(EXPIRY_INTERVAL);
m.setProperties(props);
m.setQos(2);
m.setPayload("foo".getBytes(StandardCharsets.UTF_8));
producer.publish(TOPIC, m);
producer.disconnect();
producer.close();
Wait.assertEquals(1L, () -> getSubscriptionQueue(TOPIC).getMessageCount(), 500, 100);
Thread.sleep(SLEEP);
consumer.connect(options);
assertTrue(latch.await(1, TimeUnit.SECONDS));
consumer.disconnect();
}
/*
* [MQTT-3.3.2-11] A Server MUST NOT send a PUBLISH packet with a Topic Alias greater than the Topic Alias Maximum
* value sent by the Client in the CONNECT packet.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testClientTopicAliasMaxFromServer() throws Exception {
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
final int MESSAGE_COUNT = 25;
final int ALIAS_MAX = 5;
MqttClient consumer = createPahoClient(CONSUMER_ID);
MqttConnectionOptions options = new MqttConnectionOptionsBuilder()
.topicAliasMaximum(ALIAS_MAX)
.build();
consumer.connect(options);
CountDownLatch latch = new CountDownLatch(MESSAGE_COUNT);
consumer.setCallback(new DefaultMqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Integer topicAlias = message.getProperties().getTopicAlias();
if (topicAlias != null) {
assertTrue(topicAlias <= ALIAS_MAX);
}
latch.countDown();
}
});
consumer.subscribe(TOPIC + "/#", 2);
MqttClient producer = createPahoClient("producer");
producer.connect();
for (int i = 0; i < MESSAGE_COUNT; i++) {
producer.publish(TOPIC + "/" + i, ("foo" + i).getBytes(StandardCharsets.UTF_8), 2, false);
}
producer.disconnect();
producer.close();
assertTrue(latch.await(2, TimeUnit.SECONDS));
consumer.disconnect();
}
/*
* [MQTT-3.3.2-7] A receiver MUST NOT carry forward any Topic Alias mappings from one Network Connection to another.
*
* Unfortunately the Paho MQTT 5 client performs automatic validation and therefore refuses to send a message with an
* empty topic even though the topic-alias is set appropriately. Therefore, this test won't actually run with the
* current client implementation. However, I built the client locally omitting the validation logic and the test
* passed as expected.
*
* I'm leaving this test here with @Ignore to demonstrate how to theoretically re-produce the problem. The problem
* was originally discovered using https://github.com/eclipse/paho.mqtt.testing/tree/master/interoperability to run
* the command:
*
* python3 client_test5.py Test.test_client_topic_alias
*/
@Ignore
@Test(timeout = DEFAULT_TIMEOUT)
public void testTopicAliasesNotCarriedForward() throws Exception {
final String TOPIC = "myTopicName";
MqttProperties properties = new MqttProperties();
properties.setTopicAlias(1);
MqttClient producer = createPahoClient("producer");
MqttConnectionOptions options = new MqttConnectionOptionsBuilder()
.topicAliasMaximum(2)
.sessionExpiryInterval(999L)
.cleanStart(false)
.build();
producer.connect(options);
MqttMessage m = new MqttMessage();
m.setProperties(properties);
producer.publish(TOPIC, m);
m = new MqttMessage();
m.setProperties(properties);
producer.publish("", m);
producer.disconnect();
// reconnect back to the old session, but the topic alias should now be gone so publishing should fail
producer.connect(options);
m = new MqttMessage();
m.setProperties(properties);
try {
producer.publish("", m);
fail("Publishing should fail here due to an invalid topic alias");
} catch (Exception e) {
// ignore
}
assertFalse(producer.isConnected());
producer.close();
}
/*
* [MQTT-3.3.2-12] A Server MUST accept all Topic Alias values greater than 0 and less than or equal to the Topic
* Alias Maximum value that it returned in the CONNACK packet.
*/
@Test(timeout = DEFAULT_TIMEOUT)
public void testServerTopicAliasMax() throws Exception {
final String CONSUMER_ID = RandomUtil.randomString();
final String TOPIC = this.getTopicName();
final int MESSAGE_COUNT = 25;
final int ALIAS_MAX = 5;
setAcceptorProperty("topicAliasMaximum=" + ALIAS_MAX);
MqttClient consumer = createPahoClient(CONSUMER_ID);
MqttConnectionOptions options = new MqttConnectionOptionsBuilder()
.topicAliasMaximum(ALIAS_MAX)
.build();
consumer.connect(options);
CountDownLatch latch = new CountDownLatch(MESSAGE_COUNT);
consumer.setCallback(new DefaultMqttCallback() {
@Override