public MessageHandler(IMessageConsumer consumer, MessagingClient.EventDelegate callback)
        {
            this.consumer = consumer;
            this.callback = callback;

            AddListener();
        }
 /// <summary>
 /// Add a message consumer to monitor for messages received
 /// </summary>
 public void AddMessageConsumer(IMessageConsumer consumer)
 {
     consumer.Listener += (m) =>
     {
         _lastMsgRecd = DateTime.UtcNow;
     };
 }
Example #3
0
        public void Dispose()
        {
            lock (this)
            {
                this.isDisposed = true;
                this.consumer.Dispose();
                this.consumer = null;

                if (this.replyProducer != null)
                {
                    this.replyProducer.Dispose();
                    this.replyProducer = null;
                }

                this.requestReplyCallback = null;

                this.session.Dispose();
                this.session = null;

                this.connection.ConnectionInterrupted -= new EventHandler<NmsConnectionEventArgs>(connection_ConnectionInterrupted);
                this.connection.ConnectionResumed -= new EventHandler<NmsConnectionEventArgs>(connection_ConnectionResumed);

                this.connection = null;
            }
        }
Example #4
0
        public Queue(MsgDeliveryMode mode = MsgDeliveryMode.NonPersistent)
        {
            Uri msgQueue = new Uri("activemq:tcp://localhost:61616");

            _factory = new ConnectionFactory(msgQueue);
            try
            {
                _connection = _factory.CreateConnection();
            }
            catch (NMSConnectionException ex)
            {
                Log.FatalException("Error connecting to MQ server", ex);
                throw;
            }
            // TODO check _connection for null
            _connection.RequestTimeout = TimeSpan.FromSeconds(60);
            Session = _connection.CreateSession();

            // TODO need to find out if queue exists.
            // It creates a new queue if it doesn't exist.
            _destination = Session.GetDestination("queue://TwitterSearchStream");
            _consumer = Session.CreateConsumer(_destination);

            _producer = Session.CreateProducer(_destination);
            _producer.RequestTimeout = TimeSpan.FromSeconds(60);
            _producer.DeliveryMode = mode;

            _connection.Start();

            _connection.ExceptionListener += _connection_ExceptionListener;
            _connection.ConnectionInterruptedListener += _connection_ConnectionInterruptedListener;
        }
Example #5
0
        /// <summary>
        /// 消息消费构造器
        /// </summary>
        /// <param name="brokerUri">地址</param>
        /// <param name="username">用户名</param>
        /// <param name="psw">密码</param>
        /// <param name="clientId">客户端标识 兼做队列接收目的地</param>
        /// <param name="isClient">true 客户端;false 服务端</param>
        public OpenWireConsumer(string brokerUri, string username, string psw, string clientId,bool isClient)
        {
            NMSConnectionFactory _factory = new NMSConnectionFactory(brokerUri, clientId);
            _connection = _factory.CreateConnection(username, psw);
            _connection.Start();
            _session = _connection.CreateSession(AcknowledgementMode.AutoAcknowledge);

            if (isClient)
            {
                _qReceiveDest = _session.GetDestination(clientId, DestinationType.TemporaryQueue);
            }
            else
            {
                _qReceiveDest = _session.GetQueue(clientId);
            }

            _messageConsumer = _session.CreateConsumer(_qReceiveDest);
            _messageConsumer.Listener += (message) =>
            {
                if (Listener != null)
                {
                    Listener(message);
                }
            };
        }
Example #6
0
        private void btnSubscribe_Click(object sender, EventArgs e)
        {
            try
            {
                if (!GlobalFunction.CheckControlInput(txtTopicName, "Topic Name", 0, false)) return;

                if (m_consumer != null)
                {
                    m_consumer.Close();
                }
                if (txtSelector.Text != "")
                {
                    m_consumer = m_mq.CreateConsumer(rdTopic.Checked, txtTopicName.Text, txtSelector.Text);
                }
                else
                {
                    m_consumer = m_mq.CreateConsumer(rdTopic.Checked, txtTopicName.Text);
                }

                m_consumer.Listener += new MessageListener(consumer_listener);
            }
            catch (System.Exception ex)
            {
                GlobalFunction.MsgBoxException(ex.Message, "btnSubscribe_Click");
            }
        }
Example #7
0
 public void Subscribe(IMessageConsumer consumer)
 {
     if (_consumers.Contains(consumer))
     {
         return;
     }
     _consumers.Add(consumer);
 }
Example #8
0
        public NMSConsumer(IMessageConsumer consumer, String clientId, String subscriptionId)
        {
            this.consumer = consumer;
            this.clientId = clientId;
            this.subscriptionId = subscriptionId;

            consumer.Listener += onMessage;
        }
		override public void SetUp()
        {
            base.SetUp();
			acknowledgementMode = AcknowledgementMode.Transactional;
            Drain();
            consumer = Session.CreateConsumer(Destination);
            producer = Session.CreateProducer(Destination);
        }
Example #10
0
 public void Unsubscribe(IMessageConsumer consumer)
 {
     if (!_consumers.Contains(consumer))
     {
         return;
     }
     _consumers.Remove(consumer);
 }
Example #11
0
 public Consumer(IMessageConsumer messageConsumer, string clientId, string topicName)
 {
     _consumer = messageConsumer;
     _clientId = clientId;
     _topicName = topicName;
     _consumer.Listener += Update;
     _running = true;
     Delays = new List<TimeSpan>();
 }
Example #12
0
 public MessageTransporter()
 {
     _connectionFactory = new Apache.NMS.Stomp.ConnectionFactory("tcp://0.0.0.0:61613");
     _connection = _connectionFactory.CreateConnection();
     _session = _connection.CreateSession();
     _destination = SessionUtil.GetDestination(_session, "queue://testingQueue");
     _messageProducer = _session.CreateProducer(_destination);
     _messageConsumer = _session.CreateConsumer(_destination);
 }
Example #13
0
        public void RegisterImpl(IMessageConsumer impl, string serviceId)
        {
            var rule = MetaData.GetServiceRoutingRule(serviceId);
            if (rule == null)
            {
                throw new Exception();
            }

            implements[rule.GateRule.GetServiceId()] = impl;
        }
Example #14
0
        public void RegisterDelegate(IMessageConsumer consumer, string serviceId)
        {
            var rule = MetaData.GetServiceRoutingRule(serviceId);
            if (rule == null)
            {
                throw new Exception();
            }

            delegates[rule.GateRule.GetServiceId()] = consumer;
        }
 public IMessage FudgeDecodeMessage(ISession session, IMessageConsumer consumer, IMessage message)
 {
     try
     {
         return new ActiveMQObjectMessage { Body = DecodeObject(GetMessage(message)) };
     }
     catch (Exception e)
     {
         return new ActiveMQObjectMessage { Body = e };
     }
 }
Example #16
0
        public Master(IUserService service)
        {
            DownloadUsers = new DownloadUsers(service);

            Factory = new NMSConnectionFactory("tcp://localhost:61616");
            Connection = Factory.CreateConnection();
            Connection.Start();
            Session = Connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            Destination = SessionUtil.GetDestination(Session, "Users");
            Receiver = Session.CreateConsumer(Destination);
        }
 public DistributableCommandBus(ICommandHandlerProvider handlerProvider,
     ILinearCommandManager linearCommandManager,
     IMessageConsumer commandConsumer,
     string receiveEndPoint,
     bool inProc)
     : base(handlerProvider, linearCommandManager, receiveEndPoint, inProc)
 {
     _commandConsumer = commandConsumer as IInProcMessageConsumer;
     _commandDistributor = _commandConsumer;
     _isDistributor = _commandDistributor is IMessageDistributor;
 }
        public void Connect()
        {
            while (!ableToSendEvents) {
                Uri connecturi = null;
                //if (textBoxSIPIPAddress.Text.StartsWith("ssl://"))
                //{
                Console.WriteLine ("Trying to connect to ActiveMQ broker ");
                //	connecturi = new Uri("activemq:" + textBoxSIPIPAddress.Text + ":" + textBoxSIPPort.Text + "?transport.ClientCertSubject=E%[email protected], CN%3DCommunication Tool"); // Connect to the ActiveMQ broker
                //}
                //else
                //{
                //log4.Debug(name + ": Trying to connect to ActiveMQ broker via non-secure connection");
                connecturi = new Uri ("activemq:tcp://localhost:61616"); // Connect to the ActiveMQ broker
                //}
                //Console.WriteLine("activeMQ::About to connect to " + connecturi);

                try {

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

                    // Create a new connection and session for publishing events
                    activeMQConnection = factory.CreateConnection ();
                    activeMQSession = activeMQConnection.CreateSession ();

                    IDestination destination = SessionUtil.GetDestination (activeMQSession, "topic://SIFTEO");
                    //Console.WriteLine("activeMQ::Using destination: " + destination);

                    // Create the producer
                    activeMQProducer = activeMQSession.CreateProducer (destination);
                    activeMQProducer.DeliveryMode = MsgDeliveryMode.Persistent;
                    destination = SessionUtil.GetDestination (activeMQSession, "topic://XVR.CCC");
                    activeMQConsumer = activeMQSession.CreateConsumer (destination);
                    //activeMQConsumer.Listener += new MessageListener(OnCCCMessage);

                    // Start the connection so that messages will be processed
                    activeMQConnection.Start ();
                    //activeMQProducer.Persistent = true;

                    // Enable the sending of events
                    //log4.Debug(name + ": ActiveMQ connected on topics XVR.CCC and XVR.SDK");
                    ableToSendEvents = true;

                } catch (Exception exp) {
                    // Report the problem in the output.log (Program Files (x86)\E-Semble\XVR 2012\XVR 2012\XVR_Data\output_log.txt)
                    //Console.WriteLine("*** AN ACTIVE MQ ERROR OCCURED: " + exp.ToString() + " ***");
                    //log4.Error(name + ": Error connecting to ActiveMQ broker: " + exp.Message);
                    //log4.Error((exp.InnerException != null) ? exp.InnerException.StackTrace : "");

                    Console.WriteLine (exp.Message);
                }
                System.Threading.Thread.Sleep (1000);
            }
        }
        public void Start(Address address, TransactionSettings transactionSettings)
        {
            messageProcessor.Start(transactionSettings);

            defaultConsumer = messageProcessor.CreateMessageConsumer("queue://" + address.Queue);
            defaultConsumer.Listener += messageProcessor.ProcessMessage;

            if (address == Address.Local)
            {
                eventConsumer.Start();
            }
        }
