Exemplo n.º 1
0
        private void receiver()
        {
            IConnectionFactory factory    = new NMSConnectionFactory("tcp//localhost");
            IConnection        connection = factory.CreateConnection();

            connection = factory.CreateConnection();
            connection.Start();
            ISession         session          = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            IDestination     QueueDestination = SessionUtil.GetDestination(session, "Queue");
            IMessageProducer MessageProducer  = session.CreateProducer(QueueDestination);
        }
Exemplo n.º 2
0
        /// <summary>
        /// A Psi Component to send messages through ActiveMQ
        ///
        /// messages are sent as string wrapped in xml.
        /// </summary>
        /// <param name="pipeline"></param>
        /// <param name="destinationName"></param>
        public ActiveMQ(Pipeline pipeline, string destinationRecvName, string destinationSendName) : base(pipeline)
        {
            checkConfig(); //Check that the config has all items we need, otherwise throw an exception

            //Start ActiveMQ server
            this.activeMQProcess = ActiveMQProcess.Instance;
            this.activeMQProcess.Start();

            //Connect to ActiveMQ Server (try several times in case the process takes a while to get started.
            IConnectionFactory factory = new NMSConnectionFactory(
                $"{Config.Global.ActiveMQ.Protocol}://{Config.Global.ActiveMQ.Host}:{Config.Global.ActiveMQ.Port}"
                );

            bool notConnected = true;
            int  attempts     = 0;
            int  maxAttempts  = 5;

            while (notConnected && attempts < maxAttempts)
            {
                try
                {
                    this.connection = factory.CreateConnection();
                    notConnected    = false;
                }
                catch (Apache.NMS.NMSConnectionException)
                {
                    attempts++;
                    System.Threading.Thread.Sleep(1000);
                }
            }
            Console.WriteLine($"{Config.Global.ActiveMQ.Protocol}://{Config.Global.ActiveMQ.Host}:{Config.Global.ActiveMQ.Port}");
            this.connection = factory.CreateConnection(); //Last try to connect to ActiveMQ
            this.session    = this.connection.CreateSession();

            this.destinationSendName = destinationSendName;
            this.destinationRecvName = destinationRecvName;

            //Create destinations to send and receive messages
            this.destinationSend       = SessionUtil.GetQueue(session, this.destinationSendName);
            this.destinationReceive    = SessionUtil.GetQueue(session, this.destinationRecvName);
            this.consumer              = session.CreateConsumer(this.destinationReceive);
            this.producer              = session.CreateProducer(this.destinationSend);
            this.producer.DeliveryMode = MsgDeliveryMode.NonPersistent; //TODO should this be a parameter?
            this.connection.Start();

            //Setup message listener
            consumer.Listener += new MessageListener(OnMessage);
        }
Exemplo n.º 3
0
        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://192.168.122.1:36917");

            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.GetQueue("divisas");
                    Console.WriteLine("Using destination: " + destination);

                    using (IMessageProducer producer = session.CreateProducer(destination))
                    {
                        // Start the connection so that messages will be processed.
                        connection.Start();
                        producer.DeliveryMode = MsgDeliveryMode.Persistent;

                        // Send a message
                        ITextMessage request = session.CreateTextMessage("nombreDivisa:USD|precio:14.30");

                        producer.Send(request);
                    }
                }
        }
Exemplo n.º 4
0
        private static void SendNewMessage(string text, string host, string password, string user)
        {
            //string topic = "TextQueue";
            string topic = "GPDC-LOGIN";

            // Console.WriteLine($"Adding message to queue topic: {topic}");

            String brokerUri             = "activemq:tcp://" + host + ":" + "61616";
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection(user, password))

            {
                connection.Start();

                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(topic))
                        using (IMessageProducer producer = session.CreateProducer(dest))
                        {
                            producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                            producer.Send(session.CreateTextMessage(text));
                            Console.WriteLine($"Sending: {text} ");

                            session.Dispose();
                        }
                if (connection.IsStarted)
                {
                    connection.Close();
                }
            }
        }
