コード例 #1
0
        public override IBytesMessage CreateBytesMessage(byte[] body)
        {
            IBytesMessage msg = CreateBytesMessage();

            msg.WriteBytes(body);
            return(msg);
        }
コード例 #2
0
ファイル: TestMessageSource.cs プロジェクト: megakid/Obvs
        public void ShouldDeserializeAndPublishMessageOfRightTypeName()
        {
            var consumer = A.Fake <IMessageConsumer>();

            A.CallTo(() => _session.CreateConsumer(_destination, null, false)).Returns(consumer);

            IBytesMessage bytesMessage = A.Fake <IBytesMessage>();
            ITestMessage  message      = A.Fake <ITestMessage>();

            const string serializedFixtureString = "<xml>Some fixture XML</xml>";
            var          bytes = Encoding.UTF8.GetBytes(serializedFixtureString);

            A.CallTo(() => bytesMessage.Content).Returns(bytes);
            A.CallTo(() => bytesMessage.Properties.Contains(MessagePropertyNames.TypeName)).Returns(true);
            A.CallTo(() => bytesMessage.Properties.GetString(MessagePropertyNames.TypeName)).Returns("SomeTypeName");
            A.CallTo(() => _deserializer.Deserialize(A <Stream> ._)).Returns(message);
            A.CallTo(() => _deserializer.GetTypeName()).Returns("SomeTypeName");

            _source = new MessageSource <ITestMessage>(_lazyConnection, new[] { _deserializer }, _destination,
                                                       _acknowledgementMode);

            _source.Messages.Subscribe(_observer);
            consumer.Listener += Raise.FreeForm.With((Apache.NMS.IMessage)bytesMessage);

            A.CallTo(() => _observer.OnNext(message)).MustHaveHappened();
        }
コード例 #3
0
 public void writeMessage(IBytesMessage msg, byte[] bytes)
 {
     msg.Properties.SetString("id", _id);
     msg.Properties.SetInt("index", _trivium.currentIndex());
     _trivium.run(bytes);
     msg.WriteBytes(bytes);
 }
コード例 #4
0
        public void ShouldProcessMessagesWithoutTypeNameIfOnlyOneDeserializerSupplied()
        {
            var consumer = A.Fake <IMessageConsumer>();

            A.CallTo(() => _session.CreateConsumer(_destination)).Returns(consumer);

            IBytesMessage bytesMessage = A.Fake <IBytesMessage>();
            ITestMessage  message      = A.Fake <ITestMessage>();

            const string serializedFixtureString = "<xml>Some fixture XML</xml>";
            var          bytes = Encoding.UTF8.GetBytes(serializedFixtureString);

            A.CallTo(() => bytesMessage.Content).Returns(bytes);
            A.CallTo(() => bytesMessage.Properties).Returns(new PrimitiveMap());
            A.CallTo(() => _deserializer.Deserialize(A <Stream> ._)).Returns(message);
            A.CallTo(() => _deserializer.GetTypeName()).Returns("");

            _source = new MessageSource <ITestMessage>(_lazyConnection, new[] { _deserializer }, _destination, _acknowledgementMode);

            _source.Messages.Subscribe(_observer);
            consumer.Listener += Raise.FreeForm.With((Apache.NMS.IMessage)bytesMessage);

            A.CallTo(() => _deserializer.Deserialize(A <Stream> ._)).MustHaveHappened();
            A.CallTo(() => _observer.OnNext(message)).MustHaveHappened();
        }
コード例 #5
0
ファイル: SievasController.cs プロジェクト: pxm321/PRISM
    private void onDataMessage(IMessage msg)
    {
        int bytesRead = 0;
        int zLev      = msg.Properties.GetInt("zLevReply");

        byte[] byteBuffer = new byte[1 << 3 * zLev];

        if (msg is IBytesMessage)
        {
            IBytesMessage bMsg = (IBytesMessage)msg;

            bytesRead = bMsg.ReadBytes(byteBuffer);

            print("We are receiving a DATA message of " + bytesRead + " bytes.");

            NextBrickData = byteBuffer; //This sets the byte buffer of the next brick up.
            NextBrick     = msg.Properties.GetInt("BrickNumReply");

            print("This is the nextBrick number: " + NextBrick);
        }



        ByteDataDict.Add(NextBrick, nextBrickData);
    }
コード例 #6
0
        public void TestTmpQueueWorksUnderLoad()
        {
            int count    = 500;
            int dataSize = 1024;

            ArrayList        list       = new ArrayList(count);
            Connection       connection = GetNewConnection();
            ISession         session    = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            IQueue           queue      = session.CreateTemporaryQueue();
            IMessageProducer producer   = session.CreateProducer(queue);

            producer.DeliveryMode = MsgDeliveryMode.NonPersistent;

            byte[] data = new byte[dataSize];
            for (int i = 0; i < count; i++)
            {
                IBytesMessage message = session.CreateBytesMessage();
                message.WriteBytes(data);
                message.Properties.SetInt("c", i);
                producer.Send(message);
                list.Add(message);
            }

            connection.Start();
            IMessageConsumer consumer = session.CreateConsumer(queue);

            for (int i = 0; i < count; i++)
            {
                IMessage message2 = consumer.Receive(TimeSpan.FromMilliseconds(2000));
                Assert.IsTrue(message2 != null);
                Assert.AreEqual(i, message2.Properties.GetInt("c"));
                Assert.IsTrue(message2.Equals(list[i]));
            }
        }
