public void TestReplyRetry()
        {
            adapter.DefaultListenerMethod = "Handle";
            adapter.Instance      = simpleService;
            adapter.RetryTemplate = new PollyRetryTemplate(new Dictionary <Type, bool>(), 2, true, 1, 1, 1);
            var replyMessage = new AtomicReference <IMessage>();
            var replyAddress = new AtomicReference <Address>();
            var throwable    = new AtomicReference <Exception>();

            adapter.RecoveryCallback = new TestRecoveryCallback(replyMessage, replyAddress, throwable);

            var accessor = RabbitHeaderAccessor.GetMutableAccessor(messageProperties);

            accessor.ReplyTo = "foo/bar";
            var ex          = new Exception();
            var mockChannel = new Mock <IModel>();

            mockChannel.Setup(c => c.BasicPublish("foo", "bar", false, It.IsAny <IBasicProperties>(), It.IsAny <byte[]>()))
            .Throws(ex);
            mockChannel.Setup(c => c.CreateBasicProperties()).Returns(new MockRabbitBasicProperties());
            var bytes   = EncodingUtils.GetDefaultEncoding().GetBytes("foo");
            var message = Message.Create(bytes, messageProperties);

            adapter.OnMessage(message, mockChannel.Object);
            Assert.Equal("Handle", simpleService.Called);
            Assert.NotNull(replyMessage.Value);
            var reply = EncodingUtils.GetDefaultEncoding().GetString((byte[])replyMessage.Value.Payload);

            Assert.NotNull(replyAddress.Value);
            var addr = replyAddress.Value;

            Assert.Equal("foo", addr.ExchangeName);
            Assert.Equal("bar", addr.RoutingKey);
            Assert.Same(ex, throwable.Value);
        }
Esempio n. 2
0
        public void DontHangConsumerThread()
        {
            var mockConnectionFactory = new Mock <RC.IConnectionFactory>();
            var mockConnection        = new Mock <RC.IConnection>();
            var mockChannel           = new Mock <RC.IModel>();

            mockConnectionFactory.Setup((f) => f.CreateConnection(It.IsAny <string>())).Returns(mockConnection.Object);
            mockConnection.Setup((c) => c.IsOpen).Returns(true);
            mockConnection.Setup((c) => c.CreateModel()).Returns(mockChannel.Object);
            mockChannel.Setup((c) => c.IsOpen).Returns(true);
            mockChannel.Setup((c) => c.CreateBasicProperties()).Returns(new MockRabbitBasicProperties());

            var consumer = new AtomicReference <RC.IBasicConsumer>();

            mockChannel.Setup((c) => c.QueueDeclare(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >()))
            .Returns(new RC.QueueDeclareOk("foo", 0, 0));
            mockChannel.Setup((c) => c.BasicConsume(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >(), It.IsAny <RC.IBasicConsumer>()))
            .Callback <string, bool, string, bool, bool, IDictionary <string, object>, RC.IBasicConsumer>((arg1, arg2, arg3, arg4, arg5, arg6, arg7) => consumer.Value = arg7);
            var connectionFactory = new SingleConnectionFactory(mockConnectionFactory.Object);
            var template          = new RabbitTemplate(connectionFactory)
            {
                ReplyTimeout = 1
            };
            var payload = EncodingUtils.GetDefaultEncoding().GetBytes("Hello, world!");
            var input   = Message.Create(payload, new MessageHeaders());

            template.DoSendAndReceiveWithTemporary("foo", "bar", input, null, default);

            // used to hang here because of the SynchronousQueue and doSendAndReceive() already exited
            consumer.Value.HandleBasicDeliver("foo", 1ul, false, "foo", "bar", new MockRabbitBasicProperties(), new byte[0]);
        }
        public void TestMappedListenerMethod()
        {
            var map = new Dictionary <string, string>
            {
                { "foo", "Handle" },
                { "bar", "NotDefinedOnInterface" }
            };

            adapter.DefaultListenerMethod = "AnotherHandle";
            adapter.SetQueueOrTagToMethodName(map);
            adapter.Instance = simpleService;
            var bytes    = EncodingUtils.GetDefaultEncoding().GetBytes("foo");
            var message  = Message.Create(bytes, messageProperties);
            var accessor = RabbitHeaderAccessor.GetMutableAccessor(message);

            accessor.ConsumerQueue = "foo";
            accessor.ConsumerTag   = "bar";
            adapter.OnMessage(message, null);
            Assert.Equal("Handle", simpleService.Called);
            message  = Message.Create(bytes, messageProperties);
            accessor = RabbitHeaderAccessor.GetMutableAccessor(message);
            accessor.ConsumerQueue = "junk";
            adapter.OnMessage(message, null);
            Assert.Equal("NotDefinedOnInterface", simpleService.Called);
            message              = Message.Create(bytes, messageProperties);
            accessor             = RabbitHeaderAccessor.GetMutableAccessor(message);
            accessor.ConsumerTag = "junk";
            adapter.OnMessage(message, null);
            Assert.Equal("AnotherHandle", simpleService.Called);
        }