Example #20
0
 public TopicSubscriber(string topicName, string brokerUri, string clientId, string consumerId)
 {
     this.topicName = topicName;
     this.connectionFactory = new ConnectionFactory(brokerUri);
     this.connection = this.connectionFactory.CreateConnection();
     this.connection.ClientId = clientId;
     this.connection.Start();
     this.session = connection.CreateSession();
     ActiveMQTopic topic = new ActiveMQTopic(topicName);
     this.consumer = this.session.CreateDurableConsumer(topic, consumerId, "2 > 1", false);
     this.consumer.Listener += new MessageListener(OnMessage);
 }
Example #21
0
 private void Connect()
 {
     factory = XmsUtilities.CreateConnectionFactory(destination);
     connection = factory.CreateConnection();
     connection.ExceptionListener += OnError;
     session = connection.CreateSession(transactional, AcknowledgeMode.AutoAcknowledge);
     queue = session.CreateQueue(destination.Queue);
     queue.SetIntProperty(XMSC.DELIVERY_MODE,
                          transactional ? XMSC.DELIVERY_PERSISTENT : XMSC.DELIVERY_NOT_PERSISTENT);
     consumer = session.CreateConsumer(queue);
     connection.Start();
 }
 public MessageSubscriber(IAdvancedBus bus,
     IMessageConsumer messageConsumer, 
     ILogger logger, 
     IEnvironment environment,
     IExchange exchange,
     IQueue queue)
 {
     _messageConsumer = messageConsumer;
     _bus = bus;
     _logger = logger;
     _environment = environment;
     _exchange = exchange;
     _queue = queue;
 }
Example #23
0
 public void Start(string consumerId)
 {
     ConsumerId = consumerId;
     Consumer = session.CreateDurableConsumer(topic, consumerId, null, false);
     Consumer.Listener += (message =>
     {
         var textMessage = message as ITextMessage;
         if (textMessage == null) throw new InvalidCastException();
         if (OnMessageReceived != null)
         {
             OnMessageReceived(textMessage.Text);
         }
     });
 }
Example #24
0
        static WebApiApplication()
        {
            try
            {
                Configuration.Instance.UseLog4Net()
                                      .RegisterMessageContextType(typeof(MessageContext));

                _Logger = IoCFactory.Resolve<ILoggerFactory>().Create(typeof(WebApiApplication));

                _CommandDistributor = new CommandDistributor("tcp://127.0.0.1:5000",
                                                                new string[] {
                                                                    "tcp://127.0.0.1:5001"
                                                                    , "tcp://127.0.0.1:5002"
                                                                    , "tcp://127.0.0.1:5003"
                                                                }
                                                               );

                Configuration.Instance.RegisterCommandConsumer(_CommandDistributor, "CommandDistributor")
                             .CommandHandlerProviderBuild(null, "CommandHandlers")
                             .RegisterDisposeModule()
                             .RegisterMvc();

                _EventPublisher = IoCFactory.Resolve<IEventPublisher>();
                _EventPublisher.Start();
                _DomainEventConsumer = IoCFactory.Resolve<IMessageConsumer>("DomainEventConsumer");
                _DomainEventConsumer.Start();
                _ApplicationEventConsumer = IoCFactory.Resolve<IMessageConsumer>("ApplicationEventConsumer");
                _ApplicationEventConsumer.Start();

                var commandHandlerProvider = IoCFactory.Resolve<ICommandHandlerProvider>();
                _CommandConsumer1 = new CommandConsumer(commandHandlerProvider,
                                                           "tcp://127.0.0.1:5001");
                _CommandConsumer2 = new CommandConsumer(commandHandlerProvider,
                                                           "tcp://127.0.0.1:5002");
                _CommandConsumer3 = new CommandConsumer(commandHandlerProvider,
                                                           "tcp://127.0.0.1:5003");

                _CommandConsumer1.Start();
                _CommandConsumer2.Start();
                _CommandConsumer3.Start();
                _CommandDistributor.Start();

                _CommandBus = IoCFactory.Resolve<ICommandBus>() as IMessageConsumer;
                _CommandBus.Start();
            }
            catch (Exception ex)
            {
                _Logger.Error(ex.GetBaseException().Message, ex);
            }
        }
        public ClientResultStream(OpenGammaFudgeContext fudgeContext, MQTemplate mqTemplate, bool checkSeqNumber)
        {
            _mqTemplate = mqTemplate;

            _fudgeMessageDecoder = new FudgeMessageDecoder(fudgeContext, checkSeqNumber);
            _connection = _mqTemplate.CreateConnection();
            _session = _connection.CreateSession();

            _destination = _session.CreateTemporaryQueue();

            _consumer = _session.CreateConsumer(_destination);
            _consumer.Listener += RawMessageReceived;
            _connection.Start();
        }
Example #26
0
        static WebApiApplication()
        {
            try
            {
                Configuration.Instance.UseLog4Net();
                _Logger = IoCFactory.Resolve<ILoggerFactory>().Create(typeof(WebApiApplication));

                Configuration.Instance
                             .CommandHandlerProviderBuild(null, "CommandHandlers")
                             .RegisterDisposeModule()
                             .RegisterMvc();

                #region EventPublisher init
                _MessagePublisher = IoCFactory.Resolve<IMessagePublisher>();
                _MessagePublisher.Start();
                #endregion

                #region event subscriber init
                _DomainEventConsumer = IoCFactory.Resolve<IMessageConsumer>("DomainEventSubscriber");
                _DomainEventConsumer.Start();
                #endregion

                #region application event subscriber init
                _ApplicationEventConsumer = IoCFactory.Resolve<IMessageConsumer>("ApplicationEventConsumer");
                _ApplicationEventConsumer.Start();
                #endregion

                #region CommandBus init
                _CommandBus = IoCFactory.Resolve<ICommandBus>();
                _CommandBus.Start();
                #endregion

                #region Command Consuemrs init
                var commandHandlerProvider = IoCFactory.Resolve<ICommandHandlerProvider>();
                _CommandConsumer1 = new CommandConsumer(commandHandlerProvider, _MessagePublisher, "commandqueue1");
                _CommandConsumer2 = new CommandConsumer(commandHandlerProvider, _MessagePublisher, "commandqueue2");
                _CommandConsumer3 = new CommandConsumer(commandHandlerProvider, _MessagePublisher, "commandqueue3");

                _CommandConsumer1.Start();
                _CommandConsumer2.Start();
                _CommandConsumer3.Start();
                #endregion

            }
            catch (Exception ex)
            {
                _Logger.Error(ex.GetBaseException().Message, ex);
            }
        }
Example #27
0
        public Stomp(bool durable)
        {
            _connectionFactory = new ConnectionFactory("tcp://localhost:61613");
            _connection = _connectionFactory.CreateConnection();
            _connection.ClientId = "13AC0CF8-65FE-4638-8B85-62210DD89BEE";
            _connection.Start();
            _session = _connection.CreateSession();

            var topic = _session.GetQueue("exampleQueue");

            _producer = _session.CreateProducer(topic);
            _producer.DeliveryMode = durable ? MsgDeliveryMode.Persistent : MsgDeliveryMode.NonPersistent;

            _consumer = _session.CreateConsumer(topic);
        }
Example #28
0
        public ActiveMq(bool durable)
        {
            _connectionFactory = new ConnectionFactory("tcp://localhost:61616");
            _connectionFactory.AsyncSend = true;
            _connectionFactory.ProducerWindowSize = int.MaxValue;
            _connection = _connectionFactory.CreateConnection();
            _connection.ClientId = "13AC0CF8-65FE-4638-8B85-62210DD89BEE";
            _connection.Start();
            _session = _connection.CreateSession();
            ActiveMQTopic topic = new ActiveMQTopic("topic");
            _consumer = _session.CreateDurableConsumer(topic, "durable", "2 > 1", false);

            _producer = _session.CreateProducer(topic);
            _producer.DeliveryMode = durable ? MsgDeliveryMode.Persistent : MsgDeliveryMode.NonPersistent;
        }
Example #29
0
        private void Disconnect()
        {
            log.Debug("Physical consumer about to be disconnected.");

            if (connection != null) connection.Stop();
            if (consumer != null) consumer.Dispose();
            if (queue != null) queue.Dispose();
            if (session != null) session.Dispose();
            if (connection != null) connection.Dispose();

            consumer = null;
            queue = null;
            session = null;
            connection = null;

            log.Debug("Physical consumer successfully disconnected.");
        }
 public void AddLocalInstanceSubscription(IMessageConsumer consumer)
 {
     localInstanceSubscriptions.Write(writer =>
     {
         foreach (var type in reflection.GetMessagesConsumed(consumer))
         {
             List<WeakReference> value;
             if (writer.TryGetValue(type.FullName, out value) == false)
             {
                 value = new List<WeakReference>();
                 writer.Add(type.FullName, value);
             }
             value.Add(new WeakReference(consumer));
         }
     });
     RaiseSubscriptionChanged();
 }