コード例 #7
0
        protected void sendTags()
        {
            try
            {
                IBytesMessage msg = _producer.CreateBytesMessage();
                //msg.Properties.SetBytes("aa", new byte[5]);
                MemoryStream stream     = new MemoryStream();
                GZipStream   gZipStream = new GZipStream(stream, CompressionMode.Compress);
                byte[]       bytes      = _tagsBuilder.Build().ToByteArray();
                gZipStream.Write(bytes, 0, bytes.Length);
                gZipStream.Close();
                byte[] compressedBytes = stream.ToArray();
                if (_shouldCrypto)
                {
                    _keyAgreement.writeMessage(msg, compressedBytes);
                }
                else
                {
                    msg.WriteBytes(compressedBytes);
                }

                this._producer.Send(msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);
                _lastDateTime = DateTime.Now;
                _tagsBuilder  = new XtiveTags.Builder();
            }

            catch (System.Exception e)
            {
                log.Error(e.Message);
            }
        }
コード例 #8
0
        public void MessageContentsHandlerOverloadCalls()
        {
            int           numIterations = 10;
            IBytesMessage bytesMessage  = A.Fake <IBytesMessage>();
            ASCIIEncoding encoding      = new ASCIIEncoding();

            byte[] content = encoding.GetBytes("test");
            A.CallTo(() => bytesMessage.Content).Returns(content).NumberOfTimes(numIterations / 2);

            ITextMessage textMessage = A.Fake <ITextMessage>();

            A.CallTo(() => textMessage.Text).Returns(TEXT).NumberOfTimes(numIterations / 2);

            MessageContentsHandler handler = new MessageContentsHandler();

            MessageListenerAdapter adapter = new MessageListenerAdapter(handler);

            for (int i = 0; i < numIterations / 2; i++)
            {
                adapter.OnMessage(textMessage);
                adapter.OnMessage(bytesMessage);
            }

            Assert.AreEqual(numIterations / 2, handler.HandledByteArrayCount);
            Assert.AreEqual(numIterations / 2, handler.HandledStringCount);
        }
コード例 #9
0
        public void ShouldProcessMessagesAccordingToFilter()
        {
            const string typeName = "SomeTypeName";

            var consumer = A.Fake <IMessageConsumer>();

            A.CallTo(() => _session.CreateConsumer(_destination)).Returns(consumer);

            IBytesMessage            bytesMessage = A.Fake <IBytesMessage>();
            ITestMessage             message      = A.Fake <ITestMessage>();
            Func <IDictionary, bool> filter       = properties => (int?)properties["Id"] == 123;

            const string serializedFixtureString = "<xml>Some fixture XML</xml>";
            var          bytes = Encoding.UTF8.GetBytes(serializedFixtureString);

            var messageProperties = new PrimitiveMap();

            messageProperties.SetString(MessagePropertyNames.TypeName, typeName);
            messageProperties.SetInt("Id", 123);

            A.CallTo(() => bytesMessage.Content).Returns(bytes);
            A.CallTo(() => bytesMessage.Properties).Returns(messageProperties);
            A.CallTo(() => _deserializer.Deserialize(A <Stream> ._)).Returns(message);
            A.CallTo(() => _deserializer.GetTypeName()).Returns(typeName);

            _source = new MessageSource <ITestMessage>(_lazyConnection, new[] { _deserializer }, _destination,
                                                       _acknowledgementMode, null, filter);

            _source.Messages.Subscribe(_observer);
            consumer.Listener += Raise.FreeForm.With((Apache.NMS.IMessage)bytesMessage);

            A.CallTo(() => _deserializer.Deserialize(A <Stream> ._)).MustHaveHappened();
            A.CallTo(() => _observer.OnNext(message)).MustHaveHappened();
        }