Exemplo n.º 5
0
        private static void Main(string[] args)
        {
            Console.WriteLine("ActiveMQ Producer Demo");

            string topic = "TextQueue";

            Console.WriteLine($"Adding message to queue topic: {topic}");

            string brokerUri             = $"activemq:tcp://192.168.250.198:61616"; // Default port
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection("artemis", "simetraehcapa"))
            {
                var msg = $"a log message {DateTime.UtcNow}";

                connection.Start();

                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(topic))
                        using (IMessageProducer producer = session.CreateProducer(dest))
                        {
                            producer.DeliveryMode = MsgDeliveryMode.NonPersistent;

                            producer.Send(session.CreateTextMessage(msg));
                            Console.WriteLine($"Sent {msg} messages");
                        }
            }

            Console.WriteLine($"");
            Console.WriteLine($"Press any key to finish.");
            Console.ReadKey(true);
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            Uri connecturi = new Uri("activemq:tcp://localhost:61616");

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

            IConnectionFactory factory = new NMSConnectionFactory(connecturi);

            using (IConnection connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    IDestination destination = session.GetDestination("queue://FOO.BAR");
                    connection.Start();
                    Console.WriteLine("Connection established");

                    using (IMessageProducer producer = session.CreateProducer(destination))
                    {
                        producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                        Console.WriteLine("Press enter to send another message, q to quit");
                        while ((Console.ReadLine() ?? "").ToLower() != "q")
                        {
                            var payload = "Hello there. " + DateTime.Now.ToLongTimeString();
                            var message = session.CreateTextMessage(payload);
                            producer.Send(message);
                            Console.WriteLine("Message sent. " + payload);
                            Console.WriteLine("------------------------------------------");
                        }
                    }
                }

            Console.WriteLine("Terminating..");
        }
Exemplo n.º 7
0
        public void ThreadRun()
        {
            logger.Log("Publishing thread started.");
            while (true)
            {
                // Assume that outside PublisherThread messageSource's size can only
                // be increased. No remove actions outside PublisherThread.
                if (messageSource.Count > 0)
                {
                    // The first element is valid since messageSource only increase
                    // never decrease outside PublisherThread.
                    Message request = messageSource.RemoveFirst();

                    logger.Log("Start connection " + request.GetId() + " ...");
                    IConnection connection = factory.CreateConnection(user, password);
                    connection.Start();
                    ISession         session  = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                    IDestination     dest     = session.GetTopic(topic);
                    IMessageProducer producer = session.CreateProducer(dest);
                    producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                    logger.Log("Send message " + request.GetId() + " on topic " + topic + "...");
                    producer.Send(request.ToMessage(session));
                    connection.Close();
                }
            }
        }
Exemplo n.º 8
0
        private static void ReceiveMessages()
        {
            try
            {
                IConnectionFactory     factory    = new NMSConnectionFactory(ConfigHelper.GetConfigValueByKey("QueueConnectionString"));
                Apache.NMS.IConnection connection = factory.CreateConnection();
                //"username", "password"
                connection.Start();
                ISession         session          = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                IDestination     queueDestination = SessionUtil.GetDestination(session, ConfigHelper.GetConfigValueByKey("QueueName"));
                IMessageConsumer consumer         = session.CreateConsumer(queueDestination);

                consumer.Listener += new MessageListener(Message_Listener);
                Thread.Sleep(Convert.ToInt32(ConfigHelper.GetConfigValueByKey("TimeOut")));
                connection.Close();

                Console.WriteLine("Restart message wait");
            }
            catch (Exception e)
            {
                StreamWriter sw = new StreamWriter("error.txt", true);
                sw.WriteLine("Error==={0}==={1}", DateTime.Now.ToString(), e.ToString());
                sw.Close();
            }
            ReceiveMessages();
        }
Exemplo n.º 9
0
        private void SendMessageToBackgroundProcess()
        {
            //TODO: this is copid alot. This boiler plate code should be in a common shared class and setup using the same DI setup that the db context goes through.
            Uri connecturi = new Uri("activemq:tcp://activemq:61616");

            // 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 = SessionUtil.GetDestination(session, "queue://FOO.BAR");

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

                        // Send a message
                        ITextMessage request = session.CreateTextMessage("Message from actor api service.");

                        producer.Send(request);
                    }
                }
        }
Exemplo n.º 10
0
        private static bool ReadNextMessage()
        {
            const string queueName = "TestTextQueue";

            var brokerUri = $"amqp://*****:*****@localhost:5672";

            var connectionFactory = new NMSConnectionFactory(brokerUri);

            using var connection = connectionFactory.CreateConnection();
            connection.Start();

            using var session     = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            using var destination = session.GetQueue(queueName);
            using var consumer    = session.CreateConsumer(destination);

            var message = consumer.Receive();

            if (message is ITextMessage textMessage)
            {
                Console.WriteLine($"Received message: {textMessage}");

                return(true);
            }

            Console.WriteLine("Unexpected message type: " + message.GetType().Name);
            return(false);
        }