Example #31
0
        public void RunFilterIgnoredMessagesTest(string destinationName)
        {
            TimeSpan  ttl            = TimeSpan.FromMinutes(30);
            const int MaxNumRequests = 100000;

            using (IConnection connection1 = CreateConnection(GetTestClientId()))
                using (IConnection connection2 = CreateConnection(GetTestClientId()))
                    using (IConnection connection3 = CreateConnection(GetTestClientId()))
                    {
                        connection1.Start();
                        connection2.Start();
                        connection3.Start();
                        using (ISession session1 = connection1.CreateSession(AcknowledgementMode.AutoAcknowledge))
                            using (ISession session2 = connection2.CreateSession(AcknowledgementMode.AutoAcknowledge))
                                using (ISession session3 = connection3.CreateSession(AcknowledgementMode.AutoAcknowledge))
                                {
                                    IDestination destination1 = CreateDestination(session1, destinationName);
                                    IDestination destination2 = CreateDestination(session2, destinationName);
                                    IDestination destination3 = CreateDestination(session3, destinationName);

                                    using (IMessageProducer producer = session1.CreateProducer(destination1))
                                        using (IMessageConsumer consumer1 = session2.CreateConsumer(destination2, "JMSType NOT LIKE '%IGNORE'"))
                                        {
                                            int numNonIgnoredMsgsSent = 0;
                                            int numIgnoredMsgsSent    = 0;

                                            producer.DeliveryMode = MsgDeliveryMode.NonPersistent;

                                            receivedNonIgnoredMsgCount = 0;
                                            receivedIgnoredMsgCount    = 0;
                                            consumer1.Listener        += new MessageListener(OnNonIgnoredMessage);
                                            IMessageConsumer consumer2 = null;

                                            for (int index = 1; index <= MaxNumRequests; index++)
                                            {
                                                IMessage request = session1.CreateTextMessage(String.Format("Hello World! [{0} of {1}]", index, MaxNumRequests));

                                                request.NMSTimeToLive = ttl;
                                                if (0 == (index % 2))
                                                {
                                                    request.NMSType = "ACTIVE";
                                                    numNonIgnoredMsgsSent++;
                                                }
                                                else
                                                {
                                                    request.NMSType = "ACTIVE.IGNORE";
                                                    numIgnoredMsgsSent++;
                                                }

                                                producer.Send(request);

                                                if (2000 == index)
                                                {
                                                    // Start the second consumer
                                                    if (destination3.IsTopic)
                                                    {
                                                        // Reset the ignored message sent count, since all previous messages
                                                        // will not have been consumed on a topic.
                                                        numIgnoredMsgsSent = 0;
                                                    }

                                                    consumer2           = session3.CreateConsumer(destination3, "JMSType LIKE '%IGNORE'");
                                                    consumer2.Listener += new MessageListener(OnIgnoredMessage);
                                                }
                                            }

                                            // Create a waiting loop that will coordinate the end of the test.  It checks
                                            // to see that all intended messages were received.  It will continue to wait as
                                            // long as new messages are being received.  If it stops receiving messages before
                                            // it receives everything it expects, it will eventually timeout and the test will fail.
                                            int waitCount = 0;
                                            int lastReceivedINongnoredMsgCount = receivedNonIgnoredMsgCount;
                                            int lastReceivedIgnoredMsgCount    = receivedIgnoredMsgCount;

                                            while (receivedNonIgnoredMsgCount < numNonIgnoredMsgsSent ||
                                                   receivedIgnoredMsgCount < numIgnoredMsgsSent)
                                            {
                                                if (lastReceivedINongnoredMsgCount != receivedNonIgnoredMsgCount ||
                                                    lastReceivedIgnoredMsgCount != receivedIgnoredMsgCount)
                                                {
                                                    // Reset the wait count.
                                                    waitCount = 0;
                                                }
                                                else
                                                {
                                                    waitCount++;
                                                }

                                                lastReceivedINongnoredMsgCount = receivedNonIgnoredMsgCount;
                                                lastReceivedIgnoredMsgCount    = receivedIgnoredMsgCount;

                                                Assert.IsTrue(waitCount <= 30, String.Format("Timeout waiting for all messages to be delivered. Only {0} of {1} non-ignored messages delivered.  Only {2} of {3} ignored messages delivered.",
                                                                                             receivedNonIgnoredMsgCount, numNonIgnoredMsgsSent, receivedIgnoredMsgCount, numIgnoredMsgsSent));
                                                Thread.Sleep(1000);
                                            }

                                            consumer2.Dispose();
                                        }
                                }
                    }
        }
Example #32
0
        private static void ConsumerReceiveMessage()
        {
            m_consumer = activeMqConsumer.CreateConsumer(TopicType.Topic, "ActiveMq test", "Filter='test'");

            m_consumer.Listener += new MessageListener(activeMqConsumer.consumer_listener);
        }