コード例 #10
0
ファイル: MessageProducer.cs プロジェクト: nyjin/Stomp.Net
        public void Send(IDestination destination, IBytesMessage message, MessageDeliveryMode deliveryMode, MessagePriority priority, TimeSpan timeToLive)
        {
            if (null == destination)
            {
                // See if this producer was created without a destination.
                if (null == _info.Destination)
                {
                    throw new NotSupportedException();
                }

                throw new InvalidDestinationException(
                          $"The producer was created with a destination, but an invalid destination was specified. => Destination: '{_info.Destination}'");
            }

            Destination dest;

            if (Equals(destination, _info.Destination))
            {
                dest = destination as Destination;
            }
            else if (_info.Destination == null)
            {
                dest = Destination.Transform(destination);
            }
            else
            {
                throw new NotSupportedException("This producer can only send messages to: " + _info.Destination.PhysicalName);
            }

            var stompMessage = _messageTransformation.TransformMessage <BytesMessage>(message);

            stompMessage.ProducerId        = _info.ProducerId;
            stompMessage.FromDestination   = dest;
            stompMessage.StompDeliveryMode = deliveryMode;
            stompMessage.StompPriority     = priority;

            // Always set the message Id regardless of the disable flag.
            var id = new MessageId(_info.ProducerId, Interlocked.Increment(ref _producerSequenceId));

            stompMessage.MessageId = id;

            if (!DisableMessageTimestamp)
            {
                stompMessage.StompTimestamp = DateTime.UtcNow;
            }

            if (timeToLive != TimeSpan.Zero)
            {
                stompMessage.StompTimeToLive = timeToLive;
            }

            lock ( _closedLock )
            {
                if (_closed)
                {
                    throw new ConnectionClosedException();
                }
                _session.DoSend(stompMessage, RequestTimeout);
            }
        }
コード例 #11
0
    public T TransformMessage <T>(IBytesMessage message)
    {
        if (message is T variable)
        {
            return(variable);
        }

        var msg = DoCreateBytesMessage();

        try
        {
            // ReSharper disable once PossibleNullReferenceException
            msg.Content = new Byte[message.Content.Length];
            Array.Copy(message.Content, msg.Content, message.Content.Length);
        }
        catch
        {
            // ignored
        }

        CopyProperties(message, msg);

        // Let the subclass have a chance to do any last minute configurations
        // on the newly converted message.
        DoPostProcessMessage(msg);

        return((T)msg);
    }
コード例 #12
0
        /// <summary> Create a NMS IBytesMessage for the given byte array.</summary>
        /// <param name="bytes">the byyte array to convert
        /// </param>
        /// <param name="session">current NMS session
        /// </param>
        /// <returns> the resulting message
        /// </returns>
        /// <throws>  NMSException if thrown by NMS methods </throws>
        protected virtual IBytesMessage CreateMessageForByteArray(byte[] bytes, ISession session)
        {
            IBytesMessage message = session.CreateBytesMessage();

            message.Content = bytes;
            return(message);
        }
コード例 #13
0
        public void MessageContentsHandlerOverloadCalls()
        {
            int           numIterations = 10;
            IBytesMessage bytesMessage  = mocks.StrictMock <IBytesMessage>();
            ASCIIEncoding encoding      = new ASCIIEncoding();

            byte[] content = encoding.GetBytes("test");
            Expect.Call(bytesMessage.Content).Return(content).Repeat.Times(numIterations / 2);

            ITextMessage textMessage = mocks.StrictMock <ITextMessage>();

            Expect.Call(textMessage.Text).Return(TEXT).Repeat.Times(numIterations / 2);

            MessageContentsHandler handler = new MessageContentsHandler();

            mocks.ReplayAll();

            MessageListenerAdapter adapter = new MessageListenerAdapter(handler);

            for (int i = 0; i < numIterations / 2; i++)
            {
                adapter.OnMessage(textMessage);
                adapter.OnMessage(bytesMessage);
            }
            Assert.AreEqual(numIterations / 2, handler.HandledByteArrayCount);
            Assert.AreEqual(numIterations / 2, handler.HandledStringCount);

            mocks.VerifyAll();
        }
コード例 #14
0
            public void SendMessage(object obj)
            {
                if (obj == null)
                {
                    return;
                }
                object sobj = _serialization.Serialize(obj);

                if (sobj is byte[])
                {
                    byte[] bytes = (byte[])sobj;
                    if (bytes == null || bytes.Length == 0)
                    {
                        return;
                    }
                    IBytesMessage message = _service.session.CreateBytesMessage();
                    message.WriteBytes(bytes);
                    _producer.Send(message);
                }
                else if (sobj is string)
                {
                    string       str = (string)sobj;
                    ITextMessage txt = _service.session.CreateTextMessage();
                    _producer.Send(txt);
                }
                else
                {
                    throw new Exception("obj is undefined type!");
                }
            }
コード例 #15
0
        protected void AssertMessageIsReadOnly(IMessage message)
        {
            IBytesMessage theMessage = message as IBytesMessage;

            Assert.IsNotNull(theMessage);
            try
            {
                theMessage.WriteBoolean(true);
                theMessage.WriteByte((byte)1);
                theMessage.WriteBytes(new byte[1]);
                theMessage.WriteBytes(new byte[3], 0, 2);
                theMessage.WriteChar('a');
                theMessage.WriteDouble(1.5);
                theMessage.WriteSingle((float)1.5);
                theMessage.WriteInt32(1);
                theMessage.WriteInt64(1);
                theMessage.WriteObject("stringobj");
                theMessage.WriteInt16((short)1);
                theMessage.WriteString("utfstring");
                Assert.Fail("Message should not have been Writable");
            }
            catch (MessageNotWriteableException)
            {
            }
        }
