/
AmqpClientActorTest.java
882 lines (740 loc) · 41.6 KB
/
AmqpClientActorTest.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
/*
* Copyright (c) 2017 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.services.connectivity.messaging.amqp;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.eclipse.ditto.model.base.common.ConditionChecker.checkNotNull;
import static org.eclipse.ditto.services.connectivity.messaging.TestConstants.createRandomConnectionId;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import javax.jms.CompletionListener;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.qpid.jms.JmsConnection;
import org.apache.qpid.jms.JmsConnectionListener;
import org.apache.qpid.jms.JmsMessageConsumer;
import org.apache.qpid.jms.JmsQueue;
import org.apache.qpid.jms.JmsSession;
import org.apache.qpid.jms.message.JmsMessage;
import org.apache.qpid.jms.message.JmsTextMessage;
import org.apache.qpid.jms.provider.amqp.AmqpConnection;
import org.apache.qpid.jms.provider.amqp.message.AmqpJmsTextMessageFacade;
import org.apache.qpid.proton.amqp.Symbol;
import org.assertj.core.api.ThrowableAssert;
import org.awaitility.Awaitility;
import org.eclipse.ditto.model.base.common.DittoConstants;
import org.eclipse.ditto.model.base.headers.DittoHeaders;
import org.eclipse.ditto.model.connectivity.Connection;
import org.eclipse.ditto.model.connectivity.ConnectionConfigurationInvalidException;
import org.eclipse.ditto.model.connectivity.ConnectionType;
import org.eclipse.ditto.model.connectivity.ConnectivityModelFactory;
import org.eclipse.ditto.model.connectivity.ConnectivityStatus;
import org.eclipse.ditto.model.connectivity.ResourceStatus;
import org.eclipse.ditto.model.connectivity.Source;
import org.eclipse.ditto.model.connectivity.Target;
import org.eclipse.ditto.model.connectivity.Topic;
import org.eclipse.ditto.model.things.Attributes;
import org.eclipse.ditto.protocoladapter.TopicPath;
import org.eclipse.ditto.services.connectivity.messaging.AbstractBaseClientActorTest;
import org.eclipse.ditto.services.connectivity.messaging.BaseClientState;
import org.eclipse.ditto.services.connectivity.messaging.TestConstants;
import org.eclipse.ditto.services.connectivity.messaging.TestConstants.Authorization;
import org.eclipse.ditto.services.models.connectivity.OutboundSignal;
import org.eclipse.ditto.services.models.connectivity.OutboundSignalFactory;
import org.eclipse.ditto.signals.commands.base.Command;
import org.eclipse.ditto.signals.commands.base.CommandResponse;
import org.eclipse.ditto.signals.commands.connectivity.exceptions.ConnectionFailedException;
import org.eclipse.ditto.signals.commands.connectivity.exceptions.ConnectionSignalIllegalException;
import org.eclipse.ditto.signals.commands.connectivity.modify.CloseConnection;
import org.eclipse.ditto.signals.commands.connectivity.modify.OpenConnection;
import org.eclipse.ditto.signals.commands.connectivity.modify.TestConnection;
import org.eclipse.ditto.signals.commands.connectivity.query.RetrieveConnectionStatus;
import org.eclipse.ditto.signals.commands.things.ThingErrorResponse;
import org.eclipse.ditto.signals.commands.things.exceptions.ThingNotModifiableException;
import org.eclipse.ditto.signals.commands.things.modify.ModifyThing;
import org.eclipse.ditto.signals.commands.things.modify.ModifyThingResponse;
import org.eclipse.ditto.signals.events.things.ThingModifiedEvent;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.Status;
import akka.testkit.TestProbe;
import akka.testkit.javadsl.TestKit;
@RunWith(MockitoJUnitRunner.class)
public final class AmqpClientActorTest extends AbstractBaseClientActorTest {
private static final Logger LOGGER = LoggerFactory.getLogger(AmqpClientActorTest.class);
private static final Status.Success CONNECTED_SUCCESS = new Status.Success(BaseClientState.CONNECTED);
private static final Status.Success DISCONNECTED_SUCCESS = new Status.Success(BaseClientState.DISCONNECTED);
private static final JMSException JMS_EXCEPTION = new JMSException("FAIL");
private static final URI DUMMY = URI.create("amqp://test:1234");
private static final String CONNECTION_ID = TestConstants.createRandomConnectionId();
private static final ConnectionFailedException SESSION_EXCEPTION =
ConnectionFailedException.newBuilder(CONNECTION_ID).build();
@SuppressWarnings("NullableProblems") private static ActorSystem actorSystem;
private static Connection connection;
private final ConnectivityStatus connectionStatus = ConnectivityStatus.OPEN;
@Mock
private final JmsConnection mockConnection = Mockito.mock(JmsConnection.class);
private final JmsConnectionFactory jmsConnectionFactory = (connection1, exceptionListener) -> mockConnection;
@Mock
private final JmsSession mockSession = Mockito.mock(JmsSession.class);
@Mock
private final JmsMessageConsumer mockConsumer = Mockito.mock(JmsMessageConsumer.class);
private MessageProducer mockProducer;
private ArgumentCaptor<JmsConnectionListener> listenerArgumentCaptor;
@BeforeClass
public static void setUp() {
actorSystem = ActorSystem.create("AkkaTestSystem", TestConstants.CONFIG);
connection = TestConstants.createConnection(CONNECTION_ID);
}
@AfterClass
public static void tearDown() {
TestKit.shutdownActorSystem(actorSystem, scala.concurrent.duration.Duration.apply(5, TimeUnit.SECONDS),
false);
}
@AfterClass
public static void stopMockServers() {
TestConstants.stopMockServers();
}
@Before
public void init() throws JMSException {
mockProducer = Mockito.mock(MessageProducer.class);
when(mockConnection.createSession(Session.CLIENT_ACKNOWLEDGE)).thenReturn(mockSession);
listenerArgumentCaptor = ArgumentCaptor.forClass(JmsConnectionListener.class);
doNothing().when(mockConnection).addConnectionListener(listenerArgumentCaptor.capture());
when(mockSession.createConsumer(any(JmsQueue.class))).thenReturn(mockConsumer);
prepareCreateProducer(mockSession, mockProducer);
}
private void prepareCreateProducer(final Session mockSession, final MessageProducer mockProducer)
throws JMSException {
when(mockSession.createProducer(any(Destination.class))).thenAnswer(
(Answer<MessageProducer>) destinationInv -> {
final Destination destination = destinationInv.getArgument(0);
when(mockSession.createTextMessage(anyString())).thenAnswer((Answer<JmsMessage>) textMsgInv -> {
final String textMsg = textMsgInv.getArgument(0);
final AmqpJmsTextMessageFacade facade = new AmqpJmsTextMessageFacade();
facade.initialize(Mockito.mock(AmqpConnection.class));
final JmsTextMessage jmsTextMessage = new JmsTextMessage(facade);
jmsTextMessage.setText(textMsg);
jmsTextMessage.setJMSDestination(destination);
return jmsTextMessage;
});
return mockProducer;
});
}
@Test
public void invalidSpecificOptionsThrowConnectionConfigurationInvalidException() {
final Map<String, String> specificOptions = new HashMap<>();
specificOptions.put("failover.unknown.option", "100");
specificOptions.put("failover.nested.amqp.vhost", "ditto");
final Connection connection = ConnectivityModelFactory.newConnectionBuilder(createRandomConnectionId(),
ConnectionType.AMQP_10, ConnectivityStatus.OPEN, TestConstants.getUriOfNewMockServer())
.specificConfig(specificOptions)
.sources(singletonList(
ConnectivityModelFactory.newSourceBuilder()
.authorizationContext(Authorization.AUTHORIZATION_CONTEXT)
.address("source1")
.build()))
.build();
final ThrowableAssert.ThrowingCallable props1 =
() -> AmqpClientActor.propsForTests(connection, connectionStatus, null, null);
final ThrowableAssert.ThrowingCallable props2 =
() -> AmqpClientActor.propsForTests(connection, connectionStatus, null,
jmsConnectionFactory);
Stream.of(props1, props2).forEach(throwingCallable ->
assertThatExceptionOfType(ConnectionConfigurationInvalidException.class)
.isThrownBy(throwingCallable)
.withMessageContaining("unknown.option"));
}
@Test
public void testExceptionDuringJMSConnectionCreation() {
new TestKit(actorSystem) {{
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus, getRef(),
(theConnection, exceptionListener) -> {
throw JMS_EXCEPTION;
});
final ActorRef connectionActor = actorSystem.actorOf(props);
connectionActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(new Status.Failure(SESSION_EXCEPTION));
}};
}
@Test
public void testConnectionHandling() {
new TestKit(actorSystem) {{
final TestProbe aggregator = new TestProbe(actorSystem);
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus, getRef(),
(connection1, exceptionListener) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
watch(amqpClientActor);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(CONNECTED_SUCCESS);
amqpClientActor.tell(RetrieveConnectionStatus.of(CONNECTION_ID, DittoHeaders.empty()), aggregator.ref());
final ResourceStatus resourceStatus1 = aggregator.expectMsgClass(ResourceStatus.class);
amqpClientActor.tell(CloseConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(DISCONNECTED_SUCCESS);
amqpClientActor.tell(RetrieveConnectionStatus.of(CONNECTION_ID, DittoHeaders.empty()), aggregator.ref());
final ResourceStatus resourceStatus2 = aggregator.expectMsgClass(ResourceStatus.class);
}};
}
@Test
public void testReconnect() {
new TestKit(actorSystem) {{
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus, getRef(),
(connection1, exceptionListener) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
watch(amqpClientActor);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(CONNECTED_SUCCESS);
// introduce artificial code difference from RabbitMQClientActorTest.testReconnect
for (int i = 0; i < 10; ++i) {
amqpClientActor.tell(CloseConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(DISCONNECTED_SUCCESS);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(CONNECTED_SUCCESS);
}
amqpClientActor.tell(CloseConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(DISCONNECTED_SUCCESS);
}};
}
@Test
public void testReconnectAndVerifyConnectionStatus() {
new TestKit(actorSystem) {{
final TestProbe aggregator = new TestProbe(actorSystem);
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus,
getRef(), (connection1, exceptionListener) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
watch(amqpClientActor);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(CONNECTED_SUCCESS);
amqpClientActor.tell(RetrieveConnectionStatus.of(CONNECTION_ID, DittoHeaders.empty()), aggregator.ref());
final ResourceStatus resourceStatus = aggregator.expectMsgClass(ResourceStatus.class);
System.out.println(resourceStatus);
final JmsConnectionListener connectionListener = checkNotNull(listenerArgumentCaptor.getValue());
connectionListener.onConnectionInterrupted(DUMMY);
verifyConnectionStatus(amqpClientActor, aggregator, ConnectivityStatus.FAILED);
connectionListener.onConnectionRestored(DUMMY);
verifyConnectionStatus(amqpClientActor, aggregator, ConnectivityStatus.OPEN);
amqpClientActor.tell(CloseConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(DISCONNECTED_SUCCESS);
}};
}
private static void verifyConnectionStatus(final ActorRef amqpClientActor, final TestProbe aggregator,
final ConnectivityStatus open) {
amqpClientActor.tell(RetrieveConnectionStatus.of(CONNECTION_ID, DittoHeaders.empty()), aggregator.ref());
Awaitility.await().until(() -> awaitStatusInStatusResponse(aggregator, open));
}
private static Boolean awaitStatusInStatusResponse(final TestProbe aggregator,
final ConnectivityStatus expectedStatus) {
final ResourceStatus status = aggregator.expectMsgClass(ResourceStatus.class);
System.out.println("waiting for " + expectedStatus + ", received: " + status);
return expectedStatus.equals(status.getStatus());
}
@Test
public void sendCommandDuringInit() {
new TestKit(actorSystem) {{
final CountDownLatch latch = new CountDownLatch(1);
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus,
getRef(), (ac, el) -> waitForLatchAndReturn(latch, mockConnection));
final ActorRef amqpClientActor = actorSystem.actorOf(props);
watch(amqpClientActor);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
latch.countDown();
expectMsg(CONNECTED_SUCCESS);
}};
}
@Test
public void sendConnectCommandWhenAlreadyConnected() throws JMSException {
new TestKit(actorSystem) {{
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus, getRef(),
(ac, el) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(CONNECTED_SUCCESS);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsgClass(ConnectionSignalIllegalException.class);
// no reconnect happens
Mockito.verify(mockConnection, Mockito.times(1)).start();
}};
}
@Test
public void sendDisconnectWhenAlreadyDisconnected() {
new TestKit(actorSystem) {{
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus,
getRef(), (ac, el) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
amqpClientActor.tell(CloseConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(DISCONNECTED_SUCCESS);
Mockito.verifyZeroInteractions(mockConnection);
}};
}
@Test
public void testStartConnectionFails() throws JMSException {
new TestKit(actorSystem) {{
doThrow(JMS_EXCEPTION).when(mockConnection).start();
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus,
getRef(), (ac, el) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(new Status.Failure(SESSION_EXCEPTION));
}};
}
@Test
public void testCreateSessionFails() throws JMSException {
new TestKit(actorSystem) {{
doThrow(JMS_EXCEPTION).when(mockConnection).createSession(Session.CLIENT_ACKNOWLEDGE);
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus,
getRef(), (ac, el) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(new Status.Failure(SESSION_EXCEPTION));
}};
}
@Test
public void testCreateConsumerFails() throws JMSException {
new TestKit(actorSystem) {{
when(mockConnection.createSession(Session.CLIENT_ACKNOWLEDGE)).thenReturn(mockSession);
doThrow(JMS_EXCEPTION).when(mockSession).createConsumer(any());
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus,
getRef(), (ac, el) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsgClass(Status.Failure.class);
}};
}
@Test
public void testCloseConnectionFails() throws JMSException {
new TestKit(actorSystem) {{
doThrow(JMS_EXCEPTION).when(mockConnection).close();
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus,
getRef(), (ac, el) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(CONNECTED_SUCCESS);
amqpClientActor.tell(CloseConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(DISCONNECTED_SUCCESS);
}};
}
@Test
public void testConnectionRestoredExpectRecreateSession() throws JMSException {
final String expectedAddress = "target";
final Target target = ConnectivityModelFactory.newTarget(expectedAddress, Authorization.AUTHORIZATION_CONTEXT,
null, null, Topic.TWIN_EVENTS);
final MessageProducer recoveredProducer = Mockito.mock(MessageProducer.class);
final MessageConsumer recoveredConsumer = Mockito.mock(MessageConsumer.class);
final JmsSession newSession = Mockito.mock(JmsSession.class, withSettings().name("recoveredSession"));
// existing session was closed
when(mockSession.isClosed()).thenReturn(true);
when(mockConnection.createSession(Session.CLIENT_ACKNOWLEDGE))
.thenReturn(mockSession) // initial session
.thenReturn(newSession); // recovered session
when(newSession.createConsumer(any(JmsQueue.class))).thenReturn(recoveredConsumer);
prepareCreateProducer(newSession, recoveredProducer);
new TestKit(actorSystem) {{
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus, getRef(), (ac, el) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
// connect
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(CONNECTED_SUCCESS);
// capture connection listener to close session later
final ArgumentCaptor<JmsConnectionListener> captor = ArgumentCaptor.forClass(JmsConnectionListener.class);
verify(mockConnection).addConnectionListener(captor.capture());
final JmsConnectionListener jmsConnectionListener = captor.getValue();
// verify everything is setup correctly by publishing an event
sendThingEventAndExpectPublish(amqpClientActor, target, mockProducer);
// verify message is consumed and forwarded to concierge
consumeMockMessage(mockConsumer);
expectMsgClass(Command.class);
// now close session
jmsConnectionListener.onConnectionRestored(URI.create("amqp://broker:5671"));
verify(mockConnection, timeout(2000).times(2)).createSession(Session.CLIENT_ACKNOWLEDGE);
// close is called on old session
verify(mockSession, times(2)).close();
// verify publishing an event works with new session/producer
sendThingEventAndExpectPublish(amqpClientActor, target, recoveredProducer);
// verify message is consumed with newly created consumer
consumeMockMessage(recoveredConsumer);
expectMsgClass(Command.class);
}};
}
@Test
public void testConsumeMessageAndExpectForwardToConciergeForwarder() throws JMSException {
testConsumeMessageAndExpectForwardToConciergeForwarder(connection, 1,
c -> assertThat(c.getDittoHeaders().getAuthorizationContext()).isEqualTo(
Authorization.SOURCE_SPECIFIC_CONTEXT));
}
@Test
public void testConsumeMessageForSourcesWithSameAddress() throws JMSException {
final Connection connection =
TestConstants.createConnection(CONNECTION_ID,
TestConstants.Sources.SOURCES_WITH_SAME_ADDRESS);
final AtomicBoolean messageReceivedForGlobalContext = new AtomicBoolean(false);
final AtomicBoolean messageReceivedForSourceContext = new AtomicBoolean(false);
testConsumeMessageAndExpectForwardToConciergeForwarder(connection, 2,
c -> {
if (c.getDittoHeaders()
.getAuthorizationContext()
.equals(Authorization.SOURCE_SPECIFIC_CONTEXT)) {
messageReceivedForSourceContext.set(true);
}
if (c.getDittoHeaders()
.getAuthorizationContext()
.equals(Authorization.SOURCE_SPECIFIC_CONTEXT)) {
messageReceivedForGlobalContext.set(true);
}
});
assertThat(messageReceivedForGlobalContext.get() && messageReceivedForSourceContext.get()).isTrue();
}
@Test
public void testConsumeMessageAndExpectForwardToConciergeForwarderWithCorrectAuthContext() throws JMSException {
final Connection connection =
TestConstants.createConnection(CONNECTION_ID,
TestConstants.Sources.SOURCES_WITH_AUTH_CONTEXT);
testConsumeMessageAndExpectForwardToConciergeForwarder(connection, 1,
c -> assertThat(c.getDittoHeaders().getAuthorizationContext()).isEqualTo(
Authorization.SOURCE_SPECIFIC_CONTEXT));
}
private void testConsumeMessageAndExpectForwardToConciergeForwarder(final Connection connection,
final int consumers, final Consumer<Command> commandConsumer) throws JMSException {
testConsumeMessageAndExpectForwardToConciergeForwarder(connection, consumers, commandConsumer, null);
}
private void testConsumeMessageAndExpectForwardToConciergeForwarder(final Connection connection,
final int consumers,
final Consumer<Command> commandConsumer,
@Nullable final Consumer<ActorRef> postStep) throws JMSException {
new TestKit(actorSystem) {{
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus, getRef(),
(ac, el) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(CONNECTED_SUCCESS);
final ArgumentCaptor<MessageListener> captor = ArgumentCaptor.forClass(MessageListener.class);
verify(mockConsumer, timeout(1000).atLeast(consumers)).setMessageListener(captor.capture());
for (final MessageListener messageListener : captor.getAllValues()) {
messageListener.onMessage(mockMessage());
}
for (int i = 0; i < consumers; i++) {
final Command command = expectMsgClass(Command.class);
assertThat(command.getId()).isEqualTo(TestConstants.Things.THING_ID);
assertThat(command.getDittoHeaders().getCorrelationId()).contains(TestConstants.CORRELATION_ID);
commandConsumer.accept(command);
}
if (postStep != null) {
postStep.accept(amqpClientActor);
}
}};
}
@Test
public void testConsumeMessageAndExpectForwardToConciergeForwarderAndReceiveResponse() throws JMSException {
testConsumeMessageAndExpectForwardToConciergeForwarderAndReceiveResponse(
connection, (id, headers) -> ModifyThingResponse.modified(id, DittoHeaders.of(headers)),
"replies",
message -> message.contains("\"status\":2"));
}
@Test
public void testConsumeMessageAndExpectForwardToConciergeForwarderAndReceiveResponseForConnectionWithoutTarget()
throws JMSException {
final String targetsKey = Connection.JsonFields.TARGETS.getPointer().toString();
final Connection connectionWithoutTargets
= ConnectivityModelFactory.connectionFromJson(connection.toJson().remove(targetsKey));
testConsumeMessageAndExpectForwardToConciergeForwarderAndReceiveResponse(
connectionWithoutTargets,
(id, headers) -> ModifyThingResponse.modified(id, DittoHeaders.of(headers)),
"replies",
message -> message.contains("\"status\":2"));
}
@Test
public void testConsumeMessageAndExpectForwardToConciergeForwarderAndReceiveError() throws JMSException {
testConsumeMessageAndExpectForwardToConciergeForwarderAndReceiveResponse(
connection, (id, headers) -> ThingErrorResponse.of(id,
ThingNotModifiableException.newBuilder(id).dittoHeaders(headers).build()),
"replies",
message -> message.contains("ditto/thing/things/twin/errors"));
}
private void testConsumeMessageAndExpectForwardToConciergeForwarderAndReceiveResponse(
final Connection connection,
final BiFunction<String, DittoHeaders, CommandResponse> responseSupplier,
final String expectedAddress,
final Predicate<String> messageTextPredicate) throws JMSException {
new TestKit(actorSystem) {{
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus, getRef(),
(ac, el) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(CONNECTED_SUCCESS);
final ArgumentCaptor<MessageListener> captor = ArgumentCaptor.forClass(MessageListener.class);
verify(mockConsumer, timeout(1000).atLeastOnce()).setMessageListener(captor.capture());
final MessageListener messageListener = captor.getValue();
messageListener.onMessage(mockMessage());
final Command command = expectMsgClass(Command.class);
assertThat(command.getId()).isEqualTo(TestConstants.Things.THING_ID);
assertThat(command.getDittoHeaders().getCorrelationId()).contains(TestConstants.CORRELATION_ID);
assertThat(command).isInstanceOf(ModifyThing.class);
getLastSender().tell(responseSupplier.apply(command.getId(), command.getDittoHeaders()), getRef());
final ArgumentCaptor<JmsMessage> messageCaptor = ArgumentCaptor.forClass(JmsMessage.class);
verify(mockProducer, timeout(2000)).send(messageCaptor.capture(), any(CompletionListener.class));
final Message message = messageCaptor.getValue();
assertThat(message).isNotNull();
assertThat(message.getJMSDestination()).isEqualTo(new JmsQueue(expectedAddress));
assertThat(messageTextPredicate).accepts(message.getBody(String.class));
}};
}
@Test
public void testTargetAddressPlaceholderReplacement() throws JMSException {
final Connection connection =
TestConstants.createConnection(CONNECTION_ID,
TestConstants.Targets.TARGET_WITH_PLACEHOLDER);
// target Placeholder: target:{{ thing:namespace }}/{{thing:name}}@{{ topic:channel }}
final String expectedAddress =
"target:" + TestConstants.Things.NAMESPACE + "/" + TestConstants.Things.ID + "@" +
TopicPath.Channel.TWIN.getName();
new TestKit(actorSystem) {{
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus, getRef(),
(ac, el) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(CONNECTED_SUCCESS);
final ThingModifiedEvent thingModifiedEvent = TestConstants.thingModified(singletonList(""));
final OutboundSignal outboundSignal = OutboundSignalFactory.newOutboundSignal(thingModifiedEvent,
singletonList(ConnectivityModelFactory.newTarget(
TestConstants.Targets.TARGET_WITH_PLACEHOLDER.getAddress(),
Authorization.AUTHORIZATION_CONTEXT,
null, null, Topic.TWIN_EVENTS))
);
amqpClientActor.tell(outboundSignal, getRef());
final ArgumentCaptor<JmsMessage> messageCaptor = ArgumentCaptor.forClass(JmsMessage.class);
verify(mockProducer, timeout(2000)).send(messageCaptor.capture(), any(CompletionListener.class));
final Message message = messageCaptor.getValue();
assertThat(message).isNotNull();
assertThat(message.getJMSDestination()).isEqualTo(new JmsQueue(expectedAddress));
}};
}
@Test
public void testReceiveThingEventAndExpectForwardToJMSProducer() throws JMSException {
final String expectedAddress = "target";
final Target target = ConnectivityModelFactory.newTarget(expectedAddress, Authorization.AUTHORIZATION_CONTEXT,
null, null, Topic.TWIN_EVENTS);
new TestKit(actorSystem) {{
final Props props = AmqpClientActor.propsForTests(connection, connectionStatus, getRef(),
(ac, el) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
expectMsg(CONNECTED_SUCCESS);
sendThingEventAndExpectPublish(amqpClientActor, target, AmqpClientActorTest.this.mockProducer);
}};
}
@Test
public void testSpecialCharactersInSourceAndRequestMetrics() throws JMSException {
new TestKit(actorSystem) {
{
final String sourceWithSpecialCharacters =
IntStream.range(32, 255).mapToObj(i -> (char) i)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
final String sourceWithUnicodeCharacters =
"\uD83D\uDE00\uD83D\uDE01\uD83D\uDE02\uD83D\uDE03\uD83D\uDE04" +
"\uD83D\uDE05\uD83D\uDE06\uD83D\uDE07\uD83D\uDE08\uD83D\uDE09\uD83D\uDE0A\uD83D\uDE0B\uD83D\uDE0C" +
"\uD83D\uDE0D\uD83D\uDE0E\uD83D\uDE0F";
final Source source = ConnectivityModelFactory.newSourceBuilder()
.authorizationContext(Authorization.AUTHORIZATION_CONTEXT)
.address(sourceWithSpecialCharacters)
.address(sourceWithUnicodeCharacters)
.build();
final String connectionId = createRandomConnectionId();
final Connection connectionWithSpecialCharacters =
TestConstants.createConnection(connectionId, singletonList(source));
testConsumeMessageAndExpectForwardToConciergeForwarder(connectionWithSpecialCharacters, 1, cmd -> {
// nothing to do here
}, ref -> {
ref.tell(RetrieveConnectionStatus.of(connectionId, DittoHeaders.empty()), getRef());
fishForMessage(duration("3s"), "fishing for OPEN status",
msg -> isExpectedMessage(msg, sourceWithSpecialCharacters, sourceWithUnicodeCharacters));
fishForMessage(duration("3s"), "fishing for OPEN status",
msg -> isExpectedMessage(msg, sourceWithSpecialCharacters, sourceWithUnicodeCharacters));
});
}
private boolean isExpectedMessage(final Object o, final String... expectedSources) {
if (!(o instanceof ResourceStatus)) {
return false;
}
final ResourceStatus resourceStatus = (ResourceStatus) o;
return resourceStatus.getResourceType() == ResourceStatus.ResourceType.SOURCE
&& Arrays.asList(expectedSources).contains(resourceStatus.getAddress().get())
&& ConnectivityStatus.OPEN.equals(resourceStatus.getStatus());
}
};
}
@Test
public void testRetrieveConnectionStatus() throws JMSException {
new TestKit(actorSystem) {{
final String sourceWithSpecialCharacters =
IntStream.range(32, 255).mapToObj(i -> (char) i)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
final String sourceWithUnicodeCharacters =
"\uD83D\uDE00\uD83D\uDE01\uD83D\uDE02\uD83D\uDE03\uD83D\uDE04" +
"\uD83D\uDE05\uD83D\uDE06\uD83D\uDE07\uD83D\uDE08\uD83D\uDE09\uD83D\uDE0A\uD83D\uDE0B\uD83D\uDE0C" +
"\uD83D\uDE0D\uD83D\uDE0E\uD83D\uDE0F";
final Source source = ConnectivityModelFactory.newSourceBuilder()
.authorizationContext(Authorization.AUTHORIZATION_CONTEXT)
.address(sourceWithSpecialCharacters)
.address(sourceWithUnicodeCharacters)
.build();
final String connectionId = createRandomConnectionId();
final Connection connectionWithSpecialCharacters =
TestConstants.createConnection(connectionId, singletonList(source));
testConsumeMessageAndExpectForwardToConciergeForwarder(connectionWithSpecialCharacters, 1, cmd -> {
// nothing to do here
}, ref -> ref.tell(RetrieveConnectionStatus.of(connectionId, DittoHeaders.empty()), getRef()));
}};
}
@Test
public void testTestConnection() {
new TestKit(actorSystem) {{
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus, getRef(),
(ac, el) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
amqpClientActor.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());
expectMsgClass(Status.Success.class);
}};
}
@Test
public void testTestConnectionFailsOnTimeout() throws JMSException {
new TestKit(actorSystem) {{
when(mockConnection.createSession(Session.CLIENT_ACKNOWLEDGE)).thenAnswer(
(Answer<Session>) invocationOnMock -> {
try {
Thread.sleep(15000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
return mockSession;
});
final Props props =
AmqpClientActor.propsForTests(connection, connectionStatus, getRef(),
(ac, el) -> mockConnection);
final ActorRef amqpClientActor = actorSystem.actorOf(props);
amqpClientActor.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());
expectMsgClass(java.time.Duration.ofSeconds(11), Status.Failure.class);
}};
}
private static Message mockMessage() throws JMSException {
final AmqpJmsTextMessageFacade amqpJmsTextMessageFacade = new AmqpJmsTextMessageFacade();
amqpJmsTextMessageFacade.setContentType(Symbol.getSymbol(DittoConstants.DITTO_PROTOCOL_CONTENT_TYPE));
amqpJmsTextMessageFacade.initialize(Mockito.mock(AmqpConnection.class));
final TextMessage jmsTextMessage = new JmsTextMessage(amqpJmsTextMessageFacade);
jmsTextMessage.setJMSCorrelationID("cid");
jmsTextMessage.setJMSReplyTo(new JmsQueue("reply"));
jmsTextMessage.setText(TestConstants.modifyThing());
return jmsTextMessage;
}
private static <T> T waitForLatchAndReturn(final CountDownLatch latch, final T result) {
try {
latch.await();
} catch (final InterruptedException e) {
e.printStackTrace();
}
return result;
}
@Override
protected Connection getConnection() {
return connection;
}
@Override
protected Props createClientActor(final ActorRef conciergeForwarder) {
return AmqpClientActor.propsForTests(connection, connectionStatus, conciergeForwarder, (ac, el) -> mockConnection);
}
@Override
protected ActorSystem getActorSystem() {
return actorSystem;
}
private void consumeMockMessage(final MessageConsumer mockConsumer) throws JMSException {
final ArgumentCaptor<MessageListener> listener = ArgumentCaptor.forClass(MessageListener.class);
verify(mockConsumer, timeout(1000).atLeast(1)).setMessageListener(listener.capture());
listener.getValue().onMessage(mockMessage());
}
private void sendThingEventAndExpectPublish(final ActorRef amqpClientActor, final Target target,
final MessageProducer mockProducer) throws JMSException {
final String uuid = UUID.randomUUID().toString();
final ThingModifiedEvent thingModifiedEvent = TestConstants.thingModified(singletonList(""),
Attributes.newBuilder().set("uuid", uuid).build());
final OutboundSignal outboundSignal =
OutboundSignalFactory.newOutboundSignal(thingModifiedEvent, singletonList(target));
amqpClientActor.tell(outboundSignal, ActorRef.noSender());
final ArgumentCaptor<JmsMessage> messageCaptor = ArgumentCaptor.forClass(JmsMessage.class);
verify(mockProducer, timeout(2000).times(1)).send(messageCaptor.capture(), any(CompletionListener.class));
final Message message = messageCaptor.getValue();
assertThat(message).isNotNull();
assertThat(message.getJMSDestination()).isEqualTo(new JmsQueue(target.getAddress()));
assertThat(message.getBody(String.class)).contains(uuid);
assertThat(message.getBody(String.class)).contains(
TestConstants.Things.NAMESPACE + "/" + TestConstants.Things.ID + "/" +
TopicPath.Group.THINGS.getName() + "/" + TopicPath.Channel.TWIN.getName() + "/" +
TopicPath.Criterion.EVENTS.getName() + "/" + TopicPath.Action.MODIFIED.getName());
}
}