Esempio n. 4
0
 public void WithMessageBatch(List <IMessage <byte[]> > messageBatch)
 {
     BatchPayloads = new List <object>();
     foreach (var m in messageBatch)
     {
         BatchPayloads.Add(EncodingUtils.GetDefaultEncoding().GetString((byte[])m.Payload));
     }
 }
Esempio n. 5
0
        public void TestConvertBytes()
        {
            var template = new RabbitTemplate();
            var payload  = EncodingUtils.GetDefaultEncoding().GetBytes("Hello, world!");
            var message  = template.ConvertMessageIfNecessary(payload);

            Assert.Same(payload, message.Payload);
        }
Esempio n. 6
0
        public void TestConvertMessage()
        {
            var template = new RabbitTemplate();
            var payload  = EncodingUtils.GetDefaultEncoding().GetBytes("Hello, world!");
            var input    = Message.Create(payload, new MessageHeaders());
            var message  = template.ConvertMessageIfNecessary(input);

            Assert.Same(message, input);
        }
Esempio n. 7
0
        public void TestConvertString()
        {
            var template      = new RabbitTemplate();
            var payload       = "Hello, world!";
            var message       = template.ConvertMessageIfNecessary(payload);
            var messageString = EncodingUtils.GetDefaultEncoding().GetString((byte[])message.Payload);

            Assert.Equal(payload, messageString);
        }
        public void TestExplicitListenerMethod()
        {
            adapter.DefaultListenerMethod = "Handle";
            adapter.Instance = simpleService;
            var bytes = EncodingUtils.GetDefaultEncoding().GetBytes("foo");

            adapter.OnMessage(Message.Create(bytes, messageProperties), null);
            Assert.Equal("Handle", simpleService.Called);
        }
Esempio n. 9
0
        public void TestShutdownWhileWaitingForReply()
        {
            var mockConnectionFactory = new Mock <RC.IConnectionFactory>();
            var mockConnection        = new Mock <RC.IConnection>();
            var mockChannel1          = new Mock <RC.IModel>();

            mockChannel1.Setup((c) => c.IsOpen).Returns(true);
            mockConnection.Setup((c) => c.IsOpen).Returns(true);

            mockConnectionFactory.Setup((f) => f.CreateConnection(It.IsAny <string>())).Returns(mockConnection.Object);
            mockConnection.SetupSequence((c) => c.CreateModel()).Returns(mockChannel1.Object);

            mockChannel1.Setup((c) => c.CreateBasicProperties()).Returns(new MockRabbitBasicProperties());

            mockChannel1.Setup((c) => c.QueueDeclare(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >()))
            .Returns(() => new RC.QueueDeclareOk("foo", 0, 0));

            var listener      = new AtomicReference <EventHandler <RC.ShutdownEventArgs> >();
            var shutdownLatch = new CountdownEvent(1);

            mockChannel1.SetupAdd((m) => m.ModelShutdown += It.IsAny <EventHandler <RC.ShutdownEventArgs> >())
            .Callback <EventHandler <RC.ShutdownEventArgs> >((handler) =>
            {
                listener.Value = handler;
                shutdownLatch.Signal();
            });
            var connectionFactory = new SingleConnectionFactory(mockConnectionFactory.Object);
            var template          = new RabbitTemplate(connectionFactory)
            {
                ReplyTimeout = 60_000
            };
            var input = Message.Create(EncodingUtils.GetDefaultEncoding().GetBytes("Hello, world!"), new MessageHeaders());

            Task.Run(() =>
            {
                try
                {
                    shutdownLatch.Wait(TimeSpan.FromSeconds(10));
                }
                catch (Exception)
                {
                    // Ignore
                }

                listener.Value.Invoke(null, new RC.ShutdownEventArgs(RC.ShutdownInitiator.Peer, (ushort)RabbitUtils.NotFound, string.Empty));
            });
            try
            {
                template.DoSendAndReceiveWithTemporary("foo", "bar", input, null, default);
                throw new Exception("Expected exception");
            }
            catch (RabbitException e)
            {
                var cause = e.InnerException;
                Assert.IsType <ShutdownSignalException>(cause);
            }
        }