コード例 #16
0
 private void Consumer_Listener1(IMessage message)
 {
     //if (message is ITextMessage)
     //{
     //    string str = ((ITextMessage)message).Text;
     //    object obj = getSerializationInstance(senderTopic).Deserialize<object>(str);
     //    objRecListener.OnMessage(obj);
     //}
     if (message is IBytesMessage)
     {
         IBytesMessage bms    = (IBytesMessage)message;
         int           length = (int)bms.BodyLength;
         if (length == 0)
         {
             // log error
             return;
         }
         byte[] bytes = new byte[length];
         bms.ReadBytes(bytes);
         object obj = getSerializationInstance(receiveQueue).Deserialize(bytes);
         if (obj == null)
         {
             return;
         }
         objRecListener.OnMessage(obj);
     }
     else
     {
         // log error
     }
 }
コード例 #17
0
        private static void OnMessageReceived(IMessage message)
        {
            try
            {
                OpenRailBytesMessage oMessage = null;
                IBytesMessage        msgBytes = message as IBytesMessage;
                if (msgBytes != null)
                {
                    oMessage = new OpenRailBytesMessage(message.NMSTimestamp, msgBytes.Content);
                }

                if (oMessage != null)
                {
                    miMessageCount++;
                    if ((miMessageCount % 25) == 0)
                    {
                        Pport  oPPort       = DarwinMessageHelper.GetMessageAsObjects(oMessage.Bytes);
                        string sMessageType = DarwinMessageHelper.GetMessageDescription(oPPort);
                        Console.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + ": Total Messages Received = " + miMessageCount.ToString() + ": Last Message = " + sMessageType);
                    }
                }
            }
            catch (Exception oException)
            {
                Console.WriteLine("MESSAGE ERROR:  " + oException.GetType().FullName);
                Console.WriteLine(oException.Message);
            }
        }
コード例 #18
0
 // 消息监听
 void consumer_Listener(IMessage message)
 {
     if (message is ITextMessage)
     {
         ITextMessage mqMessage = message as ITextMessage;
         if (mqMessage != null && _onMessageHandle != null)
         {
             _onMessageHandle.BeginInvoke(mqMessage.Text, null, null);
         }
     }
     else if (message is IBytesMessage)
     {
         IBytesMessage mqMessage = message as IBytesMessage;
         if (mqMessage != null && _onMessageHandle != null)
         {
             byte[]        byteContent = new byte[1024];
             int           length      = -1;
             StringBuilder content     = new StringBuilder();
             while ((length = mqMessage.ReadBytes(byteContent)) != -1)
             {
                 content.Append(Encoding.UTF8.GetString(byteContent, 0, length));
             }
             _onMessageHandle.BeginInvoke(content.ToString(), null, null);
         }
     }
 }
コード例 #19
0
ファイル: MessageProducer.cs プロジェクト: pl89/nms-amqp
        public IBytesMessage CreateBytesMessage(byte[] body)
        {
            this.ThrowIfClosed();
            IBytesMessage msg = CreateBytesMessage();

            msg.WriteBytes(body);
            return(msg);
        }
コード例 #20
0
        /// <summary>
        /// Assert that two messages are IBytesMessages and their contents are equal.
        /// </summary>
        /// <param name="expected"></param>
        /// <param name="actual"></param>
        protected void AssertBytesMessageEqual(IMessage expected, IMessage actual)
        {
            IBytesMessage expectedBytesMsg = expected as IBytesMessage;

            Assert.IsNotNull(expectedBytesMsg, "'expected' message not a bytes message");
            IBytesMessage actualBytesMsg = actual as IBytesMessage;

            Assert.IsNotNull(actualBytesMsg, "'actual' message not a bytes message");
            Assert.AreEqual(expectedBytesMsg.Content, actualBytesMsg.Content, "Bytes message contents do not match.");
        }