Example #33
0
        public void TestDurableConsumerSelectorChange(AcknowledgementMode ackMode)
        {
            try
            {
                using (IConnection connection = CreateConnection(TEST_CLIENT_ID))
                {
                    connection.Start();
                    using (ISession session = connection.CreateSession(ackMode))
                    {
                        ITopic           topic    = session.GetTopic(DURABLE_TOPIC);
                        IMessageProducer producer = session.CreateProducer(topic);
                        IMessageConsumer consumer = session.CreateDurableConsumer(topic, CONSUMER_ID, "color='red'", false);

                        producer.DeliveryMode = MsgDeliveryMode.Persistent;

                        // Send the messages
                        ITextMessage sendMessage = session.CreateTextMessage("1st");
                        sendMessage.Properties["color"] = "red";
                        producer.Send(sendMessage);
                        if (AcknowledgementMode.Transactional == ackMode)
                        {
                            session.Commit();
                        }

                        ITextMessage receiveMsg = consumer.Receive(receiveTimeout) as ITextMessage;
                        Assert.IsNotNull(receiveMsg, "Failed to retrieve 1st durable message.");
                        Assert.AreEqual("1st", receiveMsg.Text);
                        Assert.AreEqual(MsgDeliveryMode.Persistent, receiveMsg.NMSDeliveryMode, "NMSDeliveryMode does not match");
                        receiveMsg.Acknowledge();
                        if (AcknowledgementMode.Transactional == ackMode)
                        {
                            session.Commit();
                        }

                        // Change the subscription.
                        consumer.Dispose();
                        consumer = session.CreateDurableConsumer(topic, CONSUMER_ID, "color='blue'", false);

                        sendMessage = session.CreateTextMessage("2nd");
                        sendMessage.Properties["color"] = "red";
                        producer.Send(sendMessage);
                        sendMessage = session.CreateTextMessage("3rd");
                        sendMessage.Properties["color"] = "blue";
                        producer.Send(sendMessage);
                        if (AcknowledgementMode.Transactional == ackMode)
                        {
                            session.Commit();
                        }

                        // Selector should skip the 2nd message.
                        receiveMsg = consumer.Receive(receiveTimeout) as ITextMessage;
                        Assert.IsNotNull(receiveMsg, "Failed to retrieve durable message.");
                        Assert.AreEqual("3rd", receiveMsg.Text, "Retrieved the wrong durable message.");
                        Assert.AreEqual(MsgDeliveryMode.Persistent, receiveMsg.NMSDeliveryMode, "NMSDeliveryMode does not match");
                        receiveMsg.Acknowledge();
                        if (AcknowledgementMode.Transactional == ackMode)
                        {
                            session.Commit();
                        }

                        // Make sure there are no pending messages.
                        Assert.IsNull(consumer.ReceiveNoWait(), "Wrong number of messages in durable subscription.");
                    }
                }
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
            finally
            {
                UnregisterDurableConsumer(TEST_CLIENT_ID, CONSUMER_ID);
            }
        }
Example #34
0
        public static void Main(string[] args)
        {
            // This ID is important since it will be also the queue a response will be sent.
            string queueId = Guid.NewGuid().ToString();
            // This message which should be send to the server
            string requestMessage = ""
                                    + "{"
                                    // the call ID; this will also be the queue a response will be sent. Be careful to make it unqiue
                                    + "    \"callId\": \"" + queueId + "\","
                                    // if the server should answer or not
                                    + "    \"answer\": true,"
                                    // of which type the sent data is; this have to be the required java types
                                    + "    \"classes\": ["
                                    + "        \"java.lang.String\","
                                    + "        \"org.openengsb.core.common.workflow.model.ProcessBag\""
                                    + "    ],"
                                    // the method which should be executed
                                    + "    \"methodName\": \"executeWorkflow\","
                                    // the "header-data" of the message; this is not the header of JMS to use eg stomp too
                                    + "    \"metaData\": {"
                                    // the ID of the internal service to be called
                                    + "        \"serviceId\": \"workflowService\","
                                    // the context in which the service should be called
                                    + "        \"contextId\": \"foo\""
                                    + "    },"
                                    // the arguments with which the workflowService method should be called
                                    + "    \"args\": ["
                                    // the name of the workflow to be executed
                                    + "        \"simpleFlow\","
                                    // the params which should be put into the prcoess bag initially
                                    + "        {"
                                    + "        }"
                                    + "    ]"
                                    + "}";

            // the OpenEngSB connection URL
            Uri connecturi = new Uri("activemq:tcp://localhost:6549");

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

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

            using (IConnection connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    IDestination destination = session.GetDestination("receive");
                    Console.WriteLine("Using destination for sending: " + destination);


                    using (IMessageProducer producer = session.CreateProducer(destination))
                    {
                        connection.Start();
                        producer.DeliveryMode = MsgDeliveryMode.Persistent;
                        ITextMessage request = session.CreateTextMessage(requestMessage);
                        producer.Send(request);
                    }

                    IDestination receiveDest = session.GetDestination(queueId);
                    Console.WriteLine("Using destination for receiving: " + receiveDest);

                    using (IMessageConsumer consumer = session.CreateConsumer(receiveDest))
                    {
                        ITextMessage message = consumer.Receive() as ITextMessage;
                        if (message == null)
                        {
                            Console.WriteLine("No message received!");
                        }
                        else
                        {
                            Console.WriteLine("Received message with text: " + message.Text);
                        }
                    }
                }

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
Example #35
0
 public Subscriber(IModel model, string queue, IMessageConsumer consumer, ISubscriptionHelper helper, SubscriberConfigurator configurator)
     : base(model, queue, consumer, configurator)
 {
     _helper = helper;
 }
Example #36
0
 public ConnectorBuilder WithConsumer(IMessageConsumer consumer)
 {
     this.consumers.Add(consumer);
     return(this);
 }
Example #37
0
        public static void Main(string[] args)
        {
            // Example connection strings:
            //    activemq:tcp://activemqhost:61616
            //    activemq:tcp://activemqhost:61613?transport.wireformat=stomp
            //    ems:tcp://tibcohost:7222
            //    msmq://localhost

            Uri connecturi = new Uri("activemq:tcp://activemqhost: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);

            using (IConnection connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    // Examples for getting a destination:
                    //
                    // Hard coded destinations:
                    //    IDestination destination = session.GetQueue("FOO.BAR");
                    //    IDestination destination = session.GetTopic("FOO.BAR");
                    //
                    // Embedded destination type in the name:
                    //    IDestination destination = SessionUtil.GetDestination(session, "queue://FOO.BAR");
                    //    IDestination destination = SessionUtil.GetDestination(session, "topic://FOO.BAR");
                    //
                    // Defaults to queue if type is not specified:
                    //    IDestination destination = SessionUtil.GetDestination(session, "FOO.BAR");

                    IDestination destination = SessionUtil.GetDestination(session, "queue://FOO.BAR");
                    Console.WriteLine("Using destination: " + destination);

                    // Create a consumer and producer
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        using (IMessageProducer producer = session.CreateProducer(destination))
                        {
                            producer.Persistent = true;

                            // Send a message
                            ITextMessage request = session.CreateTextMessage("Hello World!");
                            request.NMSCorrelationID          = "abc";
                            request.Properties["NMSXGroupID"] = "cheese";
                            request.Properties["myHeader"]    = "Cheddar";

                            producer.Send(request);

                            // Consume a message
                            ITextMessage message = consumer.Receive() as ITextMessage;
                            if (message == null)
                            {
                                Console.WriteLine("No message received!");
                            }
                            else
                            {
                                Console.WriteLine("Received message with ID:   " + message.NMSMessageId);
                                Console.WriteLine("Received message with text: " + message.Text);
                            }
                        }
                }
        }
Example #38
0
        protected void doSendReceiveMessageProperties(bool persistent)
        {
            using (IConnection connection = CreateConnection(TEST_CLIENT_ID))
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = SessionUtil.GetDestination(session, DESTINATION_NAME);
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        using (IMessageProducer producer = session.CreateProducer(destination))
                        {
                            producer.Persistent     = persistent;
                            producer.RequestTimeout = receiveTimeout;
                            IMessage request = session.CreateMessage();
                            request.Properties["a"] = a;
                            request.Properties["b"] = b;
                            request.Properties["c"] = c;
                            request.Properties["d"] = d;
                            request.Properties["e"] = e;
                            request.Properties["f"] = f;
                            request.Properties["g"] = g;
                            request.Properties["h"] = h;
                            request.Properties["i"] = i;
                            request.Properties["j"] = j;
                            request.Properties["k"] = k;
                            request.Properties["l"] = l;
                            request.Properties["m"] = m;
                            request.Properties["n"] = n;
                            producer.Send(request);

                            IMessage message = consumer.Receive(receiveTimeout);
                            Assert.IsNotNull(message, "No message returned!");
                            Assert.AreEqual(request.Properties.Count, message.Properties.Count, "Invalid number of properties.");
                            Assert.AreEqual(persistent, message.NMSPersistent, "NMSPersistent does not match");
                            Assert.AreEqual(ToHex(f), ToHex(message.Properties.GetLong("f")), "map entry: f as hex");

                            // use generic API to access entries
                            Assert.AreEqual(a, message.Properties["a"], "generic map entry: a");
                            Assert.AreEqual(b, message.Properties["b"], "generic map entry: b");
                            Assert.AreEqual(c, message.Properties["c"], "generic map entry: c");
                            Assert.AreEqual(d, message.Properties["d"], "generic map entry: d");
                            Assert.AreEqual(e, message.Properties["e"], "generic map entry: e");
                            Assert.AreEqual(f, message.Properties["f"], "generic map entry: f");
                            Assert.AreEqual(g, message.Properties["g"], "generic map entry: g");
                            Assert.AreEqual(h, message.Properties["h"], "generic map entry: h");
                            Assert.AreEqual(i, message.Properties["i"], "generic map entry: i");
                            Assert.AreEqual(j, message.Properties["j"], "generic map entry: j");
                            Assert.AreEqual(k, message.Properties["k"], "generic map entry: k");
                            Assert.AreEqual(l, message.Properties["l"], "generic map entry: l");
                            Assert.AreEqual(m, message.Properties["m"], "generic map entry: m");
                            Assert.AreEqual(n, message.Properties["n"], "generic map entry: n");

                            // use type safe APIs
                            Assert.AreEqual(a, message.Properties.GetBool("a"), "map entry: a");
                            Assert.AreEqual(b, message.Properties.GetByte("b"), "map entry: b");
                            Assert.AreEqual(c, message.Properties.GetChar("c"), "map entry: c");
                            Assert.AreEqual(d, message.Properties.GetShort("d"), "map entry: d");
                            Assert.AreEqual(e, message.Properties.GetInt("e"), "map entry: e");
                            Assert.AreEqual(f, message.Properties.GetLong("f"), "map entry: f");
                            Assert.AreEqual(g, message.Properties.GetString("g"), "map entry: g");
                            Assert.AreEqual(h, message.Properties.GetBool("h"), "map entry: h");
                            Assert.AreEqual(i, message.Properties.GetByte("i"), "map entry: i");
                            Assert.AreEqual(j, message.Properties.GetShort("j"), "map entry: j");
                            Assert.AreEqual(k, message.Properties.GetInt("k"), "map entry: k");
                            Assert.AreEqual(l, message.Properties.GetLong("l"), "map entry: l");
                            Assert.AreEqual(m, message.Properties.GetFloat("m"), "map entry: m");
                            Assert.AreEqual(n, message.Properties.GetDouble("n"), "map entry: n");
                        }
                }
            }
        }
Example #39
0
        public static void Main(string[] args)
        {
            // Example connection strings:
            //    activemq:tcp://activemqhost:61616
            //    stomp:tcp://activemqhost:61613
            //    ems:tcp://tibcohost:7222
            //    msmq://localhost

            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())
                {
                    // Examples for getting a destination:
                    //
                    // Hard coded destinations:
                    //    IDestination destination = session.GetQueue("FOO.BAR");
                    //    Debug.Assert(destination is IQueue);
                    //    IDestination destination = session.GetTopic("FOO.BAR");
                    //    Debug.Assert(destination is ITopic);
                    //
                    // Embedded destination type in the name:
                    //    IDestination destination = SessionUtil.GetDestination(session, "queue://FOO.BAR");
                    //    Debug.Assert(destination is IQueue);
                    //    IDestination destination = SessionUtil.GetDestination(session, "topic://FOO.BAR");
                    //    Debug.Assert(destination is ITopic);
                    //
                    // Defaults to queue if type is not specified:
                    //    IDestination destination = SessionUtil.GetDestination(session, "FOO.BAR");
                    //    Debug.Assert(destination is IQueue);
                    //
                    // .NET 3.5 Supports Extension methods for a simplified syntax:
                    //    IDestination destination = session.GetDestination("queue://FOO.BAR");
                    //    Debug.Assert(destination is IQueue);
                    //    IDestination destination = session.GetDestination("topic://FOO.BAR");
                    //    Debug.Assert(destination is ITopic);
                    //IDestination destination = SessionUtil.GetDestination(session, "queue://Consumer.esb.VirtualTopic.es-data");
                    //ActiveMQQueue topic = new ActiveMQQueue("Consumer.ERIC.VirtualTopic.ESDATA");
                    ActiveMQTopic topic = new ActiveMQTopic("VirtualTopic/ESDATA");

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

                    // Create a consumer and producer
                    using (IMessageConsumer consumer = session.CreateConsumer(topic))
                    //using(IMessageProducer producer = session.CreateProducer(destination))
                    {
                        // Start the connection so that messages will be processed.
                        connection.Start();
                        //producer.DeliveryMode = MsgDeliveryMode.Persistent;
                        //producer.RequestTimeout = receiveTimeout;

                        consumer.Listener += new MessageListener(OnMessage);

                        /*
                         * // Send a message
                         * ITextMessage request = session.CreateTextMessage("Hello World!");
                         * request.NMSCorrelationID = "abc";
                         * request.Properties["NMSXGroupID"] = "cheese";
                         * request.Properties["myHeader"] = "Cheddar";
                         *
                         * producer.Send(request);
                         */

                        while (true)
                        {
                            // Wait for the message
                            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);
                                Console.WriteLine("Received message with text: " + System.Text.Encoding.UTF8.GetString(bmsg.Content));
                            }
                        }
                    }
                }
        }
Example #40
0
        public RabbitMqMessageBus(ZaminConfigurationOptions configuration, IJsonSerializer jsonSerializer, IMessageConsumer messageConsumer)
        {
            _configuration   = configuration;
            _jsonSerializer  = jsonSerializer;
            _messageConsumer = messageConsumer;
            var connectionFactory = new ConnectionFactory
            {
                Uri = configuration.MessageBus.RabbitMq.Uri
            };

            _connection = connectionFactory.CreateConnection();
            var channel = _connection.CreateModel();

            channel.ExchangeDeclare(configuration.MessageBus.RabbitMq.ExchangeName, ExchangeType.Topic, configuration.MessageBus.RabbitMq.ExchangeDurable, configuration.MessageBus.RabbitMq.ExchangeAutoDeleted);
            ReveiveMessages();
        }