Esempio n. 10
0
        protected override Encoding DetectStreamEncoding(Stream stream)
        {
            Encoding ret = EncodingUtils.GetEncodingFromConfigXMLName(fmtInfo.Encoding);

            if (ret == null)
            {
                ret = EncodingUtils.DetectEncodingFromBOM(stream, EncodingUtils.GetDefaultEncoding());
            }
            return(ret);
        }
Esempio n. 11
0
        public void TestUninterruptibleListenerDMLC()
        {
            var cf    = new CachingConnectionFactory("localhost");
            var admin = new RabbitAdmin(cf);

            admin.DeclareQueue(new Config.Queue("test.shutdown"));

            var container = new DirectMessageListenerContainer(null, cf)
            {
                ShutdownTimeout = 500
            };

            container.SetQueueNames("test.shutdown");
            var latch     = new CountdownEvent(1);
            var testEnded = new CountdownEvent(1);
            var listener  = new TestListener(latch, testEnded);

            container.MessageListener = listener;
            var connection = cf.CreateConnection() as ChannelCachingConnectionProxy;

            // var channels = TestUtils.getPropertyValue(connection, "target.delegate._channelManager._channelMap");
            var field = typeof(RC.Framing.Impl.Connection)
                        .GetField("m_sessionManager", BindingFlags.Instance | BindingFlags.NonPublic);

            Assert.NotNull(field);
            var channels = (SessionManager)field.GetValue(connection.Target.Connection);

            Assert.NotNull(channels);

            container.Start();
            Assert.True(container._startedLatch.Wait(TimeSpan.FromSeconds(10)));

            try
            {
                var template = new RabbitTemplate(cf);
                template.Execute(c =>
                {
                    var properties = c.CreateBasicProperties();
                    var bytes      = EncodingUtils.GetDefaultEncoding().GetBytes("foo");
                    c.BasicPublish(string.Empty, "test.shutdown", false, properties, bytes);
                    RabbitUtils.SetPhysicalCloseRequired(c, false);
                });
                Assert.True(latch.Wait(TimeSpan.FromSeconds(30)));
                Assert.Equal(2, channels.Count);
            }
            finally
            {
                container.Stop();
                Assert.Equal(1, channels.Count);

                cf.Destroy();
                testEnded.Signal();
                admin.DeleteQueue("test.shutdown");
            }
        }
        public void TestAlternateConstructor()
        {
            var called = new AtomicBoolean(false);
            var dele   = new TestDelegate2(called);

            adapter = new MessageListenerAdapter(null, dele, "MyPojoMessageMethod");
            var bytes = EncodingUtils.GetDefaultEncoding().GetBytes("foo");

            adapter.OnMessage(Message.Create(bytes, messageProperties), null);
            Assert.True(called.Value);
        }
        public void TestDefaultListenerMethod()
        {
            var called = new AtomicBoolean(false);
            var dele   = new TestDelegate1(called);

            adapter.Instance = dele;
            var bytes = EncodingUtils.GetDefaultEncoding().GetBytes("foo");

            adapter.OnMessage(Message.Create(bytes, messageProperties), null);
            Assert.True(called.Value);
        }