コード例 #21
0
        public void TestBytesMessageCompression()
        {
            using (Connection connection = CreateConnection(TEST_CLIENT_ID) as Connection)
            {
                connection.UseCompression = true;
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = session.CreateTemporaryQueue();
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        using (IMessageProducer producer = session.CreateProducer(destination))
                        {
                            IBytesMessage message = session.CreateBytesMessage();

                            message.WriteBoolean(a);
                            message.WriteByte(b);
                            message.WriteChar(c);
                            message.WriteInt16(d);
                            message.WriteInt32(e);
                            message.WriteInt64(f);
                            message.WriteString(g);
                            message.WriteBoolean(h);
                            message.WriteByte(i);
                            message.WriteInt16(j);
                            message.WriteInt32(k);
                            message.WriteInt64(l);
                            message.WriteSingle(m);
                            message.WriteDouble(n);

                            producer.Send(message);

                            message = consumer.Receive(receiveTimeout) as IBytesMessage;

                            Assert.IsNotNull(message);
                            Assert.IsTrue(((ActiveMQMessage)message).Compressed);

                            Assert.AreEqual(a, message.ReadBoolean(), "Stream Boolean Value: a");
                            Assert.AreEqual(b, message.ReadByte(), "Stream Byte Value: b");
                            Assert.AreEqual(c, message.ReadChar(), "Stream Char Value: c");
                            Assert.AreEqual(d, message.ReadInt16(), "Stream Int16 Value: d");
                            Assert.AreEqual(e, message.ReadInt32(), "Stream Int32 Value: e");
                            Assert.AreEqual(f, message.ReadInt64(), "Stream Int64 Value: f");
                            Assert.AreEqual(g, message.ReadString(), "Stream String Value: g");
                            Assert.AreEqual(h, message.ReadBoolean(), "Stream Boolean Value: h");
                            Assert.AreEqual(i, message.ReadByte(), "Stream Byte Value: i");
                            Assert.AreEqual(j, message.ReadInt16(), "Stream Int16 Value: j");
                            Assert.AreEqual(k, message.ReadInt32(), "Stream Int32 Value: k");
                            Assert.AreEqual(l, message.ReadInt64(), "Stream Int64 Value: l");
                            Assert.AreEqual(m, message.ReadSingle(), "Stream Single Value: m");
                            Assert.AreEqual(n, message.ReadDouble(), "Stream Double Value: n");
                        }
                }
            }
        }
コード例 #22
0
        /// <summary>
        /// Method to handle messages sent to the receiece destination through ActiveMQ
        /// </summary>
        /// <param name="receivedMsg"></param>
        private void OnMessage(IMessage receivedMsg)
        {
            IBytesMessage message       = receivedMsg as IBytesMessage;
            string        messageString = System.Text.Encoding.UTF8.GetString(message.Content);

            if (PsiMQJson.isValid(messageString))
            {
                PsiMQJson obj = PsiMQJson.FromJson(messageString);
                this.Out.Post(obj.Content, obj.DateTime);
            }
        }
コード例 #23
0
        protected override void AssertValidMessage(IMessage message)
        {
            Assert.IsTrue(message is IBytesMessage, "Did not receive a IBytesMessage: " + message);

            Console.WriteLine("Received IBytesMessage: " + message);

            IBytesMessage bytesMessage = (IBytesMessage)message;

            byte[] actual = bytesMessage.Content;
            Console.WriteLine("Received message with content: " + actual);
            Assert.AreEqual(expected, actual, "the message content");
        }
コード例 #24
0
        public static void Listen()
        {
            IDatabaseConnector dbConnector = new PgSqlDatabaseConnector();
            Uri connecturi = new Uri("activemq:tcp://es.giorgos.io:61616");

            Console.WriteLine("About to connect to " + connecturi);

            // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder.
            //IConnectionFactory factory = new NMSConnectionFactory(connecturi);
            IConnectionFactory factory = new Apache.NMS.ActiveMQ.ConnectionFactory(connecturi);

            using (IConnection connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    //ActiveMQQueue topic = new ActiveMQQueue("Consumer.ERIC.VirtualTopic.ESDATA");
                    ActiveMQTopic topic = new ActiveMQTopic("VirtualTopic/ESDATA");

                    Console.WriteLine("Using destination: " + topic);

                    using (IMessageConsumer consumer = session.CreateConsumer(topic))
                    {
                        connection.Start();

                        consumer.Listener += new MessageListener(OnMessage);

                        while (true)
                        {
                            semaphore.WaitOne((int)receiveTimeout.TotalMilliseconds, true);

                            if (message == null)
                            {
                                Console.WriteLine("No message received!");
                            }
                            else
                            {
                                IBytesMessage bmsg = message as IBytesMessage;
                                Console.WriteLine("Received message with ID:   " + bmsg.NMSMessageId);
                                var jsonString = System.Text.Encoding.UTF8.GetString(bmsg.Content);
                                AggregatedSamplingData data = JsonConvert.DeserializeObject <AggregatedSamplingData>(jsonString);
                                foreach (var sample in data.Samples)
                                {
                                    System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
                                    dtDateTime = dtDateTime.AddSeconds(sample.Timestamp).ToUniversalTime();
                                    dbConnector.InsertDeviceData(sample.MeanAngleZ, sample.StdAcc, dtDateTime);
                                }
                                //Console.WriteLine("Received message with text: " + System.Text.Encoding.UTF8.GetString(bmsg.Content));
                            }
                        }
                    }
                }
        }