Exemplo n.º 11
0
        static void ReadNextMessage()
        {
            while (true)
            {
                string topic = "TextQueue";

                string brokerUri             = $"activemq:tcp://localhost:61616"; // Default port
                NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

                using (IConnection connection = factory.CreateConnection())
                {
                    connection.Start();
                    using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                        using (IDestination dest = session.GetTopic(topic))
                            using (IMessageConsumer consumer = session.CreateConsumer(dest))
                            {
                                IMessage msg = consumer.Receive();
                                if (msg is ITextMessage)
                                {
                                    ITextMessage txtMsg = msg as ITextMessage;
                                    string       body   = txtMsg.Text;


                                    Console.WriteLine($"Messege: {txtMsg.Text}");
                                }
                                else
                                {
                                    Console.WriteLine("Unexpected message type: " + msg.GetType().Name);
                                }
                            }
                }
            }
        }
Exemplo n.º 12
0
        static bool ReadNextMessage()
        {
            string queueName = "New";

            string brokerUri             = $"activemq:tcp://localhost:61616";  // Default port
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection())
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(queueName))
                        using (IMessageConsumer consumer = session.CreateConsumer(dest))
                        {
                            IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(2000));

                            if (msg is ITextMessage)
                            {
                                ITextMessage txtMsg = msg as ITextMessage;
                                msgList.Add(txtMsg.Text);

                                Console.WriteLine($"Received message: {txtMsg.Text}");

                                return(true);
                            }
                            else
                            {
                                Console.WriteLine("Unexpected message type: ");
                                return(false);
                            }
                        }
            }
        }
Exemplo n.º 13
0
        public ActionResult <IEnumerable <string> > Get()
        {
            Uri connecturi = new Uri("activemq:tcp://activemq:61616");

            // 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 = SessionUtil.GetDestination(session, "queue://FOO.BAR");

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

                        // Send a message
                        ITextMessage request = session.CreateTextMessage("Message from title api service.");

                        producer.Send(request);
                    }
                }

            return(new string[] { "value1", "value2" });
        }
        public static String ReadNextMessageQueue2()
        {
            string queueName = "formatedFile";

            string brokerUri             = $"activemq:tcp://localhost:61616";
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection())
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(queueName))
                        using (IMessageConsumer consumer = session.CreateConsumer(dest))
                        {
                            IMessage msg = consumer.Receive();

                            if (msg is ITextMessage)
                            {
                                ITextMessage txtMsg = msg as ITextMessage;
                                string       body   = txtMsg.Text;

                                return(body);
                            }
                            else
                            {
                                return("error");
                            }
                        }
            }
        }
Exemplo n.º 15
0
        private static void Main(string[] args)
        {
            Console.WriteLine("ActiveMQ Consumer Demo");

            string topic = "TextQueue";

            string brokerUri             = $"activemq:tcp://192.168.250.198:61616"; // Default port
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection("artemis", "simetraehcapa"))
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(topic))
                        using (IMessageConsumer consumer = session.CreateConsumer(dest))
                        {
                            IMessage msg = consumer.Receive();
                            if (msg is ITextMessage)
                            {
                                ITextMessage txtMsg = msg as ITextMessage;
                                string       body   = txtMsg.Text;

                                Console.WriteLine($"Received message: {txtMsg.Text}");
                            }
                            else
                            {
                                Console.WriteLine("Unexpected message type: " + msg.GetType().Name);
                            }
                        }
            }

            Console.WriteLine($"");
            Console.WriteLine($"Press any key to finish.");
            Console.ReadKey(true);
        }
Exemplo n.º 16
0
        //enviar mensajes al servicio de comunicacion/mensajeria
        public void SendQueueMessages(Player message)
        {
            // definir nombre del queue, en caso de no existir activemq lo crea
            // definir el uri del endpoint de aws mq - aws acepta ssl no tcp asi que el string cambia en el protocolo
            // al ser ssl hay que enviar las credenciales
            // hay que configurar en aws console para que el VPC acepte trafico de afuera, agregar una politica en el security group para inbound traffic
            // connectionfactory del package apache.nms provee manejo de comunicacion con el queue
            // definir el "producer" en caso de la clase que envia de mensaje
            // definir el "receiver" en caso de ser el servicio(s) consumiendo mensajes del queue

            string queueName = "dev_queue";

            Console.WriteLine($"Adding message to queue topic: {queueName}");
            //string brokerUri = $"activemq:tcp://localhost:61616";  // dev broker

            string brokerUri             = $"activemq:ssl://b-92a12260-5d2f-4a73-be53-6c78e22ef8b4-1.mq.us-east-2.amazonaws.com:61617"; //prod broker
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection("admin", "adminactivemq"))
            {
                connection.Start();

                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(queueName))
                        using (IMessageProducer producer = session.CreateProducer(dest))
                        {
                            producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                            producer.Send(message);
                            Console.WriteLine($"Sent {message} messages");
                        }
            }
        }
