-
Notifications
You must be signed in to change notification settings - Fork 912
/
AmqpLargeMessageTest.java
1248 lines (991 loc) · 46.6 KB
/
AmqpLargeMessageTest.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.amqp;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.artemis.api.core.QueueConfiguration;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.core.message.LargeBodyReader;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.apache.activemq.artemis.logs.AssertionLoggerHandler;
import org.apache.activemq.artemis.protocol.amqp.broker.AMQPLargeMessage;
import org.apache.activemq.artemis.tests.util.CFUtil;
import org.apache.activemq.artemis.tests.util.RandomUtil;
import org.apache.activemq.artemis.tests.util.Wait;
import org.apache.activemq.artemis.utils.ByteUtil;
import org.apache.activemq.transport.amqp.client.AmqpClient;
import org.apache.activemq.transport.amqp.client.AmqpConnection;
import org.apache.activemq.transport.amqp.client.AmqpMessage;
import org.apache.activemq.transport.amqp.client.AmqpReceiver;
import org.apache.activemq.transport.amqp.client.AmqpSender;
import org.apache.activemq.transport.amqp.client.AmqpSession;
import org.apache.qpid.jms.JmsConnectionFactory;
import org.apache.qpid.proton.amqp.Binary;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.messaging.AmqpSequence;
import org.apache.qpid.proton.amqp.messaging.AmqpValue;
import org.apache.qpid.proton.amqp.messaging.Data;
import org.apache.qpid.proton.amqp.messaging.Section;
import org.apache.qpid.proton.codec.ReadableBuffer;
import org.apache.qpid.proton.message.impl.MessageImpl;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandles;
@RunWith(Parameterized.class)
public class AmqpLargeMessageTest extends AmqpClientTestSupport {
protected static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final Random rand = new Random(System.currentTimeMillis());
@Parameterized.Parameter(0)
public int frameSize = 32767;
@Parameterized.Parameter(1)
public int payload = 110 * 1024;
@Parameterized.Parameter(2)
public int amqpMinLargeMessageSize = 100 * 1024;
@Parameterized.Parameter(3)
public boolean jdbc = false;
@Parameterized.Parameters(name = "frameSize={0}, payload={1}, amqpMinLargeMessageSize={2}, jdbc={3}")
public static Collection<Object[]> parameters() {
return Arrays.asList(new Object[][] {
{32767, 110 * 1024, 100 * 1024, false},
{2 * 100 * 1024, 10 * 110 * 1024, 4 * 110 * 1024, false},
{10 * 1024, 100 * 1024, 20 * 1024, true}
});
}
String testQueueName = "ConnectionFrameSize";
@Override
protected void addConfiguration(ActiveMQServer server) {
// Make the journal file size larger than the frame+message sizes used in the tests,
// since it is by default for external brokers and it changes the behaviour.
server.getConfiguration().setJournalFileSize(5 * 1024 * 1024);
if (jdbc) {
setDBStoreType(server.getConfiguration());
}
}
@Override
protected void configureAMQPAcceptorParameters(Map<String, Object> params) {
params.put("maxFrameSize", frameSize);
params.put("amqpMinLargeMessageSize", amqpMinLargeMessageSize);
}
@Override
protected void addAdditionalAcceptors(ActiveMQServer server) throws Exception {
server.getConfiguration().addAcceptorConfiguration("tcp", "tcp://localhost:61616");
}
@Test(timeout = 60000)
public void testSendAMQPReceiveCore() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
int nMsgs = 200;
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
try {
sendMessages(nMsgs, connection);
int count = getMessageCount(server.getPostOffice(), testQueueName);
assertEquals(nMsgs, count);
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
receiveJMS(nMsgs, factory);
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testSendAndGetData() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
int nMsgs = 1;
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
try {
sendMessages(nMsgs, connection);
int count = getMessageCount(server.getPostOffice(), testQueueName);
assertEquals(nMsgs, count);
org.apache.activemq.artemis.core.server.Queue serverQueue = server.locateQueue(testQueueName);
serverQueue.forEach(ref -> {
try {
AMQPLargeMessage message = (AMQPLargeMessage) ref.getMessage();
Assert.assertFalse(message.hasScheduledDeliveryTime());
ReadableBuffer dataBuffer = message.getData();
LargeBodyReader reader = message.getLargeBodyReader();
try {
Assert.assertEquals(reader.getSize(), dataBuffer.remaining());
reader.open();
ByteBuffer buffer = ByteBuffer.allocate(dataBuffer.remaining());
reader.readInto(buffer);
ByteUtil.equals(buffer.array(), dataBuffer.array());
} finally {
reader.close();
}
} catch (AssertionError assertionError) {
throw assertionError;
} catch (Throwable e) {
throw new RuntimeException(e.getMessage(), e);
}
});
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testSendAMQPMessageWithComplexAnnotationsReceiveCore() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
try {
connection.connect();
String annotation = "x-opt-embedded-map";
Map<String, String> embeddedMap = new LinkedHashMap<>();
embeddedMap.put("test-key-1", "value-1");
embeddedMap.put("test-key-2", "value-2");
embeddedMap.put("test-key-3", "value-3");
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(testQueueName);
AmqpMessage message = createAmqpMessage((byte) 'A', payload);
message.setApplicationProperty("IntProperty", (Integer) 42);
message.setDurable(true);
message.setMessageAnnotation(annotation, embeddedMap);
sender.send(message);
session.close();
Wait.assertEquals(1, () -> getMessageCount(server.getPostOffice(), testQueueName));
try (ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
Connection connection2 = factory.createConnection()) {
Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
connection2.start();
MessageConsumer consumer = session2.createConsumer(session2.createQueue(testQueueName));
Message received = consumer.receive(5000);
Assert.assertNotNull(received);
Assert.assertEquals(42, received.getIntProperty("IntProperty"));
connection2.close();
}
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testSendAMQPReceiveOpenWire() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
int nMsgs = 200;
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
try {
sendMessages(nMsgs, connection);
int count = getMessageCount(server.getPostOffice(), testQueueName);
assertEquals(nMsgs, count);
ConnectionFactory factory = new org.apache.activemq.ActiveMQConnectionFactory("tcp://localhost:61616");
receiveJMS(nMsgs, factory);
} finally {
connection.close();
}
}
private void sendMessages(int nMsgs, AmqpConnection connection) throws Exception {
connection.connect();
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(testQueueName);
for (int i = 0; i < nMsgs; ++i) {
AmqpMessage message = createAmqpMessage((byte) 'A', payload);
message.setApplicationProperty("i", (Integer) i);
message.setDurable(true);
sender.send(message);
}
session.close();
}
private void receiveJMS(int nMsgs, ConnectionFactory factory) throws JMSException {
Connection connection2 = factory.createConnection();
Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
connection2.start();
MessageConsumer consumer = session2.createConsumer(session2.createQueue(testQueueName));
for (int i = 0; i < nMsgs; i++) {
Message message = consumer.receive(5000);
Assert.assertNotNull(message);
Assert.assertEquals(i, message.getIntProperty("i"));
}
connection2.close();
}
@Test(timeout = 60000)
public void testSendAMQPReceiveAMQP() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
String testQueueName = "ConnectionFrameSize";
int nMsgs = 200;
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
try {
sendMessages(nMsgs, connection);
int count = getMessageCount(server.getPostOffice(), testQueueName);
assertEquals(nMsgs, count);
AmqpSession session = connection.createSession();
AmqpReceiver receiver = session.createReceiver(testQueueName);
receiver.flow(nMsgs);
for (int i = 0; i < nMsgs; ++i) {
AmqpMessage message = receiver.receive(5, TimeUnit.SECONDS);
assertNotNull("failed at " + i, message);
MessageImpl wrapped = (MessageImpl) message.getWrappedMessage();
if (wrapped.getBody() instanceof Data) {
// converters can change this to AmqValue
Data data = (Data) wrapped.getBody();
logger.debug("received : message: {}", data.getValue().getLength());
assertEquals(payload, data.getValue().getLength());
}
message.accept();
}
session.close();
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testSendAMQPMessageWithComplexAnnotationsReceiveAMQP() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
String testQueueName = "ConnectionFrameSize";
int nMsgs = 200;
AmqpClient client = createAmqpClient();
Symbol annotation = Symbol.valueOf("x-opt-embedded-map");
Map<String, String> embeddedMap = new LinkedHashMap<>();
embeddedMap.put("test-key-1", "value-1");
embeddedMap.put("test-key-2", "value-2");
embeddedMap.put("test-key-3", "value-3");
{
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(testQueueName);
AmqpMessage message = createAmqpMessage((byte) 'A', payload);
message.setApplicationProperty("IntProperty", (Integer) 42);
message.setDurable(true);
message.setMessageAnnotation(annotation.toString(), embeddedMap);
sender.send(message);
session.close();
connection.close();
}
Wait.assertEquals(1, () -> getMessageCount(server.getPostOffice(), testQueueName));
{
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpReceiver receiver = session.createReceiver(testQueueName);
receiver.flow(nMsgs);
AmqpMessage message = receiver.receive(5, TimeUnit.SECONDS);
assertNotNull("Failed to read message with embedded map in annotations", message);
MessageImpl wrapped = (MessageImpl) message.getWrappedMessage();
if (wrapped.getBody() instanceof Data) {
Data data = (Data) wrapped.getBody();
logger.debug("received : message: {}", data.getValue().getLength());
assertEquals(payload, data.getValue().getLength());
}
assertNotNull(message.getWrappedMessage().getMessageAnnotations());
assertNotNull(message.getWrappedMessage().getMessageAnnotations().getValue());
assertEquals(embeddedMap, message.getWrappedMessage().getMessageAnnotations().getValue().get(annotation));
message.accept();
session.close();
connection.close();
}
}
@Test(timeout = 60000)
public void testHugeString() throws Exception {
ConnectionFactory factory = CFUtil.createConnectionFactory("AMQP", "tcp://localhost:5672");
Connection connection = factory.createConnection();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
Queue queue = session.createQueue(getQueueName());
MessageProducer producer = session.createProducer(queue);
StringBuilder unicodeStringBuilder = new StringBuilder();
for (char c = 1000; c < 11000; c++) {
unicodeStringBuilder.append(c);
}
String unicodeString = unicodeStringBuilder.toString();
StringBuilder builder = new StringBuilder();
while (builder.length() < 1024 * 1024) {
builder.append("hello " + unicodeString);
}
producer.send(session.createTextMessage(builder.toString()));
session.commit();
connection.start();
MessageConsumer consumer = session.createConsumer(queue);
TextMessage message = (TextMessage)consumer.receive(50_000);
Assert.assertNotNull(message);
session.commit();
Assert.assertEquals(builder.toString(), message.getText());
}
@Test(timeout = 60000)
public void testSendAMQPReceiveAMQPViaJMSObjectMessage() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
String testQueueName = "ConnectionFrameSize";
int nMsgs = 1;
ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:61616");
sendObjectMessages(nMsgs, new JmsConnectionFactory("amqp://localhost:61616"));
int count = getMessageCount(server.getPostOffice(), testQueueName);
assertEquals(nMsgs, count);
receiveJMS(nMsgs, factory);
}
@Test(timeout = 60000)
public void testSendAMQPReceiveAMQPViaJMSText() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
String testQueueName = "ConnectionFrameSize";
int nMsgs = 1;
ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:61616");
sendTextMessages(nMsgs, new JmsConnectionFactory("amqp://localhost:61616"));
int count = getMessageCount(server.getPostOffice(), testQueueName);
assertEquals(nMsgs, count);
receiveJMS(nMsgs, factory);
}
@Test(timeout = 60000)
public void testSendAMQPReceiveAMQPViaJMSBytes() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
String testQueueName = "ConnectionFrameSize";
int nMsgs = 1;
ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:61616");
sendBytesMessages(nMsgs, new JmsConnectionFactory("amqp://localhost:61616"));
int count = getMessageCount(server.getPostOffice(), testQueueName);
assertEquals(nMsgs, count);
receiveJMS(nMsgs, factory);
}
private byte[] createLargePayload(int sizeInBytes) {
byte[] payload = new byte[sizeInBytes];
for (int i = 0; i < sizeInBytes; i++) {
payload[i] = (byte) rand.nextInt(256);
}
logger.debug("Created buffer with size : {} bytes", sizeInBytes);
return payload;
}
@Test(timeout = 60000)
public void testSendHugeHeader() throws Exception {
Assume.assumeFalse(jdbc); // the checked rule with the property size will not be applied to JDBC, hence we skip the test
doTestSendHugeHeader(payload);
}
@Test(timeout = 60000)
public void testSendLargeMessageWithHugeHeader() throws Exception {
Assume.assumeFalse(jdbc); // the checked rule with the property size will not be applied to JDBC, hence we skip the test
doTestSendHugeHeader(1024 * 1024);
}
public void doTestSendHugeHeader(int expectedSize) throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
try {
connection.connect();
final int strLength = 512 * 1024;
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(testQueueName);
AmqpMessage message = createAmqpMessage((byte) 'A', expectedSize);
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < strLength; i++) {
buffer.append(" ");
}
message.setApplicationProperty("str", buffer.toString());
message.setDurable(true);
try {
sender.send(message);
fail();
} catch (IOException e) {
Assert.assertTrue(e.getCause() instanceof JMSException);
Assert.assertTrue(e.getMessage().contains("AMQ149005"));
}
session.close();
} finally {
connection.close();
}
}
@Test
public void testLargeHeaderTXLargeBody() throws Exception {
Assume.assumeFalse(jdbc); // the checked rule with the property size will not be applied to JDBC, hence we skip the test
testLargeHeaderTX(true);
}
@Test
public void testLargeHeaderTXSmallBody() throws Exception {
Assume.assumeFalse(jdbc); // the checked rule with the property size will not be applied to JDBC, hence we skip the test
testLargeHeaderTX(false);
}
private void testLargeHeaderTX(boolean largeBody) throws Exception {
String testQueueName = RandomUtil.randomString();
server.createQueue(new QueueConfiguration(testQueueName).setRoutingType(RoutingType.ANYCAST));
ConnectionFactory cf = CFUtil.createConnectionFactory("AMQP", "tcp://localhost:5672");
String largeString;
{
StringBuffer buffer = new StringBuffer();
while (buffer.length() < 1024 * 1024) {
buffer.append("This is a large string ");
}
largeString = buffer.toString();
}
String smallString = "small string";
String body = largeBody ? largeString : smallString;
try (Connection connection = cf.createConnection()) {
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
MessageProducer producer = session.createProducer(session.createQueue(testQueueName));
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
Message message = session.createTextMessage(body);
message.setStringProperty("test", largeString);
boolean failed = false;
try {
producer.send(message);
session.commit();
} catch (Exception expected) {
failed = true;
}
Assert.assertTrue(failed);
}
try (Connection connection = cf.createConnection()) {
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
MessageProducer producer = session.createProducer(session.createQueue(testQueueName));
Message message = session.createTextMessage(body);
message.setStringProperty("test", smallString);
producer.send(message);
session.commit();
connection.start();
MessageConsumer consumer = session.createConsumer(session.createQueue(testQueueName));
TextMessage recMessage = (TextMessage) consumer.receive(5000);
Assert.assertEquals(smallString, recMessage.getStringProperty("test"));
Assert.assertEquals(body, recMessage.getText());
session.commit();
Assert.assertNull(consumer.receiveNoWait());
}
org.apache.activemq.artemis.core.server.Queue serverQueue = server.locateQueue(testQueueName);
Wait.assertEquals(0, serverQueue::getMessageCount);
File largeMessageFolder = server.getConfiguration().getLargeMessagesLocation();
File[] files = largeMessageFolder.listFiles();
Assert.assertTrue(files == null ? "Null Files" : "There are " + files.length + " files in the large message folder", files == null || files.length == 0);
}
@Test(timeout = 60000)
public void testSendSmallerMessages() throws Exception {
for (int i = 512; i <= (8 * 1024); i += 512) {
doTestSendLargeMessage(i);
}
}
@Test(timeout = 120000)
public void testSendFixedSizedMessages() throws Exception {
doTestSendLargeMessage(65536);
doTestSendLargeMessage(65536 * 2);
doTestSendLargeMessage(65536 * 4);
}
@Test(timeout = 120000)
public void testSend1MBMessage() throws Exception {
doTestSendLargeMessage(1024 * 1024);
}
@Ignore("Useful for performance testing")
@Test(timeout = 120000)
public void testSend10MBMessage() throws Exception {
doTestSendLargeMessage(1024 * 1024 * 10);
}
@Ignore("Useful for performance testing")
@Test(timeout = 120000)
public void testSend100MBMessage() throws Exception {
doTestSendLargeMessage(1024 * 1024 * 100);
}
public void doTestSendLargeMessage(int expectedSize) throws Exception {
logger.debug("doTestSendLargeMessage called with expectedSize {}", expectedSize);
byte[] payload = createLargePayload(expectedSize);
assertEquals(expectedSize, payload.length);
ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:61616");
try (Connection connection = factory.createConnection()) {
long startTime = System.currentTimeMillis();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(name.getMethodName());
MessageProducer producer = session.createProducer(queue);
BytesMessage message = session.createBytesMessage();
message.writeBytes(payload);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// Set this to non-default to get a Header in the encoded message.
producer.setPriority(4);
producer.send(message);
long endTime = System.currentTimeMillis();
logger.debug("Returned from send after {} ms", endTime - startTime);
startTime = System.currentTimeMillis();
MessageConsumer consumer = session.createConsumer(queue);
connection.start();
logger.debug("Calling receive");
Message received = consumer.receive();
assertNotNull(received);
assertTrue(received instanceof BytesMessage);
BytesMessage bytesMessage = (BytesMessage) received;
assertNotNull(bytesMessage);
endTime = System.currentTimeMillis();
logger.debug("Returned from receive after {} ms", endTime - startTime);
byte[] bytesReceived = new byte[expectedSize];
assertEquals(expectedSize, bytesMessage.readBytes(bytesReceived, expectedSize));
assertTrue(Arrays.equals(payload, bytesReceived));
connection.close();
}
}
@Test(timeout = 60000)
public void testReceiveRedeliveredLargeMessagesWithSessionFlowControl() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
int numMsgs = 10;
int msgSize = 2_000_000;
int maxFrameSize = frameSize; // Match the brokers outgoing frame size limit to make window sizing easy
int sessionCapacity = 2_500_000; // Restrict session to 1.x messages in flight at once, make it likely send is partial.
byte[] payload = createLargePayload(msgSize);
assertEquals(msgSize, payload.length);
AmqpClient client = createAmqpClient();
AmqpConnection connection = client.createConnection();
connection.setMaxFrameSize(maxFrameSize);
connection.setSessionIncomingCapacity(sessionCapacity);
connection.connect();
addConnection(connection);
try {
String testQueueName = getTestName();
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(testQueueName);
for (int i = 0; i < numMsgs; ++i) {
AmqpMessage message = new AmqpMessage();
message.setBytes(payload);
sender.send(message);
}
Wait.assertEquals(numMsgs, () -> getMessageCount(server.getPostOffice(), testQueueName), 5000, 10);
AmqpReceiver receiver = session.createReceiver(testQueueName);
receiver.flow(numMsgs);
ArrayList<AmqpMessage> messages = new ArrayList<>();
for (int i = 0; i < numMsgs; ++i) {
AmqpMessage message = receiver.receive(5, TimeUnit.SECONDS);
assertNotNull("failed at " + i, message);
messages.add(message);
}
for (int i = 0; i < numMsgs; ++i) {
AmqpMessage msg = messages.get(i);
msg.modified(true, false);
}
receiver.close();
AmqpReceiver receiver2 = session.createReceiver(testQueueName);
receiver2.flow(numMsgs);
for (int i = 0; i < numMsgs; ++i) {
AmqpMessage message = receiver2.receive(5, TimeUnit.SECONDS);
validateMessage(payload, i, message);
message.accept();
}
session.close();
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testReceiveLargeMessagesMultiplexedOnSameSession() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
int numMsgs = 10;
int maxFrameSize = frameSize; // Match the brokers outgoing frame size limit to make window sizing easy
int msgSizeA = frameSize * 4; // Bigger multi-frame messages
int msgSizeB = maxFrameSize / 2; // Smaller single frame messages
int sessionCapacity = msgSizeA + maxFrameSize; // Restrict session to 1.X of the larger messages in flight at once, make it likely send is partial.
byte[] payloadA = createLargePayload(msgSizeA);
assertEquals(msgSizeA, payloadA.length);
byte[] payloadB = createLargePayload(msgSizeB);
assertEquals(msgSizeB, payloadB.length);
String testQueueNameA = getTestName() + "A";
String testQueueNameB = getTestName() + "B";
AmqpClient client = createAmqpClient();
AmqpConnection connection = client.createConnection();
connection.setMaxFrameSize(maxFrameSize);
connection.setSessionIncomingCapacity(sessionCapacity);
connection.connect();
addConnection(connection);
try {
AmqpSession session = connection.createSession();
AmqpSender senderA = session.createSender(testQueueNameA);
AmqpSender senderB = session.createSender(testQueueNameB);
// Send in the messages
for (int i = 0; i < numMsgs; ++i) {
AmqpMessage messageA = new AmqpMessage();
messageA.setBytes(payloadA);
senderA.send(messageA);
AmqpMessage messageB = new AmqpMessage();
messageB.setBytes(payloadB);
senderB.send(messageB);
}
Wait.assertEquals(numMsgs, () -> getMessageCount(server.getPostOffice(), testQueueNameA), 5000, 10);
Wait.assertEquals(numMsgs, () -> getMessageCount(server.getPostOffice(), testQueueNameB), 5000, 10);
AmqpReceiver receiverA = session.createReceiver(testQueueNameA);
AmqpReceiver receiverB = session.createReceiver(testQueueNameB);
// Split credit flow to encourage overlapping
// Flow initial credit for both consumers, in the same TCP frame.
receiverA.flow(numMsgs / 2, true);
receiverB.flow(numMsgs / 2);
// Flow remaining credit for both consumers, in the same TCP frame.
receiverA.flow(numMsgs / 2, true);
receiverB.flow(numMsgs / 2);
ArrayList<AmqpMessage> messagesA = new ArrayList<>();
ArrayList<AmqpMessage> messagesB = new ArrayList<>();
long timeout = 6000;
long start = System.nanoTime();
// Validate the messages are all received
boolean timeRemaining = true;
while (timeRemaining) {
if (messagesA.size() < numMsgs) {
logger.debug("Attempting to receive message for receiver A");
AmqpMessage messageA = receiverA.receive(20, TimeUnit.MILLISECONDS);
if (messageA != null) {
logger.debug("Got message for receiver A");
messagesA.add(messageA);
messageA.accept();
}
}
if (messagesB.size() < numMsgs) {
logger.debug("Attempting to receive message for receiver B");
AmqpMessage messageB = receiverB.receive(20, TimeUnit.MILLISECONDS);
if (messageB != null) {
logger.debug("Got message for receiver B");
messagesB.add(messageB);
messageB.accept();
}
}
if (messagesA.size() == numMsgs && messagesB.size() == numMsgs) {
logger.debug("Received expected messages");
break;
}
timeRemaining = System.nanoTime() - start < TimeUnit.MILLISECONDS.toNanos(timeout);
}
assertTrue("Failed to receive all messages in expected time: A=" + messagesA.size() + ", B=" + messagesB.size(), timeRemaining);
// Validate there aren't any extras
assertNull("Unexpected additional message present for A", receiverA.receiveNoWait());
assertNull("Unexpected additional message present for B", receiverB.receiveNoWait());
// Validate the transfers were reconstituted to give the expected delivery payload.
for (int i = 0; i < numMsgs; ++i) {
AmqpMessage messageA = messagesA.get(i);
validateMessage(payloadA, i, messageA);
AmqpMessage messageB = messagesB.get(i);
validateMessage(payloadB, i, messageB);
}
receiverA.close();
receiverB.close();
session.close();
} finally {
connection.close();
}
}
private void validateMessage(byte[] expectedPayload, int msgNum, AmqpMessage message) {
assertNotNull("failed at " + msgNum, message);
Section body = message.getWrappedMessage().getBody();
assertNotNull("No message body for msg " + msgNum, body);
assertTrue("Unexpected message body type for msg " + body.getClass(), body instanceof Data);
assertEquals("Unexpected body content for msg", new Binary(expectedPayload, 0, expectedPayload.length), ((Data) body).getValue());
}
@Test(timeout = 60000)
public void testMessageWithAmqpValueAndEmptyBinaryPreservesBody() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
try {
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(getTestName());
AmqpMessage message = createAmqpLargeMessageWithNoBody();
message.getWrappedMessage().setBody(new AmqpValue(new Binary(new byte[0])));
sender.send(message);
sender.close();
AmqpReceiver receiver = session.createReceiver(getTestName());
receiver.flow(1);
AmqpMessage received = receiver.receive(5, TimeUnit.SECONDS);
assertNotNull("failed to read large AMQP message", received);
MessageImpl wrapped = (MessageImpl) received.getWrappedMessage();
assertTrue(wrapped.getBody() instanceof AmqpValue);
AmqpValue body = (AmqpValue) wrapped.getBody();
assertTrue(body.getValue() instanceof Binary);
Binary payload = (Binary) body.getValue();
assertEquals(0, payload.getLength());
received.accept();
session.close();
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testMessageWithDataAndEmptyBinaryPreservesBody() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
try {
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(getTestName());
AmqpMessage message = createAmqpLargeMessageWithNoBody();
message.getWrappedMessage().setBody(new Data(new Binary(new byte[0])));
sender.send(message);
sender.close();
AmqpReceiver receiver = session.createReceiver(getTestName());
receiver.flow(1);
AmqpMessage received = receiver.receive(5, TimeUnit.SECONDS);
assertNotNull("failed to read large AMQP message", received);
MessageImpl wrapped = (MessageImpl) received.getWrappedMessage();
assertTrue(wrapped.getBody() instanceof Data);
Data body = (Data) wrapped.getBody();
assertTrue(body.getValue() instanceof Binary);
Binary payload = (Binary) body.getValue();
assertEquals(0, payload.getLength());
received.accept();
session.close();
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testMessageWithDataAndContentTypeOfTextPreservesBodyType() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
try {
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(getTestName());
AmqpMessage message = createAmqpLargeMessageWithNoBody();
String messageText = "This text will be in a Data Section";
message.getWrappedMessage().setContentType("text/plain");
message.getWrappedMessage().setBody(new Data(new Binary(messageText.getBytes(StandardCharsets.UTF_8))));
//message.setApplicationProperty("_AMQ_DUPL_ID", "11");
sender.send(message);
sender.close();
AmqpReceiver receiver = session.createReceiver(getTestName());
receiver.flow(1);
AmqpMessage received = receiver.receive(10, TimeUnit.SECONDS);
assertNotNull("failed to read large AMQP message", received);
MessageImpl wrapped = (MessageImpl) received.getWrappedMessage();
assertTrue(wrapped.getBody() instanceof Data);
Data body = (Data) wrapped.getBody();
assertTrue(body.getValue() instanceof Binary);
Binary payload = (Binary) body.getValue();
String reconstitutedString = new String(
payload.getArray(), payload.getArrayOffset(), payload.getLength(), StandardCharsets.UTF_8);
assertEquals(messageText, reconstitutedString);
received.accept();
session.close();
} finally {
connection.close();
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test(timeout = 60000)
public void testMessageWithAmqpValueListPreservesBodyType() throws Exception {
server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
try {
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(getTestName());