コード例 #25
0
        private void SendMessage()
        {
            //创建临时目的地,它们的存在时间只限于创建它们的连接所保持的时间
            //只有创建该临时目的地的连接上的消息消费者才能够从临时目的地中提取消息
            //ITemporaryQueue queue = m_session.CreateTemporaryQueue();

            IQueue queue = m_session.GetQueue("test_Queue");

            m_producer = m_session.CreateProducer(queue);



            //TextMessage消息类型,  普通文本消息
            ITextMessage textMessage = m_producer.CreateTextMessage();

            textMessage.Text = this.txtBox_消息.Text;

            //MapMessafe消息类型,   Map集合消息
            IMapMessage mapMessage = m_producer.CreateMapMessage();

            m_producer.Send(mapMessage);

            //ObjectMessage消息类型, 发送序列化对象
            Queue <string> obj = new Queue <string>();

            obj.Enqueue("one");
            obj.Enqueue("two");
            IObjectMessage objectMessage = m_producer.CreateObjectMessage(obj);

            m_producer.Send(objectMessage);

            //BytesMessage消息类型, 发送字节消息
            IBytesMessage bytesMessage = m_producer.CreateBytesMessage();

            bytesMessage.WriteBytes(System.Text.Encoding.Default.GetBytes("字节"));
            m_producer.Send(bytesMessage);

            //其它消息类型大同小异

            //设置是否持久化
            //m_producer.DeliveryMode= MsgDeliveryMode.Persistent;

            //设置优先级 默认 MsgPriority.BelowNormal 4级
            //m_producer.Priority = MsgPriority.BelowNormal;

            //设置过期时间,5秒后 只有Queue点对点有效
            //m_producer.TimeToLive=new TimeSpan(1000*5);

            //发送超时时间,默认等于0,如果设置超时,则所有的消息都是用同步发送
            //m_producer.RequestTimeout = new TimeSpan(1000*20);
        }