Exemplo n.º 17
0
        public object ReadNextObjectMessage(string destination)
        {
            NMSConnectionFactory factory = new NMSConnectionFactory(_brokerUri);

            using (IConnection connection = factory.CreateConnection())
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(destination))
                        using (IMessageConsumer consumer = session.CreateConsumer(dest))
                        {
                            IMessage msg = consumer.Receive();
                            if (msg is IObjectMessage)
                            {
                                IObjectMessage objMsg = msg as IObjectMessage;
                                var            body   = objMsg.Body;
                                //if (body == "PatientCreated")
                                //{

                                //}
                                //Console.WriteLine($"Received message: {txtMsg.Text}");

                                return(body);
                            }
                            else
                            {
                                //Console.WriteLine("Unexpected message type: " + msg.GetType().Name);
                                return("Unexpected message type: " + msg.GetType().Name);
                            }
                        }
            }
        }
Exemplo n.º 18
0
        public static T PullFromActiveMQ(int queueNumber)
        {
            Uri connecturi = new Uri("activemq:tcp://54.173.238.145:61616");

            // 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 = SessionUtil.GetDestination(session, GETQueueName(queueNumber));

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

                            // Consume a message
                            ITextMessage message = consumer.Receive() as ITextMessage;
                            if (message == null)
                            {
                                return(default(T));
                            }
                            else
                            {
                                T opld = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(message.Text);

                                return(opld);
                            }
                        }
                }
        }
Exemplo n.º 19
0
    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        _logger.LogInformation("CONSUMER running at: {time}", DateTimeOffset.Now);
        _logger.LogInformation($"CONSUMER about to connect to {_options.ConnectUri}");

        var factory = new NMSConnectionFactory(_options.ConnectUri);

        using var connection = factory.CreateConnection();
        using var session    = connection.CreateSession();

        var destination = SessionUtil.GetDestination(session, _options.Destination);

        _logger.LogInformation($"CONSUMER using destination: {destination}");

        using var consumer = session.CreateConsumer(destination);

        connection.Start();

        consumer.Listener += (IMessage message) =>
        {
            _logger.LogInformation($"Received message with ID: {message.NMSMessageId}");
            _logger.LogInformation($"Received message with text: {(message as ITextMessage).Text}");
        };

        ct.WaitHandle.WaitOne();
    }
Exemplo n.º 20
0
		public void TestMaxInactivityDuration()
		{
			string testuri = "activemq:tcp://${activemqhost}:61616" +
										"?wireFormat.maxInactivityDurationInitialDelay=5000" +
										"&wireFormat.maxInactivityDuration=10000" +
										"&connection.asyncClose=false";

			NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(testuri));
			using(IConnection connection = factory.CreateConnection("", ""))
			{
				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))
					{
						SendMessage(producer);

						IMessage receivedMsg = consumer.Receive(TimeSpan.FromSeconds(5));
						Assert.AreEqual(CORRELATION_ID, receivedMsg.NMSCorrelationID, "Invalid correlation ID.");

						// Go inactive...
						Thread.Sleep(TimeSpan.FromSeconds(30));

						// Send another message.
						SendMessage(producer);
						receivedMsg = consumer.Receive(TimeSpan.FromSeconds(5));
						Assert.AreEqual(CORRELATION_ID, receivedMsg.NMSCorrelationID, "Invalid correlation ID.");
					}
				}
			}
		}
Exemplo n.º 21
0
        private void Receive(int numberOfMessages)
        {
            IConnectionFactory connectionFactory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(BrokerUri));

            using (IConnection connection = connectionFactory.CreateConnection())
            {
                connection.Start();

                connection.ConnectionInterruptedListener += OnConnectionInterrupted;
                connection.ConnectionResumedListener     += OnConnectionResumed;

                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IQueue queue = session.GetQueue(Queue);

                    using (IMessageConsumer consumer = session.CreateConsumer(queue))
                    {
                        for (int i = 0; i < numberOfMessages; i++)
                        {
                            IMessage message = consumer.Receive(TimeSpan.FromMilliseconds(5000));
                            Assert.IsNotNull(message);
                            Tracer.Debug("Received message.");
                            received++;
                        }
                    }
                }

                connection.ConnectionInterruptedListener -= OnConnectionInterrupted;
                connection.ConnectionResumedListener     -= OnConnectionResumed;
            }
        }