Example #41
0
        public void TestRecoverOrderingWithAsyncConsumer()
        {
            int recoverCount = 5;
            int messageCount = 8;

            using (TestAmqpPeer testAmqpPeer = new TestAmqpPeer(Address, User, Password))
            {
                testAmqpPeer.Open();
                TestLinkProcessor testLinkProcessor = new TestLinkProcessor();
                testAmqpPeer.RegisterLinkProcessor(testLinkProcessor);

                for (int i = 0; i < messageCount; i++)
                {
                    testAmqpPeer.SendMessage("myQueue", i.ToString());
                }

                ManualResetEvent latch      = new ManualResetEvent(false);
                IConnection      connection = EstablishConnection();
                connection.Start();
                ISession         session     = connection.CreateSession(AcknowledgementMode.ClientAcknowledge);
                IQueue           destination = session.GetQueue("myQueue");
                IMessageConsumer consumer    = session.CreateConsumer(destination);

                bool complete      = false;
                int  messageSeen   = 0;
                int  expectedIndex = 0;
                consumer.Listener += message =>
                {
                    if (complete)
                    {
                        return;
                    }

                    int actualIndex = int.Parse((message as ITextMessage).Text);
                    Assert.AreEqual(expectedIndex, actualIndex);

                    // don't ack the message until we receive it X times
                    if (messageSeen < recoverCount)
                    {
                        session.Recover();
                        messageSeen++;
                    }
                    else
                    {
                        messageSeen = 0;
                        expectedIndex++;

                        message.Acknowledge();

                        if (expectedIndex == messageCount)
                        {
                            complete = true;
                            latch.Set();
                        }
                    }
                };


                consumer.Close();
                session.Close();
                connection.Close();
            }
        }
        public void SendReceiveMapMessage(
            [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
            MsgDeliveryMode deliveryMode)
        {
            using (IConnection connection = CreateConnection(GetTestClientId()))
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = CreateDestination(session, DestinationType.Queue);
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        using (IMessageProducer producer = session.CreateProducer(destination))
                        {
                            producer.DeliveryMode = deliveryMode;
                            IMapMessage request = session.CreateMapMessage();
                            request.Body["a"] = a;
                            request.Body["b"] = b;
                            request.Body["c"] = c;
                            request.Body["d"] = d;
                            request.Body["e"] = e;
                            request.Body["f"] = f;
                            request.Body["g"] = g;
                            request.Body["h"] = h;
                            request.Body["i"] = i;
                            request.Body["j"] = j;
                            request.Body["k"] = k;
                            request.Body["l"] = l;
                            request.Body["m"] = m;
                            request.Body["n"] = n;
                            request.Body["o"] = o;
                            producer.Send(request);

                            IMapMessage message = consumer.Receive(receiveTimeout) as IMapMessage;
                            Assert.IsNotNull(message, "No message returned!");
                            Assert.AreEqual(request.Body.Count, message.Body.Count, "Invalid number of message maps.");
                            Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match");
                            Assert.AreEqual(ToHex(f), ToHex(message.Body.GetLong("f")), "map entry: f as hex");

                            // use generic API to access entries
                            Assert.AreEqual(a, message.Body["a"], "generic map entry: a");
                            Assert.AreEqual(b, message.Body["b"], "generic map entry: b");
                            Assert.AreEqual(c, message.Body["c"], "generic map entry: c");
                            Assert.AreEqual(d, message.Body["d"], "generic map entry: d");
                            Assert.AreEqual(e, message.Body["e"], "generic map entry: e");
                            Assert.AreEqual(f, message.Body["f"], "generic map entry: f");
                            Assert.AreEqual(g, message.Body["g"], "generic map entry: g");
                            Assert.AreEqual(h, message.Body["h"], "generic map entry: h");
                            Assert.AreEqual(i, message.Body["i"], "generic map entry: i");
                            Assert.AreEqual(j, message.Body["j"], "generic map entry: j");
                            Assert.AreEqual(k, message.Body["k"], "generic map entry: k");
                            Assert.AreEqual(l, message.Body["l"], "generic map entry: l");
                            Assert.AreEqual(m, message.Body["m"], "generic map entry: m");
                            Assert.AreEqual(n, message.Body["n"], "generic map entry: n");
                            Assert.AreEqual(o, message.Body["o"], "generic map entry: o");

                            // use type safe APIs
                            Assert.AreEqual(a, message.Body.GetBool("a"), "map entry: a");
                            Assert.AreEqual(b, message.Body.GetByte("b"), "map entry: b");
                            Assert.AreEqual(c, message.Body.GetChar("c"), "map entry: c");
                            Assert.AreEqual(d, message.Body.GetShort("d"), "map entry: d");
                            Assert.AreEqual(e, message.Body.GetInt("e"), "map entry: e");
                            Assert.AreEqual(f, message.Body.GetLong("f"), "map entry: f");
                            Assert.AreEqual(g, message.Body.GetString("g"), "map entry: g");
                            Assert.AreEqual(h, message.Body.GetBool("h"), "map entry: h");
                            Assert.AreEqual(i, message.Body.GetByte("i"), "map entry: i");
                            Assert.AreEqual(j, message.Body.GetShort("j"), "map entry: j");
                            Assert.AreEqual(k, message.Body.GetInt("k"), "map entry: k");
                            Assert.AreEqual(l, message.Body.GetLong("l"), "map entry: l");
                            Assert.AreEqual(m, message.Body.GetFloat("m"), "map entry: m");
                            Assert.AreEqual(n, message.Body.GetDouble("n"), "map entry: n");
                            Assert.AreEqual(o, message.Body.GetBytes("o"), "map entry: o");
                        }
                }
            }
        }
        public void SendReceiveNestedMapMessage(
            [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
            MsgDeliveryMode deliveryMode)
        {
            using (IConnection connection = CreateConnection(GetTestClientId()))
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = CreateDestination(session, DestinationType.Queue);
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        using (IMessageProducer producer = session.CreateProducer(destination))
                        {
                            try
                            {
                                producer.DeliveryMode = deliveryMode;
                                IMapMessage  request        = session.CreateMapMessage();
                                const string textFieldValue = "Nested Map Messages Rule!";

                                request.Body.SetString("textField", textFieldValue);

                                IDictionary grandChildMap = new Hashtable();
                                grandChildMap["x"] = "abc";
                                grandChildMap["y"] = new ArrayList(new object[] { "a", "b", "c" });

                                IDictionary nestedMap = new Hashtable();
                                nestedMap["a"] = "foo";
                                nestedMap["b"] = (int)23;
                                nestedMap["c"] = (long)45;
                                nestedMap["d"] = grandChildMap;

                                request.Body.SetDictionary("mapField", nestedMap);
                                request.Body.SetList("listField", new ArrayList(new Object[] { "a", "b", "c" }));

                                producer.Send(request);

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

                                string textFieldResponse = message.Body.GetString("textField");
                                Assert.AreEqual(textFieldValue, textFieldResponse, "textField does not match.");

                                IDictionary nestedMapResponse = message.Body.GetDictionary("mapField");
                                Assert.IsNotNull(nestedMapResponse, "Nested map not returned.");
                                Assert.AreEqual(nestedMap.Count, nestedMapResponse.Count,
                                                "nestedMap: Wrong number of elements");
                                Assert.AreEqual("foo", nestedMapResponse["a"], "nestedMap: a");
                                Assert.AreEqual(23, nestedMapResponse["b"], "nestedMap: b");
                                Assert.AreEqual(45, nestedMapResponse["c"], "nestedMap: c");

                                IDictionary grandChildMapResponse = nestedMapResponse["d"] as IDictionary;
                                Assert.IsNotNull(grandChildMapResponse, "Grand child map not returned.");
                                Assert.AreEqual(grandChildMap.Count, grandChildMapResponse.Count,
                                                "grandChildMap: Wrong number of elements");
                                Assert.AreEqual(grandChildMapResponse["x"], "abc", "grandChildMap: x");

                                IList grandChildList = grandChildMapResponse["y"] as IList;
                                Assert.IsNotNull(grandChildList, "Grand child list not returned.");
                                Assert.AreEqual(3, grandChildList.Count, "grandChildList: Wrong number of list elements.");
                                Assert.AreEqual("a", grandChildList[0], "grandChildList: a");
                                Assert.AreEqual("b", grandChildList[1], "grandChildList: b");
                                Assert.AreEqual("c", grandChildList[2], "grandChildList: c");

                                IList listFieldResponse = message.Body.GetList("listField");
                                Assert.IsNotNull(listFieldResponse, "Nested list not returned.");
                                Assert.AreEqual(3, listFieldResponse.Count,
                                                "listFieldResponse: Wrong number of list elements.");
                                Assert.AreEqual("a", listFieldResponse[0], "listFieldResponse: a");
                                Assert.AreEqual("b", listFieldResponse[1], "listFieldResponse: b");
                                Assert.AreEqual("c", listFieldResponse[2], "listFieldResponse: c");
                            }
                            catch (NotSupportedException)
                            {
                            }
                            catch (NMSException e)
                            {
                                Assert.IsTrue(e.InnerException.GetType() == typeof(NotSupportedException));
                            }
                        }
                }
            }
        }
Example #44
0
        public void SendReceiveStreamMessage(
            [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
            MsgDeliveryMode deliveryMode)
        {
            using (IConnection connection = CreateConnection(GetTestClientId()))
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = SessionUtil.GetDestination(session, DESTINATION_NAME);
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        using (IMessageProducer producer = session.CreateProducer(destination))
                        {
                            producer.DeliveryMode = deliveryMode;
                            IStreamMessage request;

                            try
                            {
                                request = session.CreateStreamMessage();
                            }
                            catch (System.NotSupportedException)
                            {
                                return;
                            }

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

                            IStreamMessage message = consumer.Receive(receiveTimeout) as IStreamMessage;
                            Assert.IsNotNull(message, "No message returned!");
                            Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match");

                            // use generic API to access entries
                            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");
                        }
                }
            }
        }