コード例 #26
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="msgList"></param>
        public static void SendQueueMessage(List <byte[]> msgList, Action <Exception> exceptionHandler = null)
        {
            if (msgList == null || msgList.Count == 0)
            {
                return;
            }

            try
            {
                using (var connection = factory.CreateConnection())
                {
                    //超时16s
                    connection.RequestTimeout = new TimeSpan(0, 0, 16);
                    //start应该放在这
                    connection.Start();
                    using (var session = connection.CreateSession())
                    {
                        using (
                            var producer =
                                session.CreateProducer(session.GetDestination(
                                                           destQueueName, //queue的名称
                                                           DestinationType.Queue)))
                        {
                            foreach (byte[] msg in msgList)
                            {
                                //start不能放在这
                                //connection.Start();
                                IBytesMessage message = session.CreateBytesMessage(msg);
                                ////The timestamp of when the message was pubished in UTC time. If the publisher disables setting the timestamp on the message, the time will be set to the start of the UNIX epoc (1970-01-01 00:00:00).
                                //message.NMSTimestamp = DateTime.UtcNow;
                                ////The amount of time for which this message is valid.
                                //message.NMSTimeToLive = TimeSpan.FromHours(2);
                                ////是否持久消息
                                //message.NMSDeliveryMode = MsgDeliveryMode.Persistent;
                                //producer.Send(message);

                                producer.Send(message, MsgDeliveryMode.Persistent, MsgPriority.Normal, TimeSpan.FromHours(2));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (exceptionHandler != null)
                {
                    exceptionHandler(ex);
                }
            }
        }
コード例 #27
0
        private static byte[] ParseData(IMessage message)
        {
            IBytesMessage bytesMsg = message as IBytesMessage;

            if (bytesMsg == null)
            {
                return(null);
            }

            Trace.TraceInformation("[{0}] - Recd Msg for {1}",
                                   bytesMsg.NMSDestination,
                                   bytesMsg.NMSTimestamp);

            return(bytesMsg.Content);
        }
コード例 #28
0
        public void ByteArrayConversion()
        {
            IBytesMessage message  = A.Fake <IBytesMessage>();
            ASCIIEncoding encoding = new ASCIIEncoding();

            byte[] content = encoding.GetBytes("test");

            A.CallTo(() => session.CreateBytesMessage()).Returns(message);
            A.CallTo(() => message.Content).Returns(content).Once();

            IMessage msg = converter.ToMessage(content, session);

            Assert.AreEqual(content.Length, ((byte[])converter.FromMessage(msg)).Length);
            A.CallTo(() => message.Content).WithAnyArguments().MustHaveHappened();
        }
コード例 #29
0
        public void ShouldDeserializeByteMessagesAndPublishMessageWhenReceived()
        {
            Mock <IMessageConsumer> mockConsumer = MockConsumerExtensions.Create(_session, _destination);
            IBytesMessage           bytesMessage = A.Fake <IBytesMessage>();
            ITestMessage            message      = A.Fake <ITestMessage>();

            byte[] bytes = new byte[0];
            A.CallTo(() => bytesMessage.Content).Returns(bytes);
            A.CallTo(() => _deserializer.Deserialize(bytes)).Returns(message);

            _source.Messages.Subscribe(_observer);
            mockConsumer.RaiseFakeMessage(bytesMessage);

            A.CallTo(() => _observer.OnNext(message)).MustHaveHappened();
        }
コード例 #30
0
        public void SendReceiveForeignBytesMessageTest(
            [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
            MsgDeliveryMode deliveryMode)
        {
            using (IConnection connection = CreateConnection())
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = CreateDestination(session, DestinationType.Topic);
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        using (IMessageProducer producer = session.CreateProducer(destination))
                        {
                            try
                            {
                                producer.DeliveryMode = deliveryMode;
                                BytesMessage request = new BytesMessage();
                                request.Properties[propertyName] = propertyValue;
                                request.WriteBytes(bytesContent);

                                producer.Send(request);

                                IBytesMessage message = consumer.Receive(receiveTimeout) as IBytesMessage;
                                Assert.IsNotNull(message, "No message returned!");
                                Assert.AreEqual(request.Properties.Count, message.Properties.Count,
                                                "Invalid number of properties.");
                                Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match");

                                // Check the body
                                byte[] content = new byte[bytesContent.Length];
                                Assert.AreEqual(bytesContent.Length, message.ReadBytes(content));
                                Assert.AreEqual(bytesContent, content, "BytesMessage body was wrong.");

                                // use generic API to access entries
                                Assert.AreEqual(propertyValue, message.Properties[propertyName],
                                                "generic map entry: " + propertyName);

                                // use type safe APIs
                                Assert.AreEqual(propertyValue, message.Properties.GetString(propertyName),
                                                "map entry: " + propertyName);
                            }
                            catch (NotSupportedException)
                            {
                            }
                        }
                }
            }
        }
コード例 #31
0
        public static void Convert(TransportMessage message, IBytesMessage toSend)
        {
            if (message.Body != null)
                toSend.WriteBytes(message.Body);

            // TODO: clarify usage of JMSCorrelationID
            
            if (message.CorrelationId != null)
                toSend.JMSCorrelationID = message.CorrelationId;
            if (message.ReplyToAddress != null)
                toSend.SetStringProperty(HEADER_RETURNADDRESS, message.ReplyToAddress.ToString());
            if (message.IdForCorrelation != null)
                toSend.SetStringProperty(HEADER_IDFORCORRELATION, message.IdForCorrelation ?? string.Empty);

            toSend.JMSDeliveryMode = message.Recoverable ? DeliveryMode.Persistent : DeliveryMode.NonPersistent;
            //toSend.SetStringProperty(HEADER_WINDOWSIDENTITYNAME, message.WindowsIdentityName);
            toSend.SetIntProperty(HEADER_MESSAGEINTENT, (int)message.MessageIntent);

            //TODO: set message expiration
            //toSend.JMSReplyTo = new Destination message.ReplyToAddress;
            //if (message.TimeToBeReceived < MessageQueue.InfiniteTimeout)
            //toSend.JMSExpiration = (long) UTCNow.message.TimeToBeReceived.TotalMilliseconds;
            //if (message.TimeToBeReceived < MessageQueue.InfiniteTimeout)
            //toSend.TimeToBeReceived = message.TimeToBeReceived;

            if (message.Headers == null)
                message.Headers = new Dictionary<string, string>();
            if (!message.Headers.ContainsKey("CorrId"))
                message.Headers.Add("CorrId", null);
            if (string.IsNullOrEmpty(message.Headers["CorrId"]))
                message.Headers["CorrId"] = message.IdForCorrelation ?? string.Empty;

            var nsbHeaderKeys = new List<string>();
            foreach (var keyValue in message.Headers)
            {
                toSend.SetStringProperty(keyValue.Key.ToXmsFriendly(), keyValue.Value);
                nsbHeaderKeys.Add(keyValue.Key.ToXmsFriendly());
            }
            toSend.SetStringProperty(HEADER_NBSKEYS, WrapKeys(nsbHeaderKeys));
        }
コード例 #32
0
        public static void Convert(TransportMessage message, IBytesMessage toSend, IMessageSerializer serializer)
        {
            byte[] body;
            if (message.Body == null && message.BodyStream != null)
            {
                body = message.BodyStream.ToBytes();
            }
            else
            {
                var stream = new MemoryStream();
                serializer.Serialize(message.Body, stream);
                body = stream.ToBytes();
            }

            toSend.WriteBytes(body);

            // TODO: clarify usage of JMSCorrelationID
            toSend.JMSCorrelationID = message.CorrelationId;
            toSend.JMSDeliveryMode = message.Recoverable ? DeliveryMode.Persistent : DeliveryMode.NonPersistent;
            toSend.SetStringProperty(HEADER_RETURNADDRESS, message.ReturnAddress);
            toSend.SetStringProperty(HEADER_IDFORCORRELATION, message.IdForCorrelation);
            toSend.SetStringProperty(HEADER_WINDOWSIDENTITYNAME, message.WindowsIdentityName);
            toSend.SetIntProperty(HEADER_MESSAGEINTENT, (int) message.MessageIntent);

            //TODO: set message expiration
            //toSend.JMSReplyTo = new Destination message.ReplyToAddress;
            //if (message.TimeToBeReceived < MessageQueue.InfiniteTimeout)
            //toSend.JMSExpiration = (long) UTCNow.message.TimeToBeReceived.TotalMilliseconds;

            if (message.Headers == null)
                message.Headers = new List<HeaderInfo>();

            var nsbHeaderKeys = new List<string>();
            foreach (var keyValue in message.Headers)
            {
                toSend.SetStringProperty(keyValue.Key.ToXmsFriendly(), keyValue.Value);
                nsbHeaderKeys.Add(keyValue.Key.ToXmsFriendly());
            }
            toSend.SetStringProperty(HEADER_NBSKEYS, WrapKeys(nsbHeaderKeys));
        }
コード例 #33
0
        public void SetUp()
        {
            A.Fake<IConnectionFactory>();
            _connection = A.Fake<IConnection>();
            _lazyConnection = new Lazy<IConnection>(() =>
            {
                _connection.Start();
                return _connection;
            });
            _session = A.Fake<ISession>();
            _producer = A.Fake<IMessageProducer>();
            _serializer = A.Fake<IMessageSerializer>();
            _destination = A.Fake<IDestination>();
            _message = A.Fake<IBytesMessage>();
            _messagePropertyProvider = A.Fake<IMessagePropertyProvider<IMessage>>();

            A.CallTo(() => _connection.CreateSession(A<Apache.NMS.AcknowledgementMode>.Ignored)).Returns(_session);
            A.CallTo(() => _session.CreateProducer(_destination)).Returns(_producer);
            A.CallTo(() => _producer.CreateBytesMessage()).Returns(_message);

            _publisher = new MessagePublisher<IMessage>(_lazyConnection, _destination, _serializer, _messagePropertyProvider, _testScheduler);
        }
コード例 #34
0
 public static void CopyIntProperty(this IBytesMessage to, string propertyName, IBytesMessage from)
 {
     var value = @from.GetIntProperty(propertyName);
     to.SetIntProperty(propertyName, value);
 }
コード例 #35
0
        /// <summary> Extract a byte array from the given IBytesMessage.</summary>
        /// <param name="message">the message to convert
        /// </param>
        /// <returns> the resulting byte array
        /// </returns>
        /// <throws>  NMSException if thrown by NMS methods </throws>
        protected virtual byte[] ExtractByteArrayFromMessage(IBytesMessage message)
        {
			return message.Content;
        }
コード例 #36
0
 private object DecodeIBytesMessage(IBytesMessage msg, JSONPROXY map)
 {
     int len = (int) msg.BodyLength;
     byte[] bytes = new byte[len];
     msg.ReadBytes(bytes, len);
     MemoryStream ins = new MemoryStream(bytes);
     Schema rs = SchemeFor(msg.ContentType, map);
     Schema ws = rs;
     if (rs != null)
     {
         var sdr = new DefaultReader(rs, ws);
         Avro.IO.Decoder dc = new Avro.IO.BinaryDecoder(ins);
         try
         {
             object actual = sdr.Read<object>(null, dc);
             Type t = actual.GetType();
             return actual;
         }
         catch (Exception e)
         {
             Console.Error.WriteLine(e);
             throw;
         }
         finally
         {
             ins.Close();
         }
     }
     else
     {
         Console.WriteLine("*** NO DECODER FOR msg.ContentType='{0}' FOUND ***", msg.ContentType);
         return null;
     }
 }
コード例 #37
0
        // TODO: test this
        public static void PopulateErrorQueueMessage(IBytesMessage toSend, IBM.XMS.IBytesMessage failed, XmsDestination xmsDestination)
        {
            var body = new byte[failed.BodyLength];
            if (body.Length > 0)
            {
                failed.ReadBytes(body, body.Length);
                toSend.WriteBytes(body);
            }
            toSend.JMSCorrelationID = failed.JMSCorrelationID;
            toSend.JMSDeliveryMode = failed.JMSDeliveryMode;
            toSend.CopyStringProperty(HEADER_RETURNADDRESS, failed);
            toSend.CopyStringProperty(HEADER_IDFORCORRELATION, failed);
            toSend.CopyStringProperty(HEADER_WINDOWSIDENTITYNAME, failed);
            toSend.CopyStringProperty(HEADER_MESSAGEINTENT, failed);

            var keys = failed.GetStringProperty(HEADER_NBSKEYS);
            var unwrapedKeys = UnwrapKeys(keys);
            foreach (var unwrapedKey in unwrapedKeys)
            {
                toSend.CopyStringProperty(unwrapedKey, failed);
            }

            toSend.CopyStringProperty(HEADER_NBSKEYS, failed);
            
            // error queue specific
            toSend.SetStringProperty(HEADER_FAILEDQUEUE, xmsDestination.ToString());
            var id = failed.GetStringProperty(HEADER_ORIGINALID);
            toSend.SetStringProperty(HEADER_ORIGINALID, id);
        }
コード例 #38
0
 public void writeMessage(IBytesMessage msg, byte[] bytes)
 {
     msg.Properties.SetString("id", _id);
     msg.Properties.SetInt("index", _trivium.currentIndex());
     _trivium.run(bytes);
     msg.WriteBytes(bytes);
 }