Exemplo n.º 22
0
        private void Send(int numberOfMessages)
        {
            IConnectionFactory connectionFactory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(BrokerUri));

            using (IConnection connection = connectionFactory.CreateConnection())
            {
                connection.Start();

                using (ISession session = connection.CreateSession())
                {
                    IQueue queue = session.GetQueue(Queue);

                    using (IMessageProducer producer = session.CreateProducer(queue))
                    {
                        producer.DeliveryMode = MsgDeliveryMode.Persistent;

                        ITextMessage message = producer.CreateTextMessage(TextMessage);

                        for (int i = 0; i < numberOfMessages; i++)
                        {
                            producer.Send(message);
                            Tracer.Debug("Sent message.");
                            sent++;
                        }
                    }
                }
            }
        }
        public void TestConnectionSendsAuthenticationData()
        {
            NMSConnectionFactory factory = new NMSConnectionFactory("activemq:mock://localhost:61616");

            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using (Connection connection = factory.CreateConnection(username, password) as Connection)
            {
                Assert.IsNotNull(connection);

                MockTransport transport = (MockTransport)connection.ITransport.Narrow(typeof(MockTransport));

                transport.OutgoingCommand = new CommandHandler(OnOutgoingCommand);

                connection.Start();

                Thread.Sleep(1000);

                Assert.IsNotNull(this.info);
                Assert.AreEqual(username, info.UserName);
                Assert.AreEqual(password, info.Password);

                connection.Close();
            }
        }
Exemplo n.º 24
0
        private static bool ReadNextMessage()
        {
            const string topic = "TestTextTopic";

            var brokerUri = $"activemq:tcp://localhost:61616";

            var connectionFactory = new NMSConnectionFactory(brokerUri);

            using var connection = connectionFactory.CreateConnection("sans-app", "password");
            connection.Start();

            using var session     = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
            using var destination = session.GetTopic(topic);
            using var consumer    = session.CreateConsumer(destination);

            var message = consumer.Receive();

            if (message is ITextMessage)
            {
                var textMessage = message as ITextMessage;
                Console.WriteLine($"Received message: {textMessage.Text}");

                return(true);
            }

            Console.WriteLine("Unexpected message type: " + message.GetType().Name);
            return(false);
        }
Exemplo n.º 25
0
        public void TestConnection()
        {
            IConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(connectionUri));

            using (connection = factory.CreateConnection())
                using (ISession session = connection.CreateSession())
                {
                    IDestination destination = SessionUtil.GetDestination(session, "queue://TEST.test.in");
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                    {
                        Connection amqConnection = connection as Connection;
                        connection.ExceptionListener += ConnectionException;

                        consumer.Listener += OnMessage;

                        TcpFaultyTransport transport = amqConnection.ITransport.Narrow(typeof(TcpFaultyTransport)) as TcpFaultyTransport;
                        Assert.IsNotNull(transport);
                        transport.OnewayCommandPreProcessor += FailOnKeepAlive;

                        Thread.Sleep(TimeSpan.FromSeconds(2));

                        connection.Start();

                        Assert.IsTrue(exceptionOccuredEvent.WaitOne(TimeSpan.FromSeconds(30 * 3)),
                                      "Exception didnt occured within waiting time");
                    }
                }
        }
        public void TestURIForPrefetchHandling(int queuePreFetch, int queueBrowserPrefetch, int topicPrefetch, int durableTopicPrefetch, int maximumPendingMessageLimit)
        {
            string testuri = string.Format("activemq:tcp://${{activemqhost}}:61616" +
                                           "?nms.PrefetchPolicy.queuePrefetch={0}" +
                                           "&nms.PrefetchPolicy.queueBrowserPrefetch={1}" +
                                           "&nms.PrefetchPolicy.topicPrefetch={2}" +
                                           "&nms.PrefetchPolicy.durableTopicPrefetch={3}" +
                                           "&nms.PrefetchPolicy.maximumPendingMessageLimit={4}",
                                           queuePreFetch, queueBrowserPrefetch, topicPrefetch, durableTopicPrefetch, maximumPendingMessageLimit);

            NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(testuri));

            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using (IConnection connection = factory.CreateConnection("", ""))
            {
                Assert.IsNotNull(connection);

                Connection amqConnection = connection as Connection;
                Assert.AreEqual(queuePreFetch, amqConnection.PrefetchPolicy.QueuePrefetch);
                Assert.AreEqual(queueBrowserPrefetch, amqConnection.PrefetchPolicy.QueueBrowserPrefetch);
                Assert.AreEqual(topicPrefetch, amqConnection.PrefetchPolicy.TopicPrefetch);
                Assert.AreEqual(durableTopicPrefetch, amqConnection.PrefetchPolicy.DurableTopicPrefetch);
                Assert.AreEqual(maximumPendingMessageLimit, amqConnection.PrefetchPolicy.MaximumPendingMessageLimit);

                connection.Close();
            }
        }
        public void TestMaxInactivityDuration()
        {
            string testuri = "activemq:tcp://${activemqhost}:61616" +
                             "?wireFormat.maxInactivityDurationInitialDelay=5000" +
                             "&wireFormat.maxInactivityDuration=10000" +
                             "&connection.asyncClose=false";

            NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(testuri));

            using (IConnection connection = factory.CreateConnection("", ""))
            {
                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))
                        {
                            SendMessage(producer);

                            IMessage receivedMsg = consumer.Receive(TimeSpan.FromSeconds(5));
                            Assert.AreEqual(CORRELATION_ID, receivedMsg.NMSCorrelationID, "Invalid correlation ID.");

                            // Go inactive...
                            Thread.Sleep(TimeSpan.FromSeconds(30));

                            // Send another message.
                            SendMessage(producer);
                            receivedMsg = consumer.Receive(TimeSpan.FromSeconds(5));
                            Assert.AreEqual(CORRELATION_ID, receivedMsg.NMSCorrelationID, "Invalid correlation ID.");
                        }
                }
            }
        }