Example #45
0
        public void TestReceiveBrowseReceive()
        {
            using (IConnection connection = CreateConnection())
            {
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination     destination = session.GetQueue("TestReceiveBrowseReceive");
                    IMessageProducer producer    = session.CreateProducer(destination);
                    IMessageConsumer consumer    = session.CreateConsumer(destination);
                    connection.Start();

                    IMessage[] outbound = new IMessage[] { session.CreateTextMessage("First Message"),
                                                           session.CreateTextMessage("Second Message"),
                                                           session.CreateTextMessage("Third Message") };

                    // lets consume any outstanding messages from previous test runs
                    while (consumer.Receive(TimeSpan.FromMilliseconds(1000)) != null)
                    {
                    }

                    producer.Send(outbound[0]);
                    producer.Send(outbound[1]);
                    producer.Send(outbound[2]);

                    IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(1000));

                    // Get the first.
                    Assert.AreEqual(((ITextMessage)outbound[0]).Text, ((ITextMessage)msg).Text);
                    consumer.Close();

                    IQueueBrowser browser     = session.CreateBrowser((IQueue)destination);
                    IEnumerator   enumeration = browser.GetEnumerator();

                    // browse the second
                    Assert.IsTrue(enumeration.MoveNext(), "should have received the second message");
                    Assert.AreEqual(((ITextMessage)outbound[1]).Text, ((ITextMessage)enumeration.Current).Text);

                    // browse the third.
                    Assert.IsTrue(enumeration.MoveNext(), "Should have received the third message");
                    Assert.AreEqual(((ITextMessage)outbound[2]).Text, ((ITextMessage)enumeration.Current).Text);

                    // There should be no more.
                    bool tooMany = false;
                    while (enumeration.MoveNext())
                    {
                        Debug.WriteLine("Got extra message: " + ((ITextMessage)enumeration.Current).Text);
                        tooMany = true;
                    }
                    Assert.IsFalse(tooMany);

                    //Reset should take us back to the start.
                    enumeration.Reset();

                    // browse the second
                    Assert.IsTrue(enumeration.MoveNext(), "should have received the second message");
                    Assert.AreEqual(((ITextMessage)outbound[1]).Text, ((ITextMessage)enumeration.Current).Text);

                    // browse the third.
                    Assert.IsTrue(enumeration.MoveNext(), "Should have received the third message");
                    Assert.AreEqual(((ITextMessage)outbound[2]).Text, ((ITextMessage)enumeration.Current).Text);

                    // There should be no more.
                    tooMany = false;
                    while (enumeration.MoveNext())
                    {
                        Debug.WriteLine("Got extra message: " + ((ITextMessage)enumeration.Current).Text);
                        tooMany = true;
                    }
                    Assert.IsFalse(tooMany);

                    browser.Close();

                    // Re-open the consumer.
                    consumer = session.CreateConsumer(destination);

                    // Receive the second.
                    Assert.AreEqual(((ITextMessage)outbound[1]).Text, ((ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000))).Text);
                    // Receive the third.
                    Assert.AreEqual(((ITextMessage)outbound[2]).Text, ((ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(1000))).Text);
                    consumer.Close();
                }
            }
        }
Example #46
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnStart.Text == "停止服务")
                {
                    if (netServer != null)
                    {
                        netServer.Stop();
                        netServer.TCPReceiveData -= Server_TCPReceiveData;
                        netServer.UDPReceiveData -= Server_UDPReceiveData;
                        FormMain.m_mq.Close();
                        this.m_consumer.Listener -= this.consumer_listener;
                        this.m_consumer.Close();
                        this.m_consumer     = null;
                        this.timer1.Enabled = false;
                    }
                    isServerRun   = false;
                    btnStart.Text = "启动服务";
                    return;
                }
                this.timer1.Enabled = true;
                this.ConnectMQServer();
                string portStr = ini.ReadValue("LocalHost", "UDPLocalPort");
                if (!Regex.IsMatch(portStr, NetServer.PATTERNPORT))
                {
                    MessageBox.Show("端口号设置错误", "提示");
                    return;
                }
                ushort udpPort    = ushort.Parse(portStr);
                string tcpPortStr = ini.ReadValue("LocalHost", "TCPLocalPort");
                if (!Regex.IsMatch(tcpPortStr, NetServer.PATTERNPORT))
                {
                    MessageBox.Show("端口号设置错误", "提示");
                    return;
                }
                ushort tcpPort = ushort.Parse(tcpPortStr);

                InitDatabase();
                if (!DataBase.OpenTest())
                {
                    MessageBox.Show("数据库连接失败,请检查数据库配置", "提示");
                    return;
                }

                string ip = ini.ReadValue("LocalHost", "LoaclIP");
                if (ip == "127.0.0.1")
                {
                    var result = MessageBox.Show(this, "当前绑定IP为127.0.0.1,若要与外界通信需修改为本地公网IP,是否继续绑定127.0.0.1,选择否则返回设置?",
                                                 "提示", MessageBoxButtons.YesNo);
                    if (result == DialogResult.No)
                    {
                        return;
                    }
                }

                //启动数据处理线程和计时器
                if (!dealThread.IsAlive)
                {
                    dealThread.Start();
                }
                if (!saveThread.IsAlive)
                {
                    saveThread.Start();
                }
                if (!dbTimer.Enabled)
                {
                    dbTimer.Start();
                }

                #region  时启动tcp和udp

                netServer = new NetServer(tcpPort, udpPort, ip);
                netServer.TCPReceiveData += Server_TCPReceiveData;
                netServer.UDPReceiveData += Server_UDPReceiveData;
                netServer.Start();
                #endregion

                isServerRun   = true;
                btnStart.Text = "停止服务";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                //启动异常则关闭服务
                if (netServer != null)
                {
                    netServer.Stop();
                    netServer.TCPReceiveData -= Server_TCPReceiveData;
                    netServer.UDPReceiveData -= Server_UDPReceiveData;
                }
                isServerRun   = false;
                btnStart.Text = "启动服务";
                return;
            }
        }
        public async Task TestIncomingExpiredMessageGetsFilteredAsync()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);

                await connection.StartAsync();

                testPeer.ExpectBegin();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                IQueue queue = await session.GetQueueAsync("myQueue");

                // Expected the consumer to attach and send credit, then send it an
                // already-expired message followed by a live message.
                testPeer.ExpectReceiverAttach();

                string       expiredMsgContent = "already-expired";
                Amqp.Message message           = CreateExpiredMessage(expiredMsgContent);
                testPeer.ExpectLinkFlowRespondWithTransfer(message: message);

                string liveMsgContent = "valid";
                testPeer.SendTransferToLastOpenedLinkOnLastOpenedSession(message: new Amqp.Message()
                {
                    BodySection = new AmqpValue()
                    {
                        Value = liveMsgContent
                    }
                }, nextIncomingId: 2);

                IMessageConsumer consumer = await session.CreateConsumerAsync(queue);

                // Add message listener, expect the first message to be filtered due to expiry,
                // and the second message to be given to the test app and accepted.
                Action <DeliveryState> modifiedMatcher = state =>
                {
                    var modified = state as Modified;
                    Assert.IsNotNull(modified);
                    Assert.IsTrue(modified.DeliveryFailed);
                    Assert.IsTrue(modified.UndeliverableHere);
                };
                testPeer.ExpectDisposition(settled: true, stateMatcher: modifiedMatcher, firstDeliveryId: 1, lastDeliveryId: 1);
                testPeer.ExpectDisposition(settled: true, stateMatcher: Assert.IsInstanceOf <Accepted>, firstDeliveryId: 2, lastDeliveryId: 2);


                ManualResetEvent success         = new ManualResetEvent(false);
                ManualResetEvent listenerFailure = new ManualResetEvent(false);

                consumer.Listener += m =>
                {
                    if (liveMsgContent.Equals(((ITextMessage)m).Text))
                    {
                        success.Set();
                    }
                    else
                    {
                        listenerFailure.Set();
                    }
                };

                Assert.True(success.WaitOne(TimeSpan.FromSeconds(5)), "didn't get expected message");
                Assert.False(listenerFailure.WaitOne(TimeSpan.FromMilliseconds(100)), "Received message when message should not have been received");

                testPeer.WaitForAllMatchersToComplete(3000);

                testPeer.ExpectClose();
                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(3000);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CachedMessageConsumer"/> class.
 /// </summary>
 /// <param name="target">The target.</param>
 public CachedMessageConsumer(IMessageConsumer target)
 {
     this.target = target;
 }
Example #49
0
 /// <summary>
 /// Method Reconnect
 /// </summary>
 protected override void Reconnect()
 {
     base.Reconnect();
     consumer = Session.CreateConsumer(Destination);
     producer = Session.CreateProducer(Destination);
 }
Example #50
0
 // 连接中断监听
 void connection_ConnectionInterruptedListener()
 {
     Close();
     _consumer = CreateConsumer();
 }