Esempio n. 14
0
        public async Task TestReleaseConsumerRace()
        {
            var connectionFactory = new CachingConnectionFactory("localhost");
            var container         = new DirectReplyToMessageListenerContainer(null, connectionFactory);

            var latch = new CountdownEvent(1);

            container.MessageListener = new EmptyListener();
            var mockMessageListener = new MockChannelAwareMessageListener(container.MessageListener, latch);

            container.SetChannelAwareMessageListener(mockMessageListener);

            var foobytes = EncodingUtils.GetDefaultEncoding().GetBytes("foo");
            var barbytes = EncodingUtils.GetDefaultEncoding().GetBytes("bar");
            await container.Start();

            Assert.True(container._startedLatch.Wait(TimeSpan.FromSeconds(10)));

            var channel1 = container.GetChannelHolder();
            var props    = channel1.Channel.CreateBasicProperties();

            props.ReplyTo = Address.AMQ_RABBITMQ_REPLY_TO;
            RC.IModelExensions.BasicPublish(channel1.Channel, string.Empty, TEST_RELEASE_CONSUMER_Q, props, foobytes);
            var replyChannel = connectionFactory.CreateConnection().CreateChannel(false);
            var request      = replyChannel.BasicGet(TEST_RELEASE_CONSUMER_Q, true);
            var n            = 0;

            while (n++ < 100 && request == null)
            {
                Thread.Sleep(100);
                request = replyChannel.BasicGet(TEST_RELEASE_CONSUMER_Q, true);
            }

            Assert.NotNull(request);
            props = channel1.Channel.CreateBasicProperties();
            RC.IModelExensions.BasicPublish(replyChannel, string.Empty, request.BasicProperties.ReplyTo, props, barbytes);
            replyChannel.Close();
            Assert.True(latch.Wait(TimeSpan.FromSeconds(10)));

            var channel2 = container.GetChannelHolder();

            Assert.Same(channel1.Channel, channel2.Channel);
            container.ReleaseConsumerFor(channel1, false, null); // simulate race for future timeout/cancel and onMessage()
            var inUse = container._inUseConsumerChannels;

            Assert.Single(inUse);
            container.ReleaseConsumerFor(channel2, false, null);
            Assert.Empty(inUse);
            await container.Stop();

            connectionFactory.Destroy();
        }
        public void TestExtendedListenerAdapter()
        {
            var extendedAdapter = new ExtendedListenerAdapter(null);
            var called          = new AtomicBoolean(false);
            var channelMock     = new Mock <IModel>();
            var delgate         = new TestDelegate(called);

            extendedAdapter.Instance         = delgate;
            extendedAdapter.ContainerAckMode = Core.AcknowledgeMode.MANUAL;
            var bytes = EncodingUtils.GetDefaultEncoding().GetBytes("foo");

            extendedAdapter.OnMessage(Message.Create <byte[]>(bytes, messageProperties), channelMock.Object);
            Assert.True(called.Value);
        }
Esempio n. 16
0
        public void BuildMessageWithStandardMessage()
        {
            var result = RabbitMessageBuilder.WithPayload("Response")
                         .SetHeader("foo", "bar")
                         .SetHeader(RabbitMessageHeaders.TYPE, "msg_type")
                         .SetHeader(RabbitMessageHeaders.REPLY_TO, "reply")
                         .Build();
            var session      = new Mock <IModel>();
            var listener     = GetSimpleInstance("Echo", typeof(IMessage <string>));
            var replyMessage = listener.BuildMessage(session.Object, result, null);

            Assert.NotNull(replyMessage);
            Assert.Equal("Response", EncodingUtils.GetDefaultEncoding().GetString(replyMessage.Payload));
            Assert.Equal("msg_type", replyMessage.Headers.Type());
            Assert.Equal("reply", replyMessage.Headers.ReplyTo());
            Assert.Equal("bar", replyMessage.Headers.Get <string>("foo"));
        }
        public void TestTaskReturn()
        {
            var called = new CountdownEvent(1);
            var dele   = new TestAsyncDelegate();

            adapter = new MessageListenerAdapter(null, dele, "MyPojoMessageMethod")
            {
                ContainerAckMode = AcknowledgeMode.MANUAL,
                ResponseExchange = "default"
            };
            var mockChannel = new Mock <IModel>();

            mockChannel.Setup(c => c.CreateBasicProperties()).Returns(new MockRabbitBasicProperties());
            mockChannel.Setup(c => c.BasicAck(It.IsAny <ulong>(), false))
            .Callback(() => called.Signal());
            var bytes   = EncodingUtils.GetDefaultEncoding().GetBytes("foo");
            var message = Message.Create(bytes, messageProperties);

            adapter.OnMessage(message, mockChannel.Object);
            Assert.True(called.Wait(TimeSpan.FromSeconds(10)));
        }
Esempio n. 18
0
 public static byte[] ToBytes(string content)
 {
     return(EncodingUtils.GetDefaultEncoding().GetBytes(content));
 }
Esempio n. 19
0
 public static string ExtractText(IMessage message)
 {
     return(EncodingUtils.GetDefaultEncoding().GetString((byte[])message.Payload));
 }