Exemplo n.º 28
0
        public void SendQueueMessages(GTMS.Models.Message message)
        {
            // definir nombre del queue, en caso de no existir activemq lo crea
            // definir el uri del endpoint de aw - aws acepta ssl no tcp asi que el string cambia en el protocolo
            // al ser ssl hay que enviar las credenciales
            // apache.nms connectionfactory provee manejo de comunicacion con el queue
            // definir el "producer" en caso de la clase que envia de mensaje
            // definir el "receiver" en caso de ser el servicio consumiendo el queue

            string queueName = "dev_queue";

            Console.WriteLine($"Adding message to queue topic: {queueName}");

            string brokerUri = $"activemq:tcp://localhost:61616";  // dev broker
            //string brokerUri = $"activemq:ssl://b-57e8bf3e-69c9-4bec-b528-de407901bd09-1.mq.us-east-2.amazonaws.com:61617";

            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection("admin", "adminactivemq"))
            {
                connection.Start();

                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(queueName))
                        using (IMessageProducer producer = session.CreateProducer(dest))
                        {
                            producer.DeliveryMode = MsgDeliveryMode.NonPersistent;
                            producer.Send(message);
                            Console.WriteLine($"Sent {message} messages");
                        }
            }
        }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            var uri = new Uri("activemq:tcp://*****:*****@gmail.com"
                            });
                            producer.Send(msg);
                            Console.WriteLine("Send");
                        }
                    }
                }
        }
Exemplo n.º 30
0
        public static void PushToActiveMQ(T opldObject, int queueNumber)
        {
            Uri connecturi = new Uri("activemq:tcp://54.173.238.145:61616");

            // 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 = SessionUtil.GetDestination(session, GETQueueName(queueNumber));

                    // Create the producer
                    using (IMessageProducer producer = session.CreateProducer(destination))
                    {
                        // Start the connection so that messages will be processed.
                        connection.Start();
                        producer.DeliveryMode = MsgDeliveryMode.Persistent;

                        var messageToQueue = JsonConvert.SerializeObject(opldObject);

                        //var ss = "Test Message " + DateTime.Now;
                        ITextMessage request = session.CreateTextMessage(messageToQueue);
                        request.NMSCorrelationID = "abc";
                        //request.Properties["NMSXGroupID"] = "cheese";
                        //request.Properties["myHeader"] = "Cheddar";

                        producer.Send(request);
                    }
                }
        }