Example #51
0
        public void TestFallbackToExclusiveConsumer()
        {
            IConnection conn = createConnection(true);

            ISession exclusiveSession = null;
            ISession fallbackSession  = null;
            ISession senderSession    = null;

            purgeQueue(conn, new ActiveMQQueue("TEST.QUEUE4"));

            try
            {
                exclusiveSession = conn.CreateSession(AcknowledgementMode.AutoAcknowledge);
                fallbackSession  = conn.CreateSession(AcknowledgementMode.AutoAcknowledge);
                senderSession    = conn.CreateSession(AcknowledgementMode.AutoAcknowledge);

                // This creates the exclusive consumer first which avoids AMQ-1024
                // bug.
                ActiveMQQueue    exclusiveQueue    = new ActiveMQQueue("TEST.QUEUE4?consumer.exclusive=true");
                IMessageConsumer exclusiveConsumer = exclusiveSession.CreateConsumer(exclusiveQueue);

                ActiveMQQueue    fallbackQueue    = new ActiveMQQueue("TEST.QUEUE4");
                IMessageConsumer fallbackConsumer = fallbackSession.CreateConsumer(fallbackQueue);

                ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE4");

                IMessageProducer producer = senderSession.CreateProducer(senderQueue);
                producer.DeliveryMode = MsgDeliveryMode.NonPersistent;

                IMessage msg = senderSession.CreateTextMessage("test");
                producer.Send(msg);
                Thread.Sleep(500);

                // Verify exclusive consumer receives the message.
                Assert.IsNotNull(exclusiveConsumer.Receive(TimeSpan.FromMilliseconds(1000)));
                Assert.IsNull(fallbackConsumer.Receive(TimeSpan.FromMilliseconds(1000)));

                // Close the exclusive consumer to verify the non-exclusive consumer
                // takes over
                exclusiveConsumer.Close();

                producer.Send(msg);

                // Verify other non-exclusive consumer receices the message.
                Assert.IsNotNull(fallbackConsumer.Receive(TimeSpan.FromMilliseconds(1000)));

                // Create exclusive consumer to determine if it will start receiving
                // the messages.
                exclusiveConsumer = exclusiveSession.CreateConsumer(exclusiveQueue);

                producer.Send(msg);
                Assert.IsNotNull(exclusiveConsumer.Receive(TimeSpan.FromMilliseconds(1000)));
                Assert.IsNull(fallbackConsumer.Receive(TimeSpan.FromMilliseconds(1000)));
            }
            finally
            {
                fallbackSession.Close();
                senderSession.Close();
                conn.Close();
            }
        }
Example #52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MessageProducer"/> class.
 /// </summary>
 /// <param name="consumer">The consumer used to enqueue produced messages.</param>
 /// <param name="logger">An object used to report incidences.</param>
 public MessageProducer(IMessageConsumer consumer, ILogger <MessageProducer> logger)
 {
     Logger   = logger;
     Consumer = consumer;
 }
Example #53
0
        public void FailoverBeforeCommitSentTest()
        {
            string             uri     = "failover:(tcpfaulty://${activemqhost}:61616?transport.useLogging=true)";
            IConnectionFactory factory = new ConnectionFactory(NMSTestSupport.ReplaceEnvVar(uri));

            using (connection = factory.CreateConnection() as Connection)
            {
                connection.ConnectionInterruptedListener +=
                    new ConnectionInterruptedListener(TransportInterrupted);
                connection.ConnectionResumedListener +=
                    new ConnectionResumedListener(TransportResumed);

                connection.Start();

                ITransport         transport = (connection as Connection).ITransport;
                TcpFaultyTransport tcpFaulty = transport.Narrow(typeof(TcpFaultyTransport)) as TcpFaultyTransport;
                Assert.IsNotNull(tcpFaulty);
                tcpFaulty.OnewayCommandPreProcessor += this.FailOnCommitTransportHook;

                using (ISession session = connection.CreateSession())
                {
                    IDestination destination = session.GetQueue(destinationName);
                    PurgeQueue(connection, destination);
                }

                Tracer.Debug("Test is putting " + MSG_COUNT + " messages on the queue: " + destinationName);

                using (ISession session = connection.CreateSession(AcknowledgementMode.Transactional))
                {
                    IDestination destination = session.GetQueue(destinationName);
                    PutMsgIntoQueue(session, destination, false);

                    try
                    {
                        session.Commit();
                        Assert.Fail("Should have thrown a TransactionRolledBackException");
                    }
                    catch (TransactionRolledBackException)
                    {
                    }
                    catch
                    {
                        Assert.Fail("Should have thrown a TransactionRolledBackException");
                    }
                }

                Assert.IsTrue(this.interrupted);
                Assert.IsTrue(this.resumed);

                Tracer.Debug("Test is attempting to read a message from" +
                             destinationName + " but no messages are expected");

                using (ISession session = connection.CreateSession())
                {
                    IDestination     destination = session.GetQueue(destinationName);
                    IMessageConsumer consumer    = session.CreateConsumer(destination);
                    IMessage         msg         = consumer.Receive(TimeSpan.FromSeconds(5));
                    Assert.IsNull(msg, "Should not receive a message after commit failed.");
                }
            }

            Assert.IsTrue(this.interrupted);
            Assert.IsTrue(this.resumed);
        }
Example #54
0
 public static IEnumerable <T> RetrieveMessages <T>(this IMessageConsumer consumer, int messageAmount, int timeout) where T : new()
 {
     return(consumer.RetrieveMessages(messageAmount, timeout).Select(m => ThriftSerializer.Deserialize <T>(m.BodyStream)));
 }
Example #55
0
        public void SendReceiveMessageProperties(
            [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
            MsgDeliveryMode deliveryMode)
        {
            using (IConnection connection = CreateConnection(GetTestClientId()))
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = CreateDestination(session, DestinationType.Queue);
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        using (IMessageProducer producer = session.CreateProducer(destination))
                        {
                            producer.DeliveryMode = deliveryMode;
                            IMessage request = session.CreateMessage();
                            request.Properties["a"] = a;
                            request.Properties["b"] = b;
                            request.Properties["c"] = c;
                            request.Properties["d"] = d;
                            request.Properties["e"] = e;
                            request.Properties["f"] = f;
                            request.Properties["g"] = g;
                            request.Properties["h"] = h;
                            request.Properties["i"] = i;
                            request.Properties["j"] = j;
                            request.Properties["k"] = k;
                            request.Properties["l"] = l;
                            request.Properties["m"] = m;
                            request.Properties["n"] = n;

                            try
                            {
                                request.Properties["o"] = o;
                                Assert.Fail("Should not be able to add a Byte[] to the Properties of a Message.");
                            }
                            catch
                            {
                                // Expected
                            }

                            try
                            {
                                request.Properties.SetBytes("o", o);
                                Assert.Fail("Should not be able to add a Byte[] to the Properties of a Message.");
                            }
                            catch
                            {
                                // Expected
                            }

                            producer.Send(request);

                            IMessage message = consumer.Receive(receiveTimeout);
                            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");
                            Assert.AreEqual(ToHex(f), ToHex(message.Properties.GetLong("f")), "map entry: f as hex");

                            // use generic API to access entries
                            // Perform a string only comparison here since some NMS providers are type limited and
                            // may return only a string instance from the generic [] accessor.  Each provider should
                            // further test this functionality to determine that the correct type is returned if
                            // it is capable of doing so.
                            Assert.AreEqual(a.ToString(), message.Properties["a"].ToString(), "generic map entry: a");
                            Assert.AreEqual(b.ToString(), message.Properties["b"].ToString(), "generic map entry: b");
                            Assert.AreEqual(c.ToString(), message.Properties["c"].ToString(), "generic map entry: c");
                            Assert.AreEqual(d.ToString(), message.Properties["d"].ToString(), "generic map entry: d");
                            Assert.AreEqual(e.ToString(), message.Properties["e"].ToString(), "generic map entry: e");
                            Assert.AreEqual(f.ToString(), message.Properties["f"].ToString(), "generic map entry: f");
                            Assert.AreEqual(g.ToString(), message.Properties["g"].ToString(), "generic map entry: g");
                            Assert.AreEqual(h.ToString(), message.Properties["h"].ToString(), "generic map entry: h");
                            Assert.AreEqual(i.ToString(), message.Properties["i"].ToString(), "generic map entry: i");
                            Assert.AreEqual(j.ToString(), message.Properties["j"].ToString(), "generic map entry: j");
                            Assert.AreEqual(k.ToString(), message.Properties["k"].ToString(), "generic map entry: k");
                            Assert.AreEqual(l.ToString(), message.Properties["l"].ToString(), "generic map entry: l");
                            Assert.AreEqual(m.ToString(), message.Properties["m"].ToString(), "generic map entry: m");
                            Assert.AreEqual(n.ToString(), message.Properties["n"].ToString(), "generic map entry: n");

                            // use type safe APIs
                            Assert.AreEqual(a, message.Properties.GetBool("a"), "map entry: a");
                            Assert.AreEqual(b, message.Properties.GetByte("b"), "map entry: b");
                            Assert.AreEqual(c, message.Properties.GetChar("c"), "map entry: c");
                            Assert.AreEqual(d, message.Properties.GetShort("d"), "map entry: d");
                            Assert.AreEqual(e, message.Properties.GetInt("e"), "map entry: e");
                            Assert.AreEqual(f, message.Properties.GetLong("f"), "map entry: f");
                            Assert.AreEqual(g, message.Properties.GetString("g"), "map entry: g");
                            Assert.AreEqual(h, message.Properties.GetBool("h"), "map entry: h");
                            Assert.AreEqual(i, message.Properties.GetByte("i"), "map entry: i");
                            Assert.AreEqual(j, message.Properties.GetShort("j"), "map entry: j");
                            Assert.AreEqual(k, message.Properties.GetInt("k"), "map entry: k");
                            Assert.AreEqual(l, message.Properties.GetLong("l"), "map entry: l");
                            Assert.AreEqual(m, message.Properties.GetFloat("m"), "map entry: m");
                            Assert.AreEqual(n, message.Properties.GetDouble("n"), "map entry: n");
                        }
                }
            }
        }