Exemplo n.º 31
0
        static bool ReadNextMessageQueue()
        {
            string brokerUri             = $"activemq:tcp://{hostIp}:{hostPort}"; // Default port
            NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);

            using (IConnection connection = factory.CreateConnection())
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                    using (IDestination dest = session.GetQueue(queueName))
                        using (IMessageConsumer consumer = session.CreateConsumer(dest))
                        {
                            IMessage msg = consumer.Receive();
                            if (msg is ITextMessage)
                            {
                                ITextMessage txtMsg = msg as ITextMessage;
                                string       body   = txtMsg.Text;
                                Console.WriteLine($"Received message: {txtMsg.Text}");
                                return(true);
                            }
                            else
                            {
                                Console.WriteLine("Unexpected message type: " + msg.GetType().Name);
                            }
                        }
            }
            return(false);
        }
Exemplo n.º 32
0
		public void TestURI(string connectionURI)
		{
			NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(connectionURI));
			Assert.IsNotNull(factory);
			Assert.IsNotNull(factory.ConnectionFactory);
			using(IConnection connection = factory.CreateConnection("", ""))
			{
				Assert.IsNotNull(connection);
				connection.Close();
			}
		}
Exemplo n.º 33
0
        public void TestURIForPrefetchHandling(int queuePreFetch, int queueBrowserPrefetch, int topicPrefetch, int durableTopicPrefetch, int maximumPendingMessageLimit)
        {
            string testuri = string.Format("activemq:tcp://${{activemqhost}}:61616" +
                          				   "?nms.PrefetchPolicy.queuePrefetch={0}" +
                                           "&nms.PrefetchPolicy.queueBrowserPrefetch={1}" +
                                           "&nms.PrefetchPolicy.topicPrefetch={2}" +
                                           "&nms.PrefetchPolicy.durableTopicPrefetch={3}" +
                                           "&nms.PrefetchPolicy.maximumPendingMessageLimit={4}",
			                               queuePreFetch, queueBrowserPrefetch, topicPrefetch, durableTopicPrefetch, maximumPendingMessageLimit);

            NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(testuri));

            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using(IConnection connection = factory.CreateConnection("", ""))
            {
                Assert.IsNotNull(connection);

                Connection amqConnection = connection as Connection;
                Assert.AreEqual(queuePreFetch, amqConnection.PrefetchPolicy.QueuePrefetch);
                Assert.AreEqual(queueBrowserPrefetch, amqConnection.PrefetchPolicy.QueueBrowserPrefetch);
                Assert.AreEqual(topicPrefetch, amqConnection.PrefetchPolicy.TopicPrefetch);
                Assert.AreEqual(durableTopicPrefetch, amqConnection.PrefetchPolicy.DurableTopicPrefetch);
                Assert.AreEqual(maximumPendingMessageLimit, amqConnection.PrefetchPolicy.MaximumPendingMessageLimit);

				connection.Close();
			}
        }
Exemplo n.º 34
0
		public void TestInactivityMonitorThreadLeak(
			[Values(0, 1000)]
			int inactivityDuration)
		{
			Process currentProcess = Process.GetCurrentProcess();
			Tracer.InfoFormat("Beginning thread count: {0}, handle count: {1}", currentProcess.Threads.Count, currentProcess.HandleCount);

			string testuri = string.Format("activemq:tcp://${{activemqhost}}:61616?wireFormat.maxInactivityDuration={0}", inactivityDuration);
	
			NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(testuri));

			// We measure the initial resource counts, and then allow a certain fudge factor for the resources
			// to fluctuate at run-time.  We allow for a certain amount of fluctuation, but if the counts
			// grow outside the safe boundaries of delayed garbage collection, then we fail the test.
			currentProcess = Process.GetCurrentProcess();
			int beginThreadCount = currentProcess.Threads.Count;
			int beginHandleCount = currentProcess.HandleCount;
			int maxThreadGrowth = 10;
			int maxHandleGrowth = 500;

			for(int i = 0; i < 200; i++)
			{
				using(IConnection connection = factory.CreateConnection("ResourceLeakTest", "Password"))
				{
					using(ISession session = connection.CreateSession())
					{
						IDestination destination = SessionUtil.GetDestination(session, "topic://NMSResourceLeak.TestTopic");
						using(IMessageConsumer consumer = session.CreateConsumer(destination))
						{
							connection.Start();
						}
					}
				}

				currentProcess = Process.GetCurrentProcess();
				int endThreadCount = currentProcess.Threads.Count;
				int endHandleCount = currentProcess.HandleCount;

				Assert.Less(endThreadCount, beginThreadCount + maxThreadGrowth, string.Format("Thread count grew beyond maximum of {0} on iteration #{1}.", maxThreadGrowth, i));
				Assert.Less(endHandleCount, beginHandleCount + maxHandleGrowth, string.Format("Handle count grew beyond maximum of {0} on iteration #{1}.", maxHandleGrowth, i));
			}
		}
Exemplo n.º 35
0
        public void TestConnectionSendsAuthenticationData()
        {
            NMSConnectionFactory factory = new NMSConnectionFactory("activemq:mock://localhost:61616");
            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using(Connection connection = factory.CreateConnection(username, password) as Connection)
            {
                Assert.IsNotNull(connection);

				MockTransport transport = (MockTransport) connection.ITransport.Narrow(typeof(MockTransport));

                transport.OutgoingCommand = new CommandHandler(OnOutgoingCommand);

                connection.Start();

                Thread.Sleep(1000);
                
                Assert.IsNotNull(this.info);
                Assert.AreEqual(username, info.UserName);
                Assert.AreEqual(password, info.Password);
				
				connection.Close();
            }
        }
Exemplo n.º 36
0
        public void TestURIForRedeliverPolicyHandling()
        {
            string uri1 = "activemq:tcp://${activemqhost}:61616" +
                          "?nms.RedeliveryPolicy.BackOffMultiplier=10" +
                          "&nms.RedeliveryPolicy.InitialRedeliveryDelay=2000" +
                          "&nms.RedeliveryPolicy.UseExponentialBackOff=true" +
                          "&nms.RedeliveryPolicy.UseCollisionAvoidance=true" +
                          "&nms.RedeliveryPolicy.CollisionAvoidancePercent=20";

            string uri2 = "activemq:tcp://${activemqhost}:61616" +
                          "?nms.RedeliveryPolicy.backOffMultiplier=50" +
                          "&nms.RedeliveryPolicy.initialRedeliveryDelay=4000" +
                          "&nms.RedeliveryPolicy.useExponentialBackOff=false" +
                          "&nms.RedeliveryPolicy.useCollisionAvoidance=false" +
                          "&nms.RedeliveryPolicy.collisionAvoidancePercent=10";

            NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(uri1));

            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using(IConnection connection = factory.CreateConnection("", ""))
            {
                Assert.IsNotNull(connection);

                Connection amqConnection = connection as Connection;

                Assert.AreEqual(10, amqConnection.RedeliveryPolicy.BackOffMultiplier);
                Assert.AreEqual(2000, amqConnection.RedeliveryPolicy.InitialRedeliveryDelay);
                Assert.AreEqual(true, amqConnection.RedeliveryPolicy.UseExponentialBackOff);
                Assert.AreEqual(true, amqConnection.RedeliveryPolicy.UseCollisionAvoidance);
                Assert.AreEqual(20, amqConnection.RedeliveryPolicy.CollisionAvoidancePercent);
            }

            factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(uri2));

            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using(IConnection connection = factory.CreateConnection("", ""))
            {
                Assert.IsNotNull(connection);

                Connection amqConnection = connection as Connection;
                Assert.AreEqual(50, amqConnection.RedeliveryPolicy.BackOffMultiplier);
                Assert.AreEqual(4000, amqConnection.RedeliveryPolicy.InitialRedeliveryDelay);
                Assert.AreEqual(false, amqConnection.RedeliveryPolicy.UseExponentialBackOff);
                Assert.AreEqual(false, amqConnection.RedeliveryPolicy.UseCollisionAvoidance);
                Assert.AreEqual(10, amqConnection.RedeliveryPolicy.CollisionAvoidancePercent);
            }
        }
Exemplo n.º 37
0
        public void TestURIForPrefetchHandlingOfAll(int allPreFetch)
        {
            string testuri = string.Format("activemq:tcp://${{activemqhost}}:61616" +
                          				   "?nms.PrefetchPolicy.all={0}", allPreFetch);

            NMSConnectionFactory factory = new NMSConnectionFactory(NMSTestSupport.ReplaceEnvVar(testuri));

            Assert.IsNotNull(factory);
            Assert.IsNotNull(factory.ConnectionFactory);
            using(IConnection connection = factory.CreateConnection("", ""))
            {
                Assert.IsNotNull(connection);

                Connection amqConnection = connection as Connection;
                Assert.AreEqual(allPreFetch, amqConnection.PrefetchPolicy.QueuePrefetch);
                Assert.AreEqual(allPreFetch, amqConnection.PrefetchPolicy.QueueBrowserPrefetch);
                Assert.AreEqual(allPreFetch, amqConnection.PrefetchPolicy.TopicPrefetch);
                Assert.AreEqual(allPreFetch, amqConnection.PrefetchPolicy.DurableTopicPrefetch);

				connection.Close();
			}
        }