Example #56
0
 /// <summary>
 /// Initializes listening to a specific path on the Active MQ server.
 /// Please note, that, if not otherwise specified, it will be assumed that the path should be a queue.
 /// As such, if you want to specifically listen to a queue, prepend the path parameter with "queue://" otherwise with "topic://"
 /// </summary>
 /// <param name="path">The path to the message exchange</param>
 /// <param name="subscription">Not used by Active MQ. The subscription will be named automatically by the active mq server</param>
 /// <param name="filter">An SQL-like string to filter for values set on the meta properties of a message. This maps directly to the "properties" parameter (including "ContentType")  of SendAsync</param>
 /// <returns></returns>
 public async Task <bool> ListenAsync(string path, string subscription = null, string filter = null)
 {
     _logger.Trace(ConnectorLogging.Process((nameof(path), path), (nameof(subscription), subscription), (nameof(filter), filter)));
     if (_isInternalListeningHooked)
     {
         _logger.Error($"Currently already listening to some path. Please call {nameof(StopListening)} before calling {nameof(ListenAsync)} again");
         return(false);
     }
     if (!_isConnectionGood)
     {
         _logger.Error($"Currently not connected. Please wait for connection to be established before listening");
         return(false);
     }
     if (_session == null)
     {
         _logger.Error($"Cannot listen to path if session has not been established");
         return(false);
     }
     if (string.IsNullOrEmpty(path))
     {
         _logger.Error($"Bad Argument: {nameof(path)} was null");
         return(false);
     }
     PrependWithPathDefault(ref path);
     try
     {
         _listenToPath         = path;
         _listenToSubscription = subscription;
         _listenToFilter       = filter;
         IDestination destination;
         //todo: add code to verify, path is not for queue when subscription is not null and vice versa
         destination = SessionUtil.GetDestination(_session, path);
         ITopic topicDestination = SessionUtil.GetTopic(_session, path);
         if (string.IsNullOrEmpty(filter))
         {
             if (path.StartsWith("topic://"))
             {
                 _logger.Trace($"Creating durable consumer for {topicDestination.ToString()}");
                 _consumer = _session.CreateDurableConsumer(topicDestination, subscription, filter, false);
             }
             else if (path.StartsWith("queue://"))
             {
                 _logger.Trace($"Creating consumer for {destination.ToString()}");
                 _consumer = _session.CreateConsumer(destination);
             }
             else
             {
                 _logger.Error($"Could not start listening because a path of {path} cannot be handled");
                 return(false);
             }
         }
         else
         {
             if (path.StartsWith("topic://"))
             {
                 _logger.Trace($"Creating durable consumer for {topicDestination.ToString()}");
                 _consumer = _session.CreateDurableConsumer(topicDestination, subscription, filter, false);
             }
             else if (path.StartsWith("queue://"))
             {
                 _logger.Trace($"Creating consumer for {destination.ToString()}");
                 _consumer = _session.CreateConsumer(destination, filter);
             }
             else
             {
                 _logger.Error($"Could not start listening because a path of {path} cannot be handled");
                 return(false);
             }
         }
         _consumer.Listener        += OnMessageReceived;
         _isInternalListeningHooked = true;
         _logger.Info($"Initialization for listening to {path} successful.");
         return(true);
     }
     catch (Exception e)
     {
         _logger.Error($"Exception while starting listener: {e.ToString()}");
     }
     return(false);
 }
        /// <summary>
        /// Dispatches a message to the specified consumer.  The implementation normalizes the
        /// calling for synchronous and asynchronous message handlers.  This allows the method
        /// handler to be re-factored to one or the other without having to change any of the
        /// calling code.  This also decouples the publisher from the consumer.  The publisher
        /// should not be concerned of how the message is handled.
        /// </summary>
        /// <param name="message">The message to be dispatched.</param>
        /// <param name="consumer">Instance of the consumer to have message dispatched.</param>
        /// <param name="cancellationToken">The cancellation token passed to the message handler.</param>
        /// <returns>The response as a future task result.</returns>
        public async Task <object> Dispatch(IMessage message, IMessageConsumer consumer, CancellationToken cancellationToken)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (consumer == null)
            {
                throw new ArgumentNullException(nameof(consumer));
            }
            if (cancellationToken == null)
            {
                throw new ArgumentNullException(nameof(cancellationToken));
            }

            var taskSource = new TaskCompletionSource <object>();

            try
            {
                if (IsAsync)
                {
                    var invokeParams = new List <object> {
                        consumer, message
                    };
                    if (IsCancellable)
                    {
                        invokeParams.Add(cancellationToken);
                    }

                    var asyncResult = (Task)Invoker.DynamicInvoke(invokeParams.ToArray());
                    await asyncResult.ConfigureAwait(false);

                    object result = ProcessResult(message, asyncResult);
                    taskSource.SetResult(result);
                }
                else
                {
                    object syncResult = Invoker.DynamicInvoke(consumer, message);
                    object result     = ProcessResult(message, syncResult);
                    taskSource.SetResult(result);
                }
            }
            catch (Exception ex)
            {
                var invokeEx = ex as TargetInvocationException;
                var sourceEx = ex;

                if (invokeEx != null)
                {
                    sourceEx = invokeEx.InnerException;
                }

                var dispatchEx = new MessageDispatchException("Exception Dispatching Message.",
                                                              this,
                                                              sourceEx);

                taskSource.SetException(dispatchEx);
            }

            return(await taskSource.Task.ConfigureAwait(false));
        }
Example #58
0
 public void RegisterImpl(IMessageConsumer consumer, string serviceId)
 {
     throw new NotImplementedException();
 }
Example #59
0
        public void TestTransactedProduceConsumeWithSessionClose(
            [Values("tcp://${activemqhost}:61616")]
            string baseConnectionURI)
        {
            INetTxConnectionFactory factory = new NetTxConnectionFactory(NMSTestSupport.ReplaceEnvVar(baseConnectionURI));

            using (INetTxConnection connection = factory.CreateNetTxConnection())
            {
                connection.Start();

                IDestination destination = null;

                using (INetTxSession session = connection.CreateNetTxSession())
                {
                    session.TransactionStartedListener    += TransactionStarted;
                    session.TransactionCommittedListener  += TransactionCommitted;
                    session.TransactionRolledBackListener += TransactionRolledBack;

                    destination = session.CreateTemporaryQueue();
                    using (IMessageProducer producer = session.CreateProducer(destination))
                    {
                        using (TransactionScope scoped = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                        {
                            Assert.IsFalse(this.transactionStarted);

                            Assert.IsNotNull(Transaction.Current);
                            for (int i = 0; i < MSG_COUNT; ++i)
                            {
                                producer.Send(session.CreateTextMessage("Hello World"));
                            }

                            Assert.IsTrue(this.transactionStarted, "A TX should have been started by producing");

                            scoped.Complete();
                        }

                        Assert.IsFalse(this.transactionStarted, "TX Should have Committed and cleared Started");
                        Assert.IsTrue(this.transactionCommitted, "TX Should have Committed");
                        Assert.IsFalse(this.transactionRolledBack, "TX Should not have Rolledback");

                        session.Close();
                    }
                }

                using (INetTxSession session = connection.CreateNetTxSession())
                {
                    session.TransactionStartedListener    += TransactionStarted;
                    session.TransactionCommittedListener  += TransactionCommitted;
                    session.TransactionRolledBackListener += TransactionRolledBack;

                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                    {
                        using (TransactionScope scoped = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                        {
                            Assert.IsFalse(this.transactionStarted);

                            for (int i = 0; i < MSG_COUNT; ++i)
                            {
                                IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(2000));
                                Assert.IsNotNull(msg, "Message was null for index: " + i);
                            }

                            Assert.IsTrue(this.transactionStarted, "A TX should have been started by consuming");

                            scoped.Complete();
                        }

                        Assert.IsFalse(this.transactionStarted, "TX Should have Committed and cleared Started");
                        Assert.IsTrue(this.transactionCommitted, "TX Should have Committed");
                        Assert.IsFalse(this.transactionRolledBack, "TX Should not have Rolledback");

                        session.Close();
                    }
                }

                using (INetTxSession session = connection.CreateNetTxSession())
                {
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                    {
                        for (int i = 0; i < MSG_COUNT; ++i)
                        {
                            IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(50));
                            Assert.IsNull(msg, "Message was not null for index: " + i);
                        }
                    }

                    session.Close();
                }

                connection.Close();
            }
        }
Example #60
0
        public void TestTransactedProduceConsumeRollbackConsume(
            [Values("tcp://${activemqhost}:61616")]
            string baseConnectionURI)
        {
            INetTxConnectionFactory factory = new NetTxConnectionFactory(NMSTestSupport.ReplaceEnvVar(baseConnectionURI));

            using (INetTxConnection connection = factory.CreateNetTxConnection())
            {
                connection.Start();

                using (INetTxSession session = connection.CreateNetTxSession())
                {
                    IDestination destination = session.CreateTemporaryQueue();
                    using (IMessageProducer producer = session.CreateProducer(destination))
                    {
                        using (TransactionScope scoped = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                        {
                            Assert.IsNotNull(Transaction.Current);
                            for (int i = 0; i < MSG_COUNT; ++i)
                            {
                                producer.Send(session.CreateTextMessage("Hello World"));
                            }
                            scoped.Complete();
                        }
                    }

                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                    {
                        Thread.Sleep(200);

                        using (TransactionScope scoped = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                        {
                            for (int i = 0; i < MSG_COUNT; ++i)
                            {
                                IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(2000));
                                Assert.IsNotNull(msg, "Message was null for index: " + i);
                            }
                        }

                        using (TransactionScope scoped = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                        {
                            for (int i = 0; i < MSG_COUNT; ++i)
                            {
                                IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(2000));
                                Assert.IsNotNull(msg, "Message was null for index: " + i);
                            }
                        }
                    }

                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                    {
                        Thread.Sleep(200);

                        using (TransactionScope scoped = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                        {
                            for (int i = 0; i < MSG_COUNT; ++i)
                            {
                                IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(2000));
                                Assert.IsNotNull(msg, "Message was null for index: " + i);
                                Assert.IsTrue(msg.NMSRedelivered);
                            }
                            scoped.Complete();
                        }
                    }

                    session.Close();
                }

                connection.Close();
